Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Improve Connect playback, local tracks and playlist experience

Leloniod188e86a3250
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 2b67b37..7128684 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -187,6 +187,7 @@ android {
}
dependencies {
+ testImplementation("junit:junit:4.13.2")
implementation(libs.timber)
implementation(libs.androidx.core.ktx)
// Installs baseline-prof.txt on first run, so the code the bar and the
diff --git a/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt b/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt
new file mode 100644
index 0000000..333354f
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/FollowedReleases.kt
@@ -0,0 +1,135 @@
+package dev.lelonio.square.data
+
+import java.io.File
+import java.time.LocalDate
+import java.util.concurrent.atomic.AtomicInteger
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+
+/** Public discographies are cached per artist; the private follow list is read afresh. */
+class FollowedReleases(private val api: SpotifyApi, private val directory: File) {
+ data class Result(val albums: List<AlbumDto>, val artistCount: Int, val failedArtists: Int)
+
+ @Serializable
+ private data class Entry(val savedAt: Long, val albums: List<AlbumDto>)
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun artists(): List<ArtistDto> {
+ val gathered = mutableListOf<ArtistDto>()
+ val cursors = mutableSetOf<String>()
+ var after: String? = null
+ while (true) {
+ val page = api.followedArtists(after = after).artists
+ gathered += page.items
+ val next = page.cursors?.after?.takeIf { page.items.isNotEmpty() } ?: break
+ check(cursors.add(next)) { "Repeated followed-artist cursor" }
+ after = next
+ }
+ return gathered.distinctBy { it.id ?: it.uri }
+ }
+
+ suspend fun load(force: Boolean = false, onProgress: (Int, Int) -> Unit = { _, _ -> }): Result {
+ val artists = artists()
+ val limit = Semaphore(3)
+ val completed = AtomicInteger()
+ val failed = AtomicInteger()
+ val cutoff = LocalDate.now().minusMonths(12)
+ onProgress(0, artists.size)
+ val albums = coroutineScope {
+ artists.map { artist ->
+ async {
+ limit.withPermit {
+ val id = artist.id ?: artist.uri?.substringAfterLast(':')
+ val cached = id?.let { read(it) }
+ val releases = try {
+ if (id == null) error("Artist has no id")
+ if (!force && cached != null && System.currentTimeMillis() - cached.savedAt in 0..CACHE_MS) {
+ cached.albums
+ } else {
+ discography(id).also { write(id, it) }
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ failed.incrementAndGet()
+ cached?.albums.orEmpty()
+ }
+ // Progress is reported on the caller's coroutine dispatcher.
+ onProgress(completed.incrementAndGet(), artists.size)
+ releases
+ }
+ }
+ }.awaitAll().flatten()
+ }
+ return Result(recentReleases(albums, cutoff, LocalDate.now()), artists.size, failed.get())
+ }
+
+ private suspend fun discography(id: String): List<AlbumDto> {
+ val albums = mutableListOf<AlbumDto>()
+ var offset = 0
+ while (true) {
+ val page = api.artistAlbums(id, groups = "album,single", limit = 50, offset = offset)
+ if (page.next != null && offset > 0) {
+ val seen = albums.map { it.uri ?: it.id }.toSet()
+ check(page.items.any { (it.uri ?: it.id) !in seen }) { "Repeated artist album page" }
+ }
+ albums += page.items
+ if (page.next == null) break
+ check(page.items.isNotEmpty()) { "Empty artist page with a continuation" }
+ offset += page.items.size
+ }
+ return albums.distinctBy { it.uri ?: it.id }
+ }
+
+ private suspend fun read(id: String): Entry? = withContext(Dispatchers.IO) {
+ runCatching { json.decodeFromString<Entry>(file(id).readText()) }.getOrNull()
+ }
+
+ private suspend fun write(id: String, albums: List<AlbumDto>) = withContext(Dispatchers.IO) {
+ // Cache failures do not turn a successfully fetched artist into an error.
+ runCatching {
+ directory.mkdirs()
+ val target = file(id)
+ val temp = File(directory, "$id.tmp")
+ temp.writeText(json.encodeToString(Entry.serializer(), Entry(System.currentTimeMillis(), albums)))
+ check(temp.renameTo(target))
+ }
+ Unit
+ }
+
+ private fun file(id: String): File {
+ require(id.matches(Regex("[A-Za-z0-9]+")))
+ return File(directory, "$id.json")
+ }
+
+ companion object {
+ private const val CACHE_MS = 6 * 60 * 60 * 1_000L
+ }
+}
+
+/** Spotify can give a day, a month or just a year. Never invent a recent day. */
+internal fun releaseDay(date: String?): LocalDate? = runCatching {
+ when (date?.length) {
+ 4 -> LocalDate.parse("$date-01-01")
+ 7 -> LocalDate.parse("$date-01")
+ 10 -> LocalDate.parse(date)
+ else -> null
+ }
+}.getOrNull()
+
+internal fun recentReleases(albums: List<AlbumDto>, cutoff: LocalDate, today: LocalDate): List<AlbumDto> =
+ albums.filter { album ->
+ val day = releaseDay(album.releaseDate)
+ day != null && day >= cutoff && day <= today &&
+ (album.albumGroup == null || album.albumGroup in setOf("album", "single")) &&
+ (album.uri != null || album.id != null)
+ }.sortedWith(compareByDescending<AlbumDto> { releaseDay(it.releaseDate) }.thenBy { it.name })
+ .distinctBy { it.uri ?: it.id }
diff --git a/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt b/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt
index b2a7f22..ac1c343 100644
--- a/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt
+++ b/app/src/main/java/dev/lelonio/square/data/GatewayTracks.kt
@@ -26,19 +26,24 @@ internal object GatewayTracks {
*/
private fun localTrack(data: JSONObject, addedAt: String?): CatalogTrack? {
val uri = data.optString("uri").takeIf(LocalLibrary::isSpotifyLocal) ?: return null
+ val parts = uri.removePrefix(LocalLibrary.SPOTIFY_PREFIX).split(':')
+ fun tag(key: String, index: Int): String = data.optString(key)
+ .takeUnless { it.isBlank() || it == "null" }
+ ?: runCatching { java.net.URLDecoder.decode(parts.getOrNull(index).orEmpty(), "UTF-8") }.getOrDefault("")
return CatalogTrack(
uri = uri,
- name = data.optString("name"),
- artist = data.optString("artistName"),
- album = data.optString("albumName"),
- durationMs = data.optJSONObject("localTrackDuration")?.optLong("totalMilliseconds") ?: 0L,
+ name = tag("name", 2),
+ artist = tag("artistName", 0),
+ album = tag("albumName", 1),
+ durationMs = data.optJSONObject("localTrackDuration")?.optLong("totalMilliseconds")
+ ?.takeIf { it > 0 } ?: parts.getOrNull(3)?.toLongOrNull()?.times(1000) ?: 0L,
addedAt = addedAt,
)
}
fun track(data: JSONObject?, addedAt: String?): CatalogTrack? {
if (data == null) return null
- if (data.optString("__typename") == "LocalTrack") return localTrack(data, addedAt)
+ if (LocalLibrary.isSpotifyLocal(data.optString("uri"))) return localTrack(data, addedAt)
val uri = data.optString("uri").takeIf { it.startsWith("spotify:track:") } ?: return null
if (data.optJSONObject("playability")?.optBoolean("playable", true) == false) return null
diff --git a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
index be534fe..fc9890a 100644
--- a/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
+++ b/app/src/main/java/dev/lelonio/square/data/LocalLibrary.kt
@@ -107,14 +107,31 @@ object LocalLibrary {
* within a few seconds, so a song does not land on its live version.
*/
fun match(entry: CatalogTrack, files: List<CatalogTrack>): CatalogTrack? {
- fun close(file: CatalogTrack) = entry.durationMs <= 0 || file.durationMs <= 0 ||
- kotlin.math.abs(file.durationMs - entry.durationMs) <= MATCH_SLACK_MS
- val title = normal(entry.name)
- val artist = normal(entry.artist)
- val base = normal(bare(entry.name))
- return files.firstOrNull { normal(it.name) == title && normal(it.artist) == artist && close(it) }
- ?: files.firstOrNull { normal(it.name) == title && close(it) }
- ?: files.firstOrNull { normal(bare(it.name)) == base && close(it) }
+ val parts = entry.uri.removePrefix(SPOTIFY_PREFIX).split(':')
+ fun part(index: Int): String = runCatching {
+ java.net.URLDecoder.decode(parts.getOrNull(index).orEmpty(), "UTF-8")
+ }.getOrDefault("")
+ val name = entry.name.ifBlank { part(2) }
+ val entryArtist = entry.artist.ifBlank { part(0) }
+ val entryAlbum = entry.album.ifBlank { part(1) }
+ val duration = entry.durationMs.takeIf { it > 0 }
+ ?: parts.getOrNull(3)?.toLongOrNull()?.times(1000) ?: 0L
+ fun close(file: CatalogTrack) = duration <= 0 || file.durationMs <= 0 ||
+ kotlin.math.abs(file.durationMs - duration) <= MATCH_SLACK_MS
+ val title = normal(name)
+ if (title.isEmpty()) return null
+ val artist = normal(entryArtist)
+ val album = normal(entryAlbum)
+ val base = normal(bare(name))
+ val candidates = files.filter { close(it) }
+ fun unique(matches: List<CatalogTrack>): CatalogTrack? =
+ matches.firstOrNull { artist.isNotEmpty() && album.isNotEmpty() &&
+ normal(it.artist) == artist && normal(it.album) == album }
+ ?: matches.singleOrNull()
+ val exact = candidates.filter { normal(it.name) == title }
+ return unique(exact.filter { artist.isNotEmpty() && normal(it.artist) == artist })
+ ?: unique(exact)
+ ?: unique(candidates.filter { base.isNotEmpty() && normal(bare(it.name)) == base })
}
/** Letters and digits only, without accents and case. */
@@ -167,9 +184,10 @@ object LocalLibrary {
context.contentResolver.query(
collection(),
columns,
- // Ringtones, notification sounds and voice recordings are all
- // in here too, and none of them belong in a music library.
- "${MediaStore.Audio.Media.IS_MUSIC} != 0",
+ // Downloaded MP3s are not always marked IS_MUSIC. Include indexed
+ // audio while excluding files assigned to system alerts.
+ "${MediaStore.Audio.Media.DURATION} > 0 AND ${MediaStore.Audio.Media.IS_RINGTONE} = 0 " +
+ "AND ${MediaStore.Audio.Media.IS_NOTIFICATION} = 0 AND ${MediaStore.Audio.Media.IS_ALARM} = 0",
null,
"${MediaStore.Audio.Media.DATE_ADDED} DESC",
)?.use { cursor ->
diff --git a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
index 0c3e8b7..e423e05 100644
--- a/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PreferencesStore.kt
@@ -17,24 +17,36 @@ class PreferencesStore(context: Context) {
private val prefs = context.applicationContext
.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
- private val _trackSort = MutableStateFlow(prefs.getString(KEY_TRACK_SORT, null))
+ data class TrackOrder(val sort: String? = null, val descending: Boolean = false)
- /** How the detail screen's track list is ordered; null until first chosen. */
- val trackSort: StateFlow<String?> = _trackSort.asStateFlow()
+ private val _trackOrders = MutableStateFlow(
+ prefs.all.keys.filter { it.startsWith("track_order:") }.associate { key ->
+ val uri = key.removePrefix("track_order:")
+ uri to TrackOrder(prefs.getString(key, null), prefs.getBoolean("track_direction:$uri", false))
+ },
+ )
+ val trackOrders = _trackOrders.asStateFlow()
- fun setTrackSort(value: String) {
- _trackSort.value = value
- prefs.edit().putString(KEY_TRACK_SORT, value).apply()
+ fun setTrackSort(uri: String, value: String) {
+ val previous = _trackOrders.value[uri] ?: TrackOrder()
+ _trackOrders.value = _trackOrders.value + (uri to previous.copy(sort = value))
+ prefs.edit().putString("track_order:$uri", value).apply()
}
- private val _trackSortDescending = MutableStateFlow(prefs.getBoolean(KEY_TRACK_DESC, false))
+ fun setTrackSortDescending(uri: String, value: Boolean) {
+ val previous = _trackOrders.value[uri] ?: TrackOrder()
+ _trackOrders.value = _trackOrders.value + (uri to previous.copy(descending = value))
+ // Persist a sort key even when only the direction was changed.
+ prefs.edit().putString("track_order:$uri", previous.sort ?: "ORIGINAL")
+ .putBoolean("track_direction:$uri", value).apply()
+ }
- /** Whether that order runs backwards; the direction is part of the sort. */
- val trackSortDescending: StateFlow<Boolean> = _trackSortDescending.asStateFlow()
+ private val _showConnectedDevice = MutableStateFlow(prefs.getBoolean("show_connected_device", true))
+ val showConnectedDevice = _showConnectedDevice.asStateFlow()
- fun setTrackSortDescending(value: Boolean) {
- _trackSortDescending.value = value
- prefs.edit().putBoolean(KEY_TRACK_DESC, value).apply()
+ fun setShowConnectedDevice(value: Boolean) {
+ _showConnectedDevice.value = value
+ prefs.edit().putBoolean("show_connected_device", value).apply()
}
/**
diff --git a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
index b2e69d2..05f4089 100644
--- a/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
+++ b/app/src/main/java/dev/lelonio/square/data/RemoteConnect.kt
@@ -21,6 +21,14 @@ import org.json.JSONObject
*/
object RemoteConnect {
+ private var playingAtOpen: Boolean? = null
+ internal var resumeHereHandler: ((RemotePlayback) -> Unit)? = null
+
+ /** Capture the choice once per foreground opening, before later pauses. */
+ fun onAppOpened() {
+ playingAtOpen = _playback.value?.playing
+ }
+
/** This device's own id, read once the engine has a session. */
private var ownId: String = ""
private var sdkId: String? = null
@@ -108,7 +116,11 @@ object RemoteConnect {
// the app believed the account and not its own ears.
val elsewhere = NativeBridge.playbackElsewhere && active != sdkId
_elsewhere.value = elsewhere
- _playback.value = playback?.takeIf { elsewhere }
+ val remote = playback?.takeIf { elsewhere }
+ if (playingAtOpen == null && remote != null && remote.uri.isNotEmpty()) {
+ playingAtOpen = remote.playing
+ }
+ _playback.value = remote
// The SDK adapter already owns its queue; it must not be adopted by librespot.
_here.value = playback?.takeIf { !elsewhere && active.isNotEmpty() && active != sdkId }
}
@@ -173,6 +185,7 @@ object RemoteConnect {
/** Forgets everything. For a session ending, where none of it is true any more. */
fun clear() {
+ playingAtOpen = null
sdkId = null
_elsewhere.value = false
_playback.value = null
@@ -202,7 +215,17 @@ object RemoteConnect {
// device on the other end is written to obey. Each one blocks on a request
// to the access point, so none of them may be called from the main thread.
- fun play(deviceId: String) = command(deviceId, "resume")
+ fun play(deviceId: String) {
+ val remote = _playback.value
+ if (playingAtOpen == false && remote?.deviceId == deviceId && !remote.playing) {
+ playingAtOpen = null
+ val handler = resumeHereHandler
+ if (handler != null) handler(remote)
+ else NativeBridge.resumeHere(remote.realContext.orEmpty(), remote.uri, remote.positionMs.toInt())
+ return
+ }
+ command(deviceId, "resume")
+ }
fun pause(deviceId: String) = command(deviceId, "pause")
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
index 513b03a..4fe4613 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -159,6 +159,7 @@ interface SpotifyApi {
@Query("include_groups") groups: String = "album,single",
@Query("limit") limit: Int = 20,
@Query("market") market: String? = null,
+ @Query("offset") offset: Int = 0,
): PageDto<AlbumDto>
@GET("v1/artists/{id}/related-artists")
@@ -553,6 +554,7 @@ data class AlbumDto(
* fills it, which is the one place it is needed.
*/
@SerialName("album_group") val albumGroup: String? = null,
+ @SerialName("album_type") val albumType: String? = null,
/** ISO date, and not always a full one — Spotify returns bare years too. */
@SerialName("release_date") val releaseDate: String? = null,
@SerialName("total_tracks") val totalTracks: Int = 0,
diff --git a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
index 3ef936e..91ff048 100644
--- a/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/LibrespotPlayer.kt
@@ -495,7 +495,46 @@ class LibrespotPlayer(
kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.Default,
)
+ // A fast Wi-Fi/cellular handover can invalidate Spirc without ever
+ // entering OfflineMode. Recover on the player looper, preserving the queue
+ // and position. Explicit pauses cancel the intent before a rebuild finishes.
+ private val sessionWatch = object : Runnable {
+ override fun run() {
+ if (released) return
+ if (!reconnecting && !OfflineMode.active.value) {
+ runCatching { dev.lelonio.square.data.RemoteConnect.refresh() }
+ }
+ if (!reconnecting && remote == null && !OfflineMode.active.value &&
+ (playWhenReady || wantPlay) && queue.items.isNotEmpty() && deviceGone
+ ) {
+ withDevice {
+ if (deviceGone) return@withDevice
+ engineQueueStale = true
+ pushQueue(startPlaying = wantPlay || playWhenReady, positionMs = positionMs.toInt())
+ }
+ }
+ handler.postDelayed(this, 5_000L)
+ }
+ }
+
+ private val resumeHereHandler: (dev.lelonio.square.data.RemotePlayback) -> Unit = { target ->
+ handler.post {
+ if (!released && focus.requestFocus()) {
+ Thread({
+ runCatching {
+ NativeBridge.resumeHere(target.realContext.orEmpty(), target.uri, target.positionMs.toInt())
+ }.onFailure {
+ android.util.Log.e("SquarePlayer", "could not resume Connect playback here", it)
+ handler.post { focus.abandonFocus() }
+ }
+ }, "square-resume-here").start()
+ }
+ }
+ }
+
init {
+ dev.lelonio.square.data.RemoteConnect.resumeHereHandler = resumeHereHandler
+ handler.postDelayed(sessionWatch, 2_000L)
// Coming back online, the engine has to be given this queue again.
//
// Offline the tracks are loaded one at a time, straight into the
@@ -510,26 +549,15 @@ class LibrespotPlayer(
.distinctUntilChanged()
.collect { offline ->
if (offline) return@collect
- // On returning online, guarantee native session reconnection
- kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
- runCatching { NativeBridge.reconnect() }
- .onFailure { android.util.Log.w("SquarePlayer", "auto-reconnect failed: ${it.message}") }
- }
handler.post {
if (released || queue.items.isEmpty()) return@post
- val shouldPlay = playWhenReady || wantPlay
- android.util.Log.i(
- "SquarePlayer",
- "back online: reconnected, restoring playback at ${positionMs}ms (shouldPlay=$shouldPlay)",
- )
- if (shouldPlay) {
- playbackState = Player.STATE_BUFFERING
+ withDevice {
+ val shouldPlay = playWhenReady || wantPlay
+ if (shouldPlay) playbackState = Player.STATE_BUFFERING
+ engineQueueStale = true
+ pushQueue(startPlaying = shouldPlay, positionMs = positionMs.toInt())
invalidateState()
}
- // From where it is, playing if it was: this is a
- // handover, not a restart, and the listener should hear
- // the same second of the same song either side of it.
- pushQueue(startPlaying = shouldPlay, positionMs = positionMs.toInt())
}
}
}
@@ -889,7 +917,7 @@ class LibrespotPlayer(
// for a few seconds. A stopped player refuses "play" (it only logs
// it), so the button spun forever; the track is loaded again where
// it was paused instead.
- if ((currentMediaItem == null || engineStopped) && queue.items.isNotEmpty()) {
+ if ((currentMediaItem == null || engineStopped || engineQueueStale) && queue.items.isNotEmpty()) {
engineStopped = false
playbackState = Player.STATE_BUFFERING
invalidateState()
@@ -1221,9 +1249,7 @@ class LibrespotPlayer(
// done here at all when there is nothing to restore — activating on
// launch would pull playback away from whatever the account is actually
// playing on.
- if (queue.items.isNotEmpty() && handOverNow) {
- pushQueue(startPlaying = false, positionMs = positionMs.toInt())
- }
+ engineQueueStale = true
invalidateState()
}
@@ -1247,7 +1273,11 @@ class LibrespotPlayer(
return
}
playbackState = if (wantPlay) Player.STATE_BUFFERING else Player.STATE_READY
- pushQueue(startPlaying = wantPlay, positionMs = positionMs.toInt())
+ engineQueueStale = true
+ // Restoring the screen must not activate this device. The initial
+ // Connect cluster may still be arriving, so an "elsewhere" guard is
+ // too early here. Only a Play pressed by the listener loads the queue.
+ if (wantPlay) pushQueue(startPlaying = true, positionMs = positionMs.toInt())
invalidateState()
}
@@ -1370,7 +1400,11 @@ class LibrespotPlayer(
override fun handleRelease(): ListenableFuture<*> {
released = true
+ if (dev.lelonio.square.data.RemoteConnect.resumeHereHandler === resumeHereHandler) {
+ dev.lelonio.square.data.RemoteConnect.resumeHereHandler = null
+ }
watch.cancel()
+ handler.removeCallbacks(sessionWatch)
handler.removeCallbacks(settleSkip)
focus.release()
engine("shutdown") { NativeBridge.shutdown() }
@@ -1603,6 +1637,7 @@ class LibrespotPlayer(
handler.removeCallbacks(stallWatch)
}
"playing" -> {
+ wantPlay = true
// A new track to watch, and one this side has not moved on
// from yet.
if (uri != advancedFrom) advancedFrom = null
@@ -1618,6 +1653,7 @@ class LibrespotPlayer(
onPlaybackActive(true)
}
"paused" -> {
+ if (!reconnecting && !deviceGone) wantPlay = false
playbackState = Player.STATE_READY
playWhenReady = false
// A pause is not a stall.
@@ -1650,6 +1686,7 @@ class LibrespotPlayer(
}
}
"stopped" -> {
+ if (!reconnecting && !deviceGone) wantPlay = false
playbackState = Player.STATE_IDLE
playWhenReady = false
engineStopped = true
diff --git a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
index 880db17..be5f16e 100644
--- a/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
+++ b/app/src/main/java/dev/lelonio/square/playback/PlaybackService.kt
@@ -1719,6 +1719,12 @@ class PlaybackService : MediaLibraryService() {
// Saved first: this is the last chance to record where the track was,
// and stopping is what makes the position worth having.
runCatching { savePlayback() }
+ // Closing a controller must leave the other device playing. Media3's
+ // helper pauses every player, including our mirrored Connect player.
+ if (dev.lelonio.square.data.RemoteConnect.elsewhereActive.value) {
+ stopSelf()
+ return
+ }
// Swiping the app away stops it. The service used to survive a swipe
// while something was playing, on the grounds that killing audio
// mid-track is rude, but a player that goes on after its app has been
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index fc08f75..c36a375 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -263,6 +263,7 @@ class MainActivity : ComponentActivity() {
getBooleanExtra(dev.lelonio.square.playback.EXTRA_OPEN_PLAYER, false)
override fun onStart() {
+ dev.lelonio.square.data.RemoteConnect.onAppOpened()
androidx.core.content.ContextCompat.registerReceiver(
this,
listenRequest,
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 2bd55af..d15ba38 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -333,6 +333,59 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val newPage: StateFlow<NewPage> = _newPage.asStateFlow()
private var newPageJob: Job? = null
+ data class FollowedReleaseState(
+ val albums: List<dev.lelonio.square.data.AlbumDto> = emptyList(),
+ val loading: Boolean = false,
+ val loaded: Boolean = false,
+ val artistCount: Int = 0,
+ val completed: Int = 0,
+ val failedArtists: Int = 0,
+ val error: String? = null,
+ )
+ private val followedReleaseRepository by lazy {
+ dev.lelonio.square.data.FollowedReleases(container.api, java.io.File(getApplication<SquareApplication>().cacheDir, "followed-releases"))
+ }
+ private val _followedReleases = MutableStateFlow(FollowedReleaseState())
+ val followedReleases = _followedReleases.asStateFlow()
+ private var followedReleaseJob: Job? = null
+ private var followedReleaseLoadedAt = 0L
+
+ fun loadFollowedReleases(force: Boolean = false) {
+ if (container.activeBackend.id != BackendId.SPOTIFY || followedReleaseJob?.isActive == true) return
+ if (!force && _followedReleases.value.loaded && System.currentTimeMillis() - followedReleaseLoadedAt < 15 * 60 * 1_000L) return
+ if (!container.webApi.isReady) {
+ _followedReleases.value = FollowedReleaseState(error = string(R.string.followed_releases_connect))
+ return
+ }
+ _followedReleases.value = _followedReleases.value.copy(loading = true, completed = 0, error = null)
+ followedReleaseJob = viewModelScope.launch {
+ try {
+ val result = followedReleaseRepository.load(force) { done, total ->
+ _followedReleases.value = _followedReleases.value.copy(completed = done, artistCount = total)
+ }
+ _followedReleases.value = FollowedReleaseState(
+ albums = result.albums, loaded = true, artistCount = result.artistCount,
+ failedArtists = result.failedArtists,
+ )
+ followedReleaseLoadedAt = if (result.failedArtists == 0) System.currentTimeMillis() else 0L
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ android.util.Log.w(TAG, "followed releases unavailable: ${describe(e)}")
+ _followedReleases.value = _followedReleases.value.copy(loading = false, error = string(
+ if (e is HttpException && e.code() in listOf(401, 403)) R.string.followed_releases_connect else R.string.followed_releases_error,
+ ))
+ }
+ }
+ }
+
+ private fun resetFollowedReleases() {
+ followedReleaseJob?.cancel()
+ followedReleaseJob = null
+ followedReleaseLoadedAt = 0L
+ _followedReleases.value = FollowedReleaseState()
+ }
+
/**
* Fills the new-releases tab, once.
*
@@ -1727,6 +1780,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
fun disconnectWebApi() {
+ resetFollowedReleases()
container.webApi.disconnect()
_webApi.value = _webApi.value.copy(connected = false, error = null)
// Not needsSetup: search comes from Spotify's own gateway now, and
@@ -2069,6 +2123,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
loginJob?.cancel()
SpotifyOAuth.cancelActiveAuthorization()
container.tokenStore.clear()
+ resetFollowedReleases()
container.webApi.disconnect()
container.spotifySdkAccount.disconnect()
getApplication<android.app.Application>().getSharedPreferences("square_keys", android.content.Context.MODE_PRIVATE)
@@ -2097,6 +2152,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Starts over on the newly chosen source; see the note in `init`. */
private fun reload() {
+ resetFollowedReleases()
inFlight?.cancel()
feedJob?.cancel()
searchJob?.cancel()
@@ -2445,16 +2501,16 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
/** How the detail screen sorts its tracks; remembered between visits. */
- val trackSort: StateFlow<String?> get() = container.preferences.trackSort
-
- fun setTrackSort(value: String) = container.preferences.setTrackSort(value)
+ val trackOrders get() = container.preferences.trackOrders
- val trackSortDescending: StateFlow<Boolean> get() = container.preferences.trackSortDescending
+ fun setTrackSort(uri: String?, value: String) {
+ uri?.let { container.preferences.setTrackSort(it, value) }
+ }
- fun setTrackSortDescending(value: Boolean) =
- container.preferences.setTrackSortDescending(value)
+ fun setTrackSortDescending(uri: String?, value: Boolean) {
+ uri?.let { container.preferences.setTrackSortDescending(it, value) }
+ }
- /** False until the welcome tutorial has been finished once. */
val onboarded: StateFlow<Boolean> get() = container.preferences.onboarded
fun setOnboarded(value: Boolean) = container.preferences.setOnboarded(value)
@@ -4060,7 +4116,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
/** Called once the listener has answered the system's permission dialog. */
fun onLocalPermissionAnswered() {
val open = _playlist.value
- if (open.uri != LocalLibrary.CONTEXT_URI) return
+ if (open.uri != LocalLibrary.CONTEXT_URI) {
+ viewModelScope.launch {
+ deviceFiles = LocalLibrary.tracks(getApplication())
+ val current = _playlist.value
+ publishPlaylist(current)
+ }
+ return
+ }
openLocalFiles(
CatalogPlaylist(
uri = open.uri.orEmpty(),
@@ -5549,7 +5612,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// The other source follows through its own account.
if (!uri.startsWith("spotify:")) {
runCatching { container.activeBackend.setFollowing(uri, !was) }
- .onSuccess { loadFollowedArtists() }
+ .onSuccess {
+ resetFollowedReleases()
+ loadFollowedArtists()
+ }
.onFailure {
android.util.Log.e(TAG, "follow failed: ${chain(it)}", it)
if (_playlist.value.uri == uri) {
@@ -5573,7 +5639,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
runCatching {
if (was) container.api.unfollowArtists(ids = id) else container.api.followArtists(ids = id)
}
- .onSuccess { loadFollowedArtists() }
+ .onSuccess {
+ resetFollowedReleases()
+ loadFollowedArtists()
+ }
.onFailure {
android.util.Log.e(TAG, "follow failed: ${chain(it)}", it)
if (_playlist.value.uri == uri) {
@@ -5649,23 +5718,13 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
return@launch
}
runCatching {
- val gathered = mutableListOf<SearchItem>()
- var after: String? = null
- // Cursor-paged, and an account can follow hundreds: walk it to the
- // end rather than showing the first page and calling it the list.
- while (true) {
- val page = container.api.followedArtists(after = after).artists
- gathered += page.items.mapNotNull { artist ->
- SearchItem(
- uri = artist.uri ?: return@mapNotNull null,
- title = artist.name,
- subtitle = "",
- artworkUrl = artist.images.firstOrNull()?.url,
- )
- }
- after = page.cursors?.after?.takeIf { page.items.isNotEmpty() } ?: break
- }
- gathered.distinctBy { it.uri }.sortedBy { it.title.lowercase() }
+ followedReleaseRepository.artists().mapNotNull { artist ->
+ SearchItem(
+ uri = artist.uri ?: return@mapNotNull null,
+ title = artist.name, subtitle = "",
+ artworkUrl = artist.images.firstOrNull()?.url,
+ )
+ }.sortedBy { it.title.lowercase() }
}
.onSuccess { _followedArtists.value = it }
.onFailure {
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index 5a1b9c2..3cf49a7 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -314,12 +314,6 @@ private fun androidx.compose.foundation.layout.RowScope.BarTab(
modifier: Modifier = Modifier,
onClick: () -> Unit,
) {
- // The geometric bar draws the selected control once, outside the fixed
- // tab strip, so it can travel without leaving a second icon behind.
- if (dev.lelonio.square.ui.glass.floatingtabbar.LocalGeometricFloatingTabBar.current && selected) {
- Spacer(Modifier.weight(1f))
- return
- }
LiquidBottomTab(onClick = onClick, modifier = modifier) {
Icon(
icon,
@@ -462,8 +456,10 @@ fun SquareApp(
val inPlaylists by viewModel.inPlaylists.collectAsStateWithLifecycle()
val homeShelves by viewModel.homeShelves.collectAsStateWithLifecycle()
val remote = elsewhere?.takeIf { elsewhereActive }
+ val showConnectedDevice by (context.applicationContext as dev.lelonio.square.SquareApplication)
+ .preferences.showConnectedDevice.collectAsStateWithLifecycle()
val remoteLabel = stringResource(R.string.playing_on, remote?.deviceName.orEmpty())
- val playback = remote?.asPlaybackState(remoteLabel) ?: local
+ val playback = remote?.asPlaybackState(if (showConnectedDevice) remoteLabel else "") ?: local
// Commands to another device are HTTP requests, so none of them may run on
// the main thread; the screen redraws when the cluster update comes back.
@@ -578,6 +574,7 @@ fun SquareApp(
* Spotify's access point and means nothing on any other backend.
*/
val newPage by viewModel.newPage.collectAsStateWithLifecycle()
+ val followedReleases by viewModel.followedReleases.collectAsStateWithLifecycle()
LaunchedEffect(playback.mediaId, playback.title, playback.album, playback.artist) {
viewModel.loadNowPlayingArt(
@@ -698,8 +695,7 @@ fun SquareApp(
val devices by viewModel.devices.collectAsStateWithLifecycle()
val addToPlaylist by viewModel.addToPlaylist.collectAsStateWithLifecycle()
- val trackSort by viewModel.trackSort.collectAsStateWithLifecycle()
- val trackSortDescending by viewModel.trackSortDescending.collectAsStateWithLifecycle()
+ val trackOrders by viewModel.trackOrders.collectAsStateWithLifecycle()
val onboarded by viewModel.onboarded.collectAsStateWithLifecycle()
// Asked for again from the settings, after it has already been finished.
@@ -1591,12 +1587,15 @@ fun SquareApp(
)
return@composable
}
- LaunchedEffect(Unit) {
+ LaunchedEffect(webApi.connected) {
viewModel.loadNewPage()
viewModel.loadBrowse()
+ viewModel.loadFollowedReleases()
}
NewScreen(
page = newPage,
+ followed = followedReleases,
+ onRefreshFollowed = { viewModel.loadFollowedReleases(force = true) },
shelves = newShelves,
shelvesLoading = browseLoading,
contentPadding = listPadding,
@@ -1946,10 +1945,10 @@ fun SquareApp(
viewModel.canRemoveFrom(page.uri),
)
},
- storedSort = trackSort,
- onSortChange = viewModel::setTrackSort,
- storedSortDescending = trackSortDescending,
- onSortDescendingChange = viewModel::setTrackSortDescending,
+ storedSort = trackOrders[page.uri]?.sort,
+ onSortChange = { viewModel.setTrackSort(page.uri, it) },
+ storedSortDescending = trackOrders[page.uri]?.descending ?: false,
+ onSortDescendingChange = { viewModel.setTrackSortDescending(page.uri, it) },
onOpenItem = { item ->
viewModel.openContext(
item.uri,
@@ -2104,7 +2103,7 @@ fun SquareApp(
FloatingMiniPlayer(
state = playback,
positionMs = positionMs,
- remoteLabel = remote?.let { remoteLabel },
+ remoteLabel = remote?.takeIf { showConnectedDevice }?.let { remoteLabel },
modifier = accessoryModifier
.fillMaxWidth()
.then(pillGlass)
@@ -2398,6 +2397,7 @@ fun SquareApp(
selectedTabIndex = selectedTabIndex,
onTabSelected = { index ->
viewModel.clearPageHistory()
+ if (tabRoutes[index] == Routes.SEARCH) searchOpen = true
navController.switchTab(tabRoutes[index])
},
backdrop = pageBackdrop,
@@ -2417,7 +2417,7 @@ fun SquareApp(
// Nothing is lit while the page on screen is not
// one of these four; search is a place of its
// own.
- indicatorVisible = activeTab in TAB_ROUTES,
+ indicatorVisible = activeTab in tabRoutes,
modifier = tabsModifier,
drawContainer = !dev.lelonio.square.ui.glass.floatingtabbar.LocalGeometricFloatingTabBar.current,
) {
@@ -2461,30 +2461,26 @@ fun SquareApp(
viewModel.clearPageHistory()
navController.switchTab(Routes.LIBRARY)
}
- if (dev.lelonio.square.ui.glass.floatingtabbar.LocalGeometricFloatingTabBar.current) {
- Spacer(Modifier.weight(1f))
- } else {
- BarTab(
- R.string.search,
- // Heavy rather than solid: a filled
- // magnifier reads as a blob at this size,
- // and it is the one glyph here whose shape
- // is the whole of its meaning.
- PhosphorIcons.Bold.MagnifyingGlass,
- activeTab == Routes.SEARCH,
- tabAccent,
- barInk,
- // The circle and labelled tab share bounds,
- // retaining their surfaces during the fold.
- // The incoming tab inherits the capsule clip.
- modifier = if (dev.lelonio.square.ui.glass.LocalLiquidBottomTabsReplica.current) {
- Modifier
- } else sharedSearchTab(tabsVisibility),
- ) {
- viewModel.clearPageHistory()
- searchOpen = true
- navController.switchTab(Routes.SEARCH)
- }
+ BarTab(
+ R.string.search,
+ // Heavy rather than solid: a filled
+ // magnifier reads as a blob at this size,
+ // and it is the one glyph here whose shape
+ // is the whole of its meaning.
+ PhosphorIcons.Bold.MagnifyingGlass,
+ activeTab == Routes.SEARCH,
+ tabAccent,
+ barInk,
+ // The circle and labelled tab share bounds,
+ // retaining their surfaces during the fold.
+ // The incoming tab inherits the capsule clip.
+ modifier = if (dev.lelonio.square.ui.glass.LocalLiquidBottomTabsReplica.current) {
+ Modifier
+ } else sharedSearchTab(tabsVisibility),
+ ) {
+ viewModel.clearPageHistory()
+ searchOpen = true
+ navController.switchTab(Routes.SEARCH)
}
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
index 871c5e6..5d0b192 100644
--- a/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/browse/NewScreen.kt
@@ -65,6 +65,8 @@ import dev.lelonio.square.ui.theme.InkDim
@Composable
fun NewScreen(
page: MainViewModel.NewPage,
+ followed: MainViewModel.FollowedReleaseState,
+ onRefreshFollowed: () -> Unit,
/**
* Spotify's own rows, as it lays them out for this account.
*
@@ -82,23 +84,14 @@ fun NewScreen(
/** The same menu every other list of songs in the app opens. */
onSongMenu: (CatalogTrack) -> Unit,
) {
- val empty = page.hero.isEmpty() && page.thisWeek.isEmpty() &&
- page.recent.isEmpty() && shelves.isEmpty()
- if (empty) {
- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- if (page.loading) {
- CircularProgressIndicator(strokeWidth = 2.dp)
- } else {
- Text(
- stringResource(R.string.nothing_here),
- style = MaterialTheme.typography.bodyMedium,
- color = InkDim,
- )
- }
+ if ((followed.loading && followed.albums.isEmpty()) ||
+ (page.loading && page.hero.isEmpty() && page.songs.isEmpty() && shelves.isEmpty() && followed.albums.isEmpty())
+ ) {
+ Box(Modifier.fillMaxSize().padding(contentPadding), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
}
return
}
-
LazyColumn(
contentPadding = PaddingValues(
top = contentPadding.calculateTopPadding() + 8.dp,
@@ -125,6 +118,51 @@ fun NewScreen(
item(contentType = "songs") { SongPages(page.songs, onSongMenu, onPlaySong) }
}
+ if (followed.albums.isNotEmpty() || followed.error != null || followed.loaded) {
+ item(key = "followedHeading", contentType = "shelfHeading") {
+ Heading(stringResource(R.string.new_from_followed_artists))
+ }
+ if (followed.albums.isNotEmpty()) {
+ item(key = "followedShelf", contentType = "shelfRow") {
+ Shelf(
+ followed.albums.map { album ->
+ SearchItem(
+ uri = album.uri ?: "spotify:album:${album.id}",
+ title = album.name,
+ subtitle = album.artists.joinToString(", ") { it.name },
+ artworkUrl = album.images.firstOrNull()?.url,
+ )
+ },
+ onOpen,
+ )
+ }
+ }
+ if (followed.error != null || followed.failedArtists > 0 || followed.albums.isEmpty()) {
+ item(key = "followedStatus", contentType = "status") {
+ Column(Modifier.padding(horizontal = 20.dp, vertical = 12.dp)) {
+ Text(
+ followed.error ?: stringResource(
+ when {
+ followed.failedArtists > 0 -> R.string.followed_releases_partial
+ followed.artistCount == 0 -> R.string.followed_releases_no_artists
+ else -> R.string.followed_releases_empty
+ },
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = InkDim,
+ )
+ if (followed.error != null || followed.failedArtists > 0) {
+ Text(
+ stringResource(R.string.retry),
+ color = MaterialTheme.colorScheme.primary,
+ modifier = Modifier.pressable(onRefreshFollowed).padding(vertical = 12.dp),
+ )
+ }
+ }
+ }
+ }
+ }
+
// The outline of what is coming, while it is coming.
if (shelvesLoading && shelves.isEmpty()) {
items(
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
index fdd1160..f991499 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/LiquidBottomTabs.kt
@@ -37,11 +37,15 @@ import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.layout.layout
+import androidx.compose.ui.unit.Constraints
+import kotlin.math.roundToInt
import dev.lelonio.square.ui.glass.backdrop.BackdropEffectScope
import androidx.compose.ui.graphics.GraphicsLayerScope
import androidx.compose.ui.platform.LocalDensity
@@ -72,6 +76,8 @@ import kotlin.math.sign
// The tinted copy is a drawing source, not another shared-transition endpoint.
internal val LocalLiquidBottomTabsReplica = staticCompositionLocalOf { false }
+// The geometric shell is a sibling, captured before the selector is drawn.
+internal val LocalLiquidBottomTabsSurfaceBackdrop = staticCompositionLocalOf<Backdrop?> { null }
@Composable
fun LiquidBottomTabs(
@@ -119,6 +125,7 @@ fun LiquidBottomTabs(
val isLightTheme = !isSystemInDarkTheme()
val tabsBackdrop = rememberLayerBackdrop()
+ val surfaceBackdrop = LocalLiquidBottomTabsSurfaceBackdrop.current
// LOCAL CHANGE: the width is read where it is used, not in composition.
//
@@ -253,6 +260,8 @@ fun LiquidBottomTabs(
scaleY = scale
},
) else Modifier)
+ // Clip the row's rectangular touch glow, not its selector siblings.
+ .clip(ContinuousCapsule())
.then(interactiveHighlight.modifier)
.height(height)
.fillMaxWidth()
@@ -284,7 +293,6 @@ fun LiquidBottomTabs(
.graphicsLayer {
translationX = panelOffset
}
- .then(interactiveHighlight.modifier)
.height(height - 8f.dp)
.fillMaxWidth()
.padding(horizontal = 4f.dp)
@@ -310,12 +318,23 @@ fun LiquidBottomTabs(
if (isLtr) dampedDragAnimation.value * tabWidth() + panelOffset
else size.width - (dampedDragAnimation.value + 1f) * tabWidth() + panelOffset
}
- val slotLayer: GraphicsLayerScope.() -> Unit = {
- scaleX = dampedDragAnimation.scaleX
- scaleY = dampedDragAnimation.scaleY
+ // Grow the sampling surface itself, rather than scaling a capture of
+ // the resting slot. Both selector layers keep the same centre and read
+ // the page at their actual expanded bounds.
+ val slotGrowth = Modifier.layout { measurable, constraints ->
val velocity = dampedDragAnimation.velocity / 10f
- scaleX /= 1f - (velocity * 0.75f).fastCoerceIn(-0.2f, 0.2f)
- scaleY *= 1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f)
+ val scaleX = dampedDragAnimation.scaleX /
+ (1f - (velocity * 0.75f).fastCoerceIn(-0.2f, 0.2f))
+ val scaleY = dampedDragAnimation.scaleY *
+ (1f - (velocity * 0.25f).fastCoerceIn(-0.2f, 0.2f))
+ val width = constraints.maxWidth
+ val height = constraints.maxHeight
+ val expandedWidth = (width * scaleX).roundToInt().coerceAtLeast(1)
+ val expandedHeight = (height * scaleY).roundToInt().coerceAtLeast(1)
+ val child = measurable.measure(Constraints.fixed(expandedWidth, expandedHeight))
+ layout(width, height) {
+ child.placeRelative((width - expandedWidth) / 2, (height - expandedHeight) / 2)
+ }
}
val slotLens: BackdropEffectScope.() -> Unit = {
val progress = dampedDragAnimation.pressProgress
@@ -326,18 +345,49 @@ fun LiquidBottomTabs(
)
}
+ val pressedBackdrop = remember(backdrop, surfaceBackdrop, dampedDragAnimation) {
+ object : Backdrop {
+ private val surfacePaint = androidx.compose.ui.graphics.Paint()
+ override val isCoordinatesDependent = true
+ override fun androidx.compose.ui.graphics.drawscope.DrawScope.drawBackdrop(
+ density: androidx.compose.ui.unit.Density,
+ coordinates: androidx.compose.ui.layout.LayoutCoordinates?,
+ layerBlock: (GraphicsLayerScope.() -> Unit)?,
+ ) {
+ // Fade the actual shell in and out continuously. Selecting
+ // it until progress reaches exactly zero stacked two films
+ // on release, then removed one abruptly: a white flash.
+ with(backdrop) { drawBackdrop(density, coordinates, layerBlock) }
+ val progress = dampedDragAnimation.pressProgress.coerceIn(0f, 1f)
+ if (surfaceBackdrop != null && progress > 0f) {
+ surfacePaint.alpha = progress
+ val canvas = drawContext.canvas
+ canvas.saveLayer(androidx.compose.ui.geometry.Rect(0f, 0f, size.width, size.height), surfacePaint)
+ try {
+ with(surfaceBackdrop) { drawBackdrop(density, coordinates, layerBlock) }
+ } finally {
+ canvas.restore()
+ }
+ }
+ }
+ }
+ }
+
// The slot: the page through it, frosted and filmed the way the tabs'
// copy used to bring it, then the wash, the rim and the shadow.
Box(
slotPlacement
.then(interactiveHighlight.gestureModifier)
.then(dampedDragAnimation.modifier)
+ .height(height - 8f.dp)
+ .fillMaxWidth(1f / tabsCount)
+ .then(slotGrowth)
.drawBackdrop(
- backdrop = backdrop,
+ backdrop = pressedBackdrop,
shape = { ContinuousCapsule() },
effects = {
vibrancy()
- blur(8f.dp.toPx())
+ blur(8f.dp.toPx() * (1f - dampedDragAnimation.pressProgress.coerceIn(0f, 1f)))
slotLens()
},
highlight = {
@@ -355,10 +405,9 @@ fun LiquidBottomTabs(
alpha = progress
)
},
- layerBlock = slotLayer,
onDrawSurface = {
val progress = dampedDragAnimation.pressProgress
- drawRect(containerColor)
+ drawRect(containerColor, alpha = 1f - progress)
drawRect(
indicatorColor ?: if (isLightTheme) Color.Black.copy(0.1f)
else Color.White.copy(0.1f),
@@ -367,8 +416,6 @@ fun LiquidBottomTabs(
drawRect(Color.Black.copy(alpha = 0.03f * progress))
}
)
- .height(height - 8f.dp)
- .fillMaxWidth(1f / tabsCount)
)
// LOCAL CHANGE: the lit tab, over its slot rather than under the wash.
@@ -379,16 +426,16 @@ fun LiquidBottomTabs(
// here, so the slot underneath still gets them.
Box(
slotPlacement
+ .height(height - 8f.dp)
+ .fillMaxWidth(1f / tabsCount)
+ .then(slotGrowth)
.drawBackdrop(
backdrop = tabsBackdrop,
shape = { ContinuousCapsule() },
effects = slotLens,
highlight = null,
shadow = null,
- layerBlock = slotLayer,
)
- .height(height - 8f.dp)
- .fillMaxWidth(1f / tabsCount)
)
}
}
diff --git a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/GeometricFloatingTabBar.kt b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/GeometricFloatingTabBar.kt
index 207fbc5..b2cdd3c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/GeometricFloatingTabBar.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/glass/floatingtabbar/GeometricFloatingTabBar.kt
@@ -17,11 +17,17 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
+import dev.lelonio.square.ui.glass.LocalLiquidBottomTabsSurfaceBackdrop
+import dev.lelonio.square.ui.glass.backdrop.backdrops.rememberLayerBackdrop
+import dev.lelonio.square.ui.glass.backdrop.backdrops.layerBackdrop
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
-import androidx.compose.ui.graphics.drawscope.clipRect
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.RoundRect
+import androidx.compose.ui.graphics.drawscope.clipPath
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.semantics.clearAndSetSemantics
@@ -74,6 +80,7 @@ internal fun SharedTransitionScope.GeometricFloatingTabBar(
val tabsCount = scope.tabs.size.coerceAtLeast(1)
val ownsSelectedSlot = selected?.key == selectedTabKey
val sharedScope = this
+ val surfaceBackdrop = rememberLayerBackdrop()
// This visibility scope only satisfies the existing content contract. It
// never changes visibility and does not participate in the fold.
@@ -83,7 +90,8 @@ internal fun SharedTransitionScope.GeometricFloatingTabBar(
modifier = Modifier.fillMaxWidth(),
content = {
// 0: the single navigation surface.
- Box(Modifier.background(colors.backgroundColor, shapes.tabBarShape)
+ Box(Modifier.layerBackdrop(surfaceBackdrop)
+ .background(colors.backgroundColor, shapes.tabBarShape)
.clip(shapes.tabBarShape).then(tabBarContentModifier))
// 1: resting-width tabs, fading into the selected icon.
Box(Modifier.graphicsLayer {
@@ -92,15 +100,27 @@ internal fun SharedTransitionScope.GeometricFloatingTabBar(
val p = fold.value
val width = lerp(lerp(size.width, size.height, search.value), size.height, p)
val contentScope = this
- clipRect(right = width) { contentScope.drawContent() }
+ // At rest the pressed selector may protrude beyond the
+ // capsule. Clip only while tabs disappear into the fold.
+ if (p == 0f && search.value == 0f) {
+ contentScope.drawContent()
+ } else {
+ val outline = Path().apply {
+ addRoundRect(RoundRect(0f, 0f, width, size.height, CornerRadius(size.height / 2f)))
+ }
+ clipPath(outline) { contentScope.drawContent() }
+ }
}.then(if (isInline || searchMode) Modifier.clearAndSetSemantics {} else Modifier)) {
- CompositionLocalProvider(LocalGeometricFloatingTabBar provides true) {
+ CompositionLocalProvider(
+ LocalGeometricFloatingTabBar provides true,
+ LocalLiquidBottomTabsSurfaceBackdrop provides surfaceBackdrop,
+ ) {
sharedScope.expandedTabs(Modifier.fillMaxWidth(), visibility)
}
}
- // 2: one selected control, including its label at rest.
+ // 2: selected control only during the fold; resting tabs own their ink.
Box(Modifier.graphicsLayer {
- alpha = if (ownsSelectedSlot) 1f else maxOf(fold.value, search.value)
+ alpha = maxOf(fold.value, search.value)
}.then(if (isInline || searchMode) Modifier.clickable {
if (isInline) onExpand() else selected?.onClick?.invoke()
} else Modifier).then(if (!ownsSelectedSlot && !isInline && !searchMode) Modifier.clearAndSetSemantics {} else Modifier)) {
@@ -114,9 +134,9 @@ internal fun SharedTransitionScope.GeometricFloatingTabBar(
Box(Modifier.graphicsLayer { alpha = maxOf(fold.value, search.value) }
.background(colors.backgroundColor, shapes.standaloneTabShape)
.clip(shapes.standaloneTabShape).then(tabBarContentModifier))
- // 4: one magnifier and label, sharing the surface's geometry.
- Box(Modifier.graphicsLayer { alpha = 1f - search.value * (1f - fold.value) }
- .clickable(enabled = !searchMode || isInline) { searchTab?.onClick?.invoke() }
+ // 4: detached search control. At rest the fifth tab owns taps and drags.
+ Box(Modifier.graphicsLayer { alpha = maxOf(fold.value, search.value) * (1f - search.value * (1f - fold.value)) }
+ .then(if (isInline || searchMode) Modifier.clickable(enabled = !searchMode || isInline) { searchTab?.onClick?.invoke() } else Modifier)
.then(if (searchMode && !isInline) Modifier.clearAndSetSemantics {} else Modifier)) {
GeometricTabContent(
icon = { searchTab?.icon?.invoke() },
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
index f2e8fb8..0c6c73d 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt
@@ -309,8 +309,11 @@ fun PlaylistScreen(
// this sequence for this listener a minute ago, and sorting it by title
// throws away the only thing that made it a radio rather than a bag of
// songs. So the stored preference does not reach it.
+ val audioPermissionNeeded = state.tracks.any {
+ dev.lelonio.square.data.LocalLibrary.isSpotifyLocal(it.uri)
+ } && !dev.lelonio.square.data.LocalLibrary.granted(LocalContext.current)
val isStation = state.uri?.startsWith("spotify:station:") == true
- var sort by remember(storedSort, isStation) {
+ var sort by remember(state.uri, storedSort, isStation) {
mutableStateOf(
if (isStation) {
TrackSort.ORIGINAL
@@ -319,7 +322,7 @@ fun PlaylistScreen(
},
)
}
- var descending by remember(storedSortDescending) { mutableStateOf(storedSortDescending) }
+ var descending by remember(state.uri, storedSortDescending) { mutableStateOf(storedSortDescending) }
var sortOpen by remember { mutableStateOf(false) }
// Whether the rows on screen are the playlist itself, in its order. Sorting
@@ -846,6 +849,14 @@ fun PlaylistScreen(
}
}
+ if (audioPermissionNeeded) item(key = "localAudioPermission", contentType = "status") {
+ Column(Modifier.padding(horizontal = 24.dp, vertical = 16.dp)) {
+ LiquidButton(onClick = onAskLocalPermission, backdrop = pageBackdrop, contentPadding = 18.dp) {
+ Text(stringResource(R.string.local_files_allow))
+ }
+ }
+ }
+
when {
state.loading -> item(contentType = "status") {
StatusBox { CircularProgressIndicator(strokeWidth = 2.dp) }
diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
index 26091ab..7f8e1cd 100644
--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt
@@ -478,6 +478,18 @@ fun SettingsScreen(
CanvasSection(backdrop)
}
+ if (shown == SettingsPage.Playback && showSpotify) item("connected-device-label") {
+ val enabled by app.preferences.showConnectedDevice.collectAsStateWithLifecycle()
+ Section(stringResource(R.string.connected_device_label)) {
+ DownloadSwitch(
+ label = stringResource(R.string.connected_device_label),
+ checked = enabled,
+ onChange = app.preferences::setShowConnectedDevice,
+ backdrop = backdrop,
+ )
+ }
+ }
+
// The effects run on our own output, so this one holds for both backends.
if (shown == SettingsPage.Playback && !sdkPlayback) item("effect-quality") {
EffectQualitySection()
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 5e9603a..7257c24 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -497,4 +497,12 @@
<string name="suggested_songs_note">Basierend auf dem, was in dieser Playlist ist</string>
<string name="refresh_suggestions">Aktualisieren</string>
<string name="add_to_this_playlist">Zu dieser Playlist hinzufügen</string>
+
+ <string name="followed_releases_empty">Keine Veröffentlichungen in den letzten zwölf Monaten von Künstlern, denen du folgst.</string>
+ <string name="followed_releases_no_artists">Folge Künstlern, um hier ihre neuen Alben und Singles zu sehen.</string>
+ <string name="followed_releases_partial">Einige Künstler konnten nicht aktualisiert werden. Versuche es erneut.</string>
+ <string name="followed_releases_error">Neue Veröffentlichungen konnten nicht geladen werden. Versuche es erneut.</string>
+ <string name="followed_releases_connect">Verbinde Spotify in den Einstellungen, um Veröffentlichungen deiner gefolgten Künstler zu sehen.</string>
+ <string name="new_from_followed_artists">Neues von deinen Künstlern</string>
+ <string name="connected_device_label">Verbundenes Gerät anzeigen</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 4b661cf..cf29d58 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -503,4 +503,12 @@
<string name="suggested_songs_note">Según lo que hay en esta playlist</string>
<string name="refresh_suggestions">Actualizar</string>
<string name="add_to_this_playlist">Añadir a esta playlist</string>
+
+ <string name="followed_releases_empty">No hay lanzamientos de los artistas que sigues en los últimos doce meses.</string>
+ <string name="followed_releases_no_artists">Sigue a artistas para ver aquí sus nuevos álbumes y sencillos.</string>
+ <string name="followed_releases_partial">No se pudieron actualizar algunos artistas. Puedes reintentarlo.</string>
+ <string name="followed_releases_error">No se pudieron cargar los nuevos lanzamientos. Inténtalo de nuevo.</string>
+ <string name="followed_releases_connect">Conecta Spotify en Ajustes para ver los lanzamientos de los artistas que sigues.</string>
+ <string name="new_from_followed_artists">Novedades de tus artistas</string>
+ <string name="connected_device_label">Mostrar dispositivo conectado</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 45a183b..1a935d6 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -497,4 +497,12 @@
<string name="suggested_songs_note">D\'après ce que contient cette playlist</string>
<string name="refresh_suggestions">Actualiser</string>
<string name="add_to_this_playlist">Ajouter à cette playlist</string>
+
+ <string name="followed_releases_empty">Aucune sortie des artistes suivis au cours des douze derniers mois.</string>
+ <string name="followed_releases_no_artists">Suivez des artistes pour voir leurs nouveaux albums et singles ici.</string>
+ <string name="followed_releases_partial">Certains artistes n’ont pas pu être actualisés. Réessayez.</string>
+ <string name="followed_releases_error">Impossible de charger les nouveautés. Réessayez.</string>
+ <string name="followed_releases_connect">Connectez Spotify dans les paramètres pour voir les sorties des artistes suivis.</string>
+ <string name="new_from_followed_artists">Nouveautés de vos artistes</string>
+ <string name="connected_device_label">Afficher l’appareil connecté</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 2b702b2..18310c4 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -512,4 +512,12 @@
<string name="suggested_songs_note">इस प्लेलिस्ट में मौजूद गानों के आधार पर</string>
<string name="refresh_suggestions">रीफ़्रेश करें</string>
<string name="add_to_this_playlist">इस प्लेलिस्ट में जोड़ें</string>
+
+ <string name="followed_releases_empty">आप जिन कलाकारों को फ़ॉलो करते हैं, उनकी पिछले बारह महीनों में कोई नई रिलीज़ नहीं है।</string>
+ <string name="followed_releases_no_artists">कलाकारों को फ़ॉलो करें ताकि उनके नए एल्बम और सिंगल यहाँ दिखें।</string>
+ <string name="followed_releases_partial">कुछ कलाकारों को अपडेट नहीं किया जा सका। फिर से कोशिश करें।</string>
+ <string name="followed_releases_error">नई रिलीज़ लोड नहीं हो सकीं। फिर से कोशिश करें।</string>
+ <string name="followed_releases_connect">फ़ॉलो किए गए कलाकारों की रिलीज़ देखने के लिए सेटिंग में Spotify कनेक्ट करें।</string>
+ <string name="new_from_followed_artists">आपके कलाकारों की नई रिलीज़</string>
+ <string name="connected_device_label">कनेक्ट किया गया डिवाइस दिखाएँ</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 290cd28..1c88a96 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -532,4 +532,12 @@
<string name="suggested_songs_note">In base a quello che c\'è in questa playlist</string>
<string name="refresh_suggestions">Aggiorna</string>
<string name="add_to_this_playlist">Aggiungi a questa playlist</string>
+
+ <string name="followed_releases_empty">Nessuna uscita negli ultimi dodici mesi dagli artisti che segui.</string>
+ <string name="followed_releases_no_artists">Segui degli artisti per vedere qui i loro nuovi album e singoli.</string>
+ <string name="followed_releases_partial">Non è stato possibile aggiornare alcuni artisti. Puoi riprovare.</string>
+ <string name="followed_releases_error">Impossibile caricare le nuove uscite. Riprova.</string>
+ <string name="followed_releases_connect">Collega Spotify nelle impostazioni per vedere le uscite degli artisti che segui.</string>
+ <string name="new_from_followed_artists">Novità dai tuoi artisti</string>
+ <string name="connected_device_label">Mostra dispositivo connesso</string>
</resources>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index e6e0c82..8f37523 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -497,4 +497,12 @@
<string name="suggested_songs_note">Com base no que há nesta playlist</string>
<string name="refresh_suggestions">Atualizar</string>
<string name="add_to_this_playlist">Adicionar a esta playlist</string>
+
+ <string name="followed_releases_empty">Nenhum lançamento dos artistas que segues nos últimos doze meses.</string>
+ <string name="followed_releases_no_artists">Segue artistas para veres aqui os novos álbuns e singles.</string>
+ <string name="followed_releases_partial">Não foi possível atualizar alguns artistas. Podes tentar novamente.</string>
+ <string name="followed_releases_error">Não foi possível carregar os novos lançamentos. Tenta novamente.</string>
+ <string name="followed_releases_connect">Liga o Spotify nas definições para veres os lançamentos dos artistas que segues.</string>
+ <string name="new_from_followed_artists">Novidades dos teus artistas</string>
+ <string name="connected_device_label">Mostrar dispositivo conectado</string>
</resources>
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
index 5c5e999..8995a5b 100644
--- a/app/src/main/res/values-ru/strings.xml
+++ b/app/src/main/res/values-ru/strings.xml
@@ -524,4 +524,12 @@
<string name="suggested_songs_note">На основе того, что есть в этом плейлисте</string>
<string name="refresh_suggestions">Обновить</string>
<string name="add_to_this_playlist">Добавить в этот плейлист</string>
+
+ <string name="followed_releases_empty">За последние двенадцать месяцев у исполнителей, на которых вы подписаны, нет новых релизов.</string>
+ <string name="followed_releases_no_artists">Подпишитесь на исполнителей, чтобы видеть здесь их новые альбомы и синглы.</string>
+ <string name="followed_releases_partial">Не удалось обновить некоторых исполнителей. Попробуйте ещё раз.</string>
+ <string name="followed_releases_error">Не удалось загрузить новые релизы. Попробуйте ещё раз.</string>
+ <string name="followed_releases_connect">Подключите Spotify в настройках, чтобы видеть релизы исполнителей, на которых вы подписаны.</string>
+ <string name="new_from_followed_artists">Новинки ваших исполнителей</string>
+ <string name="connected_device_label">Показывать подключённое устройство</string>
</resources>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 0765299..ff7399e 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -510,4 +510,12 @@
<string name="suggested_songs_note">Bu çalma listesindekilere göre</string>
<string name="refresh_suggestions">Yenile</string>
<string name="add_to_this_playlist">Bu çalma listesine ekle</string>
+
+ <string name="followed_releases_empty">Takip ettiğin sanatçıların son on iki ayda yeni yayını yok.</string>
+ <string name="followed_releases_no_artists">Yeni albüm ve teklilerini burada görmek için sanatçıları takip et.</string>
+ <string name="followed_releases_partial">Bazı sanatçılar güncellenemedi. Tekrar deneyebilirsin.</string>
+ <string name="followed_releases_error">Yeni yayınlar yüklenemedi. Tekrar dene.</string>
+ <string name="followed_releases_connect">Takip ettiğin sanatçıların yayınlarını görmek için Ayarlar üzerinden Spotify bağlantısı kur.</string>
+ <string name="new_from_followed_artists">Sanatçılarından yeni yayınlar</string>
+ <string name="connected_device_label">Bağlı cihazı göster</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 2a8a785..044102c 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -559,4 +559,12 @@
<string name="suggested_songs_note">Based on what is in this playlist</string>
<string name="refresh_suggestions">Refresh</string>
<string name="add_to_this_playlist">Add to this playlist</string>
+
+ <string name="followed_releases_empty">No releases in the last twelve months from the artists you follow.</string>
+ <string name="followed_releases_no_artists">Follow artists to see their new albums and singles here.</string>
+ <string name="followed_releases_partial">Some artists could not be updated. You can retry.</string>
+ <string name="followed_releases_error">Could not load new releases. Please retry.</string>
+ <string name="followed_releases_connect">Connect Spotify in Settings to see releases from artists you follow.</string>
+ <string name="new_from_followed_artists">New from Your Artists</string>
+ <string name="connected_device_label">Show connected device</string>
</resources>
diff --git a/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt b/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt
new file mode 100644
index 0000000..c53861c
--- /dev/null
+++ b/app/src/test/java/dev/lelonio/square/data/FollowedReleasesTest.kt
@@ -0,0 +1,108 @@
+package dev.lelonio.square.data
+
+import java.lang.reflect.Proxy
+import java.nio.file.Files
+import java.time.LocalDate
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.*
+import org.junit.Test
+
+class FollowedReleasesTest {
+ private fun api(answer: (String, Array<out Any?>) -> Any?): SpotifyApi = Proxy.newProxyInstance(
+ SpotifyApi::class.java.classLoader, arrayOf(SpotifyApi::class.java),
+ ) { _, method, args -> answer(method.name, args.orEmpty()) } as SpotifyApi
+
+ private fun album(id: String, date: String, group: String = "album") = AlbumDto(
+ id = id, uri = "spotify:album:$id", name = id, releaseDate = date, albumGroup = group,
+ )
+
+ @Test fun datesDeduplicationAndReleaseGroups() {
+ val today = LocalDate.of(2026, 10, 7)
+ val result = recentReleases(listOf(
+ album("old", "2024-01-01"), album("recent", "2026-10-07", "single"),
+ album("month", "2026-09"), album("year", "2026"),
+ album("recent", "2026-10-07"), album("future", "2027-01-01"),
+ album("compilation", "2026-10-06", "compilation"), album("unknown", "bad"),
+ ), today.minusMonths(12), today)
+ assertEquals(listOf("recent", "month", "year"), result.map { it.id })
+ assertNull(releaseDay("2026-02-31"))
+ assertEquals(LocalDate.of(2026, 9, 1), releaseDay("2026-09"))
+ }
+
+ @Test fun walksEveryFollowedArtistAndEveryAlbumPage() = runBlocking {
+ var followPages = 0
+ val offsets = mutableListOf<Pair<String, Int>>()
+ val api = api { name, args ->
+ when (name) {
+ "followedArtists" -> {
+ followPages++
+ val second = args[2] != null
+ val artists = (if (second) 51..60 else 1..50).map {
+ ArtistDto(id = "A$it", uri = "spotify:artist:A$it", name = "Artist $it")
+ }
+ FollowedArtistsDto(ArtistCursorPageDto(artists, 60, CursorsDto(if (second) null else "next")))
+ }
+ "artistAlbums" -> {
+ val id = args[0] as String
+ val offset = args[4] as Int
+ offsets += id to offset
+ assertEquals("album,single", args[1])
+ PageDto(listOf(album("${id}P$offset", LocalDate.now().toString())), total = 2, next = if (offset == 0) "next" else null)
+ }
+ else -> error(name)
+ }
+ }
+ val dir = Files.createTempDirectory("followed-releases-test").toFile()
+ try {
+ val result = FollowedReleases(api, dir).load()
+ assertEquals(2, followPages)
+ assertEquals(60, result.artistCount)
+ assertEquals(120, result.albums.size)
+ assertEquals(setOf(0, 1), offsets.filter { it.first == "A60" }.map { it.second }.toSet())
+ assertEquals(0, result.failedArtists)
+ } finally { dir.deleteRecursively() }
+ }
+
+ @Test fun cachesDiscographiesButReadsFollowsAgainAndPreservesCacheOnFailure() = runBlocking {
+ var fail = false
+ var albumRequests = 0
+ var followedRequests = 0
+ val api = api { name, _ ->
+ when (name) {
+ "followedArtists" -> {
+ followedRequests++
+ FollowedArtistsDto(ArtistCursorPageDto(listOf(ArtistDto(id = "A1", name = "Artist"))))
+ }
+ "artistAlbums" -> {
+ albumRequests++
+ if (fail) error("network failure")
+ PageDto(listOf(album("release", LocalDate.now().toString())))
+ }
+ else -> error(name)
+ }
+ }
+ val dir = Files.createTempDirectory("followed-releases-test").toFile()
+ try {
+ val repository = FollowedReleases(api, dir)
+ val first = repository.load()
+ assertEquals(first.albums, repository.load().albums)
+ assertEquals(1, albumRequests)
+ assertEquals(2, followedRequests)
+ fail = true
+ val failed = repository.load(force = true)
+ assertEquals(first.albums, failed.albums)
+ assertEquals(1, failed.failedArtists)
+ assertEquals(2, albumRequests)
+ } finally { dir.deleteRecursively() }
+ }
+
+ @Test fun repeatedFollowCursorFailsInsteadOfSilentlyTruncating() = runBlocking {
+ val api = api { _, _ ->
+ FollowedArtistsDto(ArtistCursorPageDto(listOf(ArtistDto(id = "A", name = "Artist")), cursors = CursorsDto("same")))
+ }
+ val dir = Files.createTempDirectory("followed-releases-test").toFile()
+ try {
+ assertTrue(runCatching { FollowedReleases(api, dir).artists() }.exceptionOrNull() is IllegalStateException)
+ } finally { dir.deleteRecursively() }
+ }
+}
diff --git a/app/src/test/java/dev/lelonio/square/data/LocalLibraryMatchTest.kt b/app/src/test/java/dev/lelonio/square/data/LocalLibraryMatchTest.kt
new file mode 100644
index 0000000..ed15f5c
--- /dev/null
+++ b/app/src/test/java/dev/lelonio/square/data/LocalLibraryMatchTest.kt
@@ -0,0 +1,34 @@
+package dev.lelonio.square.data
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class LocalLibraryMatchTest {
+ private fun file(name: String, artist: String = "Tazenda", album: String = "Vida", duration: Long = 200_000) =
+ CatalogTrack(uri = "local:track:1", name = name, artist = artist, album = album, durationMs = duration, localFile = "/music/song.mp3")
+
+ @Test fun matchesPcUriWhenGatewayMetadataIsMissing() {
+ val local = file("Domo Mia (Feat. Eros Ramazzotti)")
+ val entry = CatalogTrack(uri = LocalLibrary.spotifyUri(local), name = "", artist = "", album = "")
+ assertEquals(local, LocalLibrary.match(entry, listOf(local)))
+ }
+
+ @Test fun toleratesTagsAndAccentsButRejectsDifferentDuration() {
+ val entry = file("Dòmo Mia (Feat. Eros Ramazzotti)").copy(uri = "spotify:local:Tazenda:Vida:Domo+Mia:200")
+ val local = file("Domo Mia")
+ assertEquals(local, LocalLibrary.match(entry, listOf(local)))
+ assertNull(LocalLibrary.match(entry, listOf(local.copy(durationMs = 230_000))))
+ }
+
+ @Test fun prefersMatchingAlbumAndDoesNotGuessAmongAmbiguousCopies() {
+ val local = file("Domo Mia")
+ val other = local.copy(uri = "local:track:2", album = "Live")
+ val entry = local.copy(uri = LocalLibrary.spotifyUri(local))
+ assertEquals(local, LocalLibrary.match(entry, listOf(other, local)))
+ assertNull(LocalLibrary.match(entry.copy(album = "Missing"), listOf(other, local)))
+ }
+
+ @Test fun missingTitleCannotMatchAnUntaggedFile() {
+ assertNull(LocalLibrary.match(file("").copy(uri = "spotify:local::::200"), listOf(file(""))))
+ }
+}
diff --git a/native/src/engine.rs b/native/src/engine.rs
index 5114a31..42f9281 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -1978,6 +1978,12 @@ static LOCAL_PLAYING: AtomicBool = AtomicBool::new(false);
///
/// The cluster is still the fallback, for the moment before there is a device
/// at all.
+/// Initial Connect state before the dealer sends its first change.
+pub fn connect_cluster() -> Option<librespot_protocol::connect::Cluster> {
+ let guard = ENGINE.try_lock().ok()?;
+ guard.as_ref()?.bundle.as_ref()?.spirc().ok()?.cluster()
+}
+
pub fn elsewhere_active() -> bool {
// Sound coming out of this phone settles it.
//
diff --git a/native/src/remote.rs b/native/src/remote.rs
index 6e60559..645d30f 100644
--- a/native/src/remote.rs
+++ b/native/src/remote.rs
@@ -42,6 +42,14 @@ pub fn clear() {
WATCHING.store(false, Ordering::SeqCst);
}
+/// Device registration returns a cluster even when playback has not changed.
+fn seed_initial_cluster() {
+ let Some(initial) = engine::connect_cluster() else { return; };
+ if let Ok(mut stored) = CLUSTER.lock() {
+ if stored.is_none() { *stored = Some(initial); }
+ }
+}
+
/// Starts listening for cluster updates on `session`'s dealer.
///
/// Runs for the life of the session. The stream ends when the dealer goes, which
@@ -130,6 +138,7 @@ pub fn elsewhere_active() -> bool {
/// [`elsewhere_active`], for a caller that already knows this device's id and
/// must not wait on the engine to be told it; see engine::elsewhere_active.
pub fn elsewhere_active_for(own: &str) -> bool {
+ seed_initial_cluster();
let Ok(guard) = CLUSTER.lock() else {
return false;
};
@@ -150,6 +159,7 @@ pub fn device_id() -> engine::EngineResult<String> {
/// "playing here" and "playing there" are the same protocol and only the id
/// tells them apart.
pub fn state_json() -> String {
+ seed_initial_cluster();
let Ok(guard) = CLUSTER.lock() else {
return "{}".into();
};
@@ -204,6 +214,7 @@ pub fn state_json() -> String {
/// Every device the account can see, as a JSON array.
pub fn devices_json() -> String {
+ seed_initial_cluster();
let Ok(guard) = CLUSTER.lock() else {
return "[]".into();
};
diff --git a/native/vendor/librespot-connect/src/spirc.rs b/native/vendor/librespot-connect/src/spirc.rs
index d837caf..8ced9ef 100644
--- a/native/vendor/librespot-connect/src/spirc.rs
+++ b/native/vendor/librespot-connect/src/spirc.rs
@@ -78,6 +78,8 @@ struct SpircTask {
active: std::sync::Arc<std::sync::atomic::AtomicBool>,
/// LOCAL PATCH: kept in step with what this device is playing; see [`Spirc`].
playing: std::sync::Arc<std::sync::Mutex<PlayingHere>>,
+ /// Latest cluster, including the initial device registration response.
+ cluster: std::sync::Arc<std::sync::Mutex<Option<Cluster>>>,
connect_established: bool,
play_request_id: Option<u64>,
@@ -184,6 +186,8 @@ pub struct Spirc {
/// before. The owner of the handle needs the current answer to keep a
/// queue of its own in step with the one being played.
playing: std::sync::Arc<std::sync::Mutex<PlayingHere>>,
+ /// Latest cluster, including the initial device registration response.
+ cluster: std::sync::Arc<std::sync::Mutex<Option<Cluster>>>,
}
/// LOCAL PATCH: a snapshot of what the device is playing, for its owner.
@@ -210,6 +214,10 @@ pub struct PlayingHere {
}
impl Spirc {
+ pub fn cluster(&self) -> Option<Cluster> {
+ self.cluster.lock().ok().and_then(|cluster| cluster.clone())
+ }
+
/// LOCAL PATCH: whether this device currently holds the account's playback.
pub fn is_active(&self) -> bool {
self.active.load(std::sync::atomic::Ordering::SeqCst)
@@ -335,6 +343,7 @@ impl Spirc {
// LOCAL PATCH: replaced with the handle's own the moment it exists.
active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
playing: std::sync::Arc::new(std::sync::Mutex::new(PlayingHere::default())),
+ cluster: std::sync::Arc::new(std::sync::Mutex::new(None)),
spirc_id,
};
@@ -344,10 +353,14 @@ impl Spirc {
let playing = std::sync::Arc::new(std::sync::Mutex::new(PlayingHere::default()));
task.playing = playing.clone();
+ let cluster = std::sync::Arc::new(std::sync::Mutex::new(None));
+ task.cluster = cluster.clone();
+
let spirc = Spirc {
commands: cmd_tx,
active,
playing,
+ cluster,
};
let initial_volume = task.connect_state.device_info().volume;
@@ -1107,6 +1120,9 @@ impl SpircTask {
self.session.device_id()
);
+ if let Ok(mut snapshot) = self.cluster.lock() {
+ *snapshot = Some(cluster.clone());
+ }
self.connect_established = true;
let same_session = cluster.player_state.session_id == self.session.session_id()
@@ -1196,6 +1212,9 @@ impl SpircTask {
);
if let Some(cluster) = cluster_update.cluster.take() {
+ if let Ok(mut snapshot) = self.cluster.lock() {
+ *snapshot = Some(cluster.clone());
+ }
let became_inactive = self.connect_state.is_active()
&& cluster.active_device_id != self.session.device_id();
if became_inactive {