diff --git a/CHANGELOG.md b/CHANGELOG.md index 439efa33e..f05f3f5fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 4.0.6 + +#### What's Improved +- Added option to enable/disable the file tree cache (disabled by default) +to prevent the library from not being updated on Samsung devices + +#### What's Fixed +- Fixed loading failing/crashing the app on some devices +- Fixed file tree cache being stored in cache storage rather than app storage + ## 4.0.5 #### What's Improved diff --git a/app/build.gradle b/app/build.gradle index 713ae9f14..e12d5daf3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -18,8 +18,8 @@ android { defaultConfig { applicationId namespace - versionName "4.0.5" - versionCode 64 + versionName "4.0.6" + versionCode 65 minSdk min_sdk targetSdk target_sdk 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..8574205b2 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicRepository.kt @@ -29,6 +29,7 @@ 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.NoOpFileTreeCache import org.oxycblt.auxio.music.shim.WriteOnlyFileTreeCache import org.oxycblt.auxio.music.shim.WriteOnlyMutableCache import org.oxycblt.musikr.IndexingProgress @@ -396,8 +397,12 @@ constructor( 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)) + if (musicSettings.useFileTreeCache) { + if (withCache) FileTreeCache.from(context) + else WriteOnlyFileTreeCache(FileTreeCache.from(context)) + } else { + NoOpFileTreeCache() + } val query = Query(source = locations, exclude = excludedLocations) val storage = Storage(cache, covers, storedPlaylists, fileTreeCache) val interpretation = Interpretation(nameFactory, separators, withHidden) 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..01f6e15e9 100644 --- a/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt +++ b/app/src/main/java/org/oxycblt/auxio/music/MusicSettings.kt @@ -51,6 +51,8 @@ interface MusicSettings : Settings { var separators: String /** Whether to enable more advanced sorting by articles and numbers. */ val intelligentSorting: Boolean + /** Whether to use the file-system cache for improved loading times. */ + val useFileTreeCache: Boolean interface Listener { /** Called when the current music locations changed. */ @@ -133,6 +135,9 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont override val intelligentSorting: Boolean get() = sharedPreferences.getBoolean(getString(R.string.set_key_auto_sort_names), true) + override val useFileTreeCache: Boolean + get() = sharedPreferences.getBoolean(getString(R.string.set_key_fs_cache), false) + override fun onSettingChanged(key: String, listener: MusicSettings.Listener) { // TODO: Differentiate "hard reloads" (Need the cache) and "Soft reloads" // (just need to manipulate data) @@ -145,7 +150,8 @@ 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_exclude_non_music), + getString(R.string.set_key_fs_cache) -> { L.d("Dispatching indexing setting change for $key") listener.onIndexingSettingChanged() } diff --git a/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt b/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt new file mode 100644 index 000000000..a28de5139 --- /dev/null +++ b/app/src/main/java/org/oxycblt/auxio/music/shim/NoOpFileTreeCache.kt @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2025 Auxio Project + * NoOpFileTreeCache.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 + +/** + * A no-op implementation of [FileTreeCache] that doesn't cache anything. This implementation always + * returns cache misses and discards all updates. + */ +class NoOpFileTreeCache : FileTreeCache { + override fun read(): FileTree = NoOpFileTree() +} + +/** + * A no-op implementation of [FileTree] that doesn't cache anything. All queries return null (cache + * miss) and all updates are discarded. + */ +class NoOpFileTree : 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) { + // Do nothing - discard the update + } + + 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) { + // Do nothing - discard the update + } + + override suspend fun write() { + // Do nothing - no cache to write + } +} diff --git a/app/src/main/res/values/settings.xml b/app/src/main/res/values/settings.xml index 86e8d255a..fd5d1857b 100644 --- a/app/src/main/res/values/settings.xml +++ b/app/src/main/res/values/settings.xml @@ -15,6 +15,7 @@ auxio_observing auxio_music_dirs auxio_excluded_dirs + auxio_fs_cache 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 26d456242..9111f1465 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 + Use file-system cache + Improves loading times, but can prevent new music from being added Excluded folders Manage folders to exclude from music loading Refresh music diff --git a/app/src/main/res/xml/preferences_root.xml b/app/src/main/res/xml/preferences_root.xml index 12f8fb94b..0b4009a44 100644 --- a/app/src/main/res/xml/preferences_root.xml +++ b/app/src/main/res/xml/preferences_root.xml @@ -38,6 +38,13 @@ app:summary="@string/set_excluded_locations_desc" app:title="@string/set_excluded_locations" /> + + + (jsonContent) + val fileTreeCache = json.decodeFromStream(cacheFile.inputStream()) FileTreeImpl( context, fileTreeCache.directories.toMutableMap(), @@ -153,9 +152,7 @@ private class FileTreeImpl( val fileTreeCache = FileTreeData( directories = mutableDirectories.toMap(), files = mutableFiles.toMap()) - - val jsonContent = json.encodeToString(fileTreeCache) - cacheFile.writeText(jsonContent) + json.encodeToStream(fileTreeCache, cacheFile.outputStream()) Log.d(TAG, "Successfully wrote cache to disk") } catch (e: Exception) { Log.e(TAG, "Failed to write cache file", e) 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..c1736e8db 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 @@ -30,6 +30,15 @@ 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/RateLimitedContentResolver.kt b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt new file mode 100644 index 000000000..548c139c4 --- /dev/null +++ b/musikr/src/main/java/org/oxycblt/musikr/fs/device/RateLimitedContentResolver.kt @@ -0,0 +1,121 @@ +/* + * 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 + } + } + } +}