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 <noreply@anthropic.com>
This commit is contained in:
1 parent
d085c169fb
commit
250e721fea
12 files changed
+115
-6
No files matched your search
@@ -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"
|
||||
|
||||
@@ -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<String, Stream>? = 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<Effect>()
|
||||
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<Effect> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,10 @@ class AppState(
|
||||
buffering: Buffering = Buffering.Default,
|
||||
/** Cover sizes the interface shows, kept with downloads so they appear offline. */
|
||||
coverSizes: List<Int> = 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.
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
<string name="toast_download_removed">«%1$s» удалено с устройства</string>
|
||||
<string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string>
|
||||
<string name="toast_downloads_cleared">Все загрузки удалены</string>
|
||||
<string name="toast_offline">Нет интернета, поэтому играют только загрузки</string>
|
||||
<string name="toast_offline_station">Нет интернета, поэтому вместо станции играют ваши загрузки</string>
|
||||
<plurals name="toast_playing_similar">
|
||||
<item quantity="one">Играем %1$d трек в духе «%2$s»</item>
|
||||
<item quantity="few">Играем %1$d трека в духе «%2$s»</item>
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
<string name="toast_download_removed">Removed “%1$s” from the device</string>
|
||||
<string name="toast_liked_download_removed">Removed Liked tracks from the device</string>
|
||||
<string name="toast_downloads_cleared">All downloads removed</string>
|
||||
<string name="toast_offline">No connection, so only downloads play</string>
|
||||
<string name="toast_offline_station">No connection, so your downloads play instead of the station</string>
|
||||
<plurals name="toast_playing_similar">
|
||||
<item quantity="one">Playing %1$d track like “%2$s”</item>
|
||||
<item quantity="other">Playing %1$d tracks like “%2$s”</item>
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -179,6 +179,7 @@
|
||||
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
||||
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
||||
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
||||
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
|
||||
<string name="menu_next_track">Следующий трек</string>
|
||||
<string name="menu_play_next">Играть следующим</string>
|
||||
<string name="menu_add_to_queue">Добавить в очередь</string>
|
||||
|
||||
@@ -180,6 +180,7 @@
|
||||
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
||||
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
||||
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
||||
<string name="notice_nothing_downloaded">None of the queued tracks are downloaded. Connect to the internet to play them.</string>
|
||||
<string name="menu_next_track">Next track</string>
|
||||
<string name="menu_play_next">Play next</string>
|
||||
<string name="menu_add_to_queue">Add to queue</string>
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -211,6 +211,7 @@
|
||||
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
|
||||
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
|
||||
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
|
||||
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
|
||||
|
||||
<string name="menu_next_track">Следующий трек</string>
|
||||
<string name="menu_play_next">Играть следующим</string>
|
||||
|
||||
@@ -225,6 +225,7 @@
|
||||
<string name="notice_station_dry">Couldn\'t load more of this station. Check your connection and try again.</string>
|
||||
<string name="notice_too_many">Several tracks in a row couldn\'t be played. Check your connection and try again.</string>
|
||||
<string name="notice_skipped">Couldn\'t play “%1$s”, so it was skipped.</string>
|
||||
<string name="notice_nothing_downloaded">None of the queued tracks are downloaded. Connect to the internet to play them.</string>
|
||||
|
||||
<!-- Track menu and dialogs -->
|
||||
<string name="menu_next_track">Next track</string>
|
||||
|
||||
Reference in new issue
Block a user