Author SHA1 Message Date
yuriy.pandClaude Opus 5.5 07e12eec6a Bump version to 0.1.8 (9)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:29:56 +06:00
yuriy.pandClaude Opus 5.5 b3a65d1612 Bump phone app version to 0.1.3 (4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:29:56 +06:00
yuriy.pandClaude Opus 5.5 05c90c03df Play downloads in Android Auto
Offline, the car showed "Sign in" and nothing to play. It now lists the downloads,
by track and by album or playlist, searches them and plays them by voice; online
they sit under Collection. Their covers come from the copies kept with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:29:49 +06:00
yuriy.pandClaude Opus 5.5 250e721fea 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>
2026-10-24 19:29:49 +06:00
19 changed files with 225 additions and 30 deletions

No files matched your search

@@ -86,7 +86,7 @@ class Downloads(
private val coverSizes: List<Int> = emptyList(), private val coverSizes: List<Int> = emptyList(),
) { ) {
private val dir = File(context.filesDir, "offline") private val dir = File(context.filesDir, "offline")
private val coverDir = File(dir, "covers") private val coverDir = coverDir(context)
private val indexFile = File(dir, "index.json") private val indexFile = File(dir, "index.json")
/** Writes the index one at a time, in the order asked. */ /** Writes the index one at a time, in the order asked. */
@@ -502,6 +502,11 @@ class Downloads(
internal fun coverName(url: String): String = sha1(url).take(24) + ".img" internal fun coverName(url: String): String = sha1(url).take(24) + ".img"
private fun coverDir(context: Context) = File(context.filesDir, "offline/covers")
/** The kept copy of a cover, found without reading the downloads, e.g. for the car. */
fun coverFile(context: Context, url: String): File? = File(coverDir(context), coverName(url)).takeIf { it.isFile }
private fun sha1(s: String): String = private fun sha1(s: String): String =
MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) } MessageDigest.getInstance("SHA-1").digest(s.toByteArray()).joinToString("") { "%02x".format(it) }
} }
@@ -54,6 +54,11 @@ class PlaybackController(
/** A downloaded track's file as a stream, or null. */ /** A downloaded track's file as a stream, or null. */
private val local: (trackId: String) -> Stream?, private val local: (trackId: String) -> Stream?,
buffering: Buffering, 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 { ) : EngineEvents {
private val core = PlayerCore() private val core = PlayerCore()
private val engine = ExoEngine(context, token, this, buffering) 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 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) { override fun playingChanged(generation: Long, playing: Boolean) {
core.onPlayingChanged(generation, playing) core.onPlayingChanged(generation, playing)
@@ -157,20 +165,25 @@ class PlaybackController(
// Downloaded tracks play without a session, so these go ahead offline too. // Downloaded tracks play without a session, so these go ahead offline too.
is Effect.Fetch -> scope.launch { is Effect.Fetch -> scope.launch {
val result = runCatching { resolve(api, effect.trackId) } 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) } update { core.fetched(effect.generation, result) }
} }
is Effect.Prefetch -> scope.launch { is Effect.Prefetch -> scope.launch {
val result = runCatching { resolve(api, effect.trackId) } val result = runCatching { resolve(api, effect.trackId) }
core.prefetched(effect.trackId, result) 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. // My Wave's settings ride along as seeds when a session starts.
val settings = if (effect.station == MY_WAVE) waveSettings() else null val settings = if (effect.station == MY_WAVE) waveSettings() else null
scope.launch { scope.launch {
val result = runCatching { 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 val session = effect.sessionId
if (session != null) c.waveMore(session, effect.queue) else c.waveStart(effect.station, settings) 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) } 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. */ /** A downloaded file when there is one, else a link from Yandex. */
private suspend fun resolve(c: YmClient?, trackId: String): Stream = 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 { private companion object {
const val TAG = "Musyx" const val TAG = "Musyx"
@@ -36,8 +36,13 @@ sealed interface Notice {
data object StationDry : Notice data object StationDry : Notice
data object TooManyFailures : Notice data object TooManyFailures : Notice
data class Skipped(val title: String) : 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. */ /** Work the app has to do on the player's behalf. */
sealed interface Effect { sealed interface Effect {
data class Fetch(val generation: Long, val trackId: String) : 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 private var prefetched: Pair<String, Stream>? = null
internal var skips: Int = 0 internal var skips: Int = 0
private set private set
/** Tracks passed over offline since one last played; the whole queue is the limit. */
private var missing = 0
var notice: Notice? = null var notice: Notice? = null
private set private set
private var wave: Wave? = null private var wave: Wave? = null
@@ -127,6 +134,7 @@ class PlayerCore(private val random: Random = Random.Default) {
currentTrackId = null currentTrackId = null
prefetched = null prefetched = null
skips = 0 skips = 0
missing = 0
notice = null notice = null
wave = null wave = null
started = null started = null
@@ -141,6 +149,7 @@ class PlayerCore(private val random: Random = Random.Default) {
wave = null wave = null
queue = Queue.of(tracks, first, this.shuffle, random) queue = Queue.of(tracks, first, this.shuffle, random)
skips = 0 skips = 0
missing = 0
notice = null notice = null
effects += loadCurrent() effects += loadCurrent()
return effects return effects
@@ -166,6 +175,7 @@ class PlayerCore(private val random: Random = Random.Default) {
stream = null stream = null
currentTrackId = null currentTrackId = null
skips = 0 skips = 0
missing = 0
notice = null notice = null
status = Status.Loading status = Status.Loading
engine?.stop() engine?.stop()
@@ -274,6 +284,8 @@ class PlayerCore(private val random: Random = Random.Default) {
onSuccess = { loadStream(it, play = !holdPaused) }, onSuccess = { loadStream(it, play = !holdPaused) },
onFailure = { e -> onFailure = { e ->
if (e is YmError.Unauthorized) return listOf(Effect.SignedOut) 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") android.util.Log.w("Musyx", "fetch: $e")
return skipUnplayable() return skipUnplayable()
}, },
@@ -296,6 +308,7 @@ class PlayerCore(private val random: Random = Random.Default) {
if (durationMs != null && durationMs > 0) this.durationMs = durationMs if (durationMs != null && durationMs > 0) this.durationMs = durationMs
status = if (holdPaused) Status.Paused else Status.Playing status = if (holdPaused) Status.Paused else Status.Playing
skips = 0 skips = 0
missing = 0
val effects = mutableListOf<Effect>() val effects = mutableListOf<Effect>()
val t = track val t = track
if (t != null) { if (t != null) {
@@ -480,4 +493,18 @@ class PlayerCore(private val random: Random = Random.Default) {
notice = Notice.Skipped(title) notice = Notice.Skipped(title)
return step(user = true, finished = false) 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, buffering: Buffering = Buffering.Default,
/** Cover sizes the interface shows, kept with downloads so they appear offline. */ /** Cover sizes the interface shows, kept with downloads so they appear offline. */
coverSizes: List<Int> = emptyList(), 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 }, private val online: () -> Boolean = { true },
) { ) {
var session: Session by mutableStateOf(Session.Restoring) var session: Session by mutableStateOf(Session.Restoring)
@@ -165,6 +168,7 @@ class AppState(
onSignedOut = ::signOut, onSignedOut = ::signOut,
local = downloads::stream, local = downloads::stream,
buffering = buffering, buffering = buffering,
onTrackFailed = ::trackFailed,
) )
val client: YmClient? get() = (session as? Session.SignedIn)?.client val client: YmClient? get() = (session as? Session.SignedIn)?.client
@@ -225,10 +229,36 @@ class AppState(
private fun unreachable() { private fun unreachable() {
// Downloads are what's left to play; the phone shows them. // Downloads are what's left to play; the phone shows them.
nav.reset(Route.Downloads()) startOver(Route.Downloads())
session = Session.Unreachable 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. */ /** Makes `creds` the session's, persisting each renewal while it still is. */
private fun keep(creds: Credentials): Tokens { private fun keep(creds: Credentials): Tokens {
lateinit var kept: Tokens lateinit var kept: Tokens
@@ -277,7 +307,7 @@ class AppState(
} }
private fun signedIn(client: YmClient, account: Account) { private fun signedIn(client: YmClient, account: Account) {
nav.reset(Route.Home) startOver(Route.Home)
session = Session.SignedIn(client, account) session = Session.SignedIn(client, account)
downloads.attach(account.uid) downloads.attach(account.uid)
// Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page. // Liked tracks drive the hearts; playlists feed "Add to playlist"; Home is the first page.
+2
View File
@@ -57,6 +57,8 @@
<string name="toast_download_removed">«%1$s» удалено с устройства</string> <string name="toast_download_removed">«%1$s» удалено с устройства</string>
<string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string> <string name="toast_liked_download_removed">«Мне нравится» удалено с устройства</string>
<string name="toast_downloads_cleared">Все загрузки удалены</string> <string name="toast_downloads_cleared">Все загрузки удалены</string>
<string name="toast_offline">Нет интернета, поэтому играют только загрузки</string>
<string name="toast_offline_station">Нет интернета, поэтому вместо станции играют ваши загрузки</string>
<plurals name="toast_playing_similar"> <plurals name="toast_playing_similar">
<item quantity="one">Играем %1$d трек в духе «%2$s»</item> <item quantity="one">Играем %1$d трек в духе «%2$s»</item>
<item quantity="few">Играем %1$d трека в духе «%2$s»</item> <item quantity="few">Играем %1$d трека в духе «%2$s»</item>
+2
View File
@@ -57,6 +57,8 @@
<string name="toast_download_removed">Removed “%1$s” from the device</string> <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_liked_download_removed">Removed Liked tracks from the device</string>
<string name="toast_downloads_cleared">All downloads removed</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"> <plurals name="toast_playing_similar">
<item quantity="one">Playing %1$d track like “%2$s”</item> <item quantity="one">Playing %1$d track like “%2$s”</item>
<item quantity="other">Playing %1$d tracks 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) 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 @Test
fun expiredTokenSignsOut() { fun expiredTokenSignsOut() {
val p = PlayerCore() val p = PlayerCore()
+2 -2
View File
@@ -13,8 +13,8 @@ android {
applicationId = "it.panov.musyx" applicationId = "it.panov.musyx"
minSdk = 23 minSdk = 23
targetSdk = 37 targetSdk = 37
versionCode = 3 versionCode = 4
versionName = "0.1.2" versionName = "0.1.3"
} }
// The same keystore.properties as the TV app; without one, release builds use the debug key. // The same keystore.properties as the TV app; without one, release builds use the debug key.
@@ -8,6 +8,7 @@ import android.content.Context
import android.database.Cursor import android.database.Cursor
import android.net.Uri import android.net.Uri
import android.os.ParcelFileDescriptor import android.os.ParcelFileDescriptor
import it.panov.musyx.data.Downloads
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.Request import okhttp3.Request
import java.io.File import java.io.File
@@ -24,6 +25,10 @@ class ArtworkProvider : ContentProvider() {
// Exported for the car, so it fetches only Yandex covers, never an arbitrary URL. // Exported for the car, so it fetches only Yandex covers, never an arbitrary URL.
val host = url.host.orEmpty() val host = url.host.orEmpty()
if (url.scheme != "https" || !(host == "yandex.net" || host.endsWith(".yandex.net"))) throw FileNotFoundException("$uri") if (url.scheme != "https" || !(host == "yandex.net" || host.endsWith(".yandex.net"))) throw FileNotFoundException("$uri")
// Covers kept with downloads show offline too.
Downloads.coverFile(requireNotNull(context), url.toString())?.let {
return ParcelFileDescriptor.open(it, ParcelFileDescriptor.MODE_READ_ONLY)
}
val file = File(requireNotNull(context).cacheDir, "artwork/${sha1(url.toString())}") val file = File(requireNotNull(context).cacheDir, "artwork/${sha1(url.toString())}")
if (!file.exists()) fetch(url.toString(), file) if (!file.exists()) fetch(url.toString(), file)
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
@@ -1,5 +1,6 @@
// The media library Android Auto browses: My Wave and stations, picks from Home, and the // The media library Android Auto browses: My Wave and stations, picks from Home, the
// collection. Playing an item starts it through PlayerCore, like a tap in the app would. // collection and downloads; offline, just the downloads. Playing an item starts it through
// PlayerCore, like a tap in the app would.
package it.panov.musyx.mobile package it.panov.musyx.mobile
import android.app.PendingIntent import android.app.PendingIntent
@@ -37,6 +38,8 @@ import it.panov.musyx.api.SearchKind
import it.panov.musyx.api.Station import it.panov.musyx.api.Station
import it.panov.musyx.api.Track import it.panov.musyx.api.Track
import it.panov.musyx.api.YmClient import it.panov.musyx.api.YmClient
import it.panov.musyx.data.OfflineSet
import it.panov.musyx.mobile.ui.components.COVER_LARGE
import it.panov.musyx.state.AppState import it.panov.musyx.state.AppState
import it.panov.musyx.state.Liked import it.panov.musyx.state.Liked
import it.panov.musyx.state.Session import it.panov.musyx.state.Session
@@ -70,6 +73,11 @@ private const val ALBUMS = "albums"
private const val STATION = "station|" private const val STATION = "station|"
private const val TRACK = "t|" private const val TRACK = "t|"
private const val SEARCH = "search:" private const val SEARCH = "search:"
private const val DOWNLOADS = "downloads"
/** Every downloaded track. */
private const val OFFLINE_ALL = "offline"
/** A downloaded album, playlist or Liked tracks, by its [it.panov.musyx.data.OfflineSet] key. */
private const val OFFLINE = "offline:"
// The buttons beside the car's transport: the heart, and "don't recommend". // The buttons beside the car's transport: the heart, and "don't recommend".
private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY) private val LIKE = SessionCommand("it.panov.musyx.LIKE", Bundle.EMPTY)
@@ -85,9 +93,9 @@ class Library(private val context: Context, private val state: AppState, private
private val searches = HashMap<String, List<MediaItem>>() private val searches = HashMap<String, List<MediaItem>>()
/** /**
* Has the car reload whenever someone signs in or out, so it never keeps showing "Sign in" * Has the car reload whenever someone signs in or out, or the app goes offline or back, so
* (or someone else's music), and keeps the heart in step with the track. Returns what * it never keeps showing "Sign in" (or someone else's music, or music it can't reach), and
* stops watching. * keeps the heart in step with the track. Returns what stops watching.
*/ */
fun watch(session: MediaLibrarySession): () -> Unit { fun watch(session: MediaLibrarySession): () -> Unit {
// snapshotFlow hears about changes through Compose's apply notifications, which only the // snapshotFlow hears about changes through Compose's apply notifications, which only the
@@ -103,7 +111,8 @@ class Library(private val context: Context, private val state: AppState, private
} }
} }
val job = scope.launch { val job = scope.launch {
snapshotFlow { state.session is Session.SignedIn } // The tree comes from the account, from the downloads, or from neither.
snapshotFlow { state.client ?: state.session.takeIf { it == Session.Unreachable } }
.distinctUntilChanged() .distinctUntilChanged()
.drop(1) .drop(1)
.collect { .collect {
@@ -203,8 +212,16 @@ class Library(private val context: Context, private val state: AppState, private
pageSize: Int, pageSize: Int,
params: LibraryParams?, params: LibraryParams?,
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> = future { ): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> = future {
val client = client() ?: return@future signedOut() val client = client()
val items = children(client, parentId) ?: return@future LibraryResult.ofError(SessionError.ERROR_BAD_VALUE) val items = when {
client != null -> children(client, parentId)
!offline() -> return@future signedOut()
state.downloads.doneTracks.isEmpty() -> return@future nothingOffline()
// Out of reach: what's on the phone is all there is.
parentId == ROOT -> listOf(folder(DOWNLOADS, context.getString(R.string.downloads_title), browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM))
parentId == DOWNLOADS -> downloads()
else -> offlineTracks(parentId)?.let { tracks -> trackItems(parentId, tracks) }
} ?: return@future LibraryResult.ofError(SessionError.ERROR_BAD_VALUE)
LibraryResult.ofItemList(items.page(page, pageSize), params) LibraryResult.ofItemList(items.page(page, pageSize), params)
} }
@@ -223,8 +240,12 @@ class Library(private val context: Context, private val state: AppState, private
query: String, query: String,
params: LibraryParams?, params: LibraryParams?,
): ListenableFuture<LibraryResult<Void>> = future { ): ListenableFuture<LibraryResult<Void>> = future {
val client = client() ?: return@future signedOut() val client = client()
val tracks = client.search(query, SearchKind.Tracks, 0).tracks val tracks = when {
client != null -> client.search(query, SearchKind.Tracks, 0).tracks
offline() -> findDownloaded(state, query)
else -> return@future signedOut()
}
val folder = SEARCH + query val folder = SEARCH + query
shown[folder] = tracks shown[folder] = tracks
searches[query] = tracks.mapIndexed { i, t -> track(folder, i, t) } searches[query] = tracks.mapIndexed { i, t -> track(folder, i, t) }
@@ -260,7 +281,7 @@ class Library(private val context: Context, private val state: AppState, private
id.startsWith(STATION) -> state.playWave(id.removePrefix(STATION)) id.startsWith(STATION) -> state.playWave(id.removePrefix(STATION))
id.startsWith(TRACK) -> { id.startsWith(TRACK) -> {
val (folder, index) = id.removePrefix(TRACK).let { it.substringBeforeLast('|') to it.substringAfterLast('|').toIntOrNull() } val (folder, index) = id.removePrefix(TRACK).let { it.substringBeforeLast('|') to it.substringAfterLast('|').toIntOrNull() }
val tracks = shown[folder] ?: client()?.let { tracks(it, folder) } val tracks = shown[folder] ?: offlineTracks(folder) ?: client()?.let { tracks(it, folder) }
if (tracks != null && index != null && index in tracks.indices) state.playTracks(tracks, index) if (tracks != null && index != null && index in tracks.indices) state.playTracks(tracks, index)
} }
id.isEmpty() -> playFromSearch(state, query) id.isEmpty() -> playFromSearch(state, query)
@@ -289,21 +310,48 @@ class Library(private val context: Context, private val state: AppState, private
folder(CHART, context.getString(R.string.section_chart), home.chart.firstOrNull()?.track?.coverUrl(ART_SIZE)), folder(CHART, context.getString(R.string.section_chart), home.chart.firstOrNull()?.track?.coverUrl(ART_SIZE)),
) + home.personal.map { playlist(it.playlist) } ) + home.personal.map { playlist(it.playlist) }
} }
COLLECTION -> listOf( COLLECTION -> listOfNotNull(
folder(LIKED, context.getString(R.string.tab_liked_tracks)), folder(LIKED, context.getString(R.string.tab_liked_tracks)),
folder(PLAYLISTS, context.getString(R.string.tab_playlists)), folder(PLAYLISTS, context.getString(R.string.tab_playlists)),
folder(ALBUMS, context.getString(R.string.tab_albums)), folder(ALBUMS, context.getString(R.string.tab_albums)),
// Music on the phone plays without using data, or a signal.
if (state.downloads.doneTracks.isEmpty()) null
else folder(DOWNLOADS, context.getString(R.string.downloads_title), browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM),
) )
PLAYLISTS -> client.libraryPlaylists().let { it.own + it.liked }.map(::playlist) PLAYLISTS -> client.libraryPlaylists().let { it.own + it.liked }.map(::playlist)
ALBUMS -> client.likedAlbums().filter { !it.isPodcast }.map(::album) ALBUMS -> client.likedAlbums().filter { !it.isPodcast }.map(::album)
else -> tracks(client, parent)?.let { tracks -> DOWNLOADS -> downloads()
shown[parent] = tracks else -> tracks(client, parent)?.let { tracks -> trackItems(parent, tracks) }
tracks.mapIndexed { i, t -> track(parent, i, t) } }
private fun trackItems(folder: String, tracks: List<Track>): List<MediaItem> {
shown[folder] = tracks
return tracks.mapIndexed { i, t -> track(folder, i, t) }
}
/** Every downloaded track, then the albums and playlists with any of theirs on the phone. */
private fun downloads(): List<MediaItem> {
val d = state.downloads
val all = d.doneTracks
val sets = d.sets.filter { set -> set.trackIds.any(d::isDone) }.map { set ->
val title = if (set.kind == OfflineSet.Kind.Liked) context.getString(R.string.tab_liked_tracks) else set.title
folder(OFFLINE + set.key, title, set.cover, browsable = MediaConstants.EXTRAS_VALUE_CONTENT_STYLE_LIST_ITEM)
}
return listOf(folder(OFFLINE_ALL, context.getString(R.string.downloads_tracks), all.firstOrNull()?.coverUrl(COVER_LARGE))) + sets
}
/** The tracks of a downloads folder that are on the phone; null for any other folder. */
private fun offlineTracks(folder: String): List<Track>? {
val d = state.downloads
return when {
folder == OFFLINE_ALL -> d.doneTracks
folder.startsWith(OFFLINE) -> d.set(folder.removePrefix(OFFLINE))?.let { set -> d.tracksOf(set).filter { d.isDone(it.id) } }
else -> null
} }
} }
/** The tracks of a track folder; null for anything else. */ /** The tracks of a track folder; null for anything else. */
private suspend fun tracks(client: YmClient, folder: String): List<Track>? = when { private suspend fun tracks(client: YmClient, folder: String): List<Track>? = offlineTracks(folder) ?: when {
folder == LIKED -> (state.liked as? Liked.Loaded)?.tracks ?: client.likedTracks() folder == LIKED -> (state.liked as? Liked.Loaded)?.tracks ?: client.likedTracks()
folder == RECENT -> client.recentlyPlayed(RECENT_SHOWN) folder == RECENT -> client.recentlyPlayed(RECENT_SHOWN)
folder == CHART -> client.chart().map { it.track } folder == CHART -> client.chart().map { it.track }
@@ -361,7 +409,8 @@ class Library(private val context: Context, private val state: AppState, private
.setTitle(t.fullTitle) .setTitle(t.fullTitle)
.setArtist(t.artistLine) .setArtist(t.artistLine)
.setAlbumTitle(t.album?.title) .setAlbumTitle(t.album?.title)
.setArtworkUri(artwork(t.coverUrl(ART_SIZE))) // Downloaded tracks keep their covers at this size, so they show offline.
.setArtworkUri(artwork(t.coverUrl(if (state.downloads.isDone(t.id)) COVER_LARGE else ART_SIZE)))
.setDurationMs(t.durationMs) .setDurationMs(t.durationMs)
.setIsBrowsable(false) .setIsBrowsable(false)
.setIsPlayable(t.available) .setIsPlayable(t.available)
@@ -376,6 +425,13 @@ class Library(private val context: Context, private val state: AppState, private
private suspend fun client(): YmClient? = awaitClient(state) private suspend fun client(): YmClient? = awaitClient(state)
/** Signed in, but Yandex is out of reach: the downloads stand in. */
private fun offline(): Boolean = state.session == Session.Unreachable
/** Offline with nothing on the phone to play. */
private fun <V : Any> nothingOffline(): LibraryResult<V> =
LibraryResult.ofError(SessionError(SessionError.ERROR_IO, context.getString(R.string.auto_offline)))
/** Signed out: the car shows why, with a button that opens the app's sign-in. */ /** Signed out: the car shows why, with a button that opens the app's sign-in. */
private fun <V : Any> signedOut(): LibraryResult<V> { private fun <V : Any> signedOut(): LibraryResult<V> {
val open = PendingIntent.getActivity( val open = PendingIntent.getActivity(
@@ -426,9 +482,26 @@ internal suspend fun awaitClient(state: AppState): YmClient? {
return state.client return state.client
} }
/** A spoken request ("play … on Musyx"): the best tracks for `query`, or My Wave when nothing was named. */ /**
* A spoken request ("play … on Musyx"): the best tracks for `query`, or My Wave when nothing
* was named. Offline, the downloads that match, or all of them shuffled.
*/
internal suspend fun playFromSearch(state: AppState, query: String?) { internal suspend fun playFromSearch(state: AppState, query: String?) {
val client = awaitClient(state)
if (client == null && state.session == Session.Unreachable) {
if (query.isNullOrBlank()) return state.playTracks(state.downloads.doneTracks, 0, shuffle = true)
return state.playTracks(findDownloaded(state, query), 0)
}
if (query.isNullOrBlank()) return state.playWave(MY_WAVE) if (query.isNullOrBlank()) return state.playWave(MY_WAVE)
val tracks = awaitClient(state)?.search(query, SearchKind.Tracks, 0)?.tracks.orEmpty() val tracks = client?.search(query, SearchKind.Tracks, 0)?.tracks.orEmpty()
if (tracks.isNotEmpty()) state.playTracks(tracks, 0) if (tracks.isNotEmpty()) state.playTracks(tracks, 0)
} }
/** Downloaded tracks whose title, artists or album hold every word of `query`. */
internal fun findDownloaded(state: AppState, query: String): List<Track> {
val words = query.lowercase().split(' ').filter { it.isNotBlank() }
return state.downloads.doneTracks.filter { t ->
val text = listOfNotNull(t.fullTitle, t.artistLine, t.album?.title).joinToString(" ").lowercase()
words.all { it in text }
}
}
@@ -82,6 +82,7 @@ internal fun noticeText(notice: Notice): String = when (notice) {
Notice.StationDry -> stringResource(R.string.notice_station_dry) Notice.StationDry -> stringResource(R.string.notice_station_dry)
Notice.TooManyFailures -> stringResource(R.string.notice_too_many) Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title) is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title)
Notice.NothingDownloaded -> stringResource(R.string.notice_nothing_downloaded)
} }
private enum class Panel { Queue, Lyrics } private enum class Panel { Queue, Lyrics }
@@ -179,6 +179,7 @@
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string> <string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string> <string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string> <string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
<string name="menu_next_track">Следующий трек</string> <string name="menu_next_track">Следующий трек</string>
<string name="menu_play_next">Играть следующим</string> <string name="menu_play_next">Играть следующим</string>
<string name="menu_add_to_queue">Добавить в очередь</string> <string name="menu_add_to_queue">Добавить в очередь</string>
@@ -4,6 +4,7 @@
<string name="signin_open_page">Открыть страницу входа Яндекса</string> <string name="signin_open_page">Открыть страницу входа Яндекса</string>
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string> <string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string> <string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
<string name="auto_offline">Нет интернета, а загруженной музыки нет.</string>
<!-- Офлайн. --> <!-- Офлайн. -->
<string name="downloads_title">Загрузки</string> <string name="downloads_title">Загрузки</string>
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string> <string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string>
+1
View File
@@ -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_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_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_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_next_track">Next track</string>
<string name="menu_play_next">Play next</string> <string name="menu_play_next">Play next</string>
<string name="menu_add_to_queue">Add to queue</string> <string name="menu_add_to_queue">Add to queue</string>
@@ -6,6 +6,8 @@
<string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string> <string name="signin_phone_hint">Opening the page copies the code. Paste it there, confirm, and come back: sign-in finishes on its own.</string>
<!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. --> <!-- Shown in the car (Android Auto or Automotive) when nobody is signed in. -->
<string name="auto_sign_in">Sign in to Musyx to see your music here.</string> <string name="auto_sign_in">Sign in to Musyx to see your music here.</string>
<!-- Shown in the car when Yandex Music can\'t be reached and nothing is downloaded. -->
<string name="auto_offline">No connection, and nothing is downloaded to play.</string>
<!-- Offline listening. --> <!-- Offline listening. -->
<string name="downloads_title">Downloads</string> <string name="downloads_title">Downloads</string>
<string name="downloads_empty">Nothing downloaded yet. Use the download button on an album, a playlist or Liked tracks, or Download in a track\'s menu, and it plays without a connection.</string> <string name="downloads_empty">Nothing downloaded yet. Use the download button on an album, a playlist or Liked tracks, or Download in a track\'s menu, and it plays without a connection.</string>
+2 -2
View File
@@ -14,8 +14,8 @@ android {
// Compose (and so Compose for TV) needs API 23. // Compose (and so Compose for TV) needs API 23.
minSdk = 23 minSdk = 23
targetSdk = 37 targetSdk = 37
versionCode = 8 versionCode = 9
versionName = "0.1.7" versionName = "0.1.8"
} }
// A release key comes from keystore.properties (gitignored): storeFile, storePassword, // A release key comes from keystore.properties (gitignored): storeFile, storePassword,
@@ -108,6 +108,7 @@ internal fun noticeText(notice: Notice): String = when (notice) {
Notice.StationDry -> stringResource(R.string.notice_station_dry) Notice.StationDry -> stringResource(R.string.notice_station_dry)
Notice.TooManyFailures -> stringResource(R.string.notice_too_many) Notice.TooManyFailures -> stringResource(R.string.notice_too_many)
is Notice.Skipped -> stringResource(R.string.notice_skipped, notice.title) 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. */ /** The cover on the stage: as large as the stage's height allows under the transport. */
+1
View File
@@ -211,6 +211,7 @@
<string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string> <string name="notice_station_dry">Не удалось загрузить продолжение станции. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string> <string name="notice_too_many">Несколько треков подряд не удалось воспроизвести. Проверьте подключение и попробуйте ещё раз.</string>
<string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string> <string name="notice_skipped">Не удалось воспроизвести «%1$s», трек пропущен.</string>
<string name="notice_nothing_downloaded">Ни один трек в очереди не загружен. Подключитесь к интернету, чтобы их послушать.</string>
<string name="menu_next_track">Следующий трек</string> <string name="menu_next_track">Следующий трек</string>
<string name="menu_play_next">Играть следующим</string> <string name="menu_play_next">Играть следующим</string>
+1
View File
@@ -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_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_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_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 --> <!-- Track menu and dialogs -->
<string name="menu_next_track">Next track</string> <string name="menu_next_track">Next track</string>