From 250e721feae7a29bbaa7ab0e743f8f0a970ca0a6 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Sat, 24 Oct 2026 19:29:49 +0600 Subject: [PATCH] Go offline when playback fails without a connection A track that failed to load, or a station that couldn't fetch more, used to skip three times and stop, even with downloads on the phone. Now a failure checks for a connection, and with none the app goes offline: a queue skips to its downloaded tracks (trying each track once, so a fully missing queue stops with a notice), and a station, which has nothing more to give offline, gives way to all downloads, shuffled. Now Playing stays open through the switch and back. Co-Authored-By: Claude Opus 5.5 --- .../panov/musyx/player/PlaybackController.kt | 19 ++++++++-- .../java/it/panov/musyx/player/PlayerCore.kt | 27 ++++++++++++++ .../java/it/panov/musyx/state/AppState.kt | 36 +++++++++++++++++-- core/src/main/res/values-ru/strings.xml | 2 ++ core/src/main/res/values/strings.xml | 2 ++ .../it/panov/musyx/player/PlayerCoreTest.kt | 29 +++++++++++++++ .../panov/musyx/mobile/ui/screens/Player.kt | 1 + mobile/src/main/res/values-ru/strings.xml | 1 + mobile/src/main/res/values/strings.xml | 1 + .../it/panov/musyx/tv/ui/screens/Player.kt | 1 + tv/src/main/res/values-ru/strings.xml | 1 + tv/src/main/res/values/strings.xml | 1 + 12 files changed, 115 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/it/panov/musyx/player/PlaybackController.kt b/core/src/main/java/it/panov/musyx/player/PlaybackController.kt index 7fac32c..87e23f0 100644 --- a/core/src/main/java/it/panov/musyx/player/PlaybackController.kt +++ b/core/src/main/java/it/panov/musyx/player/PlaybackController.kt @@ -54,6 +54,11 @@ class PlaybackController( /** A downloaded track's file as a stream, or null. */ private val local: (trackId: String) -> Stream?, buffering: Buffering, + /** + * A track couldn't be fetched or played, or a station's next tracks couldn't be fetched; + * heard before the player moves on. + */ + private val onTrackFailed: () -> Unit = {}, ) : EngineEvents { private val core = PlayerCore() private val engine = ExoEngine(context, token, this, buffering) @@ -140,7 +145,10 @@ class PlaybackController( override fun ended(generation: Long) = update { core.onEnded(generation) } - override fun failed(generation: Long, reason: String) = update { core.onFailed(generation, reason) } + override fun failed(generation: Long, reason: String) { + if (generation == core.generation) onTrackFailed() + update { core.onFailed(generation, reason) } + } override fun playingChanged(generation: Long, playing: Boolean) { core.onPlayingChanged(generation, playing) @@ -157,20 +165,25 @@ class PlaybackController( // Downloaded tracks play without a session, so these go ahead offline too. is Effect.Fetch -> scope.launch { val result = runCatching { resolve(api, effect.trackId) } + // Heard first, so that if the connection is gone the next track is looked for offline. + result.exceptionOrNull()?.let { if (it !is NotDownloaded) onTrackFailed() } update { core.fetched(effect.generation, result) } } is Effect.Prefetch -> scope.launch { val result = runCatching { resolve(api, effect.trackId) } core.prefetched(effect.trackId, result) } - is Effect.WaveFetch -> api?.let { c -> + is Effect.WaveFetch -> { // My Wave's settings ride along as seeds when a session starts. val settings = if (effect.station == MY_WAVE) waveSettings() else null scope.launch { val result = runCatching { + // Offline a station has nothing to play: failing says so rather than waiting. + val c = api ?: throw YmError.Network("offline") val session = effect.sessionId if (session != null) c.waveMore(session, effect.queue) else c.waveStart(effect.station, settings) } + if (api != null && result.isFailure) onTrackFailed() update { core.waveBatch(effect.station, effect.epoch, result) } } } @@ -191,7 +204,7 @@ class PlaybackController( /** A downloaded file when there is one, else a link from Yandex. */ private suspend fun resolve(c: YmClient?, trackId: String): Stream = - local(trackId) ?: resolveStream(c ?: throw YmError.Network("offline"), trackId, quality()) + local(trackId) ?: resolveStream(c ?: throw NotDownloaded(trackId), trackId, quality()) private companion object { const val TAG = "Musyx" diff --git a/core/src/main/java/it/panov/musyx/player/PlayerCore.kt b/core/src/main/java/it/panov/musyx/player/PlayerCore.kt index 9df8149..1c660ca 100644 --- a/core/src/main/java/it/panov/musyx/player/PlayerCore.kt +++ b/core/src/main/java/it/panov/musyx/player/PlayerCore.kt @@ -36,8 +36,13 @@ sealed interface Notice { data object StationDry : Notice data object TooManyFailures : Notice data class Skipped(val title: String) : Notice + /** Offline, and nothing in the queue is downloaded. */ + data object NothingDownloaded : Notice } +/** A track that isn't on the device, wanted with no connection to fetch it. */ +class NotDownloaded(trackId: String) : Exception("not downloaded: $trackId") + /** Work the app has to do on the player's behalf. */ sealed interface Effect { data class Fetch(val generation: Long, val trackId: String) : Effect @@ -99,6 +104,8 @@ class PlayerCore(private val random: Random = Random.Default) { private var prefetched: Pair? = null internal var skips: Int = 0 private set + /** Tracks passed over offline since one last played; the whole queue is the limit. */ + private var missing = 0 var notice: Notice? = null private set private var wave: Wave? = null @@ -127,6 +134,7 @@ class PlayerCore(private val random: Random = Random.Default) { currentTrackId = null prefetched = null skips = 0 + missing = 0 notice = null wave = null started = null @@ -141,6 +149,7 @@ class PlayerCore(private val random: Random = Random.Default) { wave = null queue = Queue.of(tracks, first, this.shuffle, random) skips = 0 + missing = 0 notice = null effects += loadCurrent() return effects @@ -166,6 +175,7 @@ class PlayerCore(private val random: Random = Random.Default) { stream = null currentTrackId = null skips = 0 + missing = 0 notice = null status = Status.Loading engine?.stop() @@ -274,6 +284,8 @@ class PlayerCore(private val random: Random = Random.Default) { onSuccess = { loadStream(it, play = !holdPaused) }, onFailure = { e -> if (e is YmError.Unauthorized) return listOf(Effect.SignedOut) + // Offline, the queue is searched for what's downloaded; that's no failure. + if (e is NotDownloaded) return skipMissing() android.util.Log.w("Musyx", "fetch: $e") return skipUnplayable() }, @@ -296,6 +308,7 @@ class PlayerCore(private val random: Random = Random.Default) { if (durationMs != null && durationMs > 0) this.durationMs = durationMs status = if (holdPaused) Status.Paused else Status.Playing skips = 0 + missing = 0 val effects = mutableListOf() val t = track if (t != null) { @@ -480,4 +493,18 @@ class PlayerCore(private val random: Random = Random.Default) { notice = Notice.Skipped(title) return step(user = true, finished = false) } + + /** Offline: moves past a track that isn't downloaded, until the whole queue has been tried. */ + private fun skipMissing(): List { + missing += 1 + stream = null + currentTrackId = null + if (missing >= (queue?.size ?: 0)) { + engine?.pause() + status = Status.Paused + notice = Notice.NothingDownloaded + return emptyList() + } + return step(user = true, finished = false) + } } diff --git a/core/src/main/java/it/panov/musyx/state/AppState.kt b/core/src/main/java/it/panov/musyx/state/AppState.kt index faccbe1..64667c4 100644 --- a/core/src/main/java/it/panov/musyx/state/AppState.kt +++ b/core/src/main/java/it/panov/musyx/state/AppState.kt @@ -90,7 +90,10 @@ class AppState( buffering: Buffering = Buffering.Default, /** Cover sizes the interface shows, kept with downloads so they appear offline. */ coverSizes: List = emptyList(), - /** Whether the device has any connection; without one, sign-in isn't attempted. */ + /** + * Whether the device has any connection; without one, sign-in isn't attempted, and a track + * that fails to play switches the app to its downloads. + */ private val online: () -> Boolean = { true }, ) { var session: Session by mutableStateOf(Session.Restoring) @@ -165,6 +168,7 @@ class AppState( onSignedOut = ::signOut, local = downloads::stream, buffering = buffering, + onTrackFailed = ::trackFailed, ) val client: YmClient? get() = (session as? Session.SignedIn)?.client @@ -225,10 +229,36 @@ class AppState( private fun unreachable() { // Downloads are what's left to play; the phone shows them. - nav.reset(Route.Downloads()) + startOver(Route.Downloads()) session = Session.Unreachable } + /** + * A track or a station's next tracks couldn't be fetched, or a track couldn't play. With the + * connection gone, carry on offline: the player looks for downloaded tracks in the queue, or, + * for a station, which has nothing more offline, plays all of them. The network callback + * reconnects later. + */ + private fun trackFailed() { + if (session !is Session.SignedIn || online()) return + Log.i(TAG, "connection lost: playing downloads") + unreachable() + val downloaded = downloads.doneTracks + if (playback.state.waveStation != null && downloaded.isNotEmpty()) { + toast(UiText.Res(R.string.toast_offline_station)) + playTracks(downloaded, 0, shuffle = true) + } else { + toast(UiText.Res(R.string.toast_offline)) + } + } + + /** Navigation starts again at `start`; Now Playing stays open over it if it was. */ + private fun startOver(start: Route) { + val playing = nav.current == Route.NowPlaying + nav.reset(start) + if (playing) nav.go(Route.NowPlaying) + } + /** Makes `creds` the session's, persisting each renewal while it still is. */ private fun keep(creds: Credentials): Tokens { lateinit var kept: Tokens @@ -277,7 +307,7 @@ class AppState( } private fun signedIn(client: YmClient, account: Account) { - nav.reset(Route.Home) + startOver(Route.Home) session = Session.SignedIn(client, account) downloads.attach(account.uid) // Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page. diff --git a/core/src/main/res/values-ru/strings.xml b/core/src/main/res/values-ru/strings.xml index 71cbb6f..54274e8 100644 --- a/core/src/main/res/values-ru/strings.xml +++ b/core/src/main/res/values-ru/strings.xml @@ -57,6 +57,8 @@ «%1$s» удалено с устройства «Мне нравится» удалено с устройства Все загрузки удалены + Нет интернета, поэтому играют только загрузки + Нет интернета, поэтому вместо станции играют ваши загрузки Играем %1$d трек в духе «%2$s» Играем %1$d трека в духе «%2$s» diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index 75b4033..8e45f8b 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -57,6 +57,8 @@ Removed “%1$s” from the device Removed Liked tracks from the device All downloads removed + No connection, so only downloads play + No connection, so your downloads play instead of the station Playing %1$d track like “%2$s” Playing %1$d tracks like “%2$s” diff --git a/core/src/test/java/it/panov/musyx/player/PlayerCoreTest.kt b/core/src/test/java/it/panov/musyx/player/PlayerCoreTest.kt index d2ae319..70c137f 100644 --- a/core/src/test/java/it/panov/musyx/player/PlayerCoreTest.kt +++ b/core/src/test/java/it/panov/musyx/player/PlayerCoreTest.kt @@ -109,6 +109,35 @@ class PlayerCoreTest { assertEquals(Notice.TooManyFailures, p.notice) } + @Test + fun offlineSkipsToTheNextDownloadedTrack() { + val p = playing(6, 0) + p.next() + // Tracks 1 to 4 aren't on the phone: more in a row than the failures given up after. + for (id in 1..4) { + assertEquals("$id", p.track!!.id) + p.fetched(p.generation, Result.failure(NotDownloaded("$id"))) + } + assertEquals("5", p.track!!.id) + assertEquals(Status.Loading, p.status) + assertEquals(0, p.skips) + assertNull(p.notice) + } + + @Test + fun offlineWithNothingDownloadedStopsAfterOneRound() { + val p = playing(3, 0) + p.cycleRepeat() + var effects = p.next() + repeat(3) { + val gen = effects.fetchGeneration() ?: return@repeat + effects = p.fetched(gen, Result.failure(NotDownloaded(p.track!!.id))) + } + assertTrue(effects.none { it is Effect.Fetch }) + assertEquals(Status.Paused, p.status) + assertEquals(Notice.NothingDownloaded, p.notice) + } + @Test fun expiredTokenSignsOut() { val p = PlayerCore() diff --git a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt index 47ca5eb..5de0880 100644 --- a/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt +++ b/mobile/src/main/java/it/panov/musyx/mobile/ui/screens/Player.kt @@ -82,6 +82,7 @@ internal fun noticeText(notice: Notice): String = when (notice) { Notice.StationDry -> stringResource(R.string.notice_station_dry) Notice.TooManyFailures -> stringResource(R.string.notice_too_many) is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title) + Notice.NothingDownloaded -> stringResource(R.string.notice_nothing_downloaded) } private enum class Panel { Queue, Lyrics } diff --git a/mobile/src/main/res/values-ru/strings.xml b/mobile/src/main/res/values-ru/strings.xml index 1c05d69..3220c90 100644 --- a/mobile/src/main/res/values-ru/strings.xml +++ b/mobile/src/main/res/values-ru/strings.xml @@ -179,6 +179,7 @@ Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз. Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз. Не удалось воспроизвести «%1$s», трек пропущен. + Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать. Следующий трек Играть следующим Добавить в очередь diff --git a/mobile/src/main/res/values/strings.xml b/mobile/src/main/res/values/strings.xml index fda4fc6..73bf744 100644 --- a/mobile/src/main/res/values/strings.xml +++ b/mobile/src/main/res/values/strings.xml @@ -180,6 +180,7 @@ Couldn\'t load more of this station. Check your connection and try again. Several tracks in a row couldn\'t be played. Check your connection and try again. Couldn\'t play “%1$s”, so it was skipped. + None of the queued tracks are downloaded. Connect to the internet to play them. Next track Play next Add to queue diff --git a/tv/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt b/tv/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt index c11aca5..b4df5b2 100644 --- a/tv/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt +++ b/tv/src/main/java/it/panov/musyx/tv/ui/screens/Player.kt @@ -108,6 +108,7 @@ internal fun noticeText(notice: Notice): String = when (notice) { Notice.StationDry -> stringResource(R.string.notice_station_dry) Notice.TooManyFailures -> stringResource(R.string.notice_too_many) is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title) + Notice.NothingDownloaded -> stringResource(R.string.notice_nothing_downloaded) } /** The cover on the stage: as large as the stage's height allows under the transport. */ diff --git a/tv/src/main/res/values-ru/strings.xml b/tv/src/main/res/values-ru/strings.xml index c3dd315..937acb6 100644 --- a/tv/src/main/res/values-ru/strings.xml +++ b/tv/src/main/res/values-ru/strings.xml @@ -211,6 +211,7 @@ Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз. Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз. Не удалось воспроизвести «%1$s», трек пропущен. + Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать. Следующий трек Играть следующим diff --git a/tv/src/main/res/values/strings.xml b/tv/src/main/res/values/strings.xml index 42ca440..c3fb66e 100644 --- a/tv/src/main/res/values/strings.xml +++ b/tv/src/main/res/values/strings.xml @@ -225,6 +225,7 @@ Couldn\'t load more of this station. Check your connection and try again. Several tracks in a row couldn\'t be played. Check your connection and try again. Couldn\'t play “%1$s”, so it was skipped. + None of the queued tracks are downloaded. Connect to the internet to play them. Next track