From b3acb31008d163d1c6c7b906d73f86c0b538e6e6 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 16 Jun 2025 07:23:55 -0600 Subject: [PATCH 01/42] musikr: hard revert to pre-filetreecache system --- AGENT.md | 1 - CLAUDE.md | 123 ------- .../oxycblt/auxio/music/MusicRepository.kt | 13 +- .../org/oxycblt/auxio/music/MusicSettings.kt | 86 +---- .../locations/ExcludedLocationAdapter.kt | 57 --- .../locations/ExcludedLocationsDialog.kt | 63 ---- .../auxio/music/locations/LocationAdapter.kt | 87 +++-- .../music/locations/MusicLocationAdapter.kt | 57 --- .../music/locations/MusicLocationsDialog.kt | 63 ---- ...cationsDialog.kt => MusicSourcesDialog.kt} | 67 ++-- .../auxio/music/service/IndexingHolder.kt | 4 +- .../music/shim/WriteOnlyFileTreeCache.kt | 59 ---- .../auxio/settings/RootPreferenceFragment.kt | 12 +- .../res/layout/dialog_music_locations.xml | 3 +- app/src/main/res/navigation/inner.xml | 2 +- app/src/main/res/navigation/outer.xml | 10 +- app/src/main/res/values/settings.xml | 2 - app/src/main/res/values/strings.xml | 2 - app/src/main/res/xml/preferences_root.xml | 5 - build.gradle | 1 - musikr/ARCHITECTURE.md | 135 -------- musikr/build.gradle | 3 - musikr/src/main/cpp/README.md | 90 ----- .../main/java/org/oxycblt/musikr/Config.kt | 10 +- .../main/java/org/oxycblt/musikr/Musikr.kt | 54 ++- .../oxycblt/musikr/cache/db/CacheDatabase.kt | 2 - .../org/oxycblt/musikr/cache/db/DBCache.kt | 16 +- .../java/org/oxycblt/musikr/covers/README.md | 74 ---- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 8 +- .../java/org/oxycblt/musikr/fs/Location.kt | 76 ---- .../org/oxycblt/musikr/fs/MusicLocation.kt | 72 ++++ .../main/java/org/oxycblt/musikr/fs/README.md | 72 ---- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 325 ++++-------------- .../musikr/fs/device/DeviceFSEntries.kt | 27 +- .../oxycblt/musikr/fs/device/FileTreeCache.kt | 165 --------- .../org/oxycblt/musikr/fs/device/QueryUtil.kt | 11 +- .../org/oxycblt/musikr/metadata/README.md | 64 ---- .../java/org/oxycblt/musikr/model/README.md | 79 ----- .../oxycblt/musikr/pipeline/ExploreStep.kt | 23 +- .../org/oxycblt/musikr/pipeline/README.md | 64 ---- .../java/org/oxycblt/musikr/tag/README.md | 83 ----- .../oxycblt/musikr/track/LocationObserver.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 8 +- 43 files changed, 318 insertions(+), 1864 deletions(-) delete mode 120000 AGENT.md delete mode 100644 CLAUDE.md delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt rename app/src/main/java/org/oxycblt/auxio/music/locations/{LocationsDialog.kt => MusicSourcesDialog.kt} (69%) delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt delete mode 100644 musikr/ARCHITECTURE.md delete mode 100644 musikr/src/main/cpp/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/covers/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/metadata/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/model/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/tag/README.md diff --git a/AGENT.md b/AGENT.md deleted file mode 120000 index 681311eb9..000000000 --- a/AGENT.md +++ /dev/null @@ -1 +0,0 @@ -CLAUDE.md \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 7ebb3c146..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,123 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Project Overview - -Auxio is a modern Android music player written in Kotlin that emphasizes simplicity and performance. It uses Media3 ExoPlayer for playback and includes a custom native music indexing library called musikr. - -## Build System & Commands - -### Prerequisites -- `cmake` and `ninja-build` must be installed before building -- Project uses git submodules - clone with `git clone --recurse-submodules` -- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts - -### Common Build Commands -```bash -# Build debug version -./gradlew assembleDebug - -# Build release version -./gradlew assembleRelease - -# Run tests -./gradlew test - -# Run connected tests -./gradlew connectedAndroidTest - -# Code formatting (Spotless) -./gradlew spotlessApply - -# Check code formatting -./gradlew spotlessCheck -``` - -### Development Modules -- `app/` - Main Android application -- `musikr/` - Native music indexing library with TagLib integration -- `media/` - Patched Media3 ExoPlayer libraries (git submodule) - -## Architecture Overview - -### Core Architecture Pattern -- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search) -- **Repository Pattern** - MusicRepository as single source of truth for music data -- **Dependency Injection** - Hilt/Dagger for modular dependency management -- **Single Activity Architecture** with Navigation Components -- **Service-Oriented** background music processing - -### Key Modules & Components - -#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`) -- `MusicRepository` - Central music library state management -- `MusicViewModel` - UI layer for music data access -- `service/` - MediaBrowserServiceCompat integration -- `shim/` - Abstraction layer for musikr integration - -#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`) -- `PlaybackViewModel` - Main playback UI interface -- `PlaybackStateManager` - Core playback state management -- `service/` - Background ExoPlayer integration -- `queue/` - Playback queue management -- `persist/` - Playback state persistence (Room database) -- `replaygain/` - Audio processing for volume normalization - -#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`) -- `home/` - Main library browsing with customizable tabs -- `detail/` - Album, artist, genre, and playlist detail views -- `search/` - Music search functionality -- `list/` - Shared list components with sorting/filtering -- `ui/` - Custom UI components, theming, animations - -#### Native Music Library (`musikr/`) -- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate) -- **TagLib integration** - Native C++ metadata extraction -- **File system caching** - Device storage access optimization -- **Cover art management** - Embedded and external cover support - -### Data Flow -1. musikr scans and indexes music files from device storage -2. MusicRepository manages indexed library and exposes to UI -3. ViewModels provide reactive state for UI components using StateFlow -4. PlaybackService handles audio playback via ExoPlayer -5. UI observes ViewModels and updates reactively - -## Code Conventions - -### Language & Libraries -- **Kotlin** - Primary language with coroutines for async operations -- **Hilt/Dagger** - Dependency injection -- **Room** - Local database for persistence -- **Navigation Components** - Fragment navigation -- **ViewBinding** - Type-safe view access -- **StateFlow/LiveData** - Reactive state management -- **Coil** - Image loading for cover art - -### Code Style -- Uses Spotless with ktfmt Dropbox style formatting -- License header required (see NOTICE file) -- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml) - -## Testing - -### Test Structure -- Unit tests: `src/test/` directories -- Integration tests: `src/androidTest/` directories -- musikr module includes Robolectric tests - -### Test Dependencies -- JUnit 4 for unit testing -- MockK for mocking -- Robolectric for Android unit tests -- Espresso for UI tests - -## Key Development Notes - -- **Custom Media3**: Uses patched Media3 ExoPlayer for enhanced playback features -- **Native Dependencies**: musikr module builds TagLib from source during compilation -- **Permission Handling**: Requires storage permissions for music file access -- **Background Services**: Foreground service for continuous music playback -- **Widget Support**: Multiple widget layouts with automatic sizing adaptation -- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index f83f202e9..6b478c520 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -29,7 +29,6 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import org.oxycblt.auxio.image.covers.SettingCovers import org.oxycblt.auxio.music.MusicRepository.IndexingWorker -import org.oxycblt.auxio.music.shim.WriteOnlyFileTreeCache import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache import org.oxycblt.musikr.IndexingProgress import org.oxycblt.musikr.Interpretation @@ -38,11 +37,9 @@ 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 -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 @@ -388,20 +385,16 @@ constructor( Naming.simple() } val locations = musicSettings.musicLocations - val excludedLocations = musicSettings.excludedLocations val withHidden = musicSettings.withHidden val currentRevision = musicSettings.revision val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) - val fileTreeCache = - if (withCache) FileTreeCache.from(context) - else WriteOnlyFileTreeCache(FileTreeCache.from(context)) - val query = Query(source = locations, exclude = excludedLocations) - val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) + val storage = Storage(cache, covers, storedPlaylists) val interpretation = Interpretation(nameFactory, separators, withHidden) - val result = Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) + val result = + Musikr.new(context, storage, interpretation).run(locations, ::emitIndexingProgress) // Music loading completed, update the revision right now so we re-use this work // later. musicSettings.revision = newRevision diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 8317f67d8..67b79ae15 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -20,13 +20,12 @@ 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.Location +import org.oxycblt.musikr.fs.MusicLocation import timber.log.Timber as L /** @@ -38,9 +37,7 @@ interface MusicSettings : Settings { /** The current library revision. */ var revision: UUID? /** The locations of music to load. */ - var musicLocations: List - /** The locations to exclude from music loading. */ - var excludedLocations: List + var musicLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -77,35 +74,20 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var musicLocations: List + override var musicLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_music_locations), null) ?: return emptyList() - return locations.toOpenedLocations() - } - set(value) { - sharedPreferences.edit { - putString(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. - listener?.onMusicLocationsChanged() - } - } - - override var excludedLocations: List - get() { - val locations = - sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) - ?: return emptyList() - return locations.toUnopenedLocations() + return MusicLocation.existing(context, locations) } set(value) { sharedPreferences.edit { putString( - getString(R.string.set_key_excluded_locations), value.stringifyLocations()) + getString(R.string.set_key_music_locations), MusicLocation.toString(value)) commit() + // Sometimes changing this setting just won't actually trigger the listener. + // Only this one. No idea why. listener?.onMusicLocationsChanged() } } @@ -137,8 +119,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) when (key) { - getString(R.string.set_key_music_locations), - getString(R.string.set_key_excluded_locations) -> { + getString(R.string.set_key_music_locations) -> { L.d("Dispatching music locations change") listener.onMusicLocationsChanged() } @@ -155,55 +136,4 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } } - - private fun List.stringify(): String = - joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - - private fun String.toOpenedLocations(): List = - splitEscaped { it == ';' } - .mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } - - private fun List.stringifyLocations(): String = - joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - - private fun String.toUnopenedLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri()) } - - private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { - val split = mutableListOf() - 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 - } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt deleted file mode 100644 index 20e4a4be2..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * ExcludedLocationAdapter.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.view.ViewGroup -import org.oxycblt.auxio.databinding.ItemMusicLocationBinding -import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.Location - -/** - * [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances. - * - * @param listener A [LocationAdapter.Listener] to bind interactions to. - * @author Alexander Capehart (OxygenCobalt) - */ -class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : - LocationAdapter(listener) { - override fun createViewHolder(parent: ViewGroup): LocationViewHolder = - ExcludedLocationViewHolder.from(parent) -} - -/** - * A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : - LocationViewHolder(binding) { - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: ViewGroup) = - ExcludedLocationViewHolder( - ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt deleted file mode 100644 index be70285d0..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * ExcludedLocationsDialog.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.content.Context -import android.net.Uri -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig -import org.oxycblt.auxio.R -import org.oxycblt.auxio.music.MusicSettings -import org.oxycblt.musikr.fs.Location - -/** - * Dialog that manages the excluded locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class ExcludedLocationsDialog : LocationsDialog() { - override val locationAdapter = ExcludedLocationAdapter(this) - - @Inject override lateinit var musicSettings: MusicSettings - - override fun getDialogTitle(): Int = R.string.set_excluded_locations - - override fun getCurrentLocations(): List = musicSettings.excludedLocations - - override fun saveLocations(locations: List) { - musicSettings.excludedLocations = locations - } - - override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS - - override fun convertUriToLocation(uri: Uri): Location.Unopened? { - return Location.Unopened.from(requireContext(), uri) - } - - override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? { - return Location.Unopened.from(context, uri) - } - - private companion object { - const val KEY_PENDING_EXCLUDED_LOCATIONS = - BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 12614dcd3..3a6ebe679 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Auxio Project + * Copyright (c) 2021 Auxio Project * LocationAdapter.kt is part of Auxio. * * This program is free software: you can redistribute it and/or modify @@ -18,59 +18,106 @@ package org.oxycblt.auxio.music.locations +import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import org.oxycblt.auxio.databinding.ItemMusicLocationBinding import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.util.context -import org.oxycblt.musikr.fs.Location +import org.oxycblt.auxio.util.inflater +import org.oxycblt.musikr.fs.MusicLocation import timber.log.Timber as L -abstract class LocationAdapter(private val listener: Listener) : - RecyclerView.Adapter>() { - private val _locations = mutableListOf() - val locations: List = _locations +/** + * [RecyclerView.Adapter] that manages a list of [MusicLocation] music directory instances. + * + * @param listener A [LocationAdapter.Listener] to bind interactions to. + * @author Alexander Capehart (OxygenCobalt) + */ +class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { + private val _locations = mutableListOf() + /** + * The current list of [MusicLocation]s, may not line up with [MusicLocation]s due to removals. + */ + val locations: List = _locations override fun getItemCount() = locations.size - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent) + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = + MusicDirViewHolder.from(parent) - override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = + override fun onBindViewHolder(holder: MusicDirViewHolder, position: Int) = holder.bind(locations[position], listener) - fun add(location: T) { + /** + * Add a [MusicLocation] to the end of the list. + * + * @param location The [MusicLocation] to add. + */ + fun add(location: MusicLocation) { if (_locations.contains(location)) return L.d("Adding $location") _locations.add(location) notifyItemInserted(_locations.lastIndex) } - fun addAll(locations: List) { + /** + * Add a list of [MusicLocation] instances to the end of the list. + * + * @param locations The [MusicLocation] instances to add. + */ + fun addAll(locations: List) { L.d("Adding ${locations.size} locations") - val oldSize = _locations.size + val oldLastIndex = locations.lastIndex _locations.addAll(locations) - notifyItemRangeInserted(oldSize, locations.size) + notifyItemRangeInserted(oldLastIndex, locations.size) } - fun remove(location: T) { + /** + * Remove a [MusicLocation] from the list. + * + * @param location The [MusicLocation] to remove. Must exist in the list. + */ + fun remove(location: MusicLocation) { L.d("Removing $location") val idx = _locations.indexOf(location) _locations.removeAt(idx) notifyItemRemoved(idx) } - protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder - - interface Listener { - fun onRemoveLocation(location: T) + /** A Listener for [LocationAdapter] interactions. */ + interface Listener { + /** Called when the delete button on a directory item is clicked. */ + fun onRemoveLocation(location: MusicLocation) } } -abstract class LocationViewHolder(protected val binding: ItemMusicLocationBinding) : +/** + * A [RecyclerView.Recycler] that displays a [MusicLocation]. Use [from] to create an instance. + * + * @author Alexander Capehart (OxygenCobalt) + */ +class MusicDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : DialogRecyclerView.ViewHolder(binding.root) { - - fun bind(location: T, listener: LocationAdapter.Listener) { + /** + * Bind new data to this instance. + * + * @param location The new [MusicLocation] to bind. + * @param listener A [LocationAdapter.Listener] to bind interactions to. + */ + fun bind(location: MusicLocation, listener: LocationAdapter.Listener) { binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: View) = + MusicDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater)) + } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt deleted file mode 100644 index cf950f963..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * MusicLocationAdapter.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.view.ViewGroup -import org.oxycblt.auxio.databinding.ItemMusicLocationBinding -import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.Location - -/** - * [LocationAdapter] that manages a list of [Location.Opened] music directory instances. - * - * @param listener A [LocationAdapter.Listener] to bind interactions to. - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicLocationAdapter(listener: LocationAdapter.Listener) : - LocationAdapter(listener) { - override fun createViewHolder(parent: ViewGroup): LocationViewHolder = - MusicLocationViewHolder.from(parent) -} - -/** - * A [LocationViewHolder] that displays a [Location.Opened]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : - LocationViewHolder(binding) { - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: ViewGroup) = - MusicLocationViewHolder( - ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt deleted file mode 100644 index cca6e1778..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * MusicLocationsDialog.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.content.Context -import android.net.Uri -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig -import org.oxycblt.auxio.R -import org.oxycblt.auxio.music.MusicSettings -import org.oxycblt.musikr.fs.Location - -/** - * Dialog that manages the music locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class MusicLocationsDialog : LocationsDialog() { - override val locationAdapter = MusicLocationAdapter(this) - - @Inject override lateinit var musicSettings: MusicSettings - - override fun getDialogTitle(): Int = R.string.set_locations - - override fun getCurrentLocations(): List = musicSettings.musicLocations - - override fun saveLocations(locations: List) { - musicSettings.musicLocations = locations - } - - override fun getPendingLocationsKey(): String = KEY_PENDING_LOCATIONS - - override fun convertUriToLocation(uri: Uri): Location.Opened? { - val context = requireContext() - return Location.Unopened.from(context, uri)?.open(context) - } - - override fun createLocationFromUri(context: Context, uri: Uri): Location.Opened? { - return Location.Unopened.from(context, uri)?.open(context) - } - - private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt similarity index 69% rename from app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt rename to app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt index daeceb95f..88a4132d5 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2024 Auxio Project - * LocationsDialog.kt is part of Auxio. + * Copyright (c) 2021 Auxio Project + * MusicSourcesDialog.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 @@ -27,33 +27,42 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.net.toUri import androidx.recyclerview.widget.ConcatAdapter +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject +import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R 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.Location +import org.oxycblt.musikr.fs.MusicLocation import timber.log.Timber as L -abstract class LocationsDialog : +/** + * Dialog that manages the music locations setting. + * + * @author Alexander Capehart (OxygenCobalt) + */ +@AndroidEntryPoint +class MusicSourcesDialog : ViewBindingMaterialDialogFragment(), - LocationAdapter.Listener, + LocationAdapter.Listener, NewLocationFooterAdapter.Listener { - protected abstract val locationAdapter: LocationAdapter + private val locationAdapter = LocationAdapter(this) private val locationFooterAdapter = NewLocationFooterAdapter(this) private var openDocumentTreeLauncher: ActivityResultLauncher? = null - abstract val musicSettings: MusicSettings + @Inject lateinit var musicSettings: MusicSettings override fun onCreateBinding(inflater: LayoutInflater) = DialogMusicLocationsBinding.inflate(inflater) override fun onConfigDialog(builder: AlertDialog.Builder) { builder - .setTitle(getDialogTitle()) + .setTitle(R.string.set_locations) .setNegativeButton(R.string.lbl_cancel, null) .setPositiveButton(R.string.lbl_save) { _, _ -> val newDirs = locationAdapter.locations - saveLocations(newDirs) + musicSettings.musicLocations = newDirs } } @@ -71,9 +80,9 @@ abstract class LocationsDialog : } val locations = - savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull { - convertUriToLocation(it.toUri()) - } ?: getCurrentLocations() + savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { + MusicLocation.existing(requireContext(), it.toUri()) + } ?: musicSettings.musicLocations locationAdapter.addAll(locations) } @@ -81,8 +90,7 @@ abstract class LocationsDialog : override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList( - getPendingLocationsKey(), - ArrayList(locationAdapter.locations.map { it.uri.toString() })) + KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { @@ -91,6 +99,10 @@ abstract class LocationsDialog : binding.locationsRecycler.adapter = null } + override fun onRemoveLocation(location: MusicLocation) { + locationAdapter.remove(location) + } + override fun onNewLocation() { L.d("Opening launcher") val launcher = @@ -99,17 +111,24 @@ abstract class LocationsDialog : try { launcher.launch(null) } catch (e: ActivityNotFoundException) { + // User doesn't have a capable file manager. requireContext().showToast(R.string.err_no_app) } } + /** + * Add a Document Tree [Uri] chosen by the user to the current [MusicLocation]s. + * + * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] + * is null or not valid. + */ private fun addDocumentTreeUriToDirs(uri: Uri?) { if (uri == null) { + // A null URI means that the user left the file picker without picking a locationectory L.d("No URI given (user closed the dialog)") return } - val context = requireContext() - val location = createLocationFromUri(context, uri) + val location = MusicLocation.new(requireContext(), uri) if (location != null) { locationAdapter.add(location) @@ -118,19 +137,7 @@ abstract class LocationsDialog : } } - override fun onRemoveLocation(location: T) { - locationAdapter.remove(location) + private companion object { + const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" } - - protected abstract fun getDialogTitle(): Int - - protected abstract fun getCurrentLocations(): List - - protected abstract fun saveLocations(locations: List) - - protected abstract fun getPendingLocationsKey(): String - - protected abstract fun convertUriToLocation(uri: Uri): T? - - protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? } diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt index 7788e10e8..638d05039 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt @@ -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.Location +import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.track.UpdateTracker import timber.log.Timber as L @@ -168,7 +168,7 @@ private constructor( } } - override fun onUpdate(location: Location.Opened) { + override fun onUpdate(location: MusicLocation) { if (musicSettings.shouldBeObserving) { musicRepository.requestIndex(true) } diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt deleted file mode 100644 index f4659cdcb..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyFileTreeCache.kt +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2025 Auxio Project - * WriteOnlyFileTreeCache.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.shim - -import android.net.Uri -import org.oxycblt.musikr.fs.device.CachedDirectory -import org.oxycblt.musikr.fs.device.CachedFile -import org.oxycblt.musikr.fs.device.FileTree -import org.oxycblt.musikr.fs.device.FileTreeCache - -class WriteOnlyFileTreeCache(private val inner: FileTreeCache) : FileTreeCache { - override fun read(): FileTree { - val innerTree = inner.read() - return WriteOnlyFileTree(innerTree) - } -} - -class WriteOnlyFileTree(private val innerTree: FileTree) : FileTree { - override suspend fun queryDirectory(uri: Uri): CachedDirectory? { - // Always return null to simulate a cache miss - return null - } - - override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { - // Forward update operations to the inner tree - innerTree.updateDirectory(uri, directory) - } - - override suspend fun queryFile(uri: Uri): CachedFile? { - // Always return null to simulate a cache miss - return null - } - - override suspend fun updateFile(uri: Uri, file: CachedFile) { - // Forward update operations to the inner tree - innerTree.updateFile(uri, file) - } - - override suspend fun write() { - // Forward write operations to the inner tree - innerTree.write() - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt index 791ba5b53..39a523c0c 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt @@ -51,15 +51,9 @@ class RootPreferenceFragment : BasePreferenceFragment(R.xml.preferences_root) { } override fun onOpenDialogPreference(preference: WrappedDialogPreference) { - when (preference.key) { - getString(R.string.set_key_music_dirs) -> { - findNavController() - .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) - } - getString(R.string.set_key_excluded_dirs) -> { - findNavController() - .navigateSafe(RootPreferenceFragmentDirections.excludedLocationsSettings()) - } + if (preference.key == getString(R.string.set_key_music_dirs)) { + findNavController() + .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) } } diff --git a/app/src/main/res/layout/dialog_music_locations.xml b/app/src/main/res/layout/dialog_music_locations.xml index 10035eec0..8f015dec3 100644 --- a/app/src/main/res/layout/dialog_music_locations.xml +++ b/app/src/main/res/layout/dialog_music_locations.xml @@ -16,5 +16,4 @@ app:layout_constraintTop_toBottomOf="@+id/locations_list_header" tools:listitem="@layout/item_music_location" /> - - + \ No newline at end of file diff --git a/app/src/main/res/navigation/inner.xml b/app/src/main/res/navigation/inner.xml index 61fcfd3a5..aa10ee2f9 100644 --- a/app/src/main/res/navigation/inner.xml +++ b/app/src/main/res/navigation/inner.xml @@ -570,7 +570,7 @@ \ No newline at end of file diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 60d81d6b2..0d15cbc8a 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -36,9 +36,6 @@ - - auxio_rescan auxio_observing auxio_music_dirs - auxio_excluded_dirs auxio_cover_mode2 auxio_square_covers auxio_exclude_non_music auxio_with_hidden auxio_music_locations2 - auxio_excluded_locations auxio_separators auxio_auto_sort_names diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 26d456242..0b5830db5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -315,8 +315,6 @@ Music folders Manage where music should be loaded from New folder - Excluded folders - Manage folders to exclude from music loading Refresh music Reload the music library, using cached tags when possible diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 12f8fb94b..5c004cb4c 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -33,11 +33,6 @@ app:summary="@string/set_locations_desc" app:title="@string/set_locations" /> - - B[Explore Step] - B --> C[Extract Step] - C --> D[Evaluate Step] - D --> E[Library] - - subgraph Pipeline - B - C - D - end -``` - -### Key Interfaces - -- **Musikr** - Main entry point for the library -- **Storage** - Manages persistent storage needs -- **Library** - Represents the loaded music collection -- **MutableLibrary** - Modifiable version of the library - -## Module Structure - -### 1. File System (`fs` package) -- **Location.Opened** - Represents a location to search for music -- **DeviceFS** - Provides access to device storage -- **FileTreeCache** - Caches filesystem structure for faster indexing - -### 2. Pipeline (`pipeline` package) -- **ExploreStep** - Discovers music files on the device -- **ExtractStep** - Extracts metadata from discovered files -- **EvaluateStep** - Processes extracted data to build the library -- **PipelineItem** - Data items flowing through the pipeline - -### 3. Metadata (`metadata` package) -- **Metadata** - Extracted file metadata -- **MetadataExtractor** - Extracts metadata using TagLib -- **TagLibJNI** - JNI bridge to native TagLib library - -### 4. Tag Processing (`tag` package) -- **TagParser** - Parses raw tag data into structured format -- **TagInterpreter** - Interprets tags based on user preferences -- **ParsedTags** - Represents parsed metadata tags - -### 5. Model (`model` package) -- **LibraryImpl** - Implementation of the music library -- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations -- **LibraryFactory** - Creates library instances from pipeline data - -### 6. Covers (`covers` package) -- **Covers** - Interface for album cover management -- **EmbeddedCovers** - Extracts covers embedded in music files -- **FSCovers** - Discovers cover art in the filesystem -- **StoredCovers** - Manages persistent storage of covers - -### 7. Cache (`cache` package) -- **Cache** - Caches processed music data -- **DBCache** - Database implementation of caching - -### 8. Playlist (`playlist` package) -- **PlaylistFile** - Represents a playlist file -- **ExternalPlaylistManager** - Manages external playlist files -- **PlaylistInterpreter** - Interprets playlist formats - -## Native Component - -Musikr includes a native component built with TagLib for fast and accurate metadata extraction: - -```mermaid -graph TD - A[TagLibJNI] --> B[JNI Bridge] - B --> C[TagLib Library] - C --> D[Music File Metadata] -``` - -### Native Files (`cpp` directory) -- **taglib_jni.cpp** - Main JNI implementation -- **JMetadataBuilder** - Builds metadata objects from TagLib -- **JTagMap** - Maps between Java and C++ tag structures -- **JInputStream** - Input stream adapter for TagLib - -## Data Flow - -```mermaid -sequenceDiagram - participant User - participant Musikr - participant ExploreStep - participant ExtractStep - participant EvaluateStep - participant Storage - - User->>Musikr: run(locations) - Musikr->>ExploreStep: explore(locations) - ExploreStep->>Storage: Read cache - ExploreStep-->>Musikr: Explored files - Musikr->>ExtractStep: extract(explored) - ExtractStep->>TagLibJNI: Extract metadata - ExtractStep-->>Musikr: Extracted metadata - Musikr->>EvaluateStep: evaluate(extracted) - EvaluateStep->>Storage: Store processed data - EvaluateStep-->>Musikr: Library - Musikr-->>User: LibraryResult -``` - -## Threading Model - -Musikr uses Kotlin Coroutines for concurrent processing: - -- Pipeline stages use `flatMapMerge` and `distributedMap` for parallel processing -- Bounded buffer channels manage backpressure -- IO operations are dispatched to `Dispatchers.IO` - -## Best Practices for Extension - -1. The API is minimized and unstable - be prepared to fork and modify -2. No defaults are provided - carefully consider parameter choices -3. Musikr is stateless except for Storage - manage long-term state yourself -4. When adding functionality, follow the pipeline architecture pattern \ No newline at end of file diff --git a/musikr/build.gradle b/musikr/build.gradle index 31d256899..9e819dcff 100644 --- a/musikr/build.gradle +++ b/musikr/build.gradle @@ -4,7 +4,6 @@ plugins { id 'com.android.library' id 'org.jetbrains.kotlin.android' id "com.google.devtools.ksp" - id "org.jetbrains.kotlin.plugin.serialization" id "com.diffplug.spotless" id "kotlin-parcelize" id "org.jetbrains.dokka" @@ -63,8 +62,6 @@ dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version" - implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0' - // AndroidX implementation "androidx.core:core-ktx:$core_version" diff --git a/musikr/src/main/cpp/README.md b/musikr/src/main/cpp/README.md deleted file mode 100644 index dc42457b8..000000000 --- a/musikr/src/main/cpp/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Native Code (C++) Component - -## Overview - -This directory contains the native C++ code that bridges between Java and TagLib. It enables fast and accurate metadata extraction from music files. - -## Key Components - -### JNI Implementation - -**taglib_jni.cpp** -- Main JNI implementation -- Registers native methods -- Handles JNI environment setup - -**JMetadataBuilder** -- Builds metadata objects from TagLib -- Extracts tags and properties -- Maps between TagLib and Java structures - -**JTagMap** -- Maps between Java and C++ tag structures -- Provides bidirectional conversion - -**JInputStream** -- Input stream adapter for TagLib -- Bridges between Java I/O and TagLib I/O - -### Utility Classes - -**JStringRef** -- Manages JNI string references -- Handles UTF conversions - -**JByteArrayRef** -- Manages JNI byte array references -- Provides safe access to Java byte arrays - -**JObjectRef** -- Manages JNI object references -- Provides RAII-style resource management - -**JClassRef** -- Manages JNI class references -- Caches class and method lookups - -**util.h** -- Utility functions for JNI -- Error handling and logging - -### Build Configuration - -**CMakeLists.txt** -- CMake build configuration -- Configures TagLib integration - -**build_taglib.sh** -- Script to build TagLib from source -- Configures platform-specific options - -**android.toolchain.cmake** -- Android-specific CMake toolchain - -## TagLib Integration - -TagLib is included as a subproject and built from source. The `taglib` directory contains the TagLib source code, which is a powerful and feature-rich library for reading and writing audio metadata. - -## Build Process - -1. The build starts with `build_taglib.sh` -2. TagLib is configured and built with CMake -3. The JNI wrapper is built against TagLib -4. The resulting library is packaged into the AAR - -## JNI Interface - -The native methods are exposed through `TagLibJNI.kt` in the Java code. The main functionalities include: - -- Reading metadata from audio files -- Extracting embedded cover art -- Accessing audio properties (bitrate, sample rate, etc.) - -## Extension Points - -When extending the native code: - -1. For new tag formats, update the TagLib integration -2. For new metadata fields, add them to JMetadataBuilder -3. For performance improvements, optimize the JNI bridge -4. For platform-specific optimizations, update the build configuration \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index 6e843a170..df7c5cf07 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -21,15 +21,10 @@ 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.Location.Opened -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, val exclude: List) - /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( /** @@ -50,10 +45,7 @@ data class Storage( * be used during music loading and mutated when creating, renaming, or deleting playlists in * the library. */ - val storedPlaylists: StoredPlaylists, - - /** A cache for file tree information to optimize file system exploration. */ - val fileTreeCache: FileTreeCache + val storedPlaylists: StoredPlaylists ) /** Configuration for how to interpret and extrapolate certain audio tags. */ diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 8c56bbc69..27b84f1f2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -19,13 +19,13 @@ package org.oxycblt.musikr import android.content.Context -import android.util.Log import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.coroutineScope 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 @@ -47,13 +47,13 @@ interface Musikr { /** * Start loading music from the given [locations] and the configuration provided earlier. * - * @param query The [Query] to load music from. + * @param locations The [MusicLocation]s to search for music in. * @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( - query: Query, + locations: List, onProgress: suspend (IndexingProgress) -> Unit = {} ): LibraryResult @@ -70,7 +70,6 @@ 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 +96,7 @@ sealed interface IndexingProgress { /** * Currently indexing and extracting tags from device music. * - * @param explored The amount of music currently found from the given [Query]. + * @param explored The amount of music currently found from the given [MusicLocation]s. * @param loaded The amount of music that has had metadata extracted and parsed. */ data class Songs(val loaded: Int, val explored: Int) : IndexingProgress @@ -111,35 +110,32 @@ 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(query: Query, onProgress: suspend (IndexingProgress) -> Unit) = - coroutineScope { - val start = System.currentTimeMillis() - var exploredCount = 0 - var extractedCount = 0 - val explored = - exploreStep - .explore(query) - .buffer(Channel.UNLIMITED) - .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } - val extracted = - extractStep - .extract(explored) - .buffer(Channel.UNLIMITED) - .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } - .onCompletion { onProgress(IndexingProgress.Indeterminate) } - val library = evaluateStep.evaluate(extracted) - Log.d( - "Musikr", - "Loaded ${library.songs.size} songs in ${System.currentTimeMillis() - start}ms") - LibraryResultImpl(storage, library) - } + override suspend fun run( + locations: List, + onProgress: suspend (IndexingProgress) -> Unit + ) = coroutineScope { + var exploredCount = 0 + var extractedCount = 0 + val explored = + exploreStep + .explore(locations) + .buffer(Channel.UNLIMITED) + .onStart { onProgress(IndexingProgress.Songs(0, 0)) } + .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } + val extracted = + extractStep + .extract(explored) + .buffer(Channel.UNLIMITED) + .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } + .onCompletion { onProgress(IndexingProgress.Indeterminate) } + val library = evaluateStep.evaluate(extracted) + LibraryResultImpl(storage, library) + } } private class LibraryResultImpl( diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt index c760de2a2..9386322e4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/CacheDatabase.kt @@ -55,8 +55,6 @@ internal abstract class CacheDatabase : RoomDatabase() { internal interface CacheReadDao { @Query("SELECT * FROM CachedSongData WHERE uri = :uri") suspend fun selectSong(uri: String): CachedSongData? - - @Query("SELECT * FROM CachedSongData") suspend fun selectAllSongs(): List } @Dao diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt index 572f6bdd3..6835dd40b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt @@ -19,8 +19,6 @@ package org.oxycblt.musikr.cache.db import android.content.Context -import android.net.Uri -import kotlinx.coroutines.sync.Mutex import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CachedSong @@ -35,20 +33,8 @@ import org.oxycblt.musikr.tag.parse.ParsedTags * Create an instance with [from]. */ class DBCache private constructor(private val readDao: CacheReadDao) : Cache { - @Volatile private var mapping: MutableMap? = null - private var mappingLock = Mutex() - override suspend fun read(file: DeviceFile): CacheResult { - mappingLock.lock() - val mapping = - this.mapping - ?: readDao - .selectAllSongs() - .associateBy { it.uri } - .toMutableMap() - .also { mapping = it } - mappingLock.unlock() - val dbSong = mapping[file.uri] ?: return CacheResult.Miss(file) + val dbSong = readDao.selectSong(file.uri.toString()) ?: return CacheResult.Miss(file) if (dbSong.modifiedMs != file.modifiedMs) { return CacheResult.Stale(file, dbSong.addedMs) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/README.md b/musikr/src/main/java/org/oxycblt/musikr/covers/README.md deleted file mode 100644 index b33e3b209..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Covers Package - -## Overview - -The covers package provides functionality for discovering, extracting, and managing album cover art. It handles embedded covers in music files, external cover images, and persistent storage. - -## Key Components - -### Core Interfaces - -**Covers** (`Covers.kt`) -- Generic interface for cover art management -- Provides methods to obtain and manage covers - -**Cover** (`Covers.kt`) -- Represents a cover image -- Contains cover metadata and access methods - -### Cover Sources - -**EmbeddedCovers** (`embedded/EmbeddedCovers.kt`) -- Extracts covers embedded in music files -- Uses metadata extraction to access embedded images - -**FSCovers** (`fs/FSCovers.kt`) -- Discovers cover art in the filesystem -- Searches for common cover image filenames - -**ChainedCovers** (`chained/ChainedCovers.kt`) -- Combines multiple cover sources -- Provides fallback mechanisms - -### Storage - -**StoredCovers** (`stored/StoredCovers.kt`) -- Manages persistent storage of covers -- Handles caching and retrieval - -**CoverStorage** (`stored/CoverStorage.kt`) -- Low-level cover storage operations -- Manages the cover storage directory - -**Transcoding** (`stored/Transcoding.kt`) -- Handles image format conversion -- Optimizes covers for storage and display - -### Identification - -**CoverIdentifier** (`embedded/CoverIdentifier.kt`) -- Generates unique identifiers for covers -- Used for caching and referencing - -## Cover Flow - -1. During music indexing, covers are extracted or discovered -2. Covers are identified and stored -3. Songs reference covers by identifier -4. When needed, covers are retrieved from storage - -## Key Features - -- **Multiple sources** - Embedded, filesystem, and custom sources -- **Efficient storage** - Avoids duplicates through identification -- **Format optimization** - Transcodes images for optimal storage -- **Lazy loading** - Loads covers only when needed - -## Extension Points - -When extending the cover functionality: - -1. For new cover sources, implement the Covers interface -2. For custom storage, extend or replace StoredCovers -3. For format-specific handling, update the Transcoding class -4. For performance improvements, optimize the identification and storage mechanisms \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 480a58d08..96f969fad 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -25,9 +25,6 @@ import android.os.ParcelFileDescriptor import androidx.core.net.toUri import java.io.InputStream import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.flow.filterIsInstance -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.toList import kotlinx.coroutines.withContext import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult @@ -99,12 +96,11 @@ class MutableFSCovers(private val context: Context) : MutableCovers { override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { // Since DeviceFiles is a streaming API, we have to wait for the current recursive // query to finally finish to be able to have a complete list of siblings to search for. - val parent = file.parent + val parent = file.parent.await() val bestCover = parent.children .filterIsInstance() .map { it to coverArtScore(it) } - .toList() .maxBy { it.second } if (bestCover.second > 0) { return CoverResult.Hit(FolderCoverImpl(context, bestCover.first.uri)) @@ -132,7 +128,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers { // See if the name contains any of the preferred cover names. This helps weed out // images that are not actually cover art and are just there., var score = - (preferredCoverNames + requireNotNull(file.parent.path.name)) + (preferredCoverNames + requireNotNull(file.parent.await().path.name)) .withIndex() .filter { name.contains(it.value, ignoreCase = true) } .sumOf { it.index + 1 } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt deleted file mode 100644 index e27cbb9b9..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * 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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.musikr.fs - -import android.content.Context -import android.content.Intent -import android.net.Uri -import android.provider.DocumentsContract -import org.oxycblt.musikr.fs.device.contentResolverSafe -import org.oxycblt.musikr.fs.path.DocumentPathFactory - -sealed class Location(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() - - class Unopened private constructor(uri: Uri, path: Path) : Location(uri, path) { - fun open(context: Context): Opened? { - if (isUnopened(context, uri)) { - try { - context.contentResolverSafe.takePersistableUriPermission( - uri, - 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 - } - - if (isUnopened(context, uri)) { - return null - } - } - return Opened(uri, path) - } - - private fun isUnopened(context: Context, uri: Uri) = - context.contentResolverSafe.persistedUriPermissions.none { - it.uri == uri && it.isReadPermission && it.isWritePermission - } - - companion object { - fun from(context: Context, uri: Uri): Unopened? { - if (!DocumentsContract.isTreeUri(uri)) return null - val documentPathFactory = DocumentPathFactory.from(context) - val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return Unopened(uri, path) - } - } - } - - class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) { - override fun equals(other: Any?) = other is Opened && uri == other.uri && path == other.path - - override fun hashCode() = 31 * uri.hashCode() + path.hashCode() - } -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt new file mode 100644 index 000000000..636d16c61 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2024 Auxio Project + * MusicLocation.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.musikr.fs + +import android.content.Context +import android.content.Intent +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 + + 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) { + context.contentResolverSafe.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + } + return MusicLocation(uri, path) + } + + fun existing(context: Context, uri: Uri): MusicLocation? { + val documentPathFactory = DocumentPathFactory.from(context) + if (!DocumentsContract.isTreeUri(uri)) return null + val notPersisted = + context.contentResolverSafe.persistedUriPermissions.none { + it.uri == uri && it.isReadPermission && it.isWritePermission + } + if (notPersisted) return null + val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null + return MusicLocation(uri, path) + } + + fun toString(list: List) = + list.joinToString(";") { it.uri.toString().replace(";", "\\;") } + + fun existing(context: Context, string: String): List { + return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) } + } + } +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md b/musikr/src/main/java/org/oxycblt/musikr/fs/README.md deleted file mode 100644 index 6e0579566..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# Filesystem Package - -## Overview - -The filesystem package provides abstraction layers for accessing music files on Android devices. It handles the complexities of the Storage Access Framework (SAF) and provides efficient caching mechanisms. - -## Key Components - -### Core Types - -**Location.Opened** (`Location.Opened.kt`) -- Represents a location to search for music -- Can be a device storage location or content URI - -**Path** (`Path.kt`) -- Abstract representation of a file path -- Handles both traditional file paths and content URIs - -**Format** (`Format.kt`) -- Represents file formats and their properties -- Maps MIME types to file extensions - -### Device Access - -**DeviceFS** (`DeviceFS.kt`) -- Provides access to device storage -- Handles SAF permissions and access -- Performs filesystem traversal - -**DeviceFSEntries** (`DeviceFSEntries.kt`) -- Represents filesystem entries (files and directories) -- Provides metadata about filesystem items - -**DeviceFile** (in `DeviceFSEntries.kt`) -- Represents a music file on the device -- Contains file metadata needed for processing - -### Caching - -**FileTreeCache** (`FileTreeCache.kt`) -- Caches filesystem structure for faster indexing -- Provides incremental updates to avoid full rescans - -### Path Interpretation - -**Path Package** (`path/` directory) -- **DocumentPathFactory** - Creates paths from document URIs -- **MediaStorePathInterpreter** - Interprets MediaStore paths -- **VolumeManager** - Manages storage volumes - -## Usage Flow - -1. User provides `Location.Opened`s to scan -2. `DeviceFS` traverses these locations -3. `FileTreeCache` optimizes subsequent scans -4. Discovered files are passed to the pipeline for processing - -## Key Features - -- **Storage Access Framework** integration for modern Android storage access -- **Incremental scanning** to minimize resource usage -- **Path abstraction** to handle different Android storage mechanisms -- **Volume mapping** to resolve relative paths - -## Extension Points - -When extending the filesystem functionality: - -1. For new storage types, implement appropriate Path implementations -2. For performance improvements, consider optimizing the FileTreeCache -3. For new file formats, update the Format class -4. For custom traversal strategies, extend DeviceFS \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 55e36ecce..a6831cc71 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -22,33 +22,20 @@ import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract -import android.util.Log -import androidx.core.net.toUri -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow -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.flatMapMerge +import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow -import kotlinx.coroutines.flow.flowOn -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 kotlinx.coroutines.flow.transform -import org.oxycblt.musikr.Query -import org.oxycblt.musikr.fs.Location -import org.oxycblt.musikr.fs.Location.Opened +import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path internal interface DeviceFS { - fun explore(query: Query, fileTree: FileTree): Flow + fun explore(locations: Flow): Flow companion object { fun from(context: Context, withHidden: Boolean): DeviceFS = @@ -56,246 +43,80 @@ internal interface DeviceFS { } } +@OptIn(ExperimentalCoroutinesApi::class) private class DeviceFSImpl( private val contentResolver: ContentResolver, private val withHidden: Boolean ) : DeviceFS { - private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) - - override fun explore(query: Query, fileTree: FileTree) = - query.source.asFlow().mapNotNull { location -> - queryRoot(location, fileTree, query.exclude) + override fun explore(locations: Flow): Flow = + locations.flatMapMerge { location -> + exploreDirectoryImpl( + location.uri, + DocumentsContract.getTreeDocumentId(location.uri), + location.path, + null) } - private suspend fun queryRoot( - location: Location.Opened, - fileTree: FileTree, - exclude: List - ): 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, exclude) - } - - private suspend fun query( + private fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, - path: Path, - modifiedMs: Long, - parent: DeviceDirectory?, - fileTree: FileTree, - exclude: List - ): 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, exclude) + relativePath: Path, + parent: Deferred? + ): Flow = flow { + // Make a kotlin future + val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) + val directoryDeferred = CompletableDeferred() + val recursive = mutableListOf>() + val children = mutableListOf() + contentResolver.useQuery(uri, PROJECTION) { 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) + + 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 + } + + val newPath = relativePath.file(displayName) + val mimeType = cursor.getString(mimeTypeIndex) + val lastModified = cursor.getLong(lastModifiedIndex) + + if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { + recursive.add( + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + } else { + 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 = directoryDeferred) + children.add(file) + emit(file) + } + } + directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) + emitAll(recursive.asFlow().flattenMerge()) } - 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() - val childFileUris = mutableListOf() - - val subqueries = mutableListOf() - - 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 - } - - val newPath = path.file(displayName) - val mimeType = cursor.getString(mimeTypeIndex) - 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, - treeDocumentId = childId, - path = newPath, - modifiedMs = modifiedMs, - parent = dir, - fileTree = fileTree, - exclude = exclude) - 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) - } - } - .shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE) - .takeWhile { it is StreamedFile.More } - .map { (it as StreamedFile.More).value } - dir - } - - private suspend fun hydrateCached( - cached: CachedDirectory, - parentDir: DeviceDirectory?, - path: Path, - fileTree: FileTree, - exclude: List - ): 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() - .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 - } - - emit( - hydrateCached( - cachedSubdir, dir, subdirPath, fileTree, exclude)) - } - .filterNotNull(), - 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 } private companion object { - private val PROJECTION = + val PROJECTION = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, @@ -304,11 +125,3 @@ private class DeviceFSImpl( DocumentsContract.Document.COLUMN_LAST_MODIFIED) } } - -private class DeviceDirectoryImpl( - override val uri: Uri, - override val path: Path, - override val modifiedMs: Long, - override val parent: DeviceDirectory?, - override var children: Flow, -) : DeviceDirectory diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt index 0938fbab3..dc43e8dab 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt @@ -19,35 +19,26 @@ package org.oxycblt.musikr.fs.device import android.net.Uri -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.emitAll -import kotlinx.coroutines.flow.transform +import kotlinx.coroutines.Deferred import org.oxycblt.musikr.fs.Path sealed interface DeviceFSEntry { val uri: Uri val path: Path - val modifiedMs: Long } -interface DeviceDirectory : DeviceFSEntry { - val parent: DeviceDirectory? - val children: Flow -} +data class DeviceDirectory( + override val uri: Uri, + override val path: Path, + val parent: Deferred?, + var children: List +) : DeviceFSEntry data class DeviceFile( override val uri: Uri, override val path: Path, - override val modifiedMs: Long, + val modifiedMs: Long, val mimeType: String, val size: Long, - val parent: DeviceDirectory + val parent: Deferred ) : DeviceFSEntry - -fun DeviceDirectory.flatten(): Flow = - children.transform { - when (it) { - is DeviceDirectory -> emitAll(it.flatten()) - is DeviceFile -> emit(it) - } - } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt deleted file mode 100644 index e8d71bbd1..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/FileTreeCache.kt +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * FileTreeCache.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -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.decodeFromString -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json - -interface FileTreeCache { - fun read(): FileTree - - companion object { - fun from(context: Context): FileTreeCache = FileTreeCacheImpl(context) - } -} - -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() -} - -// Define the sealed interface -@Serializable -private sealed interface FileSystemEntry { - val uri: String - val modifiedMs: Long -} - -@Serializable -data class CachedDirectory( - override val uri: String, - val name: String, - override val modifiedMs: Long, - val subdirUris: List, - val fileUris: List -) : FileSystemEntry - -@Serializable -data class CachedFile( - override val uri: String, - val name: String, - override val modifiedMs: Long, - val mimeType: String, - val size: Long -) : FileSystemEntry - -@Serializable -private data class FileTreeData( - val directories: Map = mapOf(), - val files: Map = mapOf() -) - -private class FileTreeCacheImpl(private val context: Context) : FileTreeCache { - companion object { - 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(jsonContent) - FileTreeImpl( - context, - fileTreeCache.directories.toMutableMap(), - fileTreeCache.files.toMutableMap()) - } catch (e: Exception) { - FileTreeImpl(context, mutableMapOf(), mutableMapOf()) - } - } else { - FileTreeImpl(context, mutableMapOf(), mutableMapOf()) - } - } -} - -private class FileTreeImpl( - private val context: Context, - private val mutableDirectories: MutableMap = mutableMapOf(), - private val mutableFiles: MutableMap = 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? { - val uriString = uri.toString() - return mutableDirectories[uriString] - } - - override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) { - val uriString = uri.toString() - mutableDirectories[uriString] = directory - } - - // File operations - override suspend fun queryFile(uri: Uri): CachedFile? { - val uriString = uri.toString() - return mutableFiles[uriString] - } - - override suspend fun updateFile(uri: Uri, file: CachedFile) { - 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 - } -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt index a2dfbc041..a305108d6 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt @@ -46,12 +46,8 @@ internal fun ContentResolver.safeQuery( uri: Uri, projection: Array, selector: String? = null, - args: Array? = null, - sortOrder: String? = null -) = - requireNotNull(query(uri, projection, selector, args, sortOrder)) { - "ContentResolver query failed" - } + args: Array? = null +) = requireNotNull(query(uri, projection, selector, args, null)) { "ContentResolver query failed" } /** * A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources @@ -72,6 +68,5 @@ internal inline fun ContentResolver.useQuery( projection: Array, selector: String? = null, args: Array? = null, - sortOrder: String? = null, block: (Cursor) -> R -) = safeQuery(uri, projection, selector, args, sortOrder).use(block) +) = safeQuery(uri, projection, selector, args).use(block) diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md b/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md deleted file mode 100644 index f52216dd9..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Metadata Package - -## Overview - -The metadata package provides the native bridge to TagLib and handles extraction of metadata from music files. This is a critical component that enables accurate and comprehensive tag parsing. - -## Key Components - -### JNI Interface - -**TagLibJNI** (`TagLibJNI.kt`) -- Loads the native library -- Provides JNI methods for interacting with TagLib -- Handles native memory management - -**NativeTagMap** (`NativeTagMap.kt`) -- Maps between native C++ and Java tag structures -- Provides type conversion utilities - -**NativeInputStream** (`NativeInputStream.kt`) -- Provides a stream interface for TagLib to read file data -- Bridges between Java I/O and native code - -### Metadata Extraction - -**MetadataExtractor** (`MetadataExtractor.kt`) -- Extracts metadata from music files using TagLib -- Handles error cases and format-specific extractions -- Manages native resource lifecycle - -**Metadata** (`Metadata.kt`) -- Container for extracted audio metadata -- Includes both tags and audio properties - -**Properties** (part of `Metadata.kt`) -- Audio-specific properties like duration, sample rate, etc. -- Format-specific information - -## Native Implementation - -The C++ side of the metadata extraction is implemented in the `cpp` directory: - -- **taglib_jni.cpp** - Main JNI implementation -- **JMetadataBuilder** - Builds metadata objects from TagLib -- **JTagMap** - Maps between Java and C++ tag structures -- **JInputStream** - Input stream adapter for TagLib - -## Usage Flow - -1. File is discovered in the exploration step -2. MetadataExtractor is called with the file -3. NativeInputStream provides file access to TagLib -4. TagLib parses the file's metadata -5. JMetadataBuilder converts TagLib structures to Java objects -6. Metadata object is returned to the pipeline - -## Extension Points - -When extending the metadata functionality: - -1. For new tag formats, extend the native JNI code in `taglib_jni.cpp` -2. For new metadata fields, add them to both Java and native interfaces -3. For performance improvements, consider caching strategies in MetadataExtractor -4. Always ensure proper resource management with native code \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/model/README.md b/musikr/src/main/java/org/oxycblt/musikr/model/README.md deleted file mode 100644 index 8170ad252..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/model/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Model Package - -## Overview - -The model package implements the core music entity model for Musikr. It provides the structures that represent songs, albums, artists, genres, and playlists, as well as their relationships. - -## Key Components - -### Core Interfaces - -These interfaces are defined in the parent package (`org.oxycblt.musikr`) and implemented in the model package: - -- **Library** - Read-only representation of the music library -- **MutableLibrary** - Modifiable version of the library -- **Song** - Represents a music track -- **Album** - Represents an album -- **Artist** - Represents an artist -- **Genre** - Represents a music genre -- **Playlist** - Represents a playlist - -### Implementations - -**LibraryImpl** (`LibraryImpl.kt`) -- Implementation of the Library and MutableLibrary interfaces -- Manages collections of songs, albums, artists, genres, and playlists -- Provides search and lookup functionality - -**SongImpl** (`SongImpl.kt`) -- Implementation of the Song interface -- Contains metadata, file information, and relationships - -**AlbumImpl** (`AlbumImpl.kt`) -- Implementation of the Album interface -- Contains songs, artists, and album metadata - -**ArtistImpl** (`ArtistImpl.kt`) -- Implementation of the Artist interface -- Contains songs, albums, and artist metadata - -**GenreImpl** (`GenreImpl.kt`) -- Implementation of the Genre interface -- Contains songs and genre metadata - -**PlaylistImpl** (`PlaylistImpl.kt`) -- Implementation of the Playlist interface -- Contains ordered songs and playlist metadata - -### Factory - -**LibraryFactory** (`LibraryFactory.kt`) -- Creates library instances from pipeline data -- Builds the entity relationships -- Resolves duplicates and conflicts - -## Entity Relationships - -The music model implements a graph structure with these relationships: - -- Songs belong to albums, artists, and genres -- Albums belong to artists -- Artists have songs and albums -- Genres have songs -- Playlists have songs - -## Key Features - -- **Identity resolution** - Properly identifies and merges duplicate entities -- **Relationship building** - Creates the connections between entities -- **Immutable interfaces** - Provides read-only access for safety -- **Mutable implementation** - Allows controlled modifications - -## Extension Points - -When extending the model: - -1. For new entity types, create new interfaces and implementations -2. For new relationships, update the appropriate entities and LibraryFactory -3. For performance improvements, consider optimizing the graph structure -4. For custom sorting or grouping, extend the LibraryImpl functionality \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 9707ed14b..675fd6db9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -20,21 +20,17 @@ package org.oxycblt.musikr.pipeline import android.content.Context import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.flatMapMerge 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.Query import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult @@ -42,22 +38,20 @@ 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.device.DeviceFS -import org.oxycblt.musikr.fs.device.FileTreeCache -import org.oxycblt.musikr.fs.device.flatten import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U internal interface ExploreStep { - fun explore(query: Query): Flow + fun explore(locations: List): Flow companion object { fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep = ExploreStepImpl( - DeviceFS.from(context = context, withHidden = interpretation.withHidden), + DeviceFS.from(context, interpretation.withHidden), storage.cache, storage.covers, - storage.fileTreeCache, storage.storedPlaylists) } } @@ -66,18 +60,15 @@ private class ExploreStepImpl( private val deviceFS: DeviceFS, private val cache: Cache, private val covers: Covers, - private val fileTreeCache: FileTreeCache, private val storedPlaylists: StoredPlaylists ) : ExploreStep { - @OptIn(ExperimentalCoroutinesApi::class) - override fun explore(query: Query): Flow { + override fun explore(locations: List): Flow { val addingMs = System.currentTimeMillis() - val fileTree = fileTreeCache.read() return merge( deviceFS - .explore(query, fileTree) - .flatMapMerge { it.flatten() } - .onCompletion { fileTree.write() } + .explore( + locations.asFlow(), + ) .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)) { diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md b/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md deleted file mode 100644 index a03fa61f2..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Pipeline Package - -## Overview - -The pipeline package implements a three-stage processing pipeline for music indexing in Musikr. It provides a concurrent, efficient way to discover, extract metadata from, and process music files. - -## Key Components - -### Pipeline Steps - -1. **ExploreStep** (`ExploreStep.kt`) - - Discovers music files on the device - - Interfaces with filesystem caches - - Produces `Explored` items for processing - -2. **ExtractStep** (`ExtractStep.kt`) - - Extracts metadata from discovered files - - Uses TagLib via JNI for metadata extraction - - Produces `Extracted` items with parsed tags - -3. **EvaluateStep** (`EvaluateStep.kt`) - - Processes extracted data to build the music library - - Creates the song/album/artist/genre relationships - - Resolves cover art references - -### Pipeline Items - -The `PipelineItem.kt` defines the data types that flow through the pipeline: - -- **Explored** - Files discovered in the filesystem - - `NewSong` - A newly discovered music file - - `RawPlaylist` - A discovered playlist file - -- **Extracted** - Files with extracted metadata - - `RawSong` - A song with extracted metadata and tags - - `InvalidSong` - A file that couldn't be processed - -### Exception Handling - -`PipelineException.kt` defines exceptions specific to the pipeline process. - -## Flow Utilities - -`FlowUtil.kt` provides utility functions for working with Kotlin Flows in the pipeline context, including: - -- `distributedMap` - Parallel mapping operations -- Flow merging and buffering utilities - -## Pipeline Flow - -``` -Location.Opened → 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. - -## Extension Points - -When extending the pipeline: - -1. Consider the stage where your functionality belongs -2. Follow the existing pattern of `Flow → Flow` transformations -3. Use the appropriate dispatchers for I/O vs CPU work -4. Buffer appropriately to manage backpressure \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/README.md b/musikr/src/main/java/org/oxycblt/musikr/tag/README.md deleted file mode 100644 index 7cdacd0f0..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# Tag Package - -## Overview - -The tag package handles parsing, interpreting, and managing music metadata tags. It provides structures for representing various tag types and interpreting them according to user preferences. - -## Key Components - -### Tag Parsing - -**TagParser** (`parse/TagParser.kt`) -- Parses raw tag data from the metadata extractor -- Handles different tag formats and structures -- Normalizes tags across different formats - -**ParsedTags** (`parse/ParsedTags.kt`) -- Container for parsed metadata tags -- Provides structured access to tag values - -**TagFields** (`parse/TagFields.kt`) -- Defines standard tag fields and their mapping -- Handles format-specific field names - -### Tag Interpretation - -**TagInterpreter** (`interpret/TagInterpreter.kt`) -- Interprets tags based on user preferences -- Resolves ambiguities in tag data -- Creates structured music metadata - -**Naming** (`interpret/Naming.kt`) -- Handles naming conventions for music entities -- Provides fallbacks for missing metadata - -**Separators** (`interpret/Separators.kt`) -- Handles multi-value separators in tags -- Splits tags with multiple artists, genres, etc. - -**PreMusic** (`interpret/PreMusic.kt`) -- Intermediate representation during tag interpretation -- Holds partially processed music data - -### Tag Types - -**Name** (`Name.kt`) -- Represents artist, album, and track names -- Handles normalization and comparison - -**Date** (`Date.kt`) -- Represents release dates -- Handles various date formats and partial dates - -**Disc** (`Disc.kt`) -- Represents disc and track numbers -- Handles various numbering formats - -**ReleaseType** (`ReleaseType.kt`) -- Represents album release types (album, EP, single, etc.) -- Handles format-specific release type tags - -### Format-Specific Handling - -**ID3** (`format/ID3.kt`) -- Handles ID3v1 and ID3v2 tag specifics - -**Vorbis** (`format/Vorbis.kt`) -- Handles Vorbis Comment tag specifics - -## Tag Flow - -1. Raw tags extracted by the metadata extractor -2. TagParser normalizes tags into ParsedTags -3. TagInterpreter interprets tags based on user preferences -4. Interpreted tags are used to build the music library - -## Extension Points - -When extending the tag functionality: - -1. For new tag types, extend the TagParser and relevant format handlers -2. For new interpretation rules, modify the TagInterpreter -3. For format-specific handling, add new format classes -4. For new metadata types, add appropriate structures and update the tag flow \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt index 29ae53bbf..f5e9cbda8 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt @@ -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.Location +import org.oxycblt.musikr.fs.MusicLocation internal class LocationObserver( private val context: Context, - private val location: Location.Opened, + private val location: MusicLocation, private val listener: UpdateTracker.Callback ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt index 48f22a1fb..88a9dec98 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt @@ -19,15 +19,15 @@ package org.oxycblt.musikr.track import android.content.Context -import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.MusicLocation interface UpdateTracker { - fun track(locations: List) + fun track(locations: List) fun release() interface Callback { - fun onUpdate(location: Location.Opened) + fun onUpdate(location: MusicLocation) } companion object { @@ -42,7 +42,7 @@ private class UpdateTrackerImpl( ) : UpdateTracker { private val observers = mutableListOf() - override fun track(locations: List) { + override fun track(locations: List) { release() observers.addAll(locations.map { LocationObserver(context, it, callback) }) } From c781ea25309fad4f8299b25a2ae074bcafafa01e Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Thu, 29 May 2025 19:55:59 -0600 Subject: [PATCH 02/42] build: agent support With Claude 4, agents are finally able to navigate Auxio's codebase without crashing and burning. Update them. --- AGENT.md | 1 + CLAUDE.md | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 120000 AGENT.md create mode 100644 CLAUDE.md diff --git a/AGENT.md b/AGENT.md new file mode 120000 index 000000000..681311eb9 --- /dev/null +++ b/AGENT.md @@ -0,0 +1 @@ +CLAUDE.md \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..7ebb3c146 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,123 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +Auxio is a modern Android music player written in Kotlin that emphasizes simplicity and performance. It uses Media3 ExoPlayer for playback and includes a custom native music indexing library called musikr. + +## Build System & Commands + +### Prerequisites +- `cmake` and `ninja-build` must be installed before building +- Project uses git submodules - clone with `git clone --recurse-submodules` +- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts + +### Common Build Commands +```bash +# Build debug version +./gradlew assembleDebug + +# Build release version +./gradlew assembleRelease + +# Run tests +./gradlew test + +# Run connected tests +./gradlew connectedAndroidTest + +# Code formatting (Spotless) +./gradlew spotlessApply + +# Check code formatting +./gradlew spotlessCheck +``` + +### Development Modules +- `app/` - Main Android application +- `musikr/` - Native music indexing library with TagLib integration +- `media/` - Patched Media3 ExoPlayer libraries (git submodule) + +## Architecture Overview + +### Core Architecture Pattern +- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search) +- **Repository Pattern** - MusicRepository as single source of truth for music data +- **Dependency Injection** - Hilt/Dagger for modular dependency management +- **Single Activity Architecture** with Navigation Components +- **Service-Oriented** background music processing + +### Key Modules & Components + +#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`) +- `MusicRepository` - Central music library state management +- `MusicViewModel` - UI layer for music data access +- `service/` - MediaBrowserServiceCompat integration +- `shim/` - Abstraction layer for musikr integration + +#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`) +- `PlaybackViewModel` - Main playback UI interface +- `PlaybackStateManager` - Core playback state management +- `service/` - Background ExoPlayer integration +- `queue/` - Playback queue management +- `persist/` - Playback state persistence (Room database) +- `replaygain/` - Audio processing for volume normalization + +#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`) +- `home/` - Main library browsing with customizable tabs +- `detail/` - Album, artist, genre, and playlist detail views +- `search/` - Music search functionality +- `list/` - Shared list components with sorting/filtering +- `ui/` - Custom UI components, theming, animations + +#### Native Music Library (`musikr/`) +- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate) +- **TagLib integration** - Native C++ metadata extraction +- **File system caching** - Device storage access optimization +- **Cover art management** - Embedded and external cover support + +### Data Flow +1. musikr scans and indexes music files from device storage +2. MusicRepository manages indexed library and exposes to UI +3. ViewModels provide reactive state for UI components using StateFlow +4. PlaybackService handles audio playback via ExoPlayer +5. UI observes ViewModels and updates reactively + +## Code Conventions + +### Language & Libraries +- **Kotlin** - Primary language with coroutines for async operations +- **Hilt/Dagger** - Dependency injection +- **Room** - Local database for persistence +- **Navigation Components** - Fragment navigation +- **ViewBinding** - Type-safe view access +- **StateFlow/LiveData** - Reactive state management +- **Coil** - Image loading for cover art + +### Code Style +- Uses Spotless with ktfmt Dropbox style formatting +- License header required (see NOTICE file) +- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml) + +## Testing + +### Test Structure +- Unit tests: `src/test/` directories +- Integration tests: `src/androidTest/` directories +- musikr module includes Robolectric tests + +### Test Dependencies +- JUnit 4 for unit testing +- MockK for mocking +- Robolectric for Android unit tests +- Espresso for UI tests + +## Key Development Notes + +- **Custom Media3**: Uses patched Media3 ExoPlayer for enhanced playback features +- **Native Dependencies**: musikr module builds TagLib from source during compilation +- **Permission Handling**: Requires storage permissions for music file access +- **Background Services**: Foreground service for continuous music playback +- **Widget Support**: Multiple widget layouts with automatic sizing adaptation +- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files \ No newline at end of file From 6b553cb9eba5c6a59aa5964851a6857cff8c5cb8 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Fri, 30 May 2025 18:16:26 -0600 Subject: [PATCH 03/42] musikr: refactor musiclocation api into location Improves the API surface pretty heavily. Assisted by Claude 4 Sonnet/Claude 3.5 Haiku. --- .../oxycblt/auxio/music/MusicRepository.kt | 4 +- .../org/oxycblt/auxio/music/MusicSettings.kt | 57 +++++++- .../auxio/music/locations/LocationAdapter.kt | 37 ++--- .../music/locations/MusicSourcesDialog.kt | 13 +- .../auxio/music/service/IndexingHolder.kt | 4 +- musikr/ARCHITECTURE.md | 135 ++++++++++++++++++ .../main/java/org/oxycblt/musikr/Config.kt | 7 + .../main/java/org/oxycblt/musikr/Musikr.kt | 13 +- .../fs/{MusicLocation.kt => Location.kt} | 64 +++++---- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 21 +-- .../oxycblt/musikr/pipeline/ExploreStep.kt | 16 ++- .../oxycblt/musikr/track/LocationObserver.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 8 +- 13 files changed, 294 insertions(+), 89 deletions(-) create mode 100644 musikr/ARCHITECTURE.md rename musikr/src/main/java/org/oxycblt/musikr/fs/{MusicLocation.kt => Location.kt} (50%) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 6b478c520..8702fe7c4 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -37,6 +37,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 @@ -392,9 +393,10 @@ constructor( val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) val storage = Storage(cache, covers, storedPlaylists) + val query = Query(source = locations, exclude = emptyList()) 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 diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 67b79ae15..b1a1a6d5e 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -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 { /** The current library revision. */ var revision: UUID? /** The locations of music to load. */ - var musicLocations: List + var musicLocations: List /** 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 + override var musicLocations: List 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.stringify(): String = + joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } + + private fun String.toOpenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + + private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { + val split = mutableListOf() + 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 + } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 3a6ebe679..1331ac84b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -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() { - private val _locations = mutableListOf() + private val _locations = mutableListOf() /** - * 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 = _locations + val locations: List = _locations override fun getItemCount() = locations.size @@ -50,11 +51,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter) { + fun addAll(locations: List) { 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 B[Explore Step] + B --> C[Extract Step] + C --> D[Evaluate Step] + D --> E[Library] + + subgraph Pipeline + B + C + D + end +``` + +### Key Interfaces + +- **Musikr** - Main entry point for the library +- **Storage** - Manages persistent storage needs +- **Library** - Represents the loaded music collection +- **MutableLibrary** - Modifiable version of the library + +## Module Structure + +### 1. File System (`fs` package) +- **OpenedLocation** - Represents a location to search for music +- **DeviceFS** - Provides access to device storage +- **FileTreeCache** - Caches filesystem structure for faster indexing + +### 2. Pipeline (`pipeline` package) +- **ExploreStep** - Discovers music files on the device +- **ExtractStep** - Extracts metadata from discovered files +- **EvaluateStep** - Processes extracted data to build the library +- **PipelineItem** - Data items flowing through the pipeline + +### 3. Metadata (`metadata` package) +- **Metadata** - Extracted file metadata +- **MetadataExtractor** - Extracts metadata using TagLib +- **TagLibJNI** - JNI bridge to native TagLib library + +### 4. Tag Processing (`tag` package) +- **TagParser** - Parses raw tag data into structured format +- **TagInterpreter** - Interprets tags based on user preferences +- **ParsedTags** - Represents parsed metadata tags + +### 5. Model (`model` package) +- **LibraryImpl** - Implementation of the music library +- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations +- **LibraryFactory** - Creates library instances from pipeline data + +### 6. Covers (`covers` package) +- **Covers** - Interface for album cover management +- **EmbeddedCovers** - Extracts covers embedded in music files +- **FSCovers** - Discovers cover art in the filesystem +- **StoredCovers** - Manages persistent storage of covers + +### 7. Cache (`cache` package) +- **Cache** - Caches processed music data +- **DBCache** - Database implementation of caching + +### 8. Playlist (`playlist` package) +- **PlaylistFile** - Represents a playlist file +- **ExternalPlaylistManager** - Manages external playlist files +- **PlaylistInterpreter** - Interprets playlist formats + +## Native Component + +Musikr includes a native component built with TagLib for fast and accurate metadata extraction: + +```mermaid +graph TD + A[TagLibJNI] --> B[JNI Bridge] + B --> C[TagLib Library] + C --> D[Music File Metadata] +``` + +### Native Files (`cpp` directory) +- **taglib_jni.cpp** - Main JNI implementation +- **JMetadataBuilder** - Builds metadata objects from TagLib +- **JTagMap** - Maps between Java and C++ tag structures +- **JInputStream** - Input stream adapter for TagLib + +## Data Flow + +```mermaid +sequenceDiagram + participant User + participant Musikr + participant ExploreStep + participant ExtractStep + participant EvaluateStep + participant Storage + + User->>Musikr: run(locations) + Musikr->>ExploreStep: explore(locations) + ExploreStep->>Storage: Read cache + ExploreStep-->>Musikr: Explored files + Musikr->>ExtractStep: extract(explored) + ExtractStep->>TagLibJNI: Extract metadata + ExtractStep-->>Musikr: Extracted metadata + Musikr->>EvaluateStep: evaluate(extracted) + EvaluateStep->>Storage: Store processed data + EvaluateStep-->>Musikr: Library + Musikr-->>User: LibraryResult +``` + +## Threading Model + +Musikr uses Kotlin Coroutines for concurrent processing: + +- Pipeline stages use `flatMapMerge` and `distributedMap` for parallel processing +- Bounded buffer channels manage backpressure +- IO operations are dispatched to `Dispatchers.IO` + +## Best Practices for Extension + +1. The API is minimized and unstable - be prepared to fork and modify +2. No defaults are provided - carefully consider parameter choices +3. Musikr is stateless except for Storage - manage long-term state yourself +4. When adding functionality, follow the pipeline architecture pattern \ No newline at end of file diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index df7c5cf07..a4969064f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -21,10 +21,17 @@ 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.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators +data class Query( + val source: List, + val exclude: List +) + /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 27b84f1f2..2fe9531c2 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -25,7 +25,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 @@ -47,13 +46,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, + query: Query, onProgress: suspend (IndexingProgress) -> Unit = {} ): LibraryResult @@ -70,6 +69,7 @@ interface Musikr { */ fun new(context: Context, storage: Storage, interpretation: Interpretation): Musikr = MusikrImpl( + context, storage, ExploreStep.from(context, storage, interpretation), ExtractStep.from(context, storage), @@ -96,7 +96,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 @@ -110,20 +110,21 @@ 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, + query: Query, onProgress: suspend (IndexingProgress) -> Unit ) = coroutineScope { var exploredCount = 0 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)) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt similarity index 50% rename from musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index 636d16c61..072c83890 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/MusicLocation.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -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) = - list.joinToString(";") { it.uri.toString().replace(";", "\\;") } - - fun existing(context: Context, string: String): List { - 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() +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index a6831cc71..aa1e5e44a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -28,18 +28,20 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll +import org.oxycblt.musikr.Query import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow -import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.Path internal interface DeviceFS { - fun explore(locations: Flow): Flow + fun explore(query: Query): Flow companion object { - fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.contentResolverSafe, withHidden) + fun from( + context: Context, + withHidden: Boolean + ): DeviceFS = DeviceFSImpl(context.contentResolverSafe, withHidden) } } @@ -48,8 +50,8 @@ private class DeviceFSImpl( private val contentResolver: ContentResolver, private val withHidden: Boolean ) : DeviceFS { - override fun explore(locations: Flow): Flow = - locations.flatMapMerge { location -> + override fun explore(query: Query): Flow = + query.source.asFlow().flatMapMerge { location -> exploreDirectoryImpl( location.uri, DocumentsContract.getTreeDocumentId(location.uri), @@ -57,6 +59,7 @@ private class DeviceFSImpl( null) } + private fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, @@ -94,7 +97,8 @@ private class DeviceFSImpl( if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) + ) } else { val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) @@ -105,7 +109,8 @@ private class DeviceFSImpl( path = newPath, size = size, modifiedMs = lastModified, - parent = directoryDeferred) + parent = directoryDeferred + ) children.add(file) emit(file) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index 675fd6db9..ea2a0d21b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -26,11 +26,13 @@ import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge 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 @@ -38,18 +40,20 @@ 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.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U internal interface ExploreStep { - fun explore(locations: List): Flow + fun explore(query: Query): Flow 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.storedPlaylists) @@ -62,13 +66,11 @@ private class ExploreStepImpl( private val covers: Covers, private val storedPlaylists: StoredPlaylists ) : ExploreStep { - override fun explore(locations: List): Flow { + override fun explore(query: Query): Flow { val addingMs = System.currentTimeMillis() return merge( deviceFS - .explore( - locations.asFlow(), - ) + .explore(query) .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)) { diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt index f5e9cbda8..a3b4a0e00 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt @@ -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()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt index 88a9dec98..a3e4f2b69 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt @@ -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) + fun track(locations: List) 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() - override fun track(locations: List) { + override fun track(locations: List) { release() observers.addAll(locations.map { LocationObserver(context, it, callback) }) } From 464b1e5c1f2f639c90120b772870e3fb95cdedd5 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 16 Jun 2025 07:36:56 -0600 Subject: [PATCH 04/42] all: reformat --- .../oxycblt/auxio/music/MusicRepository.kt | 3 +- .../org/oxycblt/auxio/music/MusicSettings.kt | 4 +- .../auxio/music/locations/LocationAdapter.kt | 4 +- .../main/java/org/oxycblt/musikr/Config.kt | 5 +-- .../main/java/org/oxycblt/musikr/Musikr.kt | 40 +++++++++---------- .../java/org/oxycblt/musikr/fs/Location.kt | 8 ++-- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 15 +++---- .../oxycblt/musikr/pipeline/ExploreStep.kt | 6 +-- 8 files changed, 35 insertions(+), 50 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 8702fe7c4..ba9774cdd 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -395,8 +395,7 @@ constructor( val storage = Storage(cache, covers, storedPlaylists) val query = Query(source = locations, exclude = emptyList()) val interpretation = Interpretation(nameFactory, separators, withHidden) - val result = - Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) + val result = 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 diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index b1a1a6d5e..d96c72624 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -85,8 +85,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } set(value) { sharedPreferences.edit { - putString( - getString(R.string.set_key_music_locations), value.stringify()) + putString(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. @@ -139,7 +138,6 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - private fun List.stringify(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 1331ac84b..ee4b8d97b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -25,7 +25,6 @@ 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.Location import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L @@ -38,7 +37,8 @@ import timber.log.Timber as L class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { private val _locations = mutableListOf() /** - * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to removals. + * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to + * removals. */ val locations: List = _locations diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index a4969064f..ab3352f9e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -27,10 +27,7 @@ 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, - val exclude: List -) +data class Query(val source: List, val exclude: List) /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 2fe9531c2..8b120cec5 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -116,27 +116,25 @@ private class MusikrImpl( private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { - override suspend fun run( - query: Query, - onProgress: suspend (IndexingProgress) -> Unit - ) = coroutineScope { - var exploredCount = 0 - var extractedCount = 0 - val explored = - exploreStep - .explore(query) - .buffer(Channel.UNLIMITED) - .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } - val extracted = - extractStep - .extract(explored) - .buffer(Channel.UNLIMITED) - .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } - .onCompletion { onProgress(IndexingProgress.Indeterminate) } - val library = evaluateStep.evaluate(extracted) - LibraryResultImpl(storage, library) - } + override suspend fun run(query: Query, onProgress: suspend (IndexingProgress) -> Unit) = + coroutineScope { + var exploredCount = 0 + var extractedCount = 0 + val explored = + exploreStep + .explore(query) + .buffer(Channel.UNLIMITED) + .onStart { onProgress(IndexingProgress.Songs(0, 0)) } + .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } + val extracted = + extractStep + .extract(explored) + .buffer(Channel.UNLIMITED) + .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } + .onCompletion { onProgress(IndexingProgress.Indeterminate) } + val library = evaluateStep.evaluate(extracted) + LibraryResultImpl(storage, library) + } } private class LibraryResultImpl( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index 072c83890..dd4b56474 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -37,8 +37,7 @@ class Location private constructor(val uri: Uri, val path: Path) { 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) @@ -68,7 +67,10 @@ class Location private constructor(val uri: Uri, val path: 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 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() } diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index aa1e5e44a..99e4a6c27 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -28,20 +28,18 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emitAll -import org.oxycblt.musikr.Query import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow +import org.oxycblt.musikr.Query import org.oxycblt.musikr.fs.Path internal interface DeviceFS { fun explore(query: Query): Flow companion object { - fun from( - context: Context, - withHidden: Boolean - ): DeviceFS = DeviceFSImpl(context.contentResolverSafe, withHidden) + fun from(context: Context, withHidden: Boolean): DeviceFS = + DeviceFSImpl(context.contentResolverSafe, withHidden) } } @@ -59,7 +57,6 @@ private class DeviceFSImpl( null) } - private fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, @@ -97,8 +94,7 @@ private class DeviceFSImpl( if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred) - ) + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) } else { val size = cursor.getLong(sizeIndex) val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) @@ -109,8 +105,7 @@ private class DeviceFSImpl( path = newPath, size = size, modifiedMs = lastModified, - parent = directoryDeferred - ) + parent = directoryDeferred) children.add(file) emit(file) } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index ea2a0d21b..c90f4600f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -26,7 +26,6 @@ import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map @@ -40,7 +39,6 @@ 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.OpenedLocation import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.m3u.M3U @@ -51,9 +49,7 @@ internal interface ExploreStep { companion object { fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep = ExploreStepImpl( - DeviceFS.from( - context = context, - withHidden = interpretation.withHidden), + DeviceFS.from(context = context, withHidden = interpretation.withHidden), storage.cache, storage.covers, storage.storedPlaylists) From bc18879a8e19921a9b0cc22365a25514bbf2a3b4 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Fri, 30 May 2025 18:31:03 -0600 Subject: [PATCH 05/42] music: implement excluded dirs settings fields Authored by Claude Code. --- .../oxycblt/auxio/music/MusicRepository.kt | 3 ++- .../org/oxycblt/auxio/music/MusicSettings.kt | 26 ++++++++++++++++++- app/src/main/res/values/settings.xml | 1 + 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index ba9774cdd..3afe6739b 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -386,14 +386,15 @@ constructor( Naming.simple() } val locations = musicSettings.musicLocations + val excludedLocations = musicSettings.excludedLocations val withHidden = musicSettings.withHidden val currentRevision = musicSettings.revision val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) + val query = Query(source = locations, exclude = excludedLocations) val storage = Storage(cache, covers, storedPlaylists) - val query = Query(source = locations, exclude = emptyList()) val interpretation = Interpretation(nameFactory, separators, withHidden) val result = Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) // Music loading completed, update the revision right now so we re-use this work diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index d96c72624..8571f2681 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -40,6 +40,8 @@ interface MusicSettings : Settings { var revision: UUID? /** The locations of music to load. */ var musicLocations: List + /** The locations to exclude from music loading. */ + var excludedLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -93,6 +95,21 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } + override var excludedLocations: List + get() { + val locations = + sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) + ?: return emptyList() + return locations.toLocations() + } + set(value) { + sharedPreferences.edit { + putString(getString(R.string.set_key_excluded_locations), value.stringifyLocations()) + commit() + listener?.onMusicLocationsChanged() + } + } + override val excludeNonMusic: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_exclude_non_music), true) @@ -120,7 +137,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) when (key) { - getString(R.string.set_key_music_locations) -> { + getString(R.string.set_key_music_locations), + getString(R.string.set_key_excluded_locations) -> { L.d("Dispatching music locations change") listener.onMusicLocationsChanged() } @@ -144,6 +162,12 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont private fun String.toOpenedLocations(): List = splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + private fun List.stringifyLocations(): String = + joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } + + private fun String.toLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri()) } + private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { val split = mutableListOf() var currentString = "" diff --git a/app/src/main/res/values/settings.xml b/app/src/main/res/values/settings.xml index 78cbeca29..5d334f7db 100644 --- a/app/src/main/res/values/settings.xml +++ b/app/src/main/res/values/settings.xml @@ -19,6 +19,7 @@ auxio_exclude_non_music auxio_with_hidden auxio_music_locations2 + auxio_excluded_locations auxio_separators auxio_auto_sort_names From 1479ec47036e96cb95cd4e5abacffa3a06976d13 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 31 May 2025 12:02:53 -0600 Subject: [PATCH 06/42] music: add excluded folders configuration Co-authored by Claude. --- .../org/oxycblt/auxio/music/MusicSettings.kt | 3 +- .../locations/ExcludedLocationAdapter.kt | 124 +++++++++++++++ .../locations/ExcludedLocationsDialog.kt | 144 ++++++++++++++++++ .../auxio/settings/RootPreferenceFragment.kt | 12 +- app/src/main/res/navigation/outer.xml | 8 + app/src/main/res/values/settings.xml | 1 + app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/preferences_root.xml | 5 + 8 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 8571f2681..d1c57b8cf 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -104,7 +104,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } set(value) { sharedPreferences.edit { - putString(getString(R.string.set_key_excluded_locations), value.stringifyLocations()) + putString( + getString(R.string.set_key_excluded_locations), value.stringifyLocations()) commit() listener?.onMusicLocationsChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt new file mode 100644 index 000000000..754ce915a --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2021 Auxio Project + * ExcludedLocationAdapter.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.auxio.music.locations + +import android.view.View +import android.view.ViewGroup +import androidx.recyclerview.widget.RecyclerView +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.Location +import timber.log.Timber as L + +/** + * [RecyclerView.Adapter] that manages a list of [Location] excluded directory instances. + * + * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + * @author Alexander Capehart (OxygenCobalt) + */ +class ExcludedLocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { + private val _locations = mutableListOf() + /** + * The current list of [Location]s, may not line up with [Location]s due to + * removals. + */ + val locations: List = _locations + + override fun getItemCount() = locations.size + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = + ExcludedDirViewHolder.from(parent) + + override fun onBindViewHolder(holder: ExcludedDirViewHolder, position: Int) = + holder.bind(locations[position], listener) + + /** + * Add a [Location] to the end of the list. + * + * @param location The [Location] to add. + */ + fun add(location: Location) { + if (_locations.contains(location)) return + L.d("Adding $location") + _locations.add(location) + notifyItemInserted(_locations.lastIndex) + } + + /** + * Add a list of [Location] instances to the end of the list. + * + * @param locations The [Location] instances to add. + */ + fun addAll(locations: List) { + L.d("Adding ${locations.size} locations") + val oldLastIndex = _locations.size + _locations.addAll(locations) + notifyItemRangeInserted(oldLastIndex, locations.size) + } + + /** + * Remove a [Location] from the list. + * + * @param location The [Location] to remove. Must exist in the list. + */ + fun remove(location: Location) { + L.d("Removing $location") + val idx = _locations.indexOf(location) + _locations.removeAt(idx) + notifyItemRemoved(idx) + } + + /** A Listener for [ExcludedLocationAdapter] interactions. */ + interface Listener { + /** Called when the delete button on a directory item is clicked. */ + fun onRemoveLocation(location: Location) + } +} + +/** + * A [RecyclerView.Recycler] that displays a [Location]. Use [from] to create an instance. + * + * @author Alexander Capehart (OxygenCobalt) + */ +class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : + DialogRecyclerView.ViewHolder(binding.root) { + /** + * Bind new data to this instance. + * + * @param location The new [Location] to bind. + * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + */ + fun bind(location: Location, listener: ExcludedLocationAdapter.Listener) { + binding.locationPath.text = location.path.resolve(binding.context) + binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } + } + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + ExcludedDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + } +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt new file mode 100644 index 000000000..16eb9b4e3 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2021 Auxio Project + * ExcludedLocationsDialog.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.auxio.music.locations + +import android.content.ActivityNotFoundException +import android.net.Uri +import android.os.Bundle +import android.view.LayoutInflater +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AlertDialog +import androidx.core.net.toUri +import androidx.recyclerview.widget.ConcatAdapter +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject +import org.oxycblt.auxio.BuildConfig +import org.oxycblt.auxio.R +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.Location +import timber.log.Timber as L + +/** + * Dialog that manages the excluded locations setting. + * + * @author Alexander Capehart (OxygenCobalt) + */ +@AndroidEntryPoint +class ExcludedLocationsDialog : + ViewBindingMaterialDialogFragment(), + ExcludedLocationAdapter.Listener, + NewLocationFooterAdapter.Listener { + private val locationAdapter = ExcludedLocationAdapter(this) + private val locationFooterAdapter = NewLocationFooterAdapter(this) + private var openDocumentTreeLauncher: ActivityResultLauncher? = null + @Inject lateinit var musicSettings: MusicSettings + + override fun onCreateBinding(inflater: LayoutInflater) = + DialogMusicLocationsBinding.inflate(inflater) + + override fun onConfigDialog(builder: AlertDialog.Builder) { + builder + .setTitle(R.string.set_excluded_locations) + .setNegativeButton(R.string.lbl_cancel, null) + .setPositiveButton(R.string.lbl_save) { _, _ -> + val newDirs = locationAdapter.locations + musicSettings.excludedLocations = newDirs + } + } + + override fun onBindingCreated( + binding: DialogMusicLocationsBinding, + savedInstanceState: Bundle? + ) { + openDocumentTreeLauncher = + registerForActivityResult( + ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs) + + binding.locationsRecycler.apply { + adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) + itemAnimator = null + } + + val locations = + savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { + Location.from(requireContext(), it.toUri()) + } ?: musicSettings.excludedLocations + + locationAdapter.addAll(locations) + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putStringArrayList( + KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) + } + + override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { + super.onDestroyBinding(binding) + openDocumentTreeLauncher = null + binding.locationsRecycler.adapter = null + } + + override fun onRemoveLocation(location: Location) { + locationAdapter.remove(location) + } + + override fun onNewLocation() { + L.d("Opening launcher") + val launcher = + requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" } + + try { + launcher.launch(null) + } catch (e: ActivityNotFoundException) { + // User doesn't have a capable file manager. + requireContext().showToast(R.string.err_no_app) + } + } + + /** + * Add a Document Tree [Uri] chosen by the user to the current [Location]s. + * + * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] + * is null or not valid. + */ + private fun addDocumentTreeUriToDirs(uri: Uri?) { + if (uri == null) { + // A null URI means that the user left the file picker without picking a directory + L.d("No URI given (user closed the dialog)") + return + } + val context = requireContext() + val location = Location.from(context, uri) + + if (location != null) { + locationAdapter.add(location) + } else { + requireContext().showToast(R.string.err_bad_location) + } + } + + private companion object { + const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + } +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt index 39a523c0c..791ba5b53 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt @@ -51,9 +51,15 @@ class RootPreferenceFragment : BasePreferenceFragment(R.xml.preferences_root) { } override fun onOpenDialogPreference(preference: WrappedDialogPreference) { - if (preference.key == getString(R.string.set_key_music_dirs)) { - findNavController() - .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) + when (preference.key) { + getString(R.string.set_key_music_dirs) -> { + findNavController() + .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) + } + getString(R.string.set_key_excluded_dirs) -> { + findNavController() + .navigateSafe(RootPreferenceFragmentDirections.excludedLocationsSettings()) + } } } diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 0d15cbc8a..4f75640ec 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -36,6 +36,9 @@ + + auxio_rescan auxio_observing auxio_music_dirs + auxio_excluded_dirs auxio_cover_mode2 auxio_square_covers auxio_exclude_non_music diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0b5830db5..26d456242 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -315,6 +315,8 @@ Music folders Manage where music should be loaded from New folder + Excluded folders + Manage folders to exclude from music loading Refresh music Reload the music library, using cached tags when possible diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 5c004cb4c..12f8fb94b 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -33,6 +33,11 @@ app:summary="@string/set_locations_desc" app:title="@string/set_locations" /> + + Date: Sat, 31 May 2025 13:36:49 -0600 Subject: [PATCH 07/42] music: share code between music/excluded locations Co-authored by Claude. --- .../org/oxycblt/auxio/music/MusicSettings.kt | 21 ++-- .../locations/ExcludedLocationAdapter.kt | 87 ++----------- .../locations/ExcludedLocationsDialog.kt | 117 +++--------------- .../auxio/music/locations/LocationAdapter.kt | 90 ++++---------- ...sicSourcesDialog.kt => LocationsDialog.kt} | 62 ++++------ .../music/locations/MusicLocationAdapter.kt | 55 ++++++++ .../music/locations/MusicLocationsDialog.kt | 64 ++++++++++ .../auxio/music/service/IndexingHolder.kt | 4 +- app/src/main/res/navigation/inner.xml | 2 +- app/src/main/res/navigation/outer.xml | 2 +- musikr/ARCHITECTURE.md | 2 +- .../main/java/org/oxycblt/musikr/Config.kt | 4 +- .../java/org/oxycblt/musikr/fs/Location.kt | 70 +++++------ .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 2 +- .../oxycblt/musikr/track/LocationObserver.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 8 +- 16 files changed, 249 insertions(+), 345 deletions(-) rename app/src/main/java/org/oxycblt/auxio/music/locations/{MusicSourcesDialog.kt => LocationsDialog.kt} (69%) create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index d1c57b8cf..ac08842ce 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -27,7 +27,6 @@ import javax.inject.Inject import org.oxycblt.auxio.R import org.oxycblt.auxio.settings.Settings import org.oxycblt.musikr.fs.Location -import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L /** @@ -39,9 +38,9 @@ interface MusicSettings : Settings { /** The current library revision. */ var revision: UUID? /** The locations of music to load. */ - var musicLocations: List + var musicLocations: List /** The locations to exclude from music loading. */ - var excludedLocations: List + var excludedLocations: List /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -78,7 +77,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var musicLocations: List + override var musicLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_music_locations), null) @@ -95,12 +94,12 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - override var excludedLocations: List + override var excludedLocations: List get() { val locations = sharedPreferences.getString(getString(R.string.set_key_excluded_locations), null) ?: return emptyList() - return locations.toLocations() + return locations.toUnopenedLocations() } set(value) { sharedPreferences.edit { @@ -157,17 +156,17 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont } } - private fun List.stringify(): String = + private fun List.stringify(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - private fun String.toOpenedLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) } + private fun String.toOpenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } private fun List.stringifyLocations(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } - private fun String.toLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri()) } + private fun String.toUnopenedLocations(): List = + splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri()) } private inline fun String.splitEscaped(selector: (Char) -> Boolean): List { val split = mutableListOf() diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt index 754ce915a..4ad1f384f 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -18,98 +18,29 @@ package org.oxycblt.auxio.music.locations -import android.view.View import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView 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.Location -import timber.log.Timber as L /** - * [RecyclerView.Adapter] that manages a list of [Location] excluded directory instances. + * [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances. * - * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. + * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedLocationAdapter(private val listener: Listener) : RecyclerView.Adapter() { - private val _locations = mutableListOf() - /** - * The current list of [Location]s, may not line up with [Location]s due to - * removals. - */ - val locations: List = _locations - - override fun getItemCount() = locations.size - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - ExcludedDirViewHolder.from(parent) - - override fun onBindViewHolder(holder: ExcludedDirViewHolder, position: Int) = - holder.bind(locations[position], listener) - - /** - * Add a [Location] to the end of the list. - * - * @param location The [Location] to add. - */ - fun add(location: Location) { - if (_locations.contains(location)) return - L.d("Adding $location") - _locations.add(location) - notifyItemInserted(_locations.lastIndex) - } - - /** - * Add a list of [Location] instances to the end of the list. - * - * @param locations The [Location] instances to add. - */ - fun addAll(locations: List) { - L.d("Adding ${locations.size} locations") - val oldLastIndex = _locations.size - _locations.addAll(locations) - notifyItemRangeInserted(oldLastIndex, locations.size) - } - - /** - * Remove a [Location] from the list. - * - * @param location The [Location] to remove. Must exist in the list. - */ - fun remove(location: Location) { - L.d("Removing $location") - val idx = _locations.indexOf(location) - _locations.removeAt(idx) - notifyItemRemoved(idx) - } - - /** A Listener for [ExcludedLocationAdapter] interactions. */ - interface Listener { - /** Called when the delete button on a directory item is clicked. */ - fun onRemoveLocation(location: Location) - } +class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { + override fun createViewHolder(parent: ViewGroup): LocationViewHolder = + ExcludedLocationViewHolder.from(parent) } /** - * A [RecyclerView.Recycler] that displays a [Location]. Use [from] to create an instance. + * A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance. * * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : - DialogRecyclerView.ViewHolder(binding.root) { - /** - * Bind new data to this instance. - * - * @param location The new [Location] to bind. - * @param listener A [ExcludedLocationAdapter.Listener] to bind interactions to. - */ - fun bind(location: Location, listener: ExcludedLocationAdapter.Listener) { - binding.locationPath.text = location.path.resolve(binding.context) - binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } - } +class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : + LocationViewHolder(binding) { companion object { /** @@ -119,6 +50,6 @@ class ExcludedDirViewHolder private constructor(private val binding: ItemMusicLo * @return A new instance. */ fun from(parent: ViewGroup) = - ExcludedDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + ExcludedLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } } \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt index 16eb9b4e3..7c031b236 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -18,25 +18,14 @@ package org.oxycblt.auxio.music.locations -import android.content.ActivityNotFoundException +import android.content.Context import android.net.Uri -import android.os.Bundle -import android.view.LayoutInflater -import androidx.activity.result.ActivityResultLauncher -import androidx.activity.result.contract.ActivityResultContracts -import androidx.appcompat.app.AlertDialog -import androidx.core.net.toUri -import androidx.recyclerview.widget.ConcatAdapter import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R -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.Location -import timber.log.Timber as L +import javax.inject.Inject /** * Dialog that manages the excluded locations setting. @@ -44,101 +33,31 @@ import timber.log.Timber as L * @author Alexander Capehart (OxygenCobalt) */ @AndroidEntryPoint -class ExcludedLocationsDialog : - ViewBindingMaterialDialogFragment(), - ExcludedLocationAdapter.Listener, - NewLocationFooterAdapter.Listener { - private val locationAdapter = ExcludedLocationAdapter(this) - private val locationFooterAdapter = NewLocationFooterAdapter(this) - private var openDocumentTreeLauncher: ActivityResultLauncher? = null - @Inject lateinit var musicSettings: MusicSettings +class ExcludedLocationsDialog : LocationsDialog() { + override val locationAdapter = ExcludedLocationAdapter(this) - override fun onCreateBinding(inflater: LayoutInflater) = - DialogMusicLocationsBinding.inflate(inflater) + @Inject + override lateinit var musicSettings: MusicSettings - override fun onConfigDialog(builder: AlertDialog.Builder) { - builder - .setTitle(R.string.set_excluded_locations) - .setNegativeButton(R.string.lbl_cancel, null) - .setPositiveButton(R.string.lbl_save) { _, _ -> - val newDirs = locationAdapter.locations - musicSettings.excludedLocations = newDirs - } + override fun getDialogTitle(): Int = R.string.set_excluded_locations + + override fun getCurrentLocations(): List = musicSettings.excludedLocations + + override fun saveLocations(locations: List) { + musicSettings.excludedLocations = locations } - override fun onBindingCreated( - binding: DialogMusicLocationsBinding, - savedInstanceState: Bundle? - ) { - openDocumentTreeLauncher = - registerForActivityResult( - ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs) + override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS - binding.locationsRecycler.apply { - adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) - itemAnimator = null - } - - val locations = - savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { - Location.from(requireContext(), it.toUri()) - } ?: musicSettings.excludedLocations - - locationAdapter.addAll(locations) + override fun convertUriToLocation(uri: Uri): Location.Unopened? { + return Location.Unopened.from(requireContext(), uri) } - override fun onSaveInstanceState(outState: Bundle) { - super.onSaveInstanceState(outState) - outState.putStringArrayList( - KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) - } - - override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { - super.onDestroyBinding(binding) - openDocumentTreeLauncher = null - binding.locationsRecycler.adapter = null - } - - override fun onRemoveLocation(location: Location) { - locationAdapter.remove(location) - } - - override fun onNewLocation() { - L.d("Opening launcher") - val launcher = - requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" } - - try { - launcher.launch(null) - } catch (e: ActivityNotFoundException) { - // User doesn't have a capable file manager. - requireContext().showToast(R.string.err_no_app) - } - } - - /** - * Add a Document Tree [Uri] chosen by the user to the current [Location]s. - * - * @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri] - * is null or not valid. - */ - private fun addDocumentTreeUriToDirs(uri: Uri?) { - if (uri == null) { - // A null URI means that the user left the file picker without picking a directory - L.d("No URI given (user closed the dialog)") - return - } - val context = requireContext() - val location = Location.from(context, uri) - - if (location != null) { - locationAdapter.add(location) - } else { - requireContext().showToast(R.string.err_bad_location) - } + override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? { + return Location.Unopened.from(context, uri) } private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + const val KEY_PENDING_EXCLUDED_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" } } \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index ee4b8d97b..37e0abe48 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2021 Auxio Project - * LocationAdapter.kt is part of Auxio. + * Copyright (c) 2024 Auxio Project + * BaseLocationAdapter.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 @@ -18,107 +18,59 @@ package org.oxycblt.auxio.music.locations -import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView 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.OpenedLocation +import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -/** - * [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() { - private val _locations = mutableListOf() - /** - * The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to - * removals. - */ - val locations: List = _locations +abstract class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter>() { + private val _locations = mutableListOf() + val locations: List = _locations override fun getItemCount() = locations.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - MusicDirViewHolder.from(parent) + createViewHolder(parent) - override fun onBindViewHolder(holder: MusicDirViewHolder, position: Int) = + override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = holder.bind(locations[position], listener) - /** - * Add a [OpenedLocation] to the end of the list. - * - * @param location The [OpenedLocation] to add. - */ - fun add(location: OpenedLocation) { + fun add(location: T) { if (_locations.contains(location)) return L.d("Adding $location") _locations.add(location) notifyItemInserted(_locations.lastIndex) } - /** - * Add a list of [OpenedLocation] instances to the end of the list. - * - * @param locations The [OpenedLocation] instances to add. - */ - fun addAll(locations: List) { + fun addAll(locations: List) { L.d("Adding ${locations.size} locations") - val oldLastIndex = locations.lastIndex + val oldSize = _locations.size _locations.addAll(locations) - notifyItemRangeInserted(oldLastIndex, locations.size) + notifyItemRangeInserted(oldSize, locations.size) } - /** - * Remove a [OpenedLocation] from the list. - * - * @param location The [OpenedLocation] to remove. Must exist in the list. - */ - fun remove(location: OpenedLocation) { + fun remove(location: T) { L.d("Removing $location") val idx = _locations.indexOf(location) _locations.removeAt(idx) notifyItemRemoved(idx) } - /** A Listener for [LocationAdapter] interactions. */ - interface Listener { - /** Called when the delete button on a directory item is clicked. */ - fun onRemoveLocation(location: OpenedLocation) + protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder + + interface Listener { + fun onRemoveLocation(location: T) } } -/** - * A [RecyclerView.Recycler] that displays a [OpenedLocation]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicDirViewHolder private constructor(private val binding: ItemMusicLocationBinding) : +abstract class LocationViewHolder(protected val binding: ItemMusicLocationBinding) : DialogRecyclerView.ViewHolder(binding.root) { - /** - * Bind new data to this instance. - * - * @param location The new [OpenedLocation] to bind. - * @param listener A [LocationAdapter.Listener] to bind interactions to. - */ - fun bind(location: OpenedLocation, listener: LocationAdapter.Listener) { + + fun bind(location: T, listener: LocationAdapter.Listener) { binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: View) = - MusicDirViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater)) - } -} +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt similarity index 69% rename from app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt rename to app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index b506f84ae..c5847338d 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicSourcesDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2021 Auxio Project - * MusicSourcesDialog.kt is part of Auxio. + * Copyright (c) 2024 Auxio Project + * BaseLocationsDialog.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 @@ -27,43 +27,33 @@ import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.core.net.toUri import androidx.recyclerview.widget.ConcatAdapter -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R 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.Location -import org.oxycblt.musikr.fs.OpenedLocation import timber.log.Timber as L -/** - * Dialog that manages the music locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class MusicSourcesDialog : +abstract class LocationsDialog : ViewBindingMaterialDialogFragment(), - LocationAdapter.Listener, + LocationAdapter.Listener, NewLocationFooterAdapter.Listener { - private val locationAdapter = LocationAdapter(this) + protected abstract val locationAdapter: LocationAdapter private val locationFooterAdapter = NewLocationFooterAdapter(this) private var openDocumentTreeLauncher: ActivityResultLauncher? = null - @Inject lateinit var musicSettings: MusicSettings + abstract val musicSettings: MusicSettings override fun onCreateBinding(inflater: LayoutInflater) = DialogMusicLocationsBinding.inflate(inflater) override fun onConfigDialog(builder: AlertDialog.Builder) { builder - .setTitle(R.string.set_locations) + .setTitle(getDialogTitle()) .setNegativeButton(R.string.lbl_cancel, null) .setPositiveButton(R.string.lbl_save) { _, _ -> val newDirs = locationAdapter.locations - musicSettings.musicLocations = newDirs + saveLocations(newDirs) } } @@ -81,10 +71,9 @@ class MusicSourcesDialog : } val locations = - savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull { - val context = requireContext() - Location.from(context, it.toUri())?.open(context) - } ?: musicSettings.musicLocations + savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull { + convertUriToLocation(it.toUri()) + } ?: getCurrentLocations() locationAdapter.addAll(locations) } @@ -92,7 +81,7 @@ class MusicSourcesDialog : override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList( - KEY_PENDING_LOCATIONS, ArrayList(locationAdapter.locations.map { it.uri.toString() })) + getPendingLocationsKey(), ArrayList(locationAdapter.locations.map { it.uri.toString() })) } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { @@ -101,10 +90,6 @@ class MusicSourcesDialog : binding.locationsRecycler.adapter = null } - override fun onRemoveLocation(location: OpenedLocation) { - locationAdapter.remove(location) - } - override fun onNewLocation() { L.d("Opening launcher") val launcher = @@ -113,25 +98,17 @@ class MusicSourcesDialog : try { launcher.launch(null) } catch (e: ActivityNotFoundException) { - // User doesn't have a capable file manager. requireContext().showToast(R.string.err_no_app) } } - /** - * 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. - */ private fun addDocumentTreeUriToDirs(uri: Uri?) { if (uri == null) { - // A null URI means that the user left the file picker without picking a locationectory L.d("No URI given (user closed the dialog)") return } val context = requireContext() - val location = Location.from(context, uri)?.open(context) + val location = createLocationFromUri(context, uri) if (location != null) { locationAdapter.add(location) @@ -140,7 +117,14 @@ class MusicSourcesDialog : } } - private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" + override fun onRemoveLocation(location: T) { + locationAdapter.remove(location) } -} + + protected abstract fun getDialogTitle(): Int + protected abstract fun getCurrentLocations(): List + protected abstract fun saveLocations(locations: List) + protected abstract fun getPendingLocationsKey(): String + protected abstract fun convertUriToLocation(uri: Uri): T? + protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? +} \ No newline at end of file diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt new file mode 100644 index 000000000..af89cd172 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Auxio Project + * LocationAdapter.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.auxio.music.locations + +import android.view.ViewGroup +import org.oxycblt.auxio.databinding.ItemMusicLocationBinding +import org.oxycblt.auxio.util.inflater +import org.oxycblt.musikr.fs.Location + +/** + * [LocationAdapter] that manages a list of [Location.Opened] music directory instances. + * + * @param listener A [LocationAdapter.Listener] to bind interactions to. + * @author Alexander Capehart (OxygenCobalt) + */ +class MusicLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { + override fun createViewHolder(parent: ViewGroup): LocationViewHolder = + MusicLocationViewHolder.from(parent) +} + +/** + * A [LocationViewHolder] that displays a [Location.Opened]. Use [from] to create an instance. + * + * @author Alexander Capehart (OxygenCobalt) + */ +class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : + LocationViewHolder(binding) { + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + MusicLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt new file mode 100644 index 000000000..90bb054c4 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2021 Auxio Project + * MusicSourcesDialog.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.auxio.music.locations + +import android.content.Context +import android.net.Uri +import dagger.hilt.android.AndroidEntryPoint +import org.oxycblt.auxio.BuildConfig +import org.oxycblt.auxio.R +import org.oxycblt.auxio.music.MusicSettings +import org.oxycblt.musikr.fs.Location +import javax.inject.Inject + +/** + * Dialog that manages the music locations setting. + * + * @author Alexander Capehart (OxygenCobalt) + */ +@AndroidEntryPoint +class MusicLocationsDialog : LocationsDialog() { + override val locationAdapter = MusicLocationAdapter(this) + + @Inject + override lateinit var musicSettings: MusicSettings + + override fun getDialogTitle(): Int = R.string.set_locations + + override fun getCurrentLocations(): List = musicSettings.musicLocations + + override fun saveLocations(locations: List) { + musicSettings.musicLocations = locations + } + + override fun getPendingLocationsKey(): String = KEY_PENDING_LOCATIONS + + override fun convertUriToLocation(uri: Uri): Location.Opened? { + val context = requireContext() + return Location.Unopened.from(context, uri)?.open(context) + } + + override fun createLocationFromUri(context: Context, uri: Uri): Location.Opened? { + return Location.Unopened.from(context, uri)?.open(context) + } + + private companion object { + const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt index 7d5226067..7788e10e8 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt @@ -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.OpenedLocation +import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.track.UpdateTracker import timber.log.Timber as L @@ -168,7 +168,7 @@ private constructor( } } - override fun onUpdate(location: OpenedLocation) { + override fun onUpdate(location: Location.Opened) { if (musicSettings.shouldBeObserving) { musicRepository.requestIndex(true) } diff --git a/app/src/main/res/navigation/inner.xml b/app/src/main/res/navigation/inner.xml index aa10ee2f9..61fcfd3a5 100644 --- a/app/src/main/res/navigation/inner.xml +++ b/app/src/main/res/navigation/inner.xml @@ -570,7 +570,7 @@ \ No newline at end of file diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 4f75640ec..60d81d6b2 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -94,7 +94,7 @@ tools:layout="@layout/dialog_pre_amp" /> , val exclude: List) +data class Query(val source: List, val exclude: List) /** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ data class Storage( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index dd4b56474..df25b2adc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -25,52 +25,52 @@ import android.provider.DocumentsContract import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory -class Location private constructor(val uri: Uri, val path: Path) { +sealed class Location(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() - 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) - } 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 - } - + class Unopened private constructor(uri: Uri, path: Path) : Location(uri, path) { + fun open(context: Context): Opened? { if (isUnopened(context, uri)) { - return null + try { + context.contentResolverSafe.takePersistableUriPermission( + uri, + 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 + } + + if (isUnopened(context, uri)) { + return null + } + } + return Opened(uri, path) + } + + private fun isUnopened(context: Context, uri: Uri) = + context.contentResolverSafe.persistedUriPermissions.none { + it.uri == uri && it.isReadPermission && it.isWritePermission + } + + companion object { + fun from(context: Context, uri: Uri): Unopened? { + if (!DocumentsContract.isTreeUri(uri)) return null + val documentPathFactory = DocumentPathFactory.from(context) + val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null + return Unopened(uri, path) } } - return OpenedLocation(uri, path) } - private fun isUnopened(context: Context, uri: Uri) = - context.contentResolverSafe.persistedUriPermissions.none { - it.uri == uri && it.isReadPermission && it.isWritePermission - } + class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) { + override fun equals(other: Any?) = + other is Opened && uri == other.uri && path == other.path - companion object { - fun from(context: Context, uri: Uri): Location? { - if (!DocumentsContract.isTreeUri(uri)) return null - val documentPathFactory = DocumentPathFactory.from(context) - val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null - return Location(uri, path) - } + override fun hashCode() = 31 * uri.hashCode() + path.hashCode() } } - -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() -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 99e4a6c27..cdb5f2bb1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -57,7 +57,7 @@ private class DeviceFSImpl( null) } - private fun exploreDirectoryImpl( + private suspend fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, relativePath: Path, diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt index a3b4a0e00..29ae53bbf 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt @@ -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.OpenedLocation +import org.oxycblt.musikr.fs.Location internal class LocationObserver( private val context: Context, - private val location: OpenedLocation, + private val location: Location.Opened, private val listener: UpdateTracker.Callback ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt index a3e4f2b69..48f22a1fb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt @@ -19,15 +19,15 @@ package org.oxycblt.musikr.track import android.content.Context -import org.oxycblt.musikr.fs.OpenedLocation +import org.oxycblt.musikr.fs.Location interface UpdateTracker { - fun track(locations: List) + fun track(locations: List) fun release() interface Callback { - fun onUpdate(location: OpenedLocation) + fun onUpdate(location: Location.Opened) } companion object { @@ -42,7 +42,7 @@ private class UpdateTrackerImpl( ) : UpdateTracker { private val observers = mutableListOf() - override fun track(locations: List) { + override fun track(locations: List) { release() observers.addAll(locations.map { LocationObserver(context, it, callback) }) } From 3979b8e6888cfe370b1219ab7db30e4984b60246 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 16 Jun 2025 07:55:03 -0600 Subject: [PATCH 08/42] all: reformat --- .../java/org/oxycblt/auxio/music/MusicSettings.kt | 3 ++- .../auxio/music/locations/ExcludedLocationAdapter.kt | 8 +++++--- .../auxio/music/locations/ExcludedLocationsDialog.kt | 10 +++++----- .../oxycblt/auxio/music/locations/LocationAdapter.kt | 10 +++++----- .../oxycblt/auxio/music/locations/LocationsDialog.kt | 12 +++++++++--- .../auxio/music/locations/MusicLocationAdapter.kt | 8 +++++--- .../auxio/music/locations/MusicLocationsDialog.kt | 7 +++---- .../src/main/java/org/oxycblt/musikr/fs/Location.kt | 6 +++--- 8 files changed, 37 insertions(+), 27 deletions(-) diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index ac08842ce..8317f67d8 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -160,7 +160,8 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } private fun String.toOpenedLocations(): List = - splitEscaped { it == ';' }.mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } + splitEscaped { it == ';' } + .mapNotNull { Location.Unopened.from(context, it.toUri())?.open(context) } private fun List.stringifyLocations(): String = joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt index 4ad1f384f..20e4a4be2 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt @@ -29,7 +29,8 @@ import org.oxycblt.musikr.fs.Location * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { +class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : + LocationAdapter(listener) { override fun createViewHolder(parent: ViewGroup): LocationViewHolder = ExcludedLocationViewHolder.from(parent) } @@ -50,6 +51,7 @@ class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationB * @return A new instance. */ fun from(parent: ViewGroup) = - ExcludedLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + ExcludedLocationViewHolder( + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt index 7c031b236..be70285d0 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt @@ -21,11 +21,11 @@ package org.oxycblt.auxio.music.locations import android.content.Context import android.net.Uri import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.musikr.fs.Location -import javax.inject.Inject /** * Dialog that manages the excluded locations setting. @@ -36,8 +36,7 @@ import javax.inject.Inject class ExcludedLocationsDialog : LocationsDialog() { override val locationAdapter = ExcludedLocationAdapter(this) - @Inject - override lateinit var musicSettings: MusicSettings + @Inject override lateinit var musicSettings: MusicSettings override fun getDialogTitle(): Int = R.string.set_excluded_locations @@ -58,6 +57,7 @@ class ExcludedLocationsDialog : LocationsDialog() { } private companion object { - const val KEY_PENDING_EXCLUDED_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" + const val KEY_PENDING_EXCLUDED_LOCATIONS = + BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 37e0abe48..12614dcd3 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2024 Auxio Project - * BaseLocationAdapter.kt is part of Auxio. + * LocationAdapter.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 @@ -26,14 +26,14 @@ import org.oxycblt.auxio.util.context import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -abstract class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter>() { +abstract class LocationAdapter(private val listener: Listener) : + RecyclerView.Adapter>() { private val _locations = mutableListOf() val locations: List = _locations override fun getItemCount() = locations.size - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - createViewHolder(parent) + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent) override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = holder.bind(locations[position], listener) @@ -73,4 +73,4 @@ abstract class LocationViewHolder(protected val binding: ItemMusic binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index c5847338d..daeceb95f 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2024 Auxio Project - * BaseLocationsDialog.kt is part of Auxio. + * LocationsDialog.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 @@ -81,7 +81,8 @@ abstract class LocationsDialog : override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putStringArrayList( - getPendingLocationsKey(), ArrayList(locationAdapter.locations.map { it.uri.toString() })) + getPendingLocationsKey(), + ArrayList(locationAdapter.locations.map { it.uri.toString() })) } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { @@ -122,9 +123,14 @@ abstract class LocationsDialog : } protected abstract fun getDialogTitle(): Int + protected abstract fun getCurrentLocations(): List + protected abstract fun saveLocations(locations: List) + protected abstract fun getPendingLocationsKey(): String + protected abstract fun convertUriToLocation(uri: Uri): T? + protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? -} \ No newline at end of file +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt index af89cd172..cf950f963 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 Auxio Project - * LocationAdapter.kt is part of Auxio. + * MusicLocationAdapter.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 @@ -29,7 +29,8 @@ import org.oxycblt.musikr.fs.Location * @param listener A [LocationAdapter.Listener] to bind interactions to. * @author Alexander Capehart (OxygenCobalt) */ -class MusicLocationAdapter(listener: LocationAdapter.Listener) : LocationAdapter(listener) { +class MusicLocationAdapter(listener: LocationAdapter.Listener) : + LocationAdapter(listener) { override fun createViewHolder(parent: ViewGroup): LocationViewHolder = MusicLocationViewHolder.from(parent) } @@ -50,6 +51,7 @@ class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBind * @return A new instance. */ fun from(parent: ViewGroup) = - MusicLocationViewHolder(ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + MusicLocationViewHolder( + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt index 90bb054c4..cca6e1778 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2021 Auxio Project - * MusicSourcesDialog.kt is part of Auxio. + * MusicLocationsDialog.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 @@ -21,11 +21,11 @@ package org.oxycblt.auxio.music.locations import android.content.Context import android.net.Uri import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject import org.oxycblt.auxio.BuildConfig import org.oxycblt.auxio.R import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.musikr.fs.Location -import javax.inject.Inject /** * Dialog that manages the music locations setting. @@ -36,8 +36,7 @@ import javax.inject.Inject class MusicLocationsDialog : LocationsDialog() { override val locationAdapter = MusicLocationAdapter(this) - @Inject - override lateinit var musicSettings: MusicSettings + @Inject override lateinit var musicSettings: MusicSettings override fun getDialogTitle(): Int = R.string.set_locations diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index df25b2adc..e27cbb9b9 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -38,7 +38,8 @@ sealed class Location(val uri: Uri, val path: Path) { 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) @@ -68,8 +69,7 @@ sealed class Location(val uri: Uri, val path: Path) { } class Opened internal constructor(uri: Uri, path: Path) : Location(uri, path) { - override fun equals(other: Any?) = - other is Opened && uri == other.uri && path == other.path + override fun equals(other: Any?) = other is Opened && uri == other.uri && path == other.path override fun hashCode() = 31 * uri.hashCode() + path.hashCode() } From fe26211068f11b87c58403c028bbe4da5314c71f Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 16 Jun 2025 07:56:45 -0600 Subject: [PATCH 09/42] musikr: reimplement directory exclusion --- .../org/oxycblt/musikr/fs/device/DeviceFS.kt | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt index 1fccee4fd..97d1f9d87 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt @@ -53,14 +53,16 @@ private class DeviceFSImpl( location.uri, DocumentsContract.getTreeDocumentId(location.uri), location.path, - null) + null, + query.exclude.mapTo(mutableSetOf()) { it.uri }) } private suspend fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, relativePath: Path, - parent: Deferred? + parent: Deferred?, + exclude: Set ): Flow = flow { // Make a kotlin future val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) @@ -90,13 +92,19 @@ private class DeviceFSImpl( val newPath = relativePath.file(displayName) val mimeType = cursor.getString(mimeTypeIndex) val lastModified = cursor.getLong(lastModifiedIndex) + val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) + + // We can check for direct equality as if we block out an excluded directory we + // will by proxy block out it's children. + if (childUri in exclude) { + continue + } if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) { recursive.add( - exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)) + exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred, exclude)) } else { val size = cursor.getLong(sizeIndex) - val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId) val file = DeviceFile( uri = childUri, From 2861acd86d3b1c2dc5946593a0e9ef83ebdd120d Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Mon, 16 Jun 2025 13:14:34 -0600 Subject: [PATCH 10/42] musikr: refactor fs api Need to make it extendable to MediaStore now. --- .../oxycblt/auxio/image/covers/NullCovers.kt | 2 +- .../oxycblt/auxio/music/MusicRepository.kt | 10 +- .../auxio/music/shim/WriteOnlyMutableCache.kt | 2 +- .../main/java/org/oxycblt/musikr/Config.kt | 13 +- .../main/java/org/oxycblt/musikr/Library.kt | 4 +- .../main/java/org/oxycblt/musikr/Musikr.kt | 67 +++++----- .../java/org/oxycblt/musikr/cache/Cache.kt | 2 +- .../org/oxycblt/musikr/cache/db/DBCache.kt | 2 +- .../java/org/oxycblt/musikr/covers/Covers.kt | 2 +- .../musikr/covers/chained/ChainedCovers.kt | 2 +- .../musikr/covers/embedded/EmbeddedCovers.kt | 2 +- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 2 +- .../musikr/covers/stored/StoredCovers.kt | 2 +- .../fs/{device/DeviceFSEntries.kt => FS.kt} | 10 +- .../java/org/oxycblt/musikr/fs/Location.kt | 2 +- .../fs/device/RateLimitedContentResolver.kt | 121 ------------------ .../musikr/fs/path/DocumentPathFactory.kt | 4 +- .../musikr/fs/{device => saf}/QueryUtil.kt | 11 +- .../fs/{device/DeviceFS.kt => saf/SAF.kt} | 46 +++---- .../musikr/metadata/MetadataExtractor.kt | 2 +- .../musikr/metadata/NativeInputStream.kt | 2 +- .../org/oxycblt/musikr/metadata/TagLibJNI.kt | 2 +- .../oxycblt/musikr/pipeline/EvaluateStep.kt | 6 +- .../oxycblt/musikr/pipeline/ExploreStep.kt | 36 ++---- .../oxycblt/musikr/pipeline/ExtractStep.kt | 9 +- .../oxycblt/musikr/pipeline/PipelineItem.kt | 2 +- .../playlist/ExternalPlaylistManager.kt | 2 +- .../musikr/tag/interpret/TagInterpreter.kt | 2 +- 28 files changed, 112 insertions(+), 257 deletions(-) rename musikr/src/main/java/org/oxycblt/musikr/fs/{device/DeviceFSEntries.kt => FS.kt} (89%) delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt rename musikr/src/main/java/org/oxycblt/musikr/fs/{device => saf}/QueryUtil.kt (87%) rename musikr/src/main/java/org/oxycblt/musikr/fs/{device/DeviceFS.kt => saf/SAF.kt} (84%) diff --git a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt index df39b5981..01ed695e1 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt @@ -22,7 +22,7 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.MutableCovers import org.oxycblt.musikr.covers.stored.CoverStorage -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata class NullCovers(private val storage: CoverStorage) : MutableCovers { diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 3afe6739b..b3a87cead 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -30,6 +30,7 @@ import kotlinx.coroutines.yield import org.oxycblt.auxio.image.covers.SettingCovers import org.oxycblt.auxio.music.MusicRepository.IndexingWorker import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache +import org.oxycblt.musikr.Config import org.oxycblt.musikr.IndexingProgress import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Library @@ -37,10 +38,10 @@ 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 +import org.oxycblt.musikr.fs.saf.SAF import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators @@ -393,10 +394,11 @@ constructor( val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) - val query = Query(source = locations, exclude = excludedLocations) + val fs = SAF.from(context, SAF.Query(locations, excludedLocations, withHidden)) val storage = Storage(cache, covers, storedPlaylists) - val interpretation = Interpretation(nameFactory, separators, withHidden) - val result = Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress) + val interpretation = Interpretation(nameFactory, separators) + val config = Config(fs, storage, interpretation) + val result = Musikr.new(context, config).run(::emitIndexingProgress) // Music loading completed, update the revision right now so we re-use this work // later. musicSettings.revision = newRevision diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt index d4076f965..09b670c79 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt @@ -21,7 +21,7 @@ package org.oxycblt.auxio.music.shim import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.MutableCache -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile class WriteOnlyMutableCache(private val inner: MutableCache) : MutableCache { override suspend fun read(file: DeviceFile): CacheResult { diff --git a/musikr/src/main/java/org/oxycblt/musikr/Config.kt b/musikr/src/main/java/org/oxycblt/musikr/Config.kt index 2291f23f5..eaa3a48a3 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Config.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Config.kt @@ -21,15 +21,14 @@ 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.Location.Opened +import org.oxycblt.musikr.fs.FS 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, val exclude: List) +data class Config(val fs: FS, val storage: Storage, val interpretation: Interpretation) -/** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */ +/** Side-effect laden [Config] for use during music loading and [MutableLibrary] operation. */ data class Storage( /** * A repository of cached metadata to read and write from over the course of music loading. This @@ -49,17 +48,13 @@ data class Storage( * be used during music loading and mutated when creating, renaming, or deleting playlists in * the library. */ - val storedPlaylists: StoredPlaylists + val storedPlaylists: StoredPlaylists, ) -/** Configuration for how to interpret and extrapolate certain audio tags. */ data class Interpretation( /** How to construct names from audio tags. */ val naming: Naming, /** What separators delimit multi-value audio tags. */ val separators: Separators, - - /** Whether to include hidden files and directories (those starting with a dot). */ - val withHidden: Boolean ) diff --git a/musikr/src/main/java/org/oxycblt/musikr/Library.kt b/musikr/src/main/java/org/oxycblt/musikr/Library.kt index fea071da0..712f05ffb 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Library.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Library.kt @@ -99,7 +99,7 @@ interface Library { /** * A mutable extension of [Library]. * - * Operations here will cause side-effects within the [Storage] used when this library was loaded. + * Operations here will cause side-effects within the [Config] used when this library was loaded. * However, it won't actually mutate the [Library] itself, rather return a cloned instance with the * changes applied. It is up to the client to update their reference to the library within their * state handling. @@ -108,7 +108,7 @@ interface MutableLibrary : Library { /** * Create a new [Playlist] with the given name and songs. * - * This will commit the new playlist to the stored playlists in the [Storage] used to load the + * This will commit the new playlist to the stored playlists in the [Config] used to load the * library. * * @param name the name of the playlist diff --git a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt index 8b120cec5..77ed3db41 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/Musikr.kt @@ -44,36 +44,32 @@ import org.oxycblt.musikr.pipeline.ExtractStep */ interface Musikr { /** - * Start loading music from the given [locations] and the configuration provided earlier. + * Start loading music using the given config and the configuration provided earlier. * - * @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( - query: Query, - onProgress: suspend (IndexingProgress) -> Unit = {} - ): LibraryResult + suspend fun run(onProgress: suspend (IndexingProgress) -> Unit = {}): LibraryResult companion object { /** * Create a new instance from the given configuration. * * @param context The context to use for loading resources. - * @param storage Side-effect laden storage for use within the music loader **and** when + * @param config Side-effect laden storage for use within the music loader **and** when * mutating [MutableLibrary]. You should take responsibility for managing their long-term * state. * @param interpretation The configuration to use for interpreting certain vague tags. This * should be configured by the user, if possible. */ - fun new(context: Context, storage: Storage, interpretation: Interpretation): Musikr = + fun new(context: Context, config: Config): Musikr = MusikrImpl( context, - storage, - ExploreStep.from(context, storage, interpretation), - ExtractStep.from(context, storage), - EvaluateStep.new(storage, interpretation)) + config, + ExploreStep.from(context, config), + ExtractStep.from(context, config), + EvaluateStep.new(config, config.interpretation)) } } @@ -111,37 +107,34 @@ sealed interface IndexingProgress { private class MusikrImpl( private val context: Context, - private val storage: Storage, + private val config: Config, private val exploreStep: ExploreStep, private val extractStep: ExtractStep, private val evaluateStep: EvaluateStep ) : Musikr { - override suspend fun run(query: Query, onProgress: suspend (IndexingProgress) -> Unit) = - coroutineScope { - var exploredCount = 0 - var extractedCount = 0 - val explored = - exploreStep - .explore(query) - .buffer(Channel.UNLIMITED) - .onStart { onProgress(IndexingProgress.Songs(0, 0)) } - .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } - val extracted = - extractStep - .extract(explored) - .buffer(Channel.UNLIMITED) - .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } - .onCompletion { onProgress(IndexingProgress.Indeterminate) } - val library = evaluateStep.evaluate(extracted) - LibraryResultImpl(storage, library) - } + override suspend fun run(onProgress: suspend (IndexingProgress) -> Unit) = coroutineScope { + var exploredCount = 0 + var extractedCount = 0 + val explored = + exploreStep + .explore() + .buffer(Channel.UNLIMITED) + .onStart { onProgress(IndexingProgress.Songs(0, 0)) } + .onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) } + val extracted = + extractStep + .extract(explored) + .buffer(Channel.UNLIMITED) + .onEach { onProgress(IndexingProgress.Songs(++extractedCount, exploredCount)) } + .onCompletion { onProgress(IndexingProgress.Indeterminate) } + val library = evaluateStep.evaluate(extracted) + LibraryResultImpl(config, library) + } } -private class LibraryResultImpl( - private val storage: Storage, - override val library: MutableLibrary -) : LibraryResult { +private class LibraryResultImpl(private val config: Config, override val library: MutableLibrary) : + LibraryResult { override suspend fun cleanup() { - storage.covers.cleanup(library.songs.mapNotNull { it.cover }) + config.storage.covers.cleanup(library.songs.mapNotNull { it.cover }) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt index 8c4c0e500..a6c940258 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/Cache.kt @@ -18,7 +18,7 @@ package org.oxycblt.musikr.cache -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.tag.parse.ParsedTags diff --git a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt index 6835dd40b..be5766dd1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/cache/db/DBCache.kt @@ -23,7 +23,7 @@ import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.MutableCache -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.tag.parse.ParsedTags diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt index aeb9b103c..4f704c5ff 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/Covers.kt @@ -20,7 +20,7 @@ package org.oxycblt.musikr.covers import android.os.ParcelFileDescriptor import java.io.InputStream -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt index 400d48112..5e7b8e257 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt @@ -22,7 +22,7 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt index ff2587b74..d25229d0a 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt @@ -23,7 +23,7 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.MemoryCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 96f969fad..9a7c20ade 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -31,7 +31,7 @@ import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.FDCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata private const val PREFIX = "mcf:" diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt index 05eedfe7d..d5c5de40b 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt @@ -24,7 +24,7 @@ import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.FDCover import org.oxycblt.musikr.covers.MemoryCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Metadata private const val PREFIX = "mcs:" diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt similarity index 89% rename from musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt index dc43e8dab..9261599dd 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFSEntries.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt @@ -1,6 +1,6 @@ /* * Copyright (c) 2025 Auxio Project - * DeviceFSEntries.kt is part of Auxio. + * FS.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 @@ -16,11 +16,15 @@ * along with this program. If not, see . */ -package org.oxycblt.musikr.fs.device +package org.oxycblt.musikr.fs import android.net.Uri import kotlinx.coroutines.Deferred -import org.oxycblt.musikr.fs.Path +import kotlinx.coroutines.flow.Flow + +interface FS { + fun explore(): Flow +} sealed interface DeviceFSEntry { val uri: Uri diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt index e27cbb9b9..0aae7d337 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Location.kt @@ -22,8 +22,8 @@ import android.content.Context import android.content.Intent 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.fs.saf.contentResolverSafe sealed class Location(val uri: Uri, val path: Path) { override fun equals(other: Any?) = other is Location && uri == other.uri diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt deleted file mode 100644 index 548c139c4..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * RateLimitedContentResolver.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.musikr.fs.device - -import android.content.ContentResolver -import android.database.Cursor -import android.net.Uri -import kotlin.math.min -import kotlinx.coroutines.delay -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.Semaphore -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.sync.withPermit - -/** - * A rate-limited wrapper around ContentResolver that uses a token bucket algorithm to limit the - * rate of queries. - * - * @param contentResolver The underlying ContentResolver to wrap - * @param maxTokens The maximum number of tokens in the bucket (burst capacity) - * @param refillRate The rate at which tokens are refilled per second - * @param maxConcurrency The maximum number of concurrent queries allowed - */ -internal class RateLimitedContentResolver( - private val contentResolver: ContentResolver, - private val maxTokens: Int = 1000, - private val refillRate: Double = 1000.0, // tokens per second - private val maxConcurrency: Int = 10 -) { - private val tokenBucket = TokenBucket(maxTokens, refillRate) - private val concurrencySemaphore = Semaphore(maxConcurrency) - - /** - * A rate-limited version of ContentResolver.query This is a suspend function that should be - * called from a coroutine - */ - suspend fun query( - uri: Uri, - projection: Array?, - selection: String?, - selectionArgs: Array?, - sortOrder: String? - ): Cursor? = - concurrencySemaphore.withPermit { - tokenBucket.acquire() - contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) - } - - /** - * A shortcut for querying the database with automatic resource management. Rate-limited version - * of the useQuery extension function. This is a suspend function that should be called from a - * coroutine - */ - suspend inline fun useQuery( - uri: Uri, - projection: Array, - selector: String? = null, - args: Array? = null, - sortOrder: String? = null, - crossinline block: suspend (Cursor) -> R - ): R = - concurrencySemaphore.withPermit { - tokenBucket.acquire() - contentResolver.useQuery(uri, projection, selector, args, sortOrder) { cursor -> - block(cursor) - } - } - - /** Token bucket implementation for rate limiting */ - internal class TokenBucket( - private val maxTokens: Int, - private val refillRate: Double // tokens per second - ) { - private var tokens: Double = maxTokens.toDouble() - private var lastRefillTime: Long = System.currentTimeMillis() - private val mutex = Mutex() - private val tokenWaitTime = (1000.0 / refillRate).toLong() // milliseconds per token - - suspend fun acquire() { - mutex.withLock { - refill() - - // Wait until a token is available - while (tokens < 1.0) { - val waitTime = ((1.0 - tokens) * tokenWaitTime).toLong() - delay(waitTime) - refill() - } - - tokens -= 1.0 - } - } - - private fun refill() { - val now = System.currentTimeMillis() - val timePassed = now - lastRefillTime - val tokensToAdd = (timePassed / 1000.0) * refillRate - - if (tokensToAdd > 0) { - tokens = min(tokens + tokensToAdd, maxTokens.toDouble()) - lastRefillTime = now - } - } - } -} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt index 92b7f825f..a412da501 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/path/DocumentPathFactory.kt @@ -26,8 +26,8 @@ import java.io.File import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Volume -import org.oxycblt.musikr.fs.device.contentResolverSafe -import org.oxycblt.musikr.fs.device.useQuery +import org.oxycblt.musikr.fs.saf.contentResolverSafe +import org.oxycblt.musikr.fs.saf.useQuery /** * A factory for parsing the reverse-engineered format of the URIs obtained from document picker. diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt similarity index 87% rename from musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt index ac8a829ce..124b93088 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/QueryUtil.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/QueryUtil.kt @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -package org.oxycblt.musikr.fs.device +package org.oxycblt.musikr.fs.saf import android.content.ContentResolver import android.content.Context @@ -30,15 +30,6 @@ import android.net.Uri internal val Context.contentResolverSafe: ContentResolver get() = applicationContext.contentResolver -internal val Context.rateLimitedContentResolver: RateLimitedContentResolver - get() = - RateLimitedContentResolver( - contentResolver = contentResolverSafe, - maxTokens = 100, // Maximum burst capacity - refillRate = 1000.0, // 1000 queries per second (100 queries per 100ms) - maxConcurrency = 10 // Maximum concurrent queries - ) - /** * A shortcut for querying the [ContentResolver] database. * diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt similarity index 84% rename from musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt index 97d1f9d87..9ff2c9c44 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/device/DeviceFS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt @@ -1,6 +1,6 @@ /* - * Copyright (c) 2024 Auxio Project - * DeviceFS.kt is part of Auxio. + * Copyright (c) 2025 Auxio Project + * SAF.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 @@ -16,8 +16,9 @@ * along with this program. If not, see . */ -package org.oxycblt.musikr.fs.device +package org.oxycblt.musikr.fs.saf +import android.content.ContentResolver import android.content.Context import android.net.Uri import android.provider.DocumentsContract @@ -30,24 +31,17 @@ import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow -import org.oxycblt.musikr.Query +import org.oxycblt.musikr.fs.DeviceDirectory +import org.oxycblt.musikr.fs.DeviceFSEntry +import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.FS +import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Path -internal interface DeviceFS { - fun explore(query: Query): Flow - - companion object { - fun from(context: Context, withHidden: Boolean): DeviceFS = - DeviceFSImpl(context.rateLimitedContentResolver, withHidden) - } -} - @OptIn(ExperimentalCoroutinesApi::class) -private class DeviceFSImpl( - private val contentResolver: RateLimitedContentResolver, - private val withHidden: Boolean -) : DeviceFS { - override fun explore(query: Query): Flow = +class SAF +private constructor(private val contentResolver: ContentResolver, private val query: Query) : FS { + override fun explore(): Flow = query.source.asFlow().flatMapMerge { location -> exploreDirectoryImpl( location.uri, @@ -57,7 +51,7 @@ private class DeviceFSImpl( query.exclude.mapTo(mutableSetOf()) { it.uri }) } - private suspend fun exploreDirectoryImpl( + private fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, relativePath: Path, @@ -85,7 +79,7 @@ private class DeviceFSImpl( val displayName = cursor.getString(displayNameIndex) // Skip hidden files/directories if ignoreHidden is true - if (!withHidden && displayName.startsWith(".")) { + if (!query.withHidden && displayName.startsWith(".")) { continue } @@ -122,8 +116,16 @@ private class DeviceFSImpl( } } - private companion object { - val PROJECTION = + data class Query( + val source: List, + val exclude: List, + val withHidden: Boolean + ) + + companion object { + fun from(context: Context, query: Query) = SAF(context.contentResolverSafe, query) + + private val PROJECTION = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt index b9f57c16f..f070f0c69 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt @@ -23,7 +23,7 @@ import android.content.Context import java.io.FileInputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile internal interface MetadataExtractor { suspend fun extract(deviceFile: DeviceFile): Metadata? diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt index 213e68ea7..c7486e220 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt @@ -21,7 +21,7 @@ package org.oxycblt.musikr.metadata import android.util.Log import java.io.FileInputStream import java.nio.ByteBuffer -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile internal class NativeInputStream(private val deviceFile: DeviceFile, fis: FileInputStream) { private val channel = fis.channel diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt index e0b48ee00..d5105f3a8 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt @@ -19,7 +19,7 @@ package org.oxycblt.musikr.metadata import java.io.FileInputStream -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile internal object TagLibJNI { init { diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt index 59e4c9438..0a417d5da 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/EvaluateStep.kt @@ -20,9 +20,9 @@ package org.oxycblt.musikr.pipeline import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filterIsInstance +import org.oxycblt.musikr.Config import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.MutableLibrary -import org.oxycblt.musikr.Storage import org.oxycblt.musikr.graph.MusicGraph import org.oxycblt.musikr.model.LibraryFactory import org.oxycblt.musikr.playlist.db.StoredPlaylists @@ -33,11 +33,11 @@ internal interface EvaluateStep { suspend fun evaluate(extractedMusic: Flow): MutableLibrary companion object { - fun new(storage: Storage, interpretation: Interpretation): EvaluateStep = + fun new(config: Config, interpretation: Interpretation): EvaluateStep = EvaluateStepImpl( TagInterpreter.new(interpretation), PlaylistInterpreter.new(interpretation), - storage.storedPlaylists, + config.storage.storedPlaylists, LibraryFactory.new()) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt index c90f4600f..8bfccf723 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExploreStep.kt @@ -30,46 +30,32 @@ import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge -import org.oxycblt.musikr.Interpretation -import org.oxycblt.musikr.Query +import org.oxycblt.musikr.Config import org.oxycblt.musikr.Storage -import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.CacheResult 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.device.DeviceFS -import org.oxycblt.musikr.playlist.db.StoredPlaylists +import org.oxycblt.musikr.fs.FS import org.oxycblt.musikr.playlist.m3u.M3U internal interface ExploreStep { - fun explore(query: Query): Flow + fun explore(): Flow companion object { - fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep = - ExploreStepImpl( - DeviceFS.from(context = context, withHidden = interpretation.withHidden), - storage.cache, - storage.covers, - storage.storedPlaylists) + fun from(context: Context, config: Config): ExploreStep = + ExploreStepImpl(config.fs, config.storage) } } -private class ExploreStepImpl( - private val deviceFS: DeviceFS, - private val cache: Cache, - private val covers: Covers, - private val storedPlaylists: StoredPlaylists -) : ExploreStep { - override fun explore(query: Query): Flow { +private class ExploreStepImpl(private val fs: FS, private val storage: Storage) : ExploreStep { + override fun explore(): Flow { val addingMs = System.currentTimeMillis() return merge( - deviceFS - .explore(query) + fs.explore() .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)) { + when (val cacheResult = storage.cache.read(file)) { is CacheResult.Hit -> NeedsCover(cacheResult.song) is CacheResult.Stale -> Finalized(NewSong(cacheResult.file, cacheResult.addedMs)) @@ -83,7 +69,7 @@ private class ExploreStepImpl( is Finalized -> it is NeedsCover -> { when (val coverResult = - it.cachedSong.coverId?.let { id -> covers.obtain(id) }) { + it.cachedSong.coverId?.let { id -> storage.covers.obtain(id) }) { is CoverResult.Hit -> Finalized(it.cachedSong.toRawSong(coverResult.cover)) null -> Finalized(it.cachedSong.toRawSong(null)) @@ -96,7 +82,7 @@ private class ExploreStepImpl( .map { it.explored } .flowOn(Dispatchers.IO) .buffer(Channel.UNLIMITED), - flow { emitAll(storedPlaylists.read().asFlow()) } + flow { emitAll(storage.storedPlaylists.read().asFlow()) } .map { RawPlaylist(it) } .flowOn(Dispatchers.IO) .buffer(Channel.UNLIMITED)) diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt index 12e17e03e..05f2c8154 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/ExtractStep.kt @@ -26,7 +26,7 @@ import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onCompletion -import org.oxycblt.musikr.Storage +import org.oxycblt.musikr.Config import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.MutableCache import org.oxycblt.musikr.covers.Cover @@ -40,9 +40,12 @@ internal interface ExtractStep { fun extract(nodes: Flow): Flow companion object { - fun from(context: Context, storage: Storage): ExtractStep = + fun from(context: Context, config: Config): ExtractStep = ExtractStepImpl( - MetadataExtractor.from(context), TagParser.new(), storage.cache, storage.covers) + MetadataExtractor.from(context), + TagParser.new(), + config.storage.cache, + config.storage.covers) } } diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt index 20cf30221..b151db5b1 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt @@ -19,7 +19,7 @@ package org.oxycblt.musikr.pipeline import org.oxycblt.musikr.covers.Cover -import org.oxycblt.musikr.fs.device.DeviceFile +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.playlist.PlaylistFile import org.oxycblt.musikr.tag.parse.ParsedTags diff --git a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt index 62efd7ca9..8f80ff48e 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/playlist/ExternalPlaylistManager.kt @@ -23,8 +23,8 @@ import android.net.Uri import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.fs.Components import org.oxycblt.musikr.fs.Path -import org.oxycblt.musikr.fs.device.contentResolverSafe import org.oxycblt.musikr.fs.path.DocumentPathFactory +import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.playlist.m3u.M3U /** diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt index 246892685..fd4bac0dd 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt @@ -20,8 +20,8 @@ package org.oxycblt.musikr.tag.interpret import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Music +import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.fs.Format -import org.oxycblt.musikr.fs.device.DeviceFile import org.oxycblt.musikr.pipeline.RawSong import org.oxycblt.musikr.tag.Disc import org.oxycblt.musikr.tag.Name From 128504250a37e74e604b16e2f3bae7ddd38325ad Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 21 Jun 2025 23:45:41 -0600 Subject: [PATCH 11/42] musikr: implement mediastore backend --- app/src/main/AndroidManifest.xml | 3 + .../oxycblt/auxio/music/MusicRepository.kt | 5 +- .../src/main/java/org/oxycblt/musikr/fs/FS.kt | 6 +- .../main/java/org/oxycblt/musikr/fs/Path.kt | 2 +- .../musikr/fs/mediastore/MediaStore.kt | 208 ++++++++++++++++++ .../java/org/oxycblt/musikr/fs/saf/SAF.kt | 3 +- 6 files changed, 219 insertions(+), 8 deletions(-) create mode 100644 musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index ecdfc44e2..2d0499edd 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,9 @@ + + + diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index b3a87cead..ffe9abe3c 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -41,7 +41,7 @@ import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Song import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.MutableCache -import org.oxycblt.musikr.fs.saf.SAF +import org.oxycblt.musikr.fs.mediastore.MediaStoreFS import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming import org.oxycblt.musikr.tag.interpret.Separators @@ -394,7 +394,8 @@ constructor( val newRevision = currentRevision?.takeIf { withCache } ?: UUID.randomUUID() val cache = if (withCache) cache else WriteOnlyMutableCache(cache) val covers = settingCovers.mutate(context, newRevision) - val fs = SAF.from(context, SAF.Query(locations, excludedLocations, withHidden)) + // val fs = SAF.from(context, SAF.Query(locations, excludedLocations, withHidden)) + val fs = MediaStoreFS.from(context) val storage = Storage(cache, covers, storedPlaylists) val interpretation = Interpretation(nameFactory, separators) val config = Config(fs, storage, interpretation) diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt index 9261599dd..0e7201b03 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt @@ -27,15 +27,15 @@ interface FS { } sealed interface DeviceFSEntry { - val uri: Uri + val uri: Uri? val path: Path } data class DeviceDirectory( - override val uri: Uri, + override val uri: Uri?, override val path: Path, val parent: Deferred?, - var children: List + var children: List ) : DeviceFSEntry data class DeviceFile( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt index f889d516b..99630df25 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/Path.kt @@ -154,7 +154,7 @@ value class Components private constructor(val components: List) { fun containing(other: Components) = Components(other.components.drop(components.size)) - internal companion object { + companion object { /** * Parses a path string into a [Components] instance by the unix path separator (/). * diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt new file mode 100644 index 000000000..fd810254a --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2025 Auxio Project + * MediaStore.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.musikr.fs.mediastore + +import android.content.Context +import android.net.Uri +import android.provider.MediaStore +import androidx.core.database.getStringOrNull +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.yield +import org.oxycblt.musikr.fs.DeviceDirectory +import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.FS +import org.oxycblt.musikr.fs.Path +import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter +import org.oxycblt.musikr.fs.path.VolumeManager +import org.oxycblt.musikr.fs.saf.contentResolverSafe +import org.oxycblt.musikr.fs.saf.useQuery + +/** + * MediaStore implementation of [FS] that queries the Android MediaStore database for audio files + * and yields them as [DeviceFile] instances. + */ +class MediaStoreFS +private constructor( + private val context: Context, + private val volumeManager: VolumeManager, + private val excludeNonMusic: Boolean = true +) : FS { + private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) + + private fun buildDirectoryHierarchy(files: List) { + // Map to store directories by their path + val directoryMap = mutableMapOf() + + // Group files by their parent directory path + val filesByParent = files.groupBy { it.path.directory } + + // First pass: Create all directories and complete file parent deferreds + for ((dirPath, dirFiles) in filesByParent) { + val directory = + directoryMap.getOrPut(dirPath) { + // Create parent deferred for this directory + val parentDeferred = + if (dirPath.components.components.isEmpty()) { + // Root directory has no parent + null + } else { + CompletableDeferred() + } + + DeviceDirectory( + uri = null, // Directories don't have MediaStore URIs + path = dirPath, + parent = parentDeferred, + children = dirFiles) + } + + // Update children if directory already existed + if (directory.children.isEmpty()) { + directory.children = dirFiles + } + + // Complete parent deferreds for all files in this directory + dirFiles.forEach { file -> + (file.parent as CompletableDeferred).complete(directory) + } + } + + // Second pass: Create any missing parent directories + val directories = directoryMap.values.toList() + for (directory in directories) { + var currentPath = directory.path + while (currentPath.components.components.isNotEmpty()) { + val parentPath = currentPath.directory + if (!directoryMap.containsKey(parentPath)) { + val grandParentDeferred = + if (parentPath.components.components.isEmpty()) { + null + } else { + CompletableDeferred() + } + + directoryMap[parentPath] = + DeviceDirectory( + uri = null, + path = parentPath, + parent = grandParentDeferred, + children = emptyList()) + } + currentPath = parentPath + } + } + + // Third pass: Complete all directory parent deferreds + for (directory in directoryMap.values) { + val parentDeferred = directory.parent as? CompletableDeferred + if (parentDeferred != null && !parentDeferred.isCompleted) { + val parentPath = directory.path.directory + val parentDirectory = directoryMap[parentPath] + if (parentDirectory != null) { + parentDeferred.complete(parentDirectory) + } + } + } + } + + @OptIn(ExperimentalCoroutinesApi::class) + override fun explore(): Flow = flow { + val projection = BASE_PROJECTION + pathInterpreterFactory.projection + var selector = BASE_SELECTOR + val args = mutableListOf() + + // Filter out audio that is not music, if enabled + if (excludeNonMusic) { + selector += " AND ${MediaStore.Audio.AudioColumns.IS_MUSIC}=1" + } + + // Collect all files and track unique directories + val allFiles = mutableListOf() + + context.contentResolverSafe.useQuery( + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, + projection, + selector, + args.toTypedArray()) { cursor -> + val pathInterpreter = pathInterpreterFactory.wrap(cursor) + val idIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns._ID) + val mimeTypeIndex = + cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.MIME_TYPE) + val sizeIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.SIZE) + val dateModifiedIndex = + cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATE_MODIFIED) + + while (cursor.moveToNext()) { + val path = pathInterpreter.extract() ?: continue + + val id = cursor.getLong(idIndex) + val uri = + Uri.withAppendedPath( + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id.toString()) + val mimeType = cursor.getStringOrNull(mimeTypeIndex) ?: "audio/*" + val size = cursor.getLong(sizeIndex) + val dateModified = + cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds + + // Create file with empty deferred parent + val parentDeferred = CompletableDeferred() + val deviceFile = + DeviceFile( + uri = uri, + path = path, + modifiedMs = dateModified, + mimeType = mimeType, + size = size, + parent = parentDeferred) + + allFiles.add(deviceFile) + emit(deviceFile) + yield() + } + } + + // Build directory hierarchy + buildDirectoryHierarchy(allFiles) + } + + companion object { + fun from(context: Context) = + MediaStoreFS( + context = context, + volumeManager = VolumeManager.from(context), + excludeNonMusic = true) + + /** + * The base selector that works across all versions of android. Excludes files with zero + * size. + */ + private const val BASE_SELECTOR = "NOT ${MediaStore.Audio.Media.SIZE}=0" + + /** The base projection that works across all versions of android. */ + private val BASE_PROJECTION = + arrayOf( + MediaStore.Audio.AudioColumns._ID, + MediaStore.Audio.AudioColumns.DATE_MODIFIED, + MediaStore.Audio.AudioColumns.SIZE, + MediaStore.Audio.AudioColumns.MIME_TYPE) + } +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt index 9ff2c9c44..7936b6ac3 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt @@ -32,7 +32,6 @@ import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow import org.oxycblt.musikr.fs.DeviceDirectory -import org.oxycblt.musikr.fs.DeviceFSEntry import org.oxycblt.musikr.fs.DeviceFile import org.oxycblt.musikr.fs.FS import org.oxycblt.musikr.fs.Location @@ -62,7 +61,7 @@ private constructor(private val contentResolver: ContentResolver, private val qu val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) val directoryDeferred = CompletableDeferred() val recursive = mutableListOf>() - val children = mutableListOf() + val children = mutableListOf() contentResolver.useQuery(uri, PROJECTION) { cursor -> val childUriIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) From 96761ac9903502132856e679b58282a6771a18f6 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sat, 28 Jun 2025 18:28:13 -0600 Subject: [PATCH 12/42] info: agent files, mk 2 --- CLAUDE.md | 216 ++++++++++++++++----------- musikr/ARCHITECTURE.md | 220 +++++++++++++-------------- musikr/DATA_FLOW.md | 306 ++++++++++++++++++++++++++++++++++++++ musikr/MODULES.md | 249 +++++++++++++++++++++++++++++++ musikr/QUICK_REFERENCE.md | 149 +++++++++++++++++++ 5 files changed, 938 insertions(+), 202 deletions(-) create mode 100644 musikr/DATA_FLOW.md create mode 100644 musikr/MODULES.md create mode 100644 musikr/QUICK_REFERENCE.md diff --git a/CLAUDE.md b/CLAUDE.md index 7ebb3c146..53bcc322b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,120 +4,162 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -Auxio is a modern Android music player written in Kotlin that emphasizes simplicity and performance. It uses Media3 ExoPlayer for playback and includes a custom native music indexing library called musikr. +Auxio is a simple, rational music player for Android built on Media3 ExoPlayer. It features gapless playback, ReplayGain support, Android Auto integration, and advanced music indexing capabilities. -## Build System & Commands +## Essential Build Commands ### Prerequisites -- `cmake` and `ninja-build` must be installed before building -- Project uses git submodules - clone with `git clone --recurse-submodules` -- **Cannot build on Windows** - requires Unix-based system for Media3 build scripts +- Unix-based system (cannot build on Windows) +- Install `cmake` and `ninja-build` +- Clone with submodules: `git clone --recurse-submodules` -### Common Build Commands +### Build Commands ```bash -# Build debug version +# Build debug APK ./gradlew assembleDebug -# Build release version +# Build release APK ./gradlew assembleRelease -# Run tests -./gradlew test +# Clean build +./gradlew clean build -# Run connected tests -./gradlew connectedAndroidTest - -# Code formatting (Spotless) -./gradlew spotlessApply - -# Check code formatting -./gradlew spotlessCheck +# Install debug build on device +./gradlew installDebug ``` -### Development Modules -- `app/` - Main Android application -- `musikr/` - Native music indexing library with TagLib integration -- `media/` - Patched Media3 ExoPlayer libraries (git submodule) +### Code Quality Commands +```bash +# Check code formatting (MUST pass before committing) +./gradlew spotlessCheck + +# Apply code formatting fixes +./gradlew spotlessApply + +# Run Android lint +./gradlew lint + +# Run lint with automatic fixes +./gradlew lintFix +``` + +### Testing Commands +```bash +# Run unit tests +./gradlew test + +# Run debug unit tests +./gradlew testDebugUnitTest + +# Run musikr module tests specifically +./gradlew musikr:testDebug + +# Run instrumentation tests (requires device/emulator) +./gradlew connectedAndroidTest +``` + +### Development Workflow +```bash +# Before committing: format code and run checks +./gradlew spotlessApply +./gradlew check + +# Run a single test class +./gradlew test --tests "org.oxycblt.auxio.YourTestClass" + +# Run a single test method +./gradlew test --tests "org.oxycblt.auxio.YourTestClass.yourTestMethod" +``` ## Architecture Overview -### Core Architecture Pattern -- **MVVM** with ViewModels for each major screen (Home, Detail, Playback, Search) -- **Repository Pattern** - MusicRepository as single source of truth for music data -- **Dependency Injection** - Hilt/Dagger for modular dependency management -- **Single Activity Architecture** with Navigation Components -- **Service-Oriented** background music processing +### High-Level Architecture +- **Pattern**: MVVM (Model-View-ViewModel) with Dagger Hilt dependency injection +- **Navigation**: Single Activity architecture with Navigation Component +- **UI**: Material Design 3 with edge-to-edge display +- **Data**: Repository pattern with Room database and custom Musikr library +- **Playback**: MediaBrowserServiceCompat with vendored Media3/ExoPlayer -### Key Modules & Components +### Key Components -#### Music Management (`app/src/main/java/org/oxycblt/auxio/music/`) -- `MusicRepository` - Central music library state management -- `MusicViewModel` - UI layer for music data access -- `service/` - MediaBrowserServiceCompat integration -- `shim/` - Abstraction layer for musikr integration +#### Service Architecture +- `AuxioService` - Main MediaBrowserService for background playback +- `PlaybackServiceFragment` - Handles all playback operations +- `MusicServiceFragment` - Manages music browsing and library -#### Playback Engine (`app/src/main/java/org/oxycblt/auxio/playback/`) -- `PlaybackViewModel` - Main playback UI interface -- `PlaybackStateManager` - Core playback state management -- `service/` - Background ExoPlayer integration -- `queue/` - Playback queue management -- `persist/` - Playback state persistence (Room database) -- `replaygain/` - Audio processing for volume normalization +#### Data Layer +- `MusicRepository` - Primary interface for music data access +- `PersistenceRepository` - Handles playback state and playlists +- `Musikr` - Custom music indexing library (separate module) + - Bypasses MediaStore limitations + - Supports advanced metadata and tags + - Background indexing with progress -#### UI Structure (`app/src/main/java/org/oxycblt/auxio/`) -- `home/` - Main library browsing with customizable tabs -- `detail/` - Album, artist, genre, and playlist detail views -- `search/` - Music search functionality -- `list/` - Shared list components with sorting/filtering -- `ui/` - Custom UI components, theming, animations +#### UI Layer Structure +``` +app/src/main/java/org/oxycblt/auxio/ +├── MainActivity.kt # Single activity host +├── MainFragment.kt # Main container with bottom sheets +├── home/ # Home screen tabs (songs, albums, artists, etc.) +├── detail/ # Detail screens for albums/artists +├── playback/ # Playback UI and controls +├── search/ # Search functionality +├── settings/ # Preferences screens +├── list/ # Reusable list components +└── music/ # Music data models and repository +``` -#### Native Music Library (`musikr/`) -- **Pipeline-based indexing** - Multi-stage scanning (Explore → Extract → Evaluate) -- **TagLib integration** - Native C++ metadata extraction -- **File system caching** - Device storage access optimization -- **Cover art management** - Embedded and external cover support +#### State Management +- StateFlow/MutableStateFlow for reactive state +- Shared ViewModels between fragments +- Event wrapper pattern for one-time UI events +- Lifecycle-aware observers -### Data Flow -1. musikr scans and indexes music files from device storage -2. MusicRepository manages indexed library and exposes to UI -3. ViewModels provide reactive state for UI components using StateFlow -4. PlaybackService handles audio playback via ExoPlayer -5. UI observes ViewModels and updates reactively +### Navigation Flow +1. `MainActivity` hosts all navigation +2. Two navigation graphs: `inner.xml` (main) and `outer.xml` (onboarding) +3. Bottom sheet for playback UI +4. Dialog destinations for popups -## Code Conventions +### Dependency Injection Setup +- `@HiltAndroidApp` on Auxio application class +- `@AndroidEntryPoint` on activities/fragments +- Modules: `MusicModule`, `PlaybackModule`, `UIModule` +- Scoped with `@Singleton` for app-wide instances -### Language & Libraries -- **Kotlin** - Primary language with coroutines for async operations -- **Hilt/Dagger** - Dependency injection -- **Room** - Local database for persistence -- **Navigation Components** - Fragment navigation -- **ViewBinding** - Type-safe view access -- **StateFlow/LiveData** - Reactive state management -- **Coil** - Image loading for cover art +## Important Development Notes ### Code Style -- Uses Spotless with ktfmt Dropbox style formatting -- License header required (see NOTICE file) -- C++ code uses Eclipse CDT formatting (eclipse-cdt.xml) +- Kotlin code formatted with ktfmt (Dropbox style) +- C++ code uses Eclipse CDT formatting +- Spotless enforces formatting automatically +- License headers required (enforced by Spotless) -## Testing +### Git Workflow +- Default branch: `dev` (development) +- PRs should target `dev` branch +- `master` contains stable releases only -### Test Structure -- Unit tests: `src/test/` directories -- Integration tests: `src/androidTest/` directories -- musikr module includes Robolectric tests +### Architectural Constraints +- Stick to F-Droid inclusion guidelines +- No proprietary dependencies +- Feature additions unlikely to be accepted +- Major UI changes discouraged -### Test Dependencies -- JUnit 4 for unit testing -- MockK for mocking -- Robolectric for Android unit tests -- Espresso for UI tests +### Testing Requirements +- Test all changes thoroughly +- Unit tests for business logic +- Consider edge cases for music metadata +- Test on different Android versions (min SDK 24) -## Key Development Notes +### Key Libraries +- AndroidX Navigation, Room, Media3 +- Dagger Hilt for DI +- Kotlin Coroutines for async +- Coil for image loading +- Material Design Components 3 -- **Custom Media3**: Uses patched Media3 ExoPlayer for enhanced playback features -- **Native Dependencies**: musikr module builds TagLib from source during compilation -- **Permission Handling**: Requires storage permissions for music file access -- **Background Services**: Foreground service for continuous music playback -- **Widget Support**: Multiple widget layouts with automatic sizing adaptation -- **ReplayGain**: Full support for MP3, FLAC, OGG, OPUS, and MP4 files \ No newline at end of file +### Custom Modifications +- Vendored/patched Media3 in `media/` directory +- Custom patches for ExoPlayer features +- Modified libraries shouldn't be updated directly \ No newline at end of file diff --git a/musikr/ARCHITECTURE.md b/musikr/ARCHITECTURE.md index cbbc8a7ca..28d6149b1 100644 --- a/musikr/ARCHITECTURE.md +++ b/musikr/ARCHITECTURE.md @@ -1,135 +1,125 @@ -# Musikr Architecture +# Musikr Architecture Overview -## Overview +Musikr is a highly opinionated, multi-threaded music loading library for Android that bypasses Android's MediaStore and uses the Storage Access Framework (SAF) with TagLib for enhanced music indexing capabilities. -Musikr is a highly opinionated multithreaded music loader that provides advanced music functionality for Auxio. It bypasses Android's MediaStore to directly access music files using the Storage Access Framework (SAF) and [TagLib](https://taglib.org/) for metadata extraction. +## Core Design Principles -## Core Components +1. **Stateless API**: Side-effects are contained within the Storage layer +2. **No Defaults**: All parameters must be explicitly configured +3. **Pipeline Architecture**: Three-step processing pipeline for music loading +4. **Native Integration**: JNI bridge to TagLib for metadata extraction +5. **Coroutine-Based**: Uses Kotlin coroutines for async operations -### Pipeline Architecture +## High-Level Architecture -Musikr uses a three-stage pipeline for music indexing: - -1. **Explore Step** - Discovers music files on the device -2. **Extract Step** - Extracts metadata from discovered files -3. **Evaluate Step** - Processes extracted data to build the music library - -```mermaid -graph LR - A[Music Locations] --> B[Explore Step] - B --> C[Extract Step] - C --> D[Evaluate Step] - D --> E[Library] - - subgraph Pipeline - B - C - D - end +``` +┌─────────────────────────────────────────────────────────────┐ +│ Application Layer │ +│ (Auxio or other apps) │ +└───────────────────────────┬─────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Musikr API │ +│ (Musikr.kt interface) │ +└───────────────────────────┬─────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Pipeline Architecture │ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ ExploreStep │ → │ ExtractStep │ → │ EvaluateStep │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +└─────────────────────────────────────────────────────────────┘ + │ + ┌───────────┴───────────┐ + │ │ + ▼ ▼ +┌──────────────────────┐ ┌──────────────────────────────┐ +│ Storage Layer │ │ Native Layer (JNI) │ +│ - Cache │ │ - TagLib integration │ +│ - Covers │ │ - Metadata extraction │ +│ - Playlists │ │ - Format support │ +└──────────────────────┘ └──────────────────────────────┘ ``` -### Key Interfaces +## Pipeline Steps -- **Musikr** - Main entry point for the library -- **Storage** - Manages persistent storage needs -- **Library** - Represents the loaded music collection -- **MutableLibrary** - Modifiable version of the library +### 1. ExploreStep +- **Purpose**: Discover music files on the device +- **Process**: + - Uses FS module to explore file system via SAF + - Filters for audio MIME types and playlists + - Checks cache for previously indexed files + - Manages cover art retrieval +- **Output**: Stream of `Explored` items (songs/playlists to process) -## Module Structure +### 2. ExtractStep +- **Purpose**: Extract metadata from discovered files +- **Process**: + - Uses JNI bridge to TagLib for metadata extraction + - Handles multiple tag formats (ID3v1/v2, MP4, Xiph, etc.) + - Extracts audio properties (bitrate, duration, etc.) + - Manages cover art extraction +- **Output**: Stream of `Extracted` items with full metadata -### 1. File System (`fs` package) -- **Location.Opened** - Represents a location to search for music -- **DeviceFS** - Provides access to device storage -- **FileTreeCache** - Caches filesystem structure for faster indexing +### 3. EvaluateStep +- **Purpose**: Build the music graph from extracted metadata +- **Process**: + - Creates relationships between songs, albums, artists, genres + - Resolves naming conflicts and duplicates + - Applies user interpretation preferences + - Builds final library structure +- **Output**: Complete `MutableLibrary` with all relationships -### 2. Pipeline (`pipeline` package) -- **ExploreStep** - Discovers music files on the device -- **ExtractStep** - Extracts metadata from discovered files -- **EvaluateStep** - Processes extracted data to build the library -- **PipelineItem** - Data items flowing through the pipeline +## Key Components -### 3. Metadata (`metadata` package) -- **Metadata** - Extracted file metadata -- **MetadataExtractor** - Extracts metadata using TagLib -- **TagLibJNI** - JNI bridge to native TagLib library +### Config & Storage +- **Config**: Main configuration container + - `fs`: File system access configuration + - `storage`: Persistent storage components + - `interpretation`: Tag interpretation rules -### 4. Tag Processing (`tag` package) -- **TagParser** - Parses raw tag data into structured format -- **TagInterpreter** - Interprets tags based on user preferences -- **ParsedTags** - Represents parsed metadata tags +- **Storage**: Side-effect laden components + - `cache`: Metadata caching (Room database) + - `covers`: Cover art storage and retrieval + - `storedPlaylists`: User playlist management -### 5. Model (`model` package) -- **LibraryImpl** - Implementation of the music library -- **SongImpl**, **AlbumImpl**, **ArtistImpl**, **GenreImpl** - Music entity implementations -- **LibraryFactory** - Creates library instances from pipeline data +### Data Models +- **Music**: Base interface for all music items + - Uses UID system for unique identification + - Supports MusicBrainz IDs +- **Song**: Individual track with full metadata +- **Album**: Collection of songs (includes EPs, singles, etc.) +- **Artist**: Can have explicit (album artist) and implicit (track artist) albums +- **Genre**: Grouping by musical genre +- **Playlist**: User-created or imported playlists -### 6. Covers (`covers` package) -- **Covers** - Interface for album cover management -- **EmbeddedCovers** - Extracts covers embedded in music files -- **FSCovers** - Discovers cover art in the filesystem -- **StoredCovers** - Manages persistent storage of covers +### File System (FS) +- Abstraction over Android's Storage Access Framework +- Supports multiple storage locations +- Handles permissions and URI management -### 7. Cache (`cache` package) -- **Cache** - Caches processed music data -- **DBCache** - Database implementation of caching - -### 8. Playlist (`playlist` package) -- **PlaylistFile** - Represents a playlist file -- **ExternalPlaylistManager** - Manages external playlist files -- **PlaylistInterpreter** - Interprets playlist formats - -## Native Component - -Musikr includes a native component built with TagLib for fast and accurate metadata extraction: - -```mermaid -graph TD - A[TagLibJNI] --> B[JNI Bridge] - B --> C[TagLib Library] - C --> D[Music File Metadata] -``` - -### Native Files (`cpp` directory) -- **taglib_jni.cpp** - Main JNI implementation -- **JMetadataBuilder** - Builds metadata objects from TagLib -- **JTagMap** - Maps between Java and C++ tag structures -- **JInputStream** - Input stream adapter for TagLib - -## Data Flow - -```mermaid -sequenceDiagram - participant User - participant Musikr - participant ExploreStep - participant ExtractStep - participant EvaluateStep - participant Storage - - User->>Musikr: run(locations) - Musikr->>ExploreStep: explore(locations) - ExploreStep->>Storage: Read cache - ExploreStep-->>Musikr: Explored files - Musikr->>ExtractStep: extract(explored) - ExtractStep->>TagLibJNI: Extract metadata - ExtractStep-->>Musikr: Extracted metadata - Musikr->>EvaluateStep: evaluate(extracted) - EvaluateStep->>Storage: Store processed data - EvaluateStep-->>Musikr: Library - Musikr-->>User: LibraryResult -``` +### Native Layer (C++) +- TagLib integration for metadata extraction +- JNI wrappers for Java/Kotlin interop +- Support for various audio formats +- Custom patches for enhanced functionality ## Threading Model +- **Coroutine-based**: All operations use Kotlin coroutines +- **Multi-threaded extraction**: Parallel metadata extraction +- **Buffered channels**: For efficient pipeline communication +- **Dispatcher control**: Explicit IO dispatcher usage -Musikr uses Kotlin Coroutines for concurrent processing: +## Error Handling +- **Pipeline exceptions**: Custom exception types +- **Graceful degradation**: Continue on individual file errors +- **Logging**: Comprehensive error logging +- **Cache invalidation**: Automatic stale cache detection -- Pipeline stages use `flatMapMerge` and `distributedMap` for parallel processing -- Bounded buffer channels manage backpressure -- IO operations are dispatched to `Dispatchers.IO` - -## Best Practices for Extension - -1. The API is minimized and unstable - be prepared to fork and modify -2. No defaults are provided - carefully consider parameter choices -3. Musikr is stateless except for Storage - manage long-term state yourself -4. When adding functionality, follow the pipeline architecture pattern \ No newline at end of file +## Performance Optimizations +- **Caching**: Aggressive metadata caching +- **Parallel processing**: Multi-threaded file processing +- **Lazy evaluation**: On-demand cover loading +- **Memory efficiency**: Streaming pipeline architecture \ No newline at end of file diff --git a/musikr/DATA_FLOW.md b/musikr/DATA_FLOW.md new file mode 100644 index 000000000..43b6f6df2 --- /dev/null +++ b/musikr/DATA_FLOW.md @@ -0,0 +1,306 @@ +# Musikr Data Flow Diagram + +This document illustrates how data flows through the Musikr music loading pipeline from file discovery to final library creation. + +## Overview Flow + +``` +┌─────────────────┐ +│ User Request │ +│ Musikr.run() │ +└────────┬────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ EXPLORE PHASE │ +│ │ +│ File System ──► SAF APIs ──► Audio Files │ +│ │ │ │ +│ └──► Cached Files ◄─────────┘ │ +│ │ │ +│ ▼ │ +│ Cover Cache ──► Explored Items │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ EXTRACT PHASE │ +│ │ +│ Explored Items ──► JNI Bridge ──► TagLib │ +│ │ │ │ +│ ▼ ▼ │ +│ Native Code Tag Parsing │ +│ │ │ │ +│ └────────────┘ │ +│ │ │ +│ ▼ │ +│ Metadata Maps │ +│ │ │ +│ ▼ │ +│ Extracted Items │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────┐ +│ EVALUATE PHASE │ +│ │ +│ Extracted Items ──► Graph Builder ──► Relationships │ +│ │ │ │ +│ ▼ ▼ │ +│ Name Resolution UID Generation │ +│ │ │ │ +│ └────────────────┘ │ +│ │ │ +│ ▼ │ +│ MutableLibrary │ +└─────────────────────────────────────────────────────────┘ +``` + +## Detailed Phase Flows + +### 1. Explore Phase Data Flow + +``` +START: FS.explore() + │ + ▼ +┌─────────────────┐ +│ Storage Access │ +│ Framework │ +└────────┬────────┘ + │ DocumentFile + ▼ +┌─────────────────┐ ┌─────────────────┐ +│ Audio Filter │ │ Playlist Filter │ +│ (audio/* MIME) │ │ (M3U MIME) │ +└────────┬────────┘ └────────┬────────┘ + │ │ + ▼ ▼ +┌─────────────────────────────────────────┐ +│ Cache Lookup │ +│ ┌─────────────┐ ┌──────────────┐ │ +│ │ Cache Hit │ │ Cache Miss │ │ +│ │ (Metadata) │ │ (New File) │ │ +│ └──────┬──────┘ └──────┬───────┘ │ +│ │ │ │ +│ ▼ ▼ │ +│ ┌─────────────┐ ┌──────────────┐ │ +│ │Cover Lookup │ │ Mark for │ │ +│ │ if Hit │ │ Extraction │ │ +│ └──────┬──────┘ └──────┬───────┘ │ +└─────────┴─────────────────┴─────────────┘ + │ + ▼ + Explored Stream + (Flow) +``` + +### 2. Extract Phase Data Flow + +``` +START: Explored Items + │ + ▼ +┌─────────────────┐ +│ Group by Type │ +│ - NewSong │ +│ - RawSong │ +│ - RawPlaylist │ +└────────┬────────┘ + │ + ┌────┴────┐ + │ NewSong │ + └────┬────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ JNI Metadata Call │ +│ │ +│ Kotlin ──► JNI ──► C++ ──► TagLib │ +│ │ │ │ +│ └─────── Results ◄────────┘ │ +└─────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ Metadata Processing │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ Properties │ │ Tags │ │ +│ │ - Duration │ │ - Title │ │ +│ │ - Bitrate │ │ - Artist │ │ +│ │ - Format │ │ - Album │ │ +│ └──────────────┘ └──────────────┘ │ +└─────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ Cache Update │ +│ - Write metadata to cache │ +│ - Store cover reference │ +└─────────────────────────────────────┘ + │ + ▼ + Extracted Stream + (Flow) +``` + +### 3. Evaluate Phase Data Flow + +``` +START: Extracted Items + │ + ▼ +┌─────────────────────────────────────┐ +│ Collect All Items │ +│ - Songs │ +│ - Playlists │ +└────────┬────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ UID Generation/Resolution │ +│ ┌──────────────┐ ┌──────────────┐ │ +│ │ MusicBrainz │ │ Hash-based │ │ +│ │ UIDs │ │ UIDs │ │ +│ └──────────────┘ └──────────────┘ │ +└────────┬────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ Name Interpretation │ +│ - Apply naming rules │ +│ - Parse separators │ +│ - Resolve conflicts │ +└────────┬────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Graph Building │ +│ │ +│ Songs ──► Albums ──► Artists │ +│ │ │ │ │ +│ └──────► Genres ◄────┘ │ +│ │ +│ Relationships: │ +│ - Song.album → Album │ +│ - Song.artists → List │ +│ - Album.artists → List │ +│ - Artist.albums → List │ +└──────────────┬──────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ Playlist Resolution │ +│ - Match paths to songs │ +│ - Create playlist objects │ +└────────┬────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────┐ +│ Final Library │ +│ MutableLibrary { │ +│ songs: List │ +│ albums: List │ +│ artists: List │ +│ genres: List │ +│ playlists: List │ +│ } │ +└─────────────────────────────────────┘ +``` + +## Key Data Transformations + +### File → Explored +``` +DocumentFile { Explored { + uri: Uri ──► file: DocumentFile + mimeType: String // + cache status +} } +``` + +### Explored → Extracted +``` +NewSong { ExtractedSong { + file: DocumentFile ──► file: DocumentFile + addedMs: Long properties: Properties +} tags: Map> + cover: Cover? + addedMs: Long + } +``` + +### Extracted → Library Items +``` +ExtractedSong { Song { + tags: Map ──► uid: UID + properties: Props name: Name +} album: Album + artists: List + // ... full metadata + } +``` + +## Caching Data Flow + +``` +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ File URI │ ──► │ Cache Key │ ──► │ Cached │ +│ │ │ Generation │ │ Metadata │ +└─────────────┘ └─────────────┘ └─────────────┘ + │ + ┌────────────────────┴────────────┐ + │ │ + ┌─────▼─────┐ ┌─────▼─────┐ + │ Valid │ │ Stale │ + │ Use Cached │ │ Re-extract│ + └───────────┘ └───────────┘ +``` + +## Cover Art Data Flow + +``` +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Embedded │ │ Cover ID │ │ Cover │ +│ Cover Data │ ──► │ Generation │ ──► │ Cache │ +└─────────────┘ └─────────────┘ └─────────────┘ + │ + ▼ + ┌─────────────┐ + │ Cover Ref │ + │ in Library │ + └─────────────┘ +``` + +## Error Handling Flow + +``` +┌─────────────┐ +│ Error │ +│ Occurs │ +└──────┬──────┘ + │ + ▼ +┌─────────────────────────────────┐ +│ Error Classification │ +│ ┌──────────┐ ┌─────────────┐ │ +│ │ Critical │ │ Recoverable │ │ +│ └────┬─────┘ └──────┬──────┘ │ +└───────┴────────────────┴────────┘ + │ │ + ▼ ▼ +┌──────────────┐ ┌───────────────┐ +│ Stop Pipeline│ │ Log & Continue│ +│ Throw Error │ │ Skip Item │ +└──────────────┘ └───────────────┘ +``` + +## Progress Reporting Flow + +``` +Pipeline Stage ──► Progress Event ──► Callback + │ + ▼ + IndexingProgress + ├── Songs(loaded, explored) + └── Indeterminate +``` \ No newline at end of file diff --git a/musikr/MODULES.md b/musikr/MODULES.md new file mode 100644 index 000000000..b1b226f93 --- /dev/null +++ b/musikr/MODULES.md @@ -0,0 +1,249 @@ +# Musikr Module Breakdown + +This document provides a detailed breakdown of all modules and packages within the Musikr library. + +## Package Structure + +``` +org.oxycblt.musikr/ +├── cache/ # Metadata caching system +├── covers/ # Cover art management +├── fs/ # File system abstraction +├── graph/ # Music relationship graph +├── metadata/ # JNI metadata extraction +├── model/ # Concrete implementations +├── pipeline/ # Processing pipeline +├── playlist/ # Playlist management +├── tag/ # Tag interpretation +├── track/ # Change tracking +└── util/ # Utility functions +``` + +## Core Modules + +### Main Entry Points + +#### `Musikr.kt` +- Main interface for the library +- Factory methods for creating instances +- Defines `LibraryResult` and `IndexingProgress` + +#### `Config.kt` +- Configuration data classes +- `Config`: Main configuration container +- `Storage`: Side-effect components +- `Interpretation`: Tag parsing rules + +#### `Music.kt` +- Core music data interfaces +- `Music`: Base interface with UID system +- `Song`, `Album`, `Artist`, `Genre`, `Playlist` interfaces +- UID implementation with MusicBrainz support + +#### `Library.kt` +- Library container interfaces +- `Library`: Read-only music library +- `MutableLibrary`: Mutable library for updates + +## Pipeline Modules (`pipeline/`) + +### `PipelineItem.kt` +- Data classes for pipeline communication +- `Explored`: Items found during exploration +- `Extracted`: Items with extracted metadata +- `NewSong`, `RawSong`, `RawPlaylist` types + +### `ExploreStep.kt` +- First pipeline stage +- Discovers music files using FS module +- Integrates with cache for optimization +- Handles cover pre-loading + +### `ExtractStep.kt` +- Second pipeline stage +- Calls native metadata extraction +- Manages metadata caching +- Handles extraction failures + +### `EvaluateStep.kt` +- Final pipeline stage +- Builds music graph from extracted data +- Resolves relationships between items +- Creates final library structure + +### `FlowUtil.kt` +- Coroutine flow utilities +- `distributedMap`: Parallel processing helper + +## File System Module (`fs/`) + +### `FS.kt` +- File system abstraction interface +- SAF integration for Android +- Multi-location support + +### `Path.kt` +- Path representation and manipulation +- Volume and document separation +- Display-friendly path formatting + +### `Location.kt` +- Storage location management +- Permission handling +- URI to path conversion + +### `Format.kt` +- Audio format enumeration +- MIME type mapping +- Format detection utilities + +## Metadata Module (`metadata/`) + +### `TagLibJNI.kt` +- JNI interface to native code +- Native method declarations + +### `MetadataExtractor.kt` +- High-level metadata extraction +- Format-specific extraction routing +- Error handling and fallbacks + +### `Metadata.kt` +- Metadata container classes +- Properties and tag maps +- Type-safe metadata access + +### Native Integration +- `NativeInputStream.kt`: Java InputStream to C++ bridge +- `NativeTagMap.kt`: Tag data transfer object + +## Cache Module (`cache/`) + +### `Cache.kt` +- Cache interfaces and data types +- `CacheResult`: Hit/Miss/Stale states +- Read/write operations + +### Implementation (not shown in detail) +- Room database integration +- Metadata persistence +- Cache invalidation logic + +## Cover Module (`covers/`) + +### `Covers.kt` +- Cover art management interfaces +- `CoverResult`: Cover loading states +- Cleanup operations + +### `Cover.kt` +- Cover identifier types +- Format information +- Collection utilities + +## Tag Module (`tag/`) + +### Tag Types +- `Date.kt`: Date parsing and representation +- `Disc.kt`: Disc number handling +- `Name.kt`: Name types (Known/Unknown) +- `ReleaseType.kt`: Album type classification +- `ReplayGainAdjustment.kt`: ReplayGain data + +### Interpretation (`tag/interpret/`) +- `Naming.kt`: Name construction rules +- `Separators.kt`: Multi-value tag parsing + +## Model Module (`model/`) + +Concrete implementations of music interfaces: +- `SongImpl.kt`: Song data implementation +- `AlbumImpl.kt`: Album with song relationships +- `ArtistImpl.kt`: Artist with album relationships +- `GenreImpl.kt`: Genre grouping implementation +- `PlaylistImpl.kt`: Playlist container +- `LibraryImpl.kt`: Complete library implementation +- `LibraryFactory.kt`: Factory for creating library instances + +## Graph Module (`graph/`) + +### `MusicGraph.kt` +- Relationship graph builder +- Artist-album-song connections +- Genre associations +- Duplicate resolution + +## Playlist Module (`playlist/`) + +### `ExternalPlaylistManager.kt` +- External playlist loading +- Format detection and parsing + +### `PlaylistFile.kt` +- Playlist file abstraction +- Common playlist operations + +### `m3u/M3U.kt` +- M3U/M3U8 playlist support +- Path resolution +- Encoding handling + +### `db/StoredPlaylists.kt` +- Database playlist interface +- CRUD operations +- Persistence management + +## Track Module (`track/`) + +### `UpdateTracker.kt` +- File system change detection +- Modification tracking +- Update notification + +### `LocationObserver.kt` +- Storage location monitoring +- Permission change handling + +## Utility Module (`util/`) + +### `LangUtil.kt` +- Language/locale utilities +- String manipulation helpers + +### `ParseUtil.kt` +- Parsing utilities +- Number parsing with validation +- UUID parsing + +## Native Layer (C++) + +### JNI Wrappers +- `JByteArrayRef`: Byte array management +- `JClassRef`: Class reference caching +- `JInputStream`: Stream adapter +- `JMetadataBuilder`: Metadata assembly +- `JObjectRef`: Object lifecycle management +- `JStringRef`: String conversion +- `JTagMap`: Tag data transfer + +### Main JNI Entry +- `taglib_jni.cpp`: Native method implementations +- Format-specific parsing functions +- Error handling and logging + +### Build System +- `CMakeLists.txt`: Native build configuration +- `build_taglib.sh`: TagLib compilation script +- `android.toolchain.cmake`: Android-specific toolchain + +## Testing + +### Unit Tests (`test/`) +- Tag parsing tests +- Date/Disc/ReleaseType validation +- Utility function tests + +### Integration +- Full pipeline testing +- Cache behavior verification +- Cover loading tests \ No newline at end of file diff --git a/musikr/QUICK_REFERENCE.md b/musikr/QUICK_REFERENCE.md new file mode 100644 index 000000000..ed33d9009 --- /dev/null +++ b/musikr/QUICK_REFERENCE.md @@ -0,0 +1,149 @@ +# Musikr Quick Reference Guide + +## What is Musikr? +A custom Android music indexing library that bypasses MediaStore, using SAF + TagLib for enhanced metadata extraction and music organization. + +## Key Features +- **No MediaStore**: Direct file access via Storage Access Framework +- **Advanced Metadata**: Full TagLib integration for rich tag support +- **Multi-threaded**: Parallel processing with Kotlin coroutines +- **Smart Caching**: Efficient metadata and cover art caching +- **MusicBrainz Support**: Proper handling of MB IDs +- **Flexible Architecture**: Pipeline-based processing + +## Quick Start + +```kotlin +// 1. Configure storage components +val storage = Storage( + cache = myCache, + covers = myCoverManager, + storedPlaylists = myPlaylistDb +) + +// 2. Set interpretation rules +val interpretation = Interpretation( + naming = Naming.SYSTEM, // or DISPLAY + separators = Separators.default() +) + +// 3. Create config +val config = Config( + fs = myFileSystem, + storage = storage, + interpretation = interpretation +) + +// 4. Run musikr +val musikr = Musikr.new(context, config) +val result = musikr.run { progress -> + // Handle progress updates +} + +// 5. Use the library +val library = result.library +println("Found ${library.songs.size} songs") + +// 6. Clean up +result.cleanup() +``` + +## Core Concepts + +### Pipeline Architecture +1. **Explore**: Find music files +2. **Extract**: Get metadata via TagLib +3. **Evaluate**: Build music graph + +### Data Model +- **Song**: Individual tracks with full metadata +- **Album**: Collections of songs (includes EPs, singles) +- **Artist**: Can have both album and track credits +- **Genre**: Musical style groupings +- **Playlist**: User-created or imported (M3U) + +### UID System +- Unique identifiers for all music items +- Supports MusicBrainz IDs +- Hash-based fallback for untagged files + +## File Structure +``` +musikr/ +├── src/main/ +│ ├── java/ # Kotlin sources +│ └── cpp/ # Native TagLib integration +├── ARCHITECTURE.md # System design overview +├── MODULES.md # Detailed module docs +└── DATA_FLOW.md # Data flow diagrams +``` + +## Common Tasks + +### Custom Cache Implementation +```kotlin +class MyCache : MutableCache { + override suspend fun read(file: DocumentFile): CacheResult { + // Your implementation + } + + override suspend fun write(extracted: List) { + // Your implementation + } +} +``` + +### Custom Cover Storage +```kotlin +class MyCovers : MutableCovers { + override suspend fun obtain(id: String): CoverResult { + // Your implementation + } + + override suspend fun write(cover: Cover): String { + // Your implementation + } +} +``` + +### Progress Monitoring +```kotlin +musikr.run { progress -> + when (progress) { + is IndexingProgress.Songs -> { + println("Loaded ${progress.loaded}/${progress.explored}") + } + is IndexingProgress.Indeterminate -> { + println("Building library...") + } + } +} +``` + +## Important Notes + +1. **No Windows Support**: Requires Unix-based build system +2. **GPL v3 License**: Viral license - entire project must be GPL +3. **Unstable API**: Interface may change between versions +4. **Thread Safety**: All operations are coroutine-safe +5. **Memory Usage**: Streaming architecture for large libraries + +## Debugging Tips + +- Enable TagLib debug output for metadata issues +- Check cache validity for performance problems +- Monitor coroutine dispatchers for threading issues +- Use flow operators for custom processing + +## Performance Tuning + +- Adjust `distributedMap` parallelism (default: 8) +- Configure channel buffer sizes +- Optimize cache implementation +- Pre-warm cover cache for common albums + +## See Also +- [ARCHITECTURE.md](ARCHITECTURE.md) - System design +- [MODULES.md](MODULES.md) - Module details +- [DATA_FLOW.md](DATA_FLOW.md) - Data flow diagrams +- [README.md](README.md) - Basic information \ No newline at end of file From 497c35d81a5bd82d18d883323da27f2b3429ff84 Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 29 Jun 2025 15:27:09 -0600 Subject: [PATCH 13/42] musikr: refactor shared tracking system --- .../oxycblt/auxio/image/covers/NullCovers.kt | 4 +- .../oxycblt/auxio/music/MusicRepository.kt | 1 - .../org/oxycblt/auxio/music/MusicSettings.kt | 3 +- .../auxio/music/service/IndexingHolder.kt | 54 +++--- .../auxio/music/shim/MusikrShimModule.kt | 4 - .../auxio/music/shim/UpdateTrackerFactory.kt | 30 --- .../auxio/music/shim/WriteOnlyMutableCache.kt | 4 +- app/src/main/res/xml/preferences_root.xml | 7 - .../java/org/oxycblt/musikr/cache/Cache.kt | 18 +- .../org/oxycblt/musikr/cache/db/DBCache.kt | 6 +- .../java/org/oxycblt/musikr/covers/Covers.kt | 6 +- .../musikr/covers/chained/ChainedCovers.kt | 4 +- .../musikr/covers/embedded/EmbeddedCovers.kt | 4 +- .../org/oxycblt/musikr/covers/fs/FSCovers.kt | 8 +- .../musikr/covers/stored/StoredCovers.kt | 4 +- .../src/main/java/org/oxycblt/musikr/fs/FS.kt | 24 ++- .../musikr/fs/mediastore/MediaStore.kt | 178 ++++++++++-------- .../java/org/oxycblt/musikr/fs/saf/SAF.kt | 46 +++-- .../musikr/{ => fs}/track/LocationObserver.kt | 12 +- .../musikr/metadata/MetadataExtractor.kt | 6 +- .../musikr/metadata/NativeInputStream.kt | 4 +- .../org/oxycblt/musikr/metadata/TagLibJNI.kt | 4 +- .../oxycblt/musikr/pipeline/PipelineItem.kt | 6 +- .../musikr/tag/interpret/TagInterpreter.kt | 4 +- .../org/oxycblt/musikr/track/UpdateTracker.kt | 54 ------ 25 files changed, 221 insertions(+), 274 deletions(-) delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/shim/UpdateTrackerFactory.kt rename musikr/src/main/java/org/oxycblt/musikr/{ => fs}/track/LocationObserver.kt (87%) delete mode 100644 musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt diff --git a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt index 01ed695e1..0eaa655b3 100644 --- a/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt +++ b/app/src/main/java/org/oxycblt/auxio/image/covers/NullCovers.kt @@ -22,13 +22,13 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.MutableCovers import org.oxycblt.musikr.covers.stored.CoverStorage -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Metadata class NullCovers(private val storage: CoverStorage) : MutableCovers { override suspend fun obtain(id: String) = CoverResult.Hit(NullCover) - override suspend fun create(file: DeviceFile, metadata: Metadata) = CoverResult.Hit(NullCover) + override suspend fun create(file: File, metadata: Metadata) = CoverResult.Hit(NullCover) override suspend fun cleanup(excluding: Collection) { storage.ls(setOf()).map { storage.rm(it) } diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt index 14730c8cb..b3a87cead 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -41,7 +41,6 @@ import org.oxycblt.musikr.Playlist import org.oxycblt.musikr.Song import org.oxycblt.musikr.Storage import org.oxycblt.musikr.cache.MutableCache -import org.oxycblt.musikr.fs.mediastore.MediaStoreFS import org.oxycblt.musikr.fs.saf.SAF import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.tag.interpret.Naming diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 01f6e15e9..85b889fb4 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -150,8 +150,7 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont getString(R.string.set_key_separators), getString(R.string.set_key_auto_sort_names), getString(R.string.set_key_with_hidden), - getString(R.string.set_key_exclude_non_music), - getString(R.string.set_key_fs_cache) -> { + getString(R.string.set_key_exclude_non_music) -> { L.d("Dispatching indexing setting change for $key") listener.onIndexingSettingChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt index 7788e10e8..2c5449d39 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/service/IndexingHolder.kt @@ -32,47 +32,36 @@ import org.oxycblt.auxio.ForegroundServiceNotification import org.oxycblt.auxio.music.IndexingState import org.oxycblt.auxio.music.MusicRepository import org.oxycblt.auxio.music.MusicSettings -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.Location -import org.oxycblt.musikr.track.UpdateTracker +import org.oxycblt.musikr.fs.saf.SAF import timber.log.Timber as L class IndexingHolder private constructor( - workerContext: Context, + private val workerContext: Context, private val foregroundListener: ForegroundListener, private val playbackManager: PlaybackStateManager, private val musicRepository: MusicRepository, private val musicSettings: MusicSettings, - private val imageLoader: ImageLoader, - updateTrackerFactory: UpdateTrackerFactory + private val imageLoader: ImageLoader ) : MusicRepository.IndexingWorker, MusicRepository.IndexingListener, MusicRepository.UpdateListener, - MusicSettings.Listener, - UpdateTracker.Callback { + MusicSettings.Listener { class Factory @Inject constructor( private val playbackManager: PlaybackStateManager, private val musicRepository: MusicRepository, private val musicSettings: MusicSettings, - private val imageLoader: ImageLoader, - private val updateTrackerFactory: UpdateTrackerFactory + private val imageLoader: ImageLoader ) { fun create(context: Context, listener: ForegroundListener) = IndexingHolder( - context, - listener, - playbackManager, - musicRepository, - musicSettings, - imageLoader, - updateTrackerFactory) + context, listener, playbackManager, musicRepository, musicSettings, imageLoader) } private val indexJob = Job() @@ -85,18 +74,18 @@ private constructor( .getSystemServiceCompat(PowerManager::class) .newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":IndexingComponent") - private val updateTracker = updateTrackerFactory.create(this) + private var trackingJob: Job? = null fun attach() { musicSettings.registerListener(this) musicRepository.addUpdateListener(this) musicRepository.addIndexingListener(this) musicRepository.registerWorker(this) - updateTracker.track(musicSettings.musicLocations) + startTracking() } fun release() { - updateTracker.release() + stopTracking() musicRepository.unregisterWorker(this) musicRepository.removeIndexingListener(this) musicRepository.removeUpdateListener(this) @@ -168,15 +157,30 @@ private constructor( } } - override fun onUpdate(location: Location.Opened) { - if (musicSettings.shouldBeObserving) { - musicRepository.requestIndex(true) - } + private fun startTracking() { + stopTracking() + val locations = musicSettings.musicLocations + if (locations.isEmpty()) return + + trackingJob = + indexScope.launch { + val query = SAF.Query(source = locations, exclude = emptyList(), withHidden = false) + SAF.from(workerContext, query).track().collect { + if (musicSettings.shouldBeObserving) { + musicRepository.requestIndex(true) + } + } + } + } + + private fun stopTracking() { + trackingJob?.cancel() + trackingJob = null } override fun onMusicLocationsChanged() { super.onMusicLocationsChanged() - updateTracker.track(musicSettings.musicLocations) + startTracking() musicRepository.requestIndex(true) } diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/MusikrShimModule.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/MusikrShimModule.kt index 827ac75c9..cd61618e3 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/MusikrShimModule.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/MusikrShimModule.kt @@ -39,8 +39,4 @@ class MusikrShimModule { @Singleton @Provides fun storedPlaylists(@ApplicationContext context: Context) = StoredPlaylists.from(context) - - @Provides - fun updateTrackerFactory(@ApplicationContext context: Context): UpdateTrackerFactory = - UpdateTrackerFactoryImpl(context) } diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/UpdateTrackerFactory.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/UpdateTrackerFactory.kt deleted file mode 100644 index fa320f888..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/UpdateTrackerFactory.kt +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2025 Auxio Project - * UpdateTrackerFactory.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.shim - -import android.content.Context -import org.oxycblt.musikr.track.UpdateTracker - -interface UpdateTrackerFactory { - fun create(callback: UpdateTracker.Callback): UpdateTracker -} - -class UpdateTrackerFactoryImpl(private val context: Context) : UpdateTrackerFactory { - override fun create(callback: UpdateTracker.Callback) = UpdateTracker.from(context, callback) -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt index 09b670c79..9079f29f0 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/WriteOnlyMutableCache.kt @@ -21,10 +21,10 @@ package org.oxycblt.auxio.music.shim import org.oxycblt.musikr.cache.CacheResult import org.oxycblt.musikr.cache.CachedSong import org.oxycblt.musikr.cache.MutableCache -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File class WriteOnlyMutableCache(private val inner: MutableCache) : MutableCache { - override suspend fun read(file: DeviceFile): CacheResult { + override suspend fun read(file: File): CacheResult { return when (val result = inner.read(file)) { is CacheResult.Hit -> CacheResult.Stale(file, result.song.addedMs) else -> result diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 0b4009a44..12f8fb94b 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -38,13 +38,6 @@ app:summary="@string/set_excluded_locations_desc" app:title="@string/set_excluded_locations" /> - - - : Covers { * This could result in side-effect-laden storage, or be a simple translation into a lazily * loaded [Cover] instance. * - * @param file The [DeviceFile] to of the file to create a cover for. + * @param file The [File] to of the file to create a cover for. * @param metadata The [Metadata] to use to create the cover. * @return a [CoverResult] indicating whether the cover was created or not */ - suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult + suspend fun create(file: File, metadata: Metadata): CoverResult /** * Cleanup the cover repository by removing any covers that are not in the [excluding] diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt index 5e7b8e257..64a286d17 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/chained/ChainedCovers.kt @@ -22,7 +22,7 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Metadata /** @@ -72,7 +72,7 @@ class MutableChainedCovers(vararg many: MutableCovers) override suspend fun obtain(id: String): CoverResult = inner.obtain(id) - override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { + override suspend fun create(file: File, metadata: Metadata): CoverResult { for (cover in _many) { val result = cover.create(file, metadata) if (result is CoverResult.Hit) { diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt index d25229d0a..a3d3eac97 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/embedded/EmbeddedCovers.kt @@ -23,7 +23,7 @@ import org.oxycblt.musikr.covers.Cover import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.MemoryCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Metadata /** @@ -44,7 +44,7 @@ import org.oxycblt.musikr.metadata.Metadata class EmbeddedCovers(private val coverIdentifier: CoverIdentifier) : MutableCovers { override suspend fun obtain(id: String): CoverResult = CoverResult.Miss() - override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { + override suspend fun create(file: File, metadata: Metadata): CoverResult { val data = metadata.cover ?: return CoverResult.Miss() val id = coverIdentifier.identify(data) return CoverResult.Hit(EmbeddedCover(id, data)) diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt index 9a7c20ade..2a3b2e6f0 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/fs/FSCovers.kt @@ -31,7 +31,7 @@ import org.oxycblt.musikr.covers.CoverResult import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.FDCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Metadata private const val PREFIX = "mcf:" @@ -93,13 +93,13 @@ class MutableFSCovers(private val context: Context) : MutableCovers { override suspend fun obtain(id: String): CoverResult = inner.obtain(id) - override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { + override suspend fun create(file: File, metadata: Metadata): CoverResult { // Since DeviceFiles is a streaming API, we have to wait for the current recursive // query to finally finish to be able to have a complete list of siblings to search for. val parent = file.parent.await() val bestCover = parent.children - .filterIsInstance() + .filterIsInstance() .map { it to coverArtScore(it) } .maxBy { it.second } if (bestCover.second > 0) { @@ -116,7 +116,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers { // that should not be managed by the app } - private suspend fun coverArtScore(file: DeviceFile): Int { + private suspend fun coverArtScore(file: File): Int { if (!file.mimeType.startsWith("image/", ignoreCase = true)) { // Not an image file. You lose! return 0 diff --git a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt index d5c5de40b..83573f72f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/covers/stored/StoredCovers.kt @@ -24,7 +24,7 @@ import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.FDCover import org.oxycblt.musikr.covers.MemoryCover import org.oxycblt.musikr.covers.MutableCovers -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Metadata private const val PREFIX = "mcs:" @@ -75,7 +75,7 @@ class MutableStoredCovers( override suspend fun obtain(id: String): CoverResult = base.obtain(id) - override suspend fun create(file: DeviceFile, metadata: Metadata): CoverResult { + override suspend fun create(file: File, metadata: Metadata): CoverResult { val memoryCover = when (val cover = src.create(file, metadata)) { is CoverResult.Hit -> cover.cover diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt index 0e7201b03..3b39db3e7 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/FS.kt @@ -23,26 +23,32 @@ import kotlinx.coroutines.Deferred import kotlinx.coroutines.flow.Flow interface FS { - fun explore(): Flow + fun explore(): Flow + + fun track(): Flow } -sealed interface DeviceFSEntry { +sealed interface FSEntry { val uri: Uri? val path: Path } -data class DeviceDirectory( +data class Directory( override val uri: Uri?, override val path: Path, - val parent: Deferred?, - var children: List -) : DeviceFSEntry + val parent: Deferred?, + var children: List +) : FSEntry -data class DeviceFile( +data class File( override val uri: Uri, override val path: Path, val modifiedMs: Long, val mimeType: String, val size: Long, - val parent: Deferred -) : DeviceFSEntry + val parent: Deferred +) : FSEntry + +sealed interface FSUpdate { + data class LocationChanged(val location: Location.Opened?) : FSUpdate +} diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt index fd810254a..61e426cdc 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/mediastore/MediaStore.kt @@ -24,21 +24,25 @@ import android.provider.MediaStore import androidx.core.database.getStringOrNull import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.yield -import org.oxycblt.musikr.fs.DeviceDirectory -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.Directory import org.oxycblt.musikr.fs.FS +import org.oxycblt.musikr.fs.FSUpdate +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.path.MediaStorePathInterpreter import org.oxycblt.musikr.fs.path.VolumeManager import org.oxycblt.musikr.fs.saf.contentResolverSafe import org.oxycblt.musikr.fs.saf.useQuery +import org.oxycblt.musikr.fs.track.LocationObserver /** * MediaStore implementation of [FS] that queries the Android MediaStore database for audio files - * and yields them as [DeviceFile] instances. + * and yields them as [File] instances. */ class MediaStoreFS private constructor( @@ -48,84 +52,8 @@ private constructor( ) : FS { private val pathInterpreterFactory = MediaStorePathInterpreter.Factory.from(volumeManager) - private fun buildDirectoryHierarchy(files: List) { - // Map to store directories by their path - val directoryMap = mutableMapOf() - - // Group files by their parent directory path - val filesByParent = files.groupBy { it.path.directory } - - // First pass: Create all directories and complete file parent deferreds - for ((dirPath, dirFiles) in filesByParent) { - val directory = - directoryMap.getOrPut(dirPath) { - // Create parent deferred for this directory - val parentDeferred = - if (dirPath.components.components.isEmpty()) { - // Root directory has no parent - null - } else { - CompletableDeferred() - } - - DeviceDirectory( - uri = null, // Directories don't have MediaStore URIs - path = dirPath, - parent = parentDeferred, - children = dirFiles) - } - - // Update children if directory already existed - if (directory.children.isEmpty()) { - directory.children = dirFiles - } - - // Complete parent deferreds for all files in this directory - dirFiles.forEach { file -> - (file.parent as CompletableDeferred).complete(directory) - } - } - - // Second pass: Create any missing parent directories - val directories = directoryMap.values.toList() - for (directory in directories) { - var currentPath = directory.path - while (currentPath.components.components.isNotEmpty()) { - val parentPath = currentPath.directory - if (!directoryMap.containsKey(parentPath)) { - val grandParentDeferred = - if (parentPath.components.components.isEmpty()) { - null - } else { - CompletableDeferred() - } - - directoryMap[parentPath] = - DeviceDirectory( - uri = null, - path = parentPath, - parent = grandParentDeferred, - children = emptyList()) - } - currentPath = parentPath - } - } - - // Third pass: Complete all directory parent deferreds - for (directory in directoryMap.values) { - val parentDeferred = directory.parent as? CompletableDeferred - if (parentDeferred != null && !parentDeferred.isCompleted) { - val parentPath = directory.path.directory - val parentDirectory = directoryMap[parentPath] - if (parentDirectory != null) { - parentDeferred.complete(parentDirectory) - } - } - } - } - @OptIn(ExperimentalCoroutinesApi::class) - override fun explore(): Flow = flow { + override fun explore(): Flow = flow { val projection = BASE_PROJECTION + pathInterpreterFactory.projection var selector = BASE_SELECTOR val args = mutableListOf() @@ -136,7 +64,7 @@ private constructor( } // Collect all files and track unique directories - val allFiles = mutableListOf() + val allFiles = mutableListOf() context.contentResolverSafe.useQuery( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, @@ -164,9 +92,9 @@ private constructor( cursor.getLong(dateModifiedIndex) * 1000 // Convert to milliseconds // Create file with empty deferred parent - val parentDeferred = CompletableDeferred() + val parentDeferred = CompletableDeferred() val deviceFile = - DeviceFile( + File( uri = uri, path = path, modifiedMs = dateModified, @@ -184,6 +112,90 @@ private constructor( buildDirectoryHierarchy(allFiles) } + override fun track(): Flow = callbackFlow { + val observer = + LocationObserver(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI) { + trySend(FSUpdate.LocationChanged(null)) + } + awaitClose { observer.release() } + } + + private fun buildDirectoryHierarchy(files: List) { + // Map to store directories by their path + val directoryMap = mutableMapOf() + + // Group files by their parent directory path + val filesByParent = files.groupBy { it.path.directory } + + // First pass: Create all directories and complete file parent deferreds + for ((dirPath, dirFiles) in filesByParent) { + val directory = + directoryMap.getOrPut(dirPath) { + // Create parent deferred for this directory + val parentDeferred = + if (dirPath.components.components.isEmpty()) { + // Root directory has no parent + null + } else { + CompletableDeferred() + } + + Directory( + uri = null, // Directories don't have MediaStore URIs + path = dirPath, + parent = parentDeferred, + children = dirFiles) + } + + // Update children if directory already existed + if (directory.children.isEmpty()) { + directory.children = dirFiles + } + + // Complete parent deferreds for all files in this directory + dirFiles.forEach { file -> + (file.parent as CompletableDeferred).complete(directory) + } + } + + // Second pass: Create any missing parent directories + val directories = directoryMap.values.toList() + for (directory in directories) { + var currentPath = directory.path + while (currentPath.components.components.isNotEmpty()) { + val parentPath = currentPath.directory + if (!directoryMap.containsKey(parentPath)) { + val grandParentDeferred = + if (parentPath.components.components.isEmpty()) { + null + } else { + CompletableDeferred() + } + + directoryMap[parentPath] = + Directory( + uri = null, + path = parentPath, + parent = grandParentDeferred, + children = emptyList()) + } + currentPath = parentPath + } + } + + // Third pass: Complete all directory parent deferreds + for (directory in directoryMap.values) { + val parentDeferred = directory.parent as? CompletableDeferred + if (parentDeferred != null && !parentDeferred.isCompleted) { + val parentPath = directory.path.directory + val parentDirectory = directoryMap[parentPath] + if (parentDirectory != null) { + parentDeferred.complete(parentDirectory) + } + } + } + } + companion object { fun from(context: Context) = MediaStoreFS( diff --git a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt index 7936b6ac3..96a05d58f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/saf/SAF.kt @@ -25,22 +25,30 @@ import android.provider.DocumentsContract import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow +import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.flatMapMerge import kotlinx.coroutines.flow.flattenMerge import kotlinx.coroutines.flow.flow -import org.oxycblt.musikr.fs.DeviceDirectory -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.Directory import org.oxycblt.musikr.fs.FS +import org.oxycblt.musikr.fs.FSUpdate +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.Location import org.oxycblt.musikr.fs.Path +import org.oxycblt.musikr.fs.track.LocationObserver @OptIn(ExperimentalCoroutinesApi::class) class SAF -private constructor(private val contentResolver: ContentResolver, private val query: Query) : FS { - override fun explore(): Flow = +private constructor( + private val context: Context, + private val contentResolver: ContentResolver, + private val query: Query +) : FS { + override fun explore(): Flow = query.source.asFlow().flatMapMerge { location -> exploreDirectoryImpl( location.uri, @@ -50,18 +58,32 @@ private constructor(private val contentResolver: ContentResolver, private val qu query.exclude.mapTo(mutableSetOf()) { it.uri }) } + override fun track(): Flow = callbackFlow { + val observers = mutableListOf() + + query.source.forEach { location -> + val observer = + LocationObserver(context, location.uri) { + trySend(FSUpdate.LocationChanged(location)) + } + observers.add(observer) + } + + awaitClose { observers.forEach { observer -> observer.release() } } + } + private fun exploreDirectoryImpl( rootUri: Uri, treeDocumentId: String, relativePath: Path, - parent: Deferred?, + parent: Deferred?, exclude: Set - ): Flow = flow { + ): Flow = flow { // Make a kotlin future val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId) - val directoryDeferred = CompletableDeferred() - val recursive = mutableListOf>() - val children = mutableListOf() + val directoryDeferred = CompletableDeferred() + val recursive = mutableListOf>() + val children = mutableListOf() contentResolver.useQuery(uri, PROJECTION) { cursor -> val childUriIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID) @@ -99,7 +121,7 @@ private constructor(private val contentResolver: ContentResolver, private val qu } else { val size = cursor.getLong(sizeIndex) val file = - DeviceFile( + File( uri = childUri, mimeType = mimeType, path = newPath, @@ -110,7 +132,7 @@ private constructor(private val contentResolver: ContentResolver, private val qu emit(file) } } - directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children)) + directoryDeferred.complete(Directory(uri, relativePath, parent, children)) emitAll(recursive.asFlow().flattenMerge()) } } @@ -122,7 +144,7 @@ private constructor(private val contentResolver: ContentResolver, private val qu ) companion object { - fun from(context: Context, query: Query) = SAF(context.contentResolverSafe, query) + fun from(context: Context, query: Query) = SAF(context, context.contentResolverSafe, query) private val PROJECTION = arrayOf( diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt similarity index 87% rename from musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt rename to musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt index 29ae53bbf..c6bb55f66 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/track/LocationObserver.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/track/LocationObserver.kt @@ -16,23 +16,23 @@ * along with this program. If not, see . */ -package org.oxycblt.musikr.track +package org.oxycblt.musikr.fs.track import android.content.Context import android.database.ContentObserver +import android.net.Uri import android.os.Handler import android.os.Looper -import org.oxycblt.musikr.fs.Location internal class LocationObserver( private val context: Context, - private val location: Location.Opened, - private val listener: UpdateTracker.Callback + private val uri: Uri, + private val onUpdate: () -> Unit ) : ContentObserver(Handler(Looper.getMainLooper())), Runnable { private val handler = Handler(Looper.getMainLooper()) init { - context.applicationContext.contentResolver.registerContentObserver(location.uri, true, this) + context.applicationContext.contentResolver.registerContentObserver(uri, true, this) } fun release() { @@ -47,7 +47,7 @@ internal class LocationObserver( } override fun run() { - listener.onUpdate(location) + onUpdate() } private companion object { diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt index f070f0c69..205df5654 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/MetadataExtractor.kt @@ -23,10 +23,10 @@ import android.content.Context import java.io.FileInputStream import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File internal interface MetadataExtractor { - suspend fun extract(deviceFile: DeviceFile): Metadata? + suspend fun extract(deviceFile: File): Metadata? companion object { fun from(context: Context): MetadataExtractor = @@ -36,7 +36,7 @@ internal interface MetadataExtractor { private class MetadataExtractorImpl(private val contentResolver: ContentResolver) : MetadataExtractor { - override suspend fun extract(deviceFile: DeviceFile): Metadata? = + override suspend fun extract(deviceFile: File): Metadata? = withContext(Dispatchers.IO) { contentResolver.openFileDescriptor(deviceFile.uri, "r")?.use { fd -> val fis = FileInputStream(fd.fileDescriptor) diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt index c7486e220..d33a3d9f4 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/NativeInputStream.kt @@ -21,9 +21,9 @@ package org.oxycblt.musikr.metadata import android.util.Log import java.io.FileInputStream import java.nio.ByteBuffer -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File -internal class NativeInputStream(private val deviceFile: DeviceFile, fis: FileInputStream) { +internal class NativeInputStream(private val deviceFile: File, fis: FileInputStream) { private val channel = fis.channel fun name() = requireNotNull(deviceFile.path.name) diff --git a/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt b/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt index d5105f3a8..6fd23a253 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/metadata/TagLibJNI.kt @@ -19,7 +19,7 @@ package org.oxycblt.musikr.metadata import java.io.FileInputStream -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File internal object TagLibJNI { init { @@ -31,7 +31,7 @@ internal object TagLibJNI { * * Note: This method is blocking and should be handled as such if calling from a coroutine. */ - fun open(deviceFile: DeviceFile, fis: FileInputStream): Metadata? { + fun open(deviceFile: File, fis: FileInputStream): Metadata? { val inputStream = NativeInputStream(deviceFile, fis) val tag = openNative(inputStream) inputStream.close() diff --git a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt index b151db5b1..a727ab41f 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/pipeline/PipelineItem.kt @@ -19,7 +19,7 @@ package org.oxycblt.musikr.pipeline import org.oxycblt.musikr.covers.Cover -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.metadata.Properties import org.oxycblt.musikr.playlist.PlaylistFile import org.oxycblt.musikr.tag.parse.ParsedTags @@ -36,7 +36,7 @@ internal sealed interface Explored : PipelineItem { sealed interface Known : Explored, Complete } -internal data class NewSong(val file: DeviceFile, val addedMs: Long) : Explored.New +internal data class NewSong(val file: File, val addedMs: Long) : Explored.New internal sealed interface Extracted : PipelineItem { sealed interface Valid : Complete, Extracted @@ -49,7 +49,7 @@ internal data object InvalidSong : Extracted.Invalid internal data class RawPlaylist(val file: PlaylistFile) : Explored.Known, Extracted.Valid internal data class RawSong( - val file: DeviceFile, + val file: File, val properties: Properties, val tags: ParsedTags, val cover: Cover?, diff --git a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt index fd4bac0dd..9d06722be 100644 --- a/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt +++ b/musikr/src/main/java/org/oxycblt/musikr/tag/interpret/TagInterpreter.kt @@ -20,7 +20,7 @@ package org.oxycblt.musikr.tag.interpret import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Music -import org.oxycblt.musikr.fs.DeviceFile +import org.oxycblt.musikr.fs.File import org.oxycblt.musikr.fs.Format import org.oxycblt.musikr.pipeline.RawSong import org.oxycblt.musikr.tag.Disc @@ -151,7 +151,7 @@ private class TagInterpreterImpl(private val interpretation: Interpretation) : T private fun makePreAlbum( parsedTags: ParsedTags, - deviceFile: DeviceFile, + deviceFile: File, individualPreArtists: List, albumPreArtists: List, interpretation: Interpretation diff --git a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt b/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt deleted file mode 100644 index 48f22a1fb..000000000 --- a/musikr/src/main/java/org/oxycblt/musikr/track/UpdateTracker.kt +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2025 Auxio Project - * UpdateTracker.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.musikr.track - -import android.content.Context -import org.oxycblt.musikr.fs.Location - -interface UpdateTracker { - fun track(locations: List) - - fun release() - - interface Callback { - fun onUpdate(location: Location.Opened) - } - - companion object { - fun from(context: Context, callback: Callback): UpdateTracker = - UpdateTrackerImpl(context, callback) - } -} - -private class UpdateTrackerImpl( - private val context: Context, - private val callback: UpdateTracker.Callback -) : UpdateTracker { - private val observers = mutableListOf() - - override fun track(locations: List) { - release() - observers.addAll(locations.map { LocationObserver(context, it, callback) }) - } - - override fun release() { - observers.forEach { it.release() } - observers.clear() - } -} From b6b5b3b87d882f62b7614252f07e513cfe52314a Mon Sep 17 00:00:00 2001 From: Alexander Capehart Date: Sun, 29 Jun 2025 19:20:38 -0600 Subject: [PATCH 14/42] music: new location dialog --- .../org/oxycblt/auxio/music/MusicSettings.kt | 51 ++ .../locations/ExcludedLocationAdapter.kt | 57 --- .../locations/ExcludedLocationsDialog.kt | 63 --- .../auxio/music/locations/LocationAdapter.kt | 97 +++- .../auxio/music/locations/LocationConfig.kt | 80 ++++ .../auxio/music/locations/LocationsDialog.kt | 436 ++++++++++++++++-- .../music/locations/MusicLocationAdapter.kt | 57 --- .../music/locations/MusicLocationsDialog.kt | 63 --- .../locations/NewLocationFooterAdapter.kt | 82 ---- .../auxio/settings/RootPreferenceFragment.kt | 4 - .../java/org/oxycblt/auxio/util/LangUtil.kt | 45 ++ app/src/main/res/drawable/drop_down_24.xml | 10 + app/src/main/res/drawable/drop_up_24.xml | 10 + app/src/main/res/drawable/ic_open_20.xml | 11 + .../res/layout/dialog_music_locations.xml | 404 +++++++++++++++- app/src/main/res/layout/item_no_locations.xml | 26 ++ app/src/main/res/navigation/inner.xml | 2 +- app/src/main/res/navigation/outer.xml | 10 +- app/src/main/res/values/settings.xml | 1 + app/src/main/res/values/strings.xml | 27 +- app/src/main/res/values/typography.xml | 7 + app/src/main/res/xml/preferences_root.xml | 5 - .../musikr/fs/mediastore/MediaStore.kt | 34 +- 23 files changed, 1170 insertions(+), 412 deletions(-) delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt create mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/LocationConfig.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt delete mode 100644 app/src/main/java/org/oxycblt/auxio/music/locations/NewLocationFooterAdapter.kt create mode 100644 app/src/main/res/drawable/drop_down_24.xml create mode 100644 app/src/main/res/drawable/drop_up_24.xml create mode 100644 app/src/main/res/drawable/ic_open_20.xml create mode 100644 app/src/main/res/layout/item_no_locations.xml diff --git a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt index 85b889fb4..8ecec53e9 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -27,8 +27,20 @@ import javax.inject.Inject import org.oxycblt.auxio.R import org.oxycblt.auxio.settings.Settings import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.mediastore.MediaStoreFS +import org.oxycblt.musikr.fs.saf.SAF import timber.log.Timber as L +/** + * Represents the mode for loading music locations. + */ +enum class MusicLocationMode { + /** Use Storage Access Framework (file picker) to select specific folders */ + SAF, + /** Use system MediaStore database to load all music */ + SYSTEM +} + /** * User configuration specific to music system. * @@ -41,6 +53,10 @@ interface MusicSettings : Settings { var musicLocations: List /** The locations to exclude from music loading. */ var excludedLocations: List + /** The currently configured SAF query (if any) * */ + val safQuery: SAF.Query? + /** The currently configured MediaStore query (if any) * */ + val mediaStoreQuery: MediaStoreFS.Query? /** Whether to exclude non-music audio files from the music library. */ val excludeNonMusic: Boolean /** Whether to ignore hidden files and directories during music loading. */ @@ -53,6 +69,8 @@ interface MusicSettings : Settings { val intelligentSorting: Boolean /** Whether to use the file-system cache for improved loading times. */ val useFileTreeCache: Boolean + /** The mode for loading music locations (SAF or System database). */ + var locationMode: MusicLocationMode interface Listener { /** Called when the current music locations changed. */ @@ -138,6 +156,39 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont override val useFileTreeCache: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), false) + override var locationMode: MusicLocationMode + get() { + val ordinal = sharedPreferences.getInt(getString(R.string.set_key_saf_mode), 0) + return MusicLocationMode.values().getOrNull(ordinal) ?: MusicLocationMode.SAF + } + set(value) { + sharedPreferences.edit { + putInt(getString(R.string.set_key_saf_mode), value.ordinal) + apply() + } + } + + override val safQuery: SAF.Query? + get() { + // SAF query is used when in SAF mode and we have music locations configured + if (locationMode != MusicLocationMode.SAF) return null + val locations = musicLocations + if (locations.isEmpty()) return null + return SAF.Query( + source = locations, exclude = excludedLocations, withHidden = withHidden) + } + + override val mediaStoreQuery: MediaStoreFS.Query? + get() { + // MediaStore query is used when in system database mode + if (locationMode != MusicLocationMode.SYSTEM) return null + + return MediaStoreFS.Query( + include = emptyList(), // No include filter in system database mode + exclude = excludedLocations, + excludeNonMusic = excludeNonMusic) + } + override fun onSettingChanged(key: String, listener: MusicSettings.Listener) { // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt deleted file mode 100644 index 20e4a4be2..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationAdapter.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * ExcludedLocationAdapter.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.view.ViewGroup -import org.oxycblt.auxio.databinding.ItemMusicLocationBinding -import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.Location - -/** - * [LocationAdapter] that manages a list of [Location.Unopened] excluded directory instances. - * - * @param listener A [LocationAdapter.Listener] to bind interactions to. - * @author Alexander Capehart (OxygenCobalt) - */ -class ExcludedLocationAdapter(listener: LocationAdapter.Listener) : - LocationAdapter(listener) { - override fun createViewHolder(parent: ViewGroup): LocationViewHolder = - ExcludedLocationViewHolder.from(parent) -} - -/** - * A [LocationViewHolder] that displays a [Location.Unopened]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class ExcludedLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : - LocationViewHolder(binding) { - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: ViewGroup) = - ExcludedLocationViewHolder( - ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt deleted file mode 100644 index be70285d0..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/ExcludedLocationsDialog.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * ExcludedLocationsDialog.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.content.Context -import android.net.Uri -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig -import org.oxycblt.auxio.R -import org.oxycblt.auxio.music.MusicSettings -import org.oxycblt.musikr.fs.Location - -/** - * Dialog that manages the excluded locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class ExcludedLocationsDialog : LocationsDialog() { - override val locationAdapter = ExcludedLocationAdapter(this) - - @Inject override lateinit var musicSettings: MusicSettings - - override fun getDialogTitle(): Int = R.string.set_excluded_locations - - override fun getCurrentLocations(): List = musicSettings.excludedLocations - - override fun saveLocations(locations: List) { - musicSettings.excludedLocations = locations - } - - override fun getPendingLocationsKey(): String = KEY_PENDING_EXCLUDED_LOCATIONS - - override fun convertUriToLocation(uri: Uri): Location.Unopened? { - return Location.Unopened.from(requireContext(), uri) - } - - override fun createLocationFromUri(context: Context, uri: Uri): Location.Unopened? { - return Location.Unopened.from(context, uri) - } - - private companion object { - const val KEY_PENDING_EXCLUDED_LOCATIONS = - BuildConfig.APPLICATION_ID + ".key.PENDING_EXCLUDED_LOCATIONS" - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt index 12614dcd3..15fe56ed6 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationAdapter.kt @@ -20,57 +20,126 @@ package org.oxycblt.auxio.music.locations import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView +import org.oxycblt.auxio.R import org.oxycblt.auxio.databinding.ItemMusicLocationBinding +import org.oxycblt.auxio.databinding.ItemNoLocationsBinding import org.oxycblt.auxio.list.recycler.DialogRecyclerView import org.oxycblt.auxio.util.context +import org.oxycblt.auxio.util.inflater import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -abstract class LocationAdapter(private val listener: Listener) : - RecyclerView.Adapter>() { +class LocationAdapter(private val listener: Listener) : + RecyclerView.Adapter() { private val _locations = mutableListOf() val locations: List = _locations - override fun getItemCount() = locations.size + override fun getItemCount() = if (locations.isEmpty()) 1 else locations.size - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = createViewHolder(parent) + override fun getItemViewType(position: Int): Int { + return if (locations.isEmpty()) VIEW_TYPE_EMPTY else VIEW_TYPE_LOCATION + } - override fun onBindViewHolder(holder: LocationViewHolder, position: Int) = - holder.bind(locations[position], listener) + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + return when (viewType) { + VIEW_TYPE_EMPTY -> EmptyLocationViewHolder.from(parent) + VIEW_TYPE_LOCATION -> LocationViewHolder.from(parent) + else -> throw IllegalArgumentException("Unknown view type: $viewType") + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + when (holder) { + is LocationViewHolder<*> -> { + @Suppress("UNCHECKED_CAST") + (holder as LocationViewHolder).bind(locations[position], listener) + } + is EmptyLocationViewHolder -> holder.bind() + } + } fun add(location: T) { if (_locations.contains(location)) return L.d("Adding $location") + val wasEmpty = _locations.isEmpty() _locations.add(location) - notifyItemInserted(_locations.lastIndex) + if (wasEmpty) { + notifyItemChanged(0) + } else { + notifyItemInserted(_locations.lastIndex) + } } fun addAll(locations: List) { L.d("Adding ${locations.size} locations") + val wasEmpty = _locations.isEmpty() val oldSize = _locations.size _locations.addAll(locations) - notifyItemRangeInserted(oldSize, locations.size) + if (wasEmpty && locations.isNotEmpty()) { + notifyItemChanged(0) + } else if (locations.isNotEmpty()) { + notifyItemRangeInserted(oldSize, locations.size) + } } fun remove(location: T) { L.d("Removing $location") val idx = _locations.indexOf(location) _locations.removeAt(idx) - notifyItemRemoved(idx) + if (_locations.isEmpty()) { + notifyItemChanged(0) + } else { + notifyItemRemoved(idx) + } } - protected abstract fun createViewHolder(parent: ViewGroup): LocationViewHolder + interface Listener { + fun onRemoveLocation(location: Location) + } - interface Listener { - fun onRemoveLocation(location: T) + companion object { + private const val VIEW_TYPE_EMPTY = 0 + private const val VIEW_TYPE_LOCATION = 1 } } -abstract class LocationViewHolder(protected val binding: ItemMusicLocationBinding) : +class LocationViewHolder(private val binding: ItemMusicLocationBinding) : DialogRecyclerView.ViewHolder(binding.root) { - fun bind(location: T, listener: LocationAdapter.Listener) { + fun bind(location: T, listener: LocationAdapter.Listener) { binding.locationPath.text = location.path.resolve(binding.context) binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) } } + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + LocationViewHolder( + ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) + } +} + +class EmptyLocationViewHolder(private val binding: ItemNoLocationsBinding) : + DialogRecyclerView.ViewHolder(binding.root) { + + fun bind() { + binding.locationPath.text = binding.context.getString(R.string.lbl_no_folders) + } + + companion object { + /** + * Create a new instance. + * + * @param parent The parent to inflate this instance from. + * @return A new instance. + */ + fun from(parent: ViewGroup) = + EmptyLocationViewHolder( + ItemNoLocationsBinding.inflate(parent.context.inflater, parent, false)) + } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationConfig.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationConfig.kt new file mode 100644 index 000000000..d2032e094 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationConfig.kt @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2025 Auxio Project + * LocationConfig.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 + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package org.oxycblt.auxio.music.locations + +import android.content.Context +import androidx.core.net.toUri +import org.oxycblt.auxio.util.splitEscaped +import org.oxycblt.musikr.fs.Location +import org.oxycblt.musikr.fs.mediastore.MediaStoreFS +import org.oxycblt.musikr.fs.saf.SAF + +sealed interface LocationConfig { + data class Filesystem(private val query: SAF.Query) : LocationConfig + + data class SystemDatabase(private val query: MediaStoreFS.Query) : LocationConfig + + companion object { + fun from(context: Context, string: String): LocationConfig? { + val typeSplit = string.splitEscaped('!') + if (typeSplit.size != 2) return null + val type = typeSplit[0] + val args = typeSplit[1].splitEscaped('|') + return when (type) { + "saf" -> { + if (args.size < 3) return null + val source = + args[0] + .splitEscaped(';') + .map { it.toUri() } + .mapNotNull { Location.Unopened.from(context, it)?.open(context) } + val exclude = + args[1] + .splitEscaped(';') + .map { it.toUri() } + .mapNotNull { Location.Unopened.from(context, it) } + val withHidden = args[2].toBoolean() + val query = + SAF.Query(source = source, exclude = exclude, withHidden = withHidden) + Filesystem(query = query) + } + "media" -> { + if (args.size < 3) return null + val include = + args[0] + .splitEscaped(';') + .map { it.toUri() } + .mapNotNull { Location.Unopened.from(context, it) } + val exclude = + args[1] + .splitEscaped(';') + .map { it.toUri() } + .mapNotNull { Location.Unopened.from(context, it) } + val excludeNonMusic = args[1].toBoolean() + SystemDatabase( + MediaStoreFS.Query( + include = include, + exclude = exclude, + excludeNonMusic = excludeNonMusic)) + } + else -> null + } + } + } +} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt index daeceb95f..3b70508bf 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/locations/LocationsDialog.kt @@ -25,36 +25,68 @@ import android.view.LayoutInflater import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog -import androidx.core.net.toUri -import androidx.recyclerview.widget.ConcatAdapter +import androidx.core.content.edit +import androidx.core.view.isVisible +import com.google.android.material.R as MR +import dagger.hilt.android.AndroidEntryPoint +import javax.inject.Inject import org.oxycblt.auxio.R import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding +import org.oxycblt.auxio.music.MusicLocationMode import org.oxycblt.auxio.music.MusicSettings import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment +import org.oxycblt.auxio.util.getAttrColorCompat import org.oxycblt.auxio.util.showToast import org.oxycblt.musikr.fs.Location import timber.log.Timber as L -abstract class LocationsDialog : - ViewBindingMaterialDialogFragment(), - LocationAdapter.Listener, - NewLocationFooterAdapter.Listener { - protected abstract val locationAdapter: LocationAdapter - private val locationFooterAdapter = NewLocationFooterAdapter(this) +@AndroidEntryPoint +class LocationsDialog : ViewBindingMaterialDialogFragment() { + + private val includeLocationListener = + object : LocationAdapter.Listener { + override fun onRemoveLocation(location: Location) { + includeLocationAdapter.remove(location as Location.Opened) + } + } + + private val excludeLocationListener = + object : LocationAdapter.Listener { + override fun onRemoveLocation(location: Location) { + excludeLocationAdapter.remove(location as Location.Unopened) + } + } + + private val filterLocationListener = + object : LocationAdapter.Listener { + override fun onRemoveLocation(location: Location) { + filterLocationAdapter.remove(location as Location.Unopened) + } + } + + private val includeLocationAdapter: LocationAdapter = + LocationAdapter(includeLocationListener) + private val excludeLocationAdapter: LocationAdapter = + LocationAdapter(excludeLocationListener) + private val filterLocationAdapter: LocationAdapter = + LocationAdapter(filterLocationListener) private var openDocumentTreeLauncher: ActivityResultLauncher? = null - abstract val musicSettings: MusicSettings + @Inject lateinit var musicSettings: MusicSettings + + private var isFilePickerMode = true + private var isIncludeMode = true + private var hasStoragePermission = false + private var isExtrasExpanded = false + private var pendingLocationCallback: ((Location.Unopened) -> Unit)? = null override fun onCreateBinding(inflater: LayoutInflater) = DialogMusicLocationsBinding.inflate(inflater) override fun onConfigDialog(builder: AlertDialog.Builder) { builder - .setTitle(getDialogTitle()) + .setTitle(R.string.lbl_music_sources) .setNegativeButton(R.string.lbl_cancel, null) - .setPositiveButton(R.string.lbl_save) { _, _ -> - val newDirs = locationAdapter.locations - saveLocations(newDirs) - } + .setPositiveButton(R.string.lbl_save) { _, _ -> saveChanges() } } override fun onBindingCreated( @@ -62,36 +94,152 @@ abstract class LocationsDialog : savedInstanceState: Bundle? ) { openDocumentTreeLauncher = - registerForActivityResult( - ActivityResultContracts.OpenDocumentTree(), ::addDocumentTreeUriToDirs) + registerForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri -> + addDocumentTreeUriToDirs(uri) + } - binding.locationsRecycler.apply { - adapter = ConcatAdapter(locationAdapter, locationFooterAdapter) + binding.locationsIncludeRecycler.apply { + adapter = includeLocationAdapter itemAnimator = null } - val locations = - savedInstanceState?.getStringArrayList(getPendingLocationsKey())?.mapNotNull { - convertUriToLocation(it.toUri()) - } ?: getCurrentLocations() + binding.locationsExcludeRecycler.apply { + adapter = excludeLocationAdapter + itemAnimator = null + } - locationAdapter.addAll(locations) + binding.locationsFilterRecycler.apply { + adapter = filterLocationAdapter + itemAnimator = null + } + + // Load initial state from MusicSettings + loadInitialState(binding) + + // Set up string resources + binding.locationsModeHeader.setText(R.string.lbl_load_from) + binding.locationsModeExclude.setText(R.string.lbl_file_picker) + binding.locationsModeInclude.setText(R.string.lbl_system_database) + binding.locationsExcludeModeHeader.setText(R.string.lbl_filter_mode) + binding.locationsExcludeModeExclude.setText(R.string.lbl_include) + binding.locationsExcludeModeInclude.setText(R.string.lbl_exclude) + binding.locationsIncludeListHeader.setText(R.string.lbl_folders_to_load) + binding.locationsIncludeAdd.contentDescription = getString(R.string.desc_add_folder) + binding.locationsExcludeAdd.contentDescription = getString(R.string.desc_add_folder) + binding.locationsFilterAdd.contentDescription = getString(R.string.desc_add_folder) + binding.locationsExtrasDropdown.setText(R.string.lbl_extra_settings) + + // Set up extras dropdown click listener + binding.locationsExtrasDropdown.setOnClickListener { + isExtrasExpanded = !isExtrasExpanded + updateExtrasVisibility(binding) + } + + // Set up mode toggle listener + binding.folderModeGroup.addOnButtonCheckedListener { group, checkedId, isChecked -> + if (!isChecked) return@addOnButtonCheckedListener + + when (checkedId) { + R.id.locations_mode_exclude -> { + isFilePickerMode = true + updateModeUI(binding) + } + R.id.locations_mode_include -> { + isFilePickerMode = false + updateModeUI(binding) + } + } + } + + // Set up exclude/include mode toggle listener for System Database mode + binding.locationsExcludeModeGroup.addOnButtonCheckedListener { group, checkedId, isChecked + -> + if (!isChecked) return@addOnButtonCheckedListener + + when (checkedId) { + R.id.locations_exclude_mode_exclude -> { + isIncludeMode = true + updateExcludeModeUI(binding) + } + R.id.locations_exclude_mode_include -> { + isIncludeMode = false + updateExcludeModeUI(binding) + } + } + } + + // Set up add folder buttons + binding.locationsIncludeAdd.setOnClickListener { + pendingLocationCallback = { location -> + location.open(requireContext())?.let { opened -> + includeLocationAdapter.add(opened) + } + } + onNewLocation() + } + binding.locationsExcludeAdd.setOnClickListener { + pendingLocationCallback = { location -> excludeLocationAdapter.add(location) } + onNewLocation() + } + binding.locationsFilterAdd.setOnClickListener { + pendingLocationCallback = { location -> filterLocationAdapter.add(location) } + onNewLocation() + } + + // Set up grant permission card click + binding.locationsPermsContainer.setOnClickListener { + // TODO: Implement permission request + L.d("Grant permission clicked") + } + + // Initialize UI state + updateModeUI(binding) + updateExtrasVisibility(binding) + } + + private fun loadInitialState(binding: DialogMusicLocationsBinding) { + // Determine mode based on the locationMode setting + isFilePickerMode = musicSettings.locationMode == MusicLocationMode.SAF + + if (isFilePickerMode) { + // File picker mode - load music locations and excluded locations + includeLocationAdapter.addAll(musicSettings.musicLocations) + excludeLocationAdapter.addAll(musicSettings.excludedLocations) + binding.configSwitchFilePicker.isChecked = musicSettings.withHidden + binding.folderModeGroup.check(R.id.locations_mode_exclude) + } else { + // System database mode - load excluded locations + // Filter locations come from exclude list + filterLocationAdapter.addAll(musicSettings.excludedLocations) + binding.configSwitchSystem.isChecked = !musicSettings.excludeNonMusic + + // Determine include/exclude mode based on whether we have exclude locations + // If we have exclude locations, we're in exclude mode + isIncludeMode = musicSettings.excludedLocations.isEmpty() + binding.locationsExcludeModeGroup.check( + if (isIncludeMode) R.id.locations_exclude_mode_exclude + else R.id.locations_exclude_mode_include) + binding.folderModeGroup.check(R.id.locations_mode_include) + } + + // TODO: Check storage permission status + hasStoragePermission = false } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) - outState.putStringArrayList( - getPendingLocationsKey(), - ArrayList(locationAdapter.locations.map { it.uri.toString() })) + // TODO } override fun onDestroyBinding(binding: DialogMusicLocationsBinding) { super.onDestroyBinding(binding) openDocumentTreeLauncher = null - binding.locationsRecycler.adapter = null + binding.locationsIncludeRecycler.adapter = null + binding.locationsExcludeRecycler.adapter = null + binding.locationsFilterRecycler.adapter = null } - override fun onNewLocation() { + private fun onNewLocation() { L.d("Opening launcher") val launcher = requireNotNull(openDocumentTreeLauncher) { "Document tree launcher was not available" } @@ -106,31 +254,243 @@ abstract class LocationsDialog : private fun addDocumentTreeUriToDirs(uri: Uri?) { if (uri == null) { L.d("No URI given (user closed the dialog)") + pendingLocationCallback = null return } val context = requireContext() - val location = createLocationFromUri(context, uri) + val location = Location.Unopened.from(context, uri) if (location != null) { - locationAdapter.add(location) + pendingLocationCallback?.invoke(location) } else { requireContext().showToast(R.string.err_bad_location) } + pendingLocationCallback = null } - override fun onRemoveLocation(location: T) { - locationAdapter.remove(location) + private fun updateModeUI(binding: DialogMusicLocationsBinding) { + with(binding) { + if (isFilePickerMode) { + // File Picker mode + locationsModeDesc.setText(R.string.desc_file_picker) + + // Update permission section + locationsPermsDesc.setText(R.string.lbl_grant_storage_anyway) + locationsPermsSubtitle.setText(R.string.desc_grant_storage_anyway) + + // File Picker mode - no need to update switch text as it's set in XML + } else { + // System Database mode + locationsModeDesc.setText(R.string.desc_system_database) + + // Update permission section + locationsPermsDesc.setText(R.string.lbl_grant_storage) + locationsPermsSubtitle.setText(R.string.desc_grant_storage_required) + + // Update exclude mode description based on selection + updateExcludeModeUI(binding) + + // System Database mode - no need to update switch text as it's set in XML + } + + // Update enabled state based on permission + updatePermissionDependentUI(binding) + // Update card colors based on mode and permission + updatePermissionCardColors(binding) + // Update permission card visibility + updatePermissionCardVisibility(binding) + // Update extras visibility based on current state + updateExtrasVisibility(binding) + } } - protected abstract fun getDialogTitle(): Int + private fun updateExcludeModeUI(binding: DialogMusicLocationsBinding) { + with(binding) { + if (isIncludeMode) { + locationsExcludeModeDesc.setText(R.string.desc_include_folders) + } else { + locationsExcludeModeDesc.setText(R.string.desc_exclude_folders) + } + } + } - protected abstract fun getCurrentLocations(): List + private fun updatePermissionDependentUI(binding: DialogMusicLocationsBinding) { + with(binding) { + // Only disable views in System Database mode when permission not granted + // File Picker mode doesn't require storage permission + val isEnabled = isFilePickerMode || hasStoragePermission - protected abstract fun saveLocations(locations: List) + locationsIncludeListHeader.isEnabled = isEnabled + locationsIncludeAdd.isEnabled = isEnabled + locationsIncludeRecycler.isEnabled = isEnabled - protected abstract fun getPendingLocationsKey(): String + locationsExcludeModeHeader.isEnabled = isEnabled + locationsExcludeModeGroup.isEnabled = isEnabled + locationsExcludeModeDesc.isEnabled = isEnabled + locationsExcludeModeExclude.isEnabled = isEnabled + locationsExcludeModeInclude.isEnabled = isEnabled - protected abstract fun convertUriToLocation(uri: Uri): T? + locationsExcludeListHeader.isEnabled = isEnabled + locationsExcludeAdd.isEnabled = isEnabled + locationsExcludeRecycler.isEnabled = isEnabled - protected abstract fun createLocationFromUri(context: android.content.Context, uri: Uri): T? + locationsFilterListHeader.isEnabled = isEnabled + locationsFilterAdd.isEnabled = isEnabled + locationsFilterRecycler.isEnabled = isEnabled + + configSwitchFilePicker.isEnabled = isEnabled + configSwitchSystem.isEnabled = isEnabled + } + } + + private fun updatePermissionCardColors(binding: DialogMusicLocationsBinding) { + val context = requireContext() + with(binding.locationsPermsCard) { + if (isFilePickerMode) { + // File Picker mode - use secondary colors + setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorSecondaryContainer)) + binding.locationsPermsDesc.setTextColor( + context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)) + binding.locationsPermsSubtitle.setTextColor( + context.getAttrColorCompat(MR.attr.colorSecondary)) + binding.locationsPermsOpen.imageTintList = + context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer) + } else { + // System Database mode - use error colors if no permission, secondary colors if + // granted + if (hasStoragePermission) { + // Has permission - use secondary colors + setCardBackgroundColor( + context.getAttrColorCompat(MR.attr.colorSecondaryContainer)) + binding.locationsPermsDesc.setTextColor( + context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer)) + binding.locationsPermsSubtitle.setTextColor( + context.getAttrColorCompat(MR.attr.colorSecondary)) + binding.locationsPermsOpen.imageTintList = + context.getAttrColorCompat(MR.attr.colorOnSecondaryContainer) + } else { + setCardBackgroundColor(context.getAttrColorCompat(MR.attr.colorErrorContainer)) + binding.locationsPermsDesc.setTextColor( + context.getAttrColorCompat(MR.attr.colorOnErrorContainer)) + binding.locationsPermsSubtitle.setTextColor( + context.getAttrColorCompat(MR.attr.colorError)) + binding.locationsPermsOpen.imageTintList = + context.getAttrColorCompat(MR.attr.colorOnErrorContainer) + } + } + } + } + + private fun updatePermissionCardVisibility(binding: DialogMusicLocationsBinding) { + with(binding) { + // Hide the permission card when permissions are granted + locationsPermsContainer.isVisible = !hasStoragePermission + } + } + + private fun updateExtrasVisibility(binding: DialogMusicLocationsBinding) { + with(binding) { + // Update dropdown icon rotation + locationsExtrasDropdownIcon.rotation = if (isExtrasExpanded) 180f else 0f + + if (isFilePickerMode) { + // File Picker mode - show include/exclude lists when expanded + // Include section + locationsIncludeListHeaderDivider.isVisible = true + locationsIncludeListHeader.isVisible = true + locationsIncludeAdd.isVisible = true + locationsIncludeRecycler.isVisible = true + + // Show dividers and exclude section only when expanded + locationsExcludeListHeader.isVisible = isExtrasExpanded + locationsExcludeAdd.isVisible = isExtrasExpanded + locationsExcludeRecycler.isVisible = isExtrasExpanded + + // Hide filter mode section completely + locationsExcludeModeHeader.isVisible = false + locationsExcludeModeGroup.isVisible = false + locationsExcludeModeDesc.isVisible = false + locationsFilterModeDivider.isVisible = false + locationsFilterListHeader.isVisible = false + locationsFilterAdd.isVisible = false + locationsFilterRecycler.isVisible = false + locationsExcludeListDivider.isVisible = false + + // Config section + configDivider.isVisible = isExtrasExpanded + configSwitchFilePicker.isVisible = isExtrasExpanded + configSwitchSystem.isVisible = false + } else { + // System Database mode - show filter mode when expanded + // Hide include section + locationsIncludeListHeaderDivider.isVisible = false + locationsIncludeListHeader.isVisible = false + locationsIncludeAdd.isVisible = false + locationsIncludeRecycler.isVisible = false + + // Hide exclude section (at bottom) + locationsExcludeListDivider.isVisible = false + locationsExcludeListHeader.isVisible = false + locationsExcludeAdd.isVisible = false + locationsExcludeRecycler.isVisible = false + + // Show filter mode section only when expanded + locationsExcludeModeHeader.isVisible = isExtrasExpanded + locationsExcludeModeGroup.isVisible = isExtrasExpanded + locationsExcludeModeDesc.isVisible = isExtrasExpanded + locationsFilterModeDivider.isVisible = isExtrasExpanded + locationsFilterListHeader.isVisible = isExtrasExpanded + locationsFilterAdd.isVisible = isExtrasExpanded + locationsFilterRecycler.isVisible = isExtrasExpanded + + // Config section + configDivider.isVisible = isExtrasExpanded + configSwitchFilePicker.isVisible = false + configSwitchSystem.isVisible = isExtrasExpanded + } + } + } + + private fun saveChanges() { + val binding = requireBinding() + + // Save the mode setting + musicSettings.locationMode = if (isFilePickerMode) MusicLocationMode.SAF else MusicLocationMode.SYSTEM + + if (isFilePickerMode) { + // File picker mode - save include and exclude locations + musicSettings.musicLocations = includeLocationAdapter.locations + musicSettings.excludedLocations = excludeLocationAdapter.locations + + // Update withHidden setting + val withHidden = binding.configSwitchFilePicker.isChecked + if (musicSettings.withHidden != withHidden) { + binding.root.context.getSharedPreferences("auxio_preferences", 0).edit { + putBoolean(getString(R.string.set_key_with_hidden), withHidden) + apply() + } + } + } else { + // System database mode - clear music locations and save filter locations + musicSettings.musicLocations = emptyList() + + // In include mode, we don't have any excluded locations + // In exclude mode, we save the filter locations as excluded + musicSettings.excludedLocations = + if (isIncludeMode) { + emptyList() + } else { + filterLocationAdapter.locations + } + + // Update excludeNonMusic setting + val excludeNonMusic = !binding.configSwitchSystem.isChecked + if (musicSettings.excludeNonMusic != excludeNonMusic) { + binding.root.context.getSharedPreferences("auxio_preferences", 0).edit { + putBoolean(getString(R.string.set_key_exclude_non_music), excludeNonMusic) + apply() + } + } + } + } } diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt deleted file mode 100644 index cf950f963..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationAdapter.kt +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * MusicLocationAdapter.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.view.ViewGroup -import org.oxycblt.auxio.databinding.ItemMusicLocationBinding -import org.oxycblt.auxio.util.inflater -import org.oxycblt.musikr.fs.Location - -/** - * [LocationAdapter] that manages a list of [Location.Opened] music directory instances. - * - * @param listener A [LocationAdapter.Listener] to bind interactions to. - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicLocationAdapter(listener: LocationAdapter.Listener) : - LocationAdapter(listener) { - override fun createViewHolder(parent: ViewGroup): LocationViewHolder = - MusicLocationViewHolder.from(parent) -} - -/** - * A [LocationViewHolder] that displays a [Location.Opened]. Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class MusicLocationViewHolder private constructor(binding: ItemMusicLocationBinding) : - LocationViewHolder(binding) { - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: ViewGroup) = - MusicLocationViewHolder( - ItemMusicLocationBinding.inflate(parent.context.inflater, parent, false)) - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt deleted file mode 100644 index cca6e1778..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/MusicLocationsDialog.kt +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 Auxio Project - * MusicLocationsDialog.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.content.Context -import android.net.Uri -import dagger.hilt.android.AndroidEntryPoint -import javax.inject.Inject -import org.oxycblt.auxio.BuildConfig -import org.oxycblt.auxio.R -import org.oxycblt.auxio.music.MusicSettings -import org.oxycblt.musikr.fs.Location - -/** - * Dialog that manages the music locations setting. - * - * @author Alexander Capehart (OxygenCobalt) - */ -@AndroidEntryPoint -class MusicLocationsDialog : LocationsDialog() { - override val locationAdapter = MusicLocationAdapter(this) - - @Inject override lateinit var musicSettings: MusicSettings - - override fun getDialogTitle(): Int = R.string.set_locations - - override fun getCurrentLocations(): List = musicSettings.musicLocations - - override fun saveLocations(locations: List) { - musicSettings.musicLocations = locations - } - - override fun getPendingLocationsKey(): String = KEY_PENDING_LOCATIONS - - override fun convertUriToLocation(uri: Uri): Location.Opened? { - val context = requireContext() - return Location.Unopened.from(context, uri)?.open(context) - } - - override fun createLocationFromUri(context: Context, uri: Uri): Location.Opened? { - return Location.Unopened.from(context, uri)?.open(context) - } - - private companion object { - const val KEY_PENDING_LOCATIONS = BuildConfig.APPLICATION_ID + ".key.PENDING_LOCATIONS" - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/music/locations/NewLocationFooterAdapter.kt b/app/src/main/java/org/oxycblt/auxio/music/locations/NewLocationFooterAdapter.kt deleted file mode 100644 index 4623db510..000000000 --- a/app/src/main/java/org/oxycblt/auxio/music/locations/NewLocationFooterAdapter.kt +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2024 Auxio Project - * NewLocationFooterAdapter.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 - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.oxycblt.auxio.music.locations - -import android.view.View -import android.view.ViewGroup -import androidx.recyclerview.widget.RecyclerView -import org.oxycblt.auxio.databinding.ItemNewMusicLocationBinding -import org.oxycblt.auxio.list.recycler.DialogRecyclerView -import org.oxycblt.auxio.music.decision.AddToPlaylistDialog -import org.oxycblt.auxio.util.inflater - -/** - * A purely-visual [RecyclerView.Adapter] that acts as a footer providing a "New Playlist" choice in - * [AddToPlaylistDialog]. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class NewLocationFooterAdapter(private val listener: Listener) : - RecyclerView.Adapter() { - override fun getItemCount() = 1 - - override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = - NewLocationFooterViewHolder.from(parent) - - override fun onBindViewHolder(holder: NewLocationFooterViewHolder, position: Int) { - holder.bind(listener) - } - - /** A listener for [NewLocationFooterAdapter] interactions. */ - interface Listener { - /** Called when the footer has been pressed, requesting to create a new location. */ - fun onNewLocation() - } -} - -/** - * A [RecyclerView.ViewHolder] that displays a "New Playlist" choice in [NewLocationFooterAdapter]. - * Use [from] to create an instance. - * - * @author Alexander Capehart (OxygenCobalt) - */ -class NewLocationFooterViewHolder -private constructor(private val binding: ItemNewMusicLocationBinding) : - DialogRecyclerView.ViewHolder(binding.root) { - /** - * Bind new data to this instance. - * - * @param listener A [NewLocationFooterAdapter.Listener] to bind interactions to. - */ - fun bind(listener: NewLocationFooterAdapter.Listener) { - binding.root.setOnClickListener { listener.onNewLocation() } - } - - companion object { - /** - * Create a new instance. - * - * @param parent The parent to inflate this instance from. - * @return A new instance. - */ - fun from(parent: View) = - NewLocationFooterViewHolder( - ItemNewMusicLocationBinding.inflate(parent.context.inflater)) - } -} diff --git a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt index 791ba5b53..3ee3e47b9 100644 --- a/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt +++ b/app/src/main/java/org/oxycblt/auxio/settings/RootPreferenceFragment.kt @@ -56,10 +56,6 @@ class RootPreferenceFragment : BasePreferenceFragment(R.xml.preferences_root) { findNavController() .navigateSafe(RootPreferenceFragmentDirections.musicLocationsSettings()) } - getString(R.string.set_key_excluded_dirs) -> { - findNavController() - .navigateSafe(RootPreferenceFragmentDirections.excludedLocationsSettings()) - } } } diff --git a/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt b/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt index d5f9465f0..f1273fcc5 100644 --- a/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt +++ b/app/src/main/java/org/oxycblt/auxio/util/LangUtil.kt @@ -63,3 +63,48 @@ fun lazyReflectedMethod(clazz: KClass<*>, method: String, vararg params: KClass< it.isAccessible = true } } + +/** + * Split a [String] by the given selector, automatically handling escaped characters that satisfy + * the selector. + * + * @param selector A block that determines if the string should be split at a given character. + * @return One or more [String]s split by the selector. + */ +internal fun String.splitEscaped(selector: Char): List { + val split = mutableListOf() + var currentString = "" + var i = 0 + + while (i < length) { + val a = get(i) + val b = getOrNull(i + 1) + + if (a == selector) { + // Non-escaped separator, split the string here, making sure any stray whitespace + // is removed. + split.add(currentString) + currentString = "" + i++ + continue + } + + if (b != null && a == '\\' && a == selector) { + // 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 +} diff --git a/app/src/main/res/drawable/drop_down_24.xml b/app/src/main/res/drawable/drop_down_24.xml new file mode 100644 index 000000000..dfea22cd0 --- /dev/null +++ b/app/src/main/res/drawable/drop_down_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/drop_up_24.xml b/app/src/main/res/drawable/drop_up_24.xml new file mode 100644 index 000000000..05735c6a5 --- /dev/null +++ b/app/src/main/res/drawable/drop_up_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_open_20.xml b/app/src/main/res/drawable/ic_open_20.xml new file mode 100644 index 000000000..cc6758d3e --- /dev/null +++ b/app/src/main/res/drawable/ic_open_20.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/layout/dialog_music_locations.xml b/app/src/main/res/layout/dialog_music_locations.xml index 8f015dec3..fa18e9658 100644 --- a/app/src/main/res/layout/dialog_music_locations.xml +++ b/app/src/main/res/layout/dialog_music_locations.xml @@ -1,19 +1,399 @@ - + android:layout_height="match_parent" + android:orientation="vertical"> - + android:layout_height="match_parent"> - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/item_no_locations.xml b/app/src/main/res/layout/item_no_locations.xml new file mode 100644 index 000000000..95f5f8409 --- /dev/null +++ b/app/src/main/res/layout/item_no_locations.xml @@ -0,0 +1,26 @@ + + + + + + diff --git a/app/src/main/res/navigation/inner.xml b/app/src/main/res/navigation/inner.xml index 61fcfd3a5..8602877b4 100644 --- a/app/src/main/res/navigation/inner.xml +++ b/app/src/main/res/navigation/inner.xml @@ -570,7 +570,7 @@ \ No newline at end of file diff --git a/app/src/main/res/navigation/outer.xml b/app/src/main/res/navigation/outer.xml index 60d81d6b2..0891e4b91 100644 --- a/app/src/main/res/navigation/outer.xml +++ b/app/src/main/res/navigation/outer.xml @@ -36,9 +36,6 @@ - - auxio_excluded_locations auxio_separators auxio_auto_sort_names + auxio_saf_mode auxio_headset_autoplay auxio_replay_gain diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9111f1465..1eb5ee534 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -16,9 +16,33 @@ Monitoring music library Retry - Pick folders + Music Sources + Grant + + + Load From + File Picker + System + Load music from the folders that you select. Slower, but more reliable. Requires the vanilla file manager app to be installed. + Load music that the Android OS automatically detects. Faster, but less reliable. Manufacturers might break this. + Storage Access Recommended + Granting external storage permissions can fix issues on some devices. + Storage Access Required + Grant external storage permissions to enable this option. + Folders to Load + Folders to Ignore + Filtered Folders + Filter Mode + Include + Exclude + Audio files outside of the selected folders will be ignored. + Audio files in the selected folders will be ignored. + Exclude Non-Music + Load Hidden Folders + Extra Settings + Add Folder Songs Song @@ -332,6 +356,7 @@ No app found that can handle this task This folder is not supported + No Folders diff --git a/app/src/main/res/values/typography.xml b/app/src/main/res/values/typography.xml index af958330b..fabc21d6b 100644 --- a/app/src/main/res/values/typography.xml +++ b/app/src/main/res/values/typography.xml @@ -78,6 +78,13 @@ -0.01125 + +