Skip to content

Native Android client for Spotify, built with Jetpack Compose

Stall repairs (seek, reload, next past the end) wait while the phone has no network and resume once it is back, a player page that failed offline loads again as soon as the network returns, and the Podcasts chip waits for the shows, says "No podcasts followed yet" or "Couldn't load your podcasts" with Try again in both looks, the error logged instead of swallowed (#136)

kota-zo12f17a11d326
diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
index cd71ce04..d15e9067 100644
--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt
+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt
@@ -321,24 +321,37 @@ class Api constructor(
/**
* Every show the user follows (library "Podcasts" filter), as library rows. The list is read
- * page after page to its end: the Home podcasts shelf holds only the first 20.
+ * page after page to its end: the Home podcasts shelf holds only the first 20. Empty when it
+ * could not be read; [followedShows] tells that apart from no show followed.
*/
- suspend fun getFollowedShows(): List<LibraryEntry> {
- if (!ready()) return emptyList()
+ suspend fun getFollowedShows(): List<LibraryEntry> = followedShows().getOrDefault(emptyList())
+
+ /**
+ * [getFollowedShows], failing when Spotify did not answer its first page (no session, an error):
+ * the Podcasts chip said "nothing followed" for an error and logged nothing (#136). A later
+ * page that fails ends the list with the shows already read.
+ */
+ suspend fun followedShows(): Result<List<LibraryEntry>> {
+ if (!ready()) return Result.failure(IllegalStateException(notSignedIn()))
val out = ArrayList<LibraryEntry>()
var offset = 0
while (true) {
- val page = runCatching { api.library.items(filter = LibraryFilter.PODCASTS, offset = offset, limit = 50) }.getOrNull() ?: break
+ val page = runCatching { api.library.items(filter = LibraryFilter.PODCASTS, offset = offset, limit = 50) }.getOrElse {
+ if (it is CancellationException) throw it
+ Log.e("Api", "getFollowedShows failed at $offset", it)
+ if (offset == 0) return Result.failure(it)
+ null
+ } ?: break
page.items.filter { it.kind == MediaKind.SHOW }.forEach {
out += LibraryEntry(SHOW_PREFIX + it.uri.substringAfterLast(':'), it.name,
context.getString(R.string.album_type_podcast) + (it.subtitle?.let { s -> " • $s" } ?: ""), cover(it.images), isPlaylist = false)
}
offset = page.nextOffset ?: break
}
- if (out.isEmpty()) return out
+ if (out.isEmpty()) return Result.success(out)
val news = LibraryEntry(NEW_EPISODES_ID, context.getString(R.string.new_episodes_title), context.getString(R.string.new_episodes_subtitle),
out.first().coverUri, isPlaylist = true)
- return listOf(news) + out
+ return Result.success(listOf(news) + out)
}
/**
diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt
index 44e2d28a..6503af38 100644
--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt
@@ -150,7 +150,8 @@ fun ImmersiveLibraryScreen(navController: NavController) {
val entries by vm.entries.collectAsState()
val account by vm.account.collectAsState()
val followedArtists by vm.followedArtists.collectAsState()
- val followedShows by vm.followedShows.collectAsState()
+ val showsLoad by vm.followedShows.collectAsState()
+ val followedShows = (showsLoad as? Response.Success)?.data.orEmpty()
val context = LocalContext.current
LaunchedEffect(Unit) { ProfileCache.ensure(context) }
@@ -207,6 +208,14 @@ fun ImmersiveLibraryScreen(navController: NavController) {
}
// Only the whole library, unfiltered, can be put in a new order.
val reorderLevel = if (kind == LibraryChip.ALL && searchQuery.isBlank()) LibraryOrder.ROOT else null
+ // The Podcasts chip waits for the shows, and says when none is followed or they could not be read (#136).
+ val podcasts = kind == LibraryChip.PODCASTS
+ val showsLoading = podcasts && showsLoad is Response.Loading
+ val showsFailed = podcasts && showsLoad is Response.Error
+ val chipEmpty = if (podcasts && showsLoad is Response.Success && followedShows.isEmpty() && searchQuery.isBlank())
+ stringResource(R.string.library_podcasts_empty) else null
+ val chipError = if (showsFailed) stringResource(R.string.library_podcasts_error) else null
+ val retry: () -> Unit = { if (showsFailed) vm.loadFollowedShows(); if (entries !is Response.Success) vm.load() }
val title = stringResource(R.string.navigationbar_musicappitems_yourlibrary_title)
val listState = rememberLazyListState()
@@ -237,31 +246,35 @@ fun ImmersiveLibraryScreen(navController: NavController) {
onRefresh = { vm.refresh() },
modifier = Modifier.fillMaxSize(),
) {
- if (gridView && !loading) {
+ if (gridView && !loading && !showsLoading) {
LibraryGrid(
gridState = gridState,
header = header,
entries = shownEntries,
artists = shownArtists,
- loadFailed = entries !is Response.Success,
- onRetry = { vm.load() },
+ loadFailed = entries !is Response.Success || showsFailed,
+ onRetry = retry,
navController = navController,
reorderLevel = reorderLevel,
pinned = pinned,
+ emptyText = chipEmpty,
+ errorText = chipError,
)
} else {
LibraryList(
listState = listState,
header = header,
- loading = loading,
+ loading = loading || showsLoading,
entries = shownEntries,
artists = shownArtists,
- loadFailed = !loading && entries !is Response.Success,
- onRetry = { vm.load() },
+ loadFailed = !loading && (entries !is Response.Success || showsFailed),
+ onRetry = retry,
navController = navController,
reorderLevel = reorderLevel,
pinned = pinned,
onMenu = { itemMenu = it },
+ emptyText = chipEmpty,
+ errorText = chipError,
)
}
}
@@ -493,6 +506,8 @@ internal fun LibraryList(
reorderLevel: String?,
pinned: Int,
onMenu: (LibraryEntry) -> Unit,
+ emptyText: String? = null,
+ errorText: String? = null,
) {
val haptic = LocalHapticFeedback.current
val density = LocalDensity.current
@@ -568,7 +583,7 @@ internal fun LibraryList(
immersiveLibrarySkeleton()
return@LazyColumn
}
- if (entries.isEmpty() && artists.isEmpty() && !loadFailed) {
+ if (entries.isEmpty() && artists.isEmpty() && !loadFailed && emptyText == null) {
item(key = "library:empty") { ImmersiveMessageState(stringResource(R.string.library_empty)) }
}
itemsIndexed(rows, key = { _, e -> LibraryOrder.key(e) }) { index, entry ->
@@ -641,10 +656,12 @@ internal fun LibraryList(
}
}
}
+ // A chip with nothing of its own (no show followed) says so under the rows it keeps.
+ if (emptyText != null && !loadFailed) item(key = "library:chip-empty") { ImmersiveMessageState(emptyText) }
if (loadFailed) {
item(key = "library:error") {
ImmersiveMessageState(
- message = stringResource(R.string.library_error),
+ message = errorText ?: stringResource(R.string.library_error),
actionLabel = stringResource(R.string.home_retry),
onAction = onRetry,
)
@@ -703,6 +720,8 @@ private fun LibraryGrid(
navController: NavController,
reorderLevel: String?,
pinned: Int,
+ emptyText: String? = null,
+ errorText: String? = null,
) {
val haptic = LocalHapticFeedback.current
val density = LocalDensity.current
@@ -782,7 +801,7 @@ private fun LibraryGrid(
item(key = "library:header", span = { GridItemSpan(maxLineSpan) }) {
Box(Modifier.immersiveBleed(Immersive.Gutter)) { header() }
}
- if (entries.isEmpty() && artists.isEmpty() && !loadFailed) {
+ if (entries.isEmpty() && artists.isEmpty() && !loadFailed && emptyText == null) {
item(key = "library:empty", span = { GridItemSpan(maxLineSpan) }) {
ImmersiveMessageState(stringResource(R.string.library_empty))
}
@@ -867,10 +886,13 @@ private fun LibraryGrid(
}
}
}
+ if (emptyText != null && !loadFailed) {
+ item(key = "library:chip-empty", span = { GridItemSpan(maxLineSpan) }) { ImmersiveMessageState(emptyText) }
+ }
if (loadFailed) {
item(key = "library:error", span = { GridItemSpan(maxLineSpan) }) {
ImmersiveMessageState(
- message = stringResource(R.string.library_error),
+ message = errorText ?: stringResource(R.string.library_error),
actionLabel = stringResource(R.string.home_retry),
onAction = onRetry,
)
diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
index 430c6956..128719dc 100644
--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt
@@ -276,7 +276,8 @@ fun LibraryScreen(navController: NavController) {
}
val followedArtists by libraryViewModel.followedArtists.collectAsState()
- val followedShows by libraryViewModel.followedShows.collectAsState()
+ val showsLoad by libraryViewModel.followedShows.collectAsState()
+ val followedShows = (showsLoad as? Response.Success)?.data.orEmpty()
// The shows are only read once the Podcasts chip is chosen.
androidx.compose.runtime.LaunchedEffect(chip) {
if (chip == com.music.spotui.data.local.LibraryChip.PODCASTS) libraryViewModel.loadFollowedShows()
@@ -351,11 +352,21 @@ fun LibraryScreen(navController: NavController) {
else chipArtists.filter { it.name.contains(searchQuery, ignoreCase = true) }
// Moving rows only makes sense on the whole list.
val movable = searchQuery.isBlank() && chip == com.music.spotui.data.local.LibraryChip.ALL
- if (gridView) LibraryGridScreen(PaddingValues(0.dp), filteredEntries, filteredArtists, navController,
- reorderLevel = if (movable) LibraryOrder.ROOT else null, pinned = rootPinned)
+ // The Podcasts chip waits for the shows, and says when none is followed or they could not be read (#136).
+ val podcasts = chip == com.music.spotui.data.local.LibraryChip.PODCASTS
+ val chipNote = when {
+ !podcasts -> null
+ showsLoad is Response.Error -> stringResource(R.string.library_podcasts_error)
+ showsLoad is Response.Success && followedShows.isEmpty() && searchQuery.isBlank() -> stringResource(R.string.library_podcasts_empty)
+ else -> null
+ }
+ val chipRetry: (() -> Unit)? = if (podcasts && showsLoad is Response.Error) { { libraryViewModel.loadFollowedShows() } } else null
+ if (podcasts && showsLoad is Response.Loading) LibrarySkeleton(PaddingValues(0.dp))
+ else if (gridView) LibraryGridScreen(PaddingValues(0.dp), filteredEntries, filteredArtists, navController,
+ reorderLevel = if (movable) LibraryOrder.ROOT else null, pinned = rootPinned, note = chipNote, onRetry = chipRetry)
else SumUpLibraryScreen(PaddingValues(0.dp), filteredEntries, filteredArtists, navController,
reorderLevel = if (movable) LibraryOrder.ROOT else null, pinned = rootPinned,
- onChanged = { libraryViewModel.load() })
+ onChanged = { libraryViewModel.load() }, note = chipNote, onRetry = chipRetry)
if (entries !is Response.Success) Box(modifier = Modifier.padding(20.dp, 100.dp)) { Snackbar(showMessage = stringResource(R.string.library_error)) }
}
}
@@ -422,10 +433,14 @@ fun SumUpLibraryScreen(
pinned: Int = 0,
/** A pin, move or delete changed the library: load it again. */
onChanged: () -> Unit = {},
+ /** Said under the rows, in place of "Your Library is empty" (a chip with nothing of its own). */
+ note: String? = null,
+ /** With [note]: it tells a failure, and offers to try again. */
+ onRetry: (() -> Unit)? = null,
) {
var itemMenu by remember { mutableStateOf<LibraryEntry?>(null) }
itemMenu?.let { LibraryItemSheet(it, onDismiss = { itemMenu = null }, onChanged = onChanged) }
- if (entries.isEmpty() && followedArtists.isEmpty()) {
+ if (entries.isEmpty() && followedArtists.isEmpty() && note == null) {
Box(modifier = Modifier.padding(20.dp, 40.dp)) { Snackbar(showMessage = stringResource(R.string.library_empty)) }
return
}
@@ -597,6 +612,7 @@ fun SumUpLibraryScreen(
}
}
}
+ if (note != null) item(key = "library:note") { LibraryNote(note, onRetry) }
}
com.music.spotui.ui.components.FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))
}
@@ -663,8 +679,11 @@ fun LibraryGridScreen(
reorderLevel: String? = null,
/** Entries at the top that never move (Liked Songs, Local Files, Downloaded). */
pinned: Int = 0,
+ /** As in [SumUpLibraryScreen]. */
+ note: String? = null,
+ onRetry: (() -> Unit)? = null,
) {
- if (entries.isEmpty() && followedArtists.isEmpty()) {
+ if (entries.isEmpty() && followedArtists.isEmpty() && note == null) {
Box(modifier = Modifier.padding(20.dp, 40.dp)) { Snackbar(showMessage = stringResource(R.string.library_empty)) }
return
}
@@ -824,6 +843,21 @@ fun LibraryGridScreen(
}
}
}
+ if (note != null) item(key = "library:note", span = { GridItemSpan(maxLineSpan) }) { LibraryNote(note, onRetry) }
+ }
+}
+
+/** A line under the library's rows: why a chip shows nothing, with "Try again" when it failed. */
+@Composable
+private fun LibraryNote(text: String, onRetry: (() -> Unit)?) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier.fillMaxWidth().padding(20.dp, 24.dp),
+ ) {
+ Text(text = text, color = AppText, fontSize = 15.sp, textAlign = TextAlign.Center)
+ if (onRetry != null) androidx.compose.material3.TextButton(onClick = onRetry) {
+ Text(stringResource(R.string.home_retry), color = com.music.spotui.ui.theme.AppAccent)
+ }
}
}
diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt
index ccb73f09..9fb2344c 100644
--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt
+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt
@@ -22,6 +22,7 @@ import kotlinx.coroutines.launch
class LibraryViewModel constructor(
private val repository: AppRepository = Graph.repository,
private val context: android.content.Context = Graph.app,
+ private val api: com.music.spotui.data.api.Api = Graph.api,
) : ViewModel() {
private val _entries: MutableStateFlow<Response<List<LibraryEntry>>> = MutableStateFlow(Response.Loading())
@@ -34,9 +35,12 @@ class LibraryViewModel constructor(
MutableStateFlow(emptyList())
val followedArtists: StateFlow<List<com.music.spotui.data.entity.ArtistsModel>> = _followedArtists
- private val _followedShows: MutableStateFlow<List<LibraryEntry>> = MutableStateFlow(emptyList())
- /** The shows the user follows, read when the Podcasts chip is chosen (see [loadFollowedShows]). */
- val followedShows: StateFlow<List<LibraryEntry>> = _followedShows
+ private val _followedShows: MutableStateFlow<Response<List<LibraryEntry>>> = MutableStateFlow(Response.Loading())
+ /**
+ * The shows the user follows, read when the Podcasts chip is chosen (see [loadFollowedShows]):
+ * an error only while none was ever read, so the chip says so instead of "none followed".
+ */
+ val followedShows: StateFlow<Response<List<LibraryEntry>>> = _followedShows
/** The list as Spotify gave it; [entries] is this with the changes not yet in Spotify's list on top. */
@Volatile private var server: List<LibraryEntry>? = null
@@ -102,11 +106,14 @@ class LibraryViewModel constructor(
/** The Podcasts chip was chosen once: a pull-to-refresh reads the shows again too. */
@Volatile private var showsAsked = false
- /** Reads the followed shows again; the list stays as it was when Spotify does not answer. */
+ /** Reads the followed shows again; a list already read stays when Spotify does not answer. */
fun loadFollowedShows() = viewModelScope.launch(Dispatchers.IO) {
showsAsked = true
- val shows = repository.provideFollowedShows()
- if (shows.isNotEmpty()) _followedShows.value = shows
+ if (_followedShows.value !is Response.Success) _followedShows.value = Response.Loading()
+ api.followedShows().fold(
+ onSuccess = { _followedShows.value = Response.Success(it) },
+ onFailure = { if (_followedShows.value !is Response.Success) _followedShows.value = Response.Error(it.message ?: "error") },
+ )
}
private fun loadAccount() = viewModelScope.launch(Dispatchers.IO) {
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
index b0736464..dd88089f 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt
@@ -39,7 +39,10 @@ object MyspotiRuntime {
// Repairs wait while Spotify limits playback, and while a Spotify sign-in page is open:
// the player is not there to answer, and the "page not answering" reload threw the user
// off the e-mail code step while they were away reading the code (reported, log seen).
- spotify.player.recoveryHeld = { host.licenseLimited() || host.loginRequired.value }
+ // And while the phone is offline (airplane mode): a stalled song got a seek, a skip, then
+ // a reload whose page could not load, so the music on screen was thrown away for nothing.
+ // Downloads and extension audio play outside the page and never ask this.
+ spotify.player.recoveryHeld = { host.licenseLimited() || host.loginRequired.value || !host.online.value }
spotify.player.playbackHeld = { host.licenseLimited() }
// Spotify limiting this client: stop asking (a paused player requests no licence).
scope.launch {
@@ -62,7 +65,7 @@ object MyspotiRuntime {
kotlinx.coroutines.delay(10_000)
val clock = android.os.SystemClock.elapsedRealtime()
val waiting = !spotify.ready.value && !host.loginRequired.value && !host.licenseLimited() &&
- host.url.value.startsWith(WebPlayerHost.PLAYER_URL)
+ host.online.value && host.url.value.startsWith(WebPlayerHost.PLAYER_URL)
if (!waiting) { notReadySince = 0L; if (spotify.ready.value) notReadyWait = 60_000L }
else if (notReadySince == 0L) notReadySince = clock
else if (clock - notReadySince >= notReadyWait) {
diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
index 9d0aa136..df58bbe5 100644
--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt
@@ -47,6 +47,13 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
/** The page's current URL. */
val url: StateFlow<String> = _url
+ private val _online = MutableStateFlow(true)
+ /**
+ * The phone's default network can reach the internet (airplane mode, no signal: false). Kept by
+ * [watchNetwork]; true when connectivity cannot be watched, so nothing is held for nothing.
+ */
+ val online: StateFlow<Boolean> = _online
+
/*
* Spotify limiting this client: measured on the test phone after an evening of test runs,
* the page asked for an audio licence ~4 times a second, each answered 429, and every repair
@@ -118,19 +125,57 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
private fun watchNetwork() {
val connectivity = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return
runCatching {
+ // No default network at start (airplane mode) calls nothing: the state is read once here.
+ _online.value = hasInternet(connectivity.getNetworkCapabilities(connectivity.activeNetwork))
connectivity.registerDefaultNetworkCallback(object : android.net.ConnectivityManager.NetworkCallback() {
private var current: android.net.Network? = null
override fun onAvailable(network: android.net.Network) {
val was = current
current = network
+ setOnline(true)
// The first call names the network the app started on: nothing to drop.
if (was == null || was == network) return
Logbook.log("network changed: the relay's idle connections dropped")
ControlRelay.resetConnections()
}
+
+ override fun onCapabilitiesChanged(network: android.net.Network, caps: android.net.NetworkCapabilities) {
+ if (network == current) setOnline(hasInternet(caps))
+ }
+
+ // Called for the default network only when no other one takes its place.
+ override fun onLost(network: android.net.Network) {
+ if (network != current) return
+ current = null
+ setOnline(false)
+ }
})
- }.onFailure { Logbook.log("network changes not watched: ${it.message}") }
+ }.onFailure { _online.value = true; Logbook.log("network changes not watched: ${it.message}") }
+ }
+
+ /*
+ * INTERNET, not VALIDATED: a network the system has not validated (some carriers, a portal
+ * that answers late) still plays, and taking it for offline held every repair on it.
+ */
+ private fun hasInternet(caps: android.net.NetworkCapabilities?): Boolean =
+ caps?.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
+
+ /**
+ * Offline, the player's repairs wait (see MyspotiRuntime): a seek, a reload or a skip can do
+ * nothing without a network but throw the page away. The network back, a player page that
+ * failed to load meanwhile is loaded again at once rather than at its next retry.
+ */
+ private fun setOnline(now: Boolean) {
+ if (_online.value == now) return
+ _online.value = now
+ Logbook.log(if (now) "network back: repairs resume" else "network lost: repairs held until it is back")
+ if (now) main.post {
+ if (!mainFrameFailed || !loadAsked || _loginRequired.value) return@post
+ pageFailures = 0
+ main.removeCallbacks(retryPlayerPage)
+ retryPlayerPage.run()
+ }
}
private lateinit var relay: ControlRelay
@@ -528,6 +573,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {
private var pageFailures = 0
private val retryPlayerPage = Runnable {
if (!loadAsked || _loginRequired.value) return@Runnable
+ // Offline, the load could only fail again: [setOnline] loads it when the network is back.
+ if (!_online.value) { Logbook.log("player page: offline, loaded again when the network is back"); return@Runnable }
Logbook.log("player page: load again (attempt ${pageFailures + 1})")
view.stopLoading()
view.loadUrl(playerRoot())