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>
This commit is contained in:
1 parent
250e721fea
commit
05c90c03df
5 files changed
+106
-20
No files matched your search
@@ -8,6 +8,7 @@ import android.content.Context
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.ParcelFileDescriptor
|
||||
import it.panov.musyx.data.Downloads
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
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.
|
||||
val host = url.host.orEmpty()
|
||||
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())}")
|
||||
if (!file.exists()) fetch(url.toString(), file)
|
||||
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
|
||||
// collection. Playing an item starts it through PlayerCore, like a tap in the app would.
|
||||
// The media library Android Auto browses: My Wave and stations, picks from Home, the
|
||||
// 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
|
||||
|
||||
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.Track
|
||||
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.Liked
|
||||
import it.panov.musyx.state.Session
|
||||
@@ -70,6 +73,11 @@ private const val ALBUMS = "albums"
|
||||
private const val STATION = "station|"
|
||||
private const val TRACK = "t|"
|
||||
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".
|
||||
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>>()
|
||||
|
||||
/**
|
||||
* Has the car reload whenever someone signs in or out, so it never keeps showing "Sign in"
|
||||
* (or someone else's music), and keeps the heart in step with the track. Returns what
|
||||
* stops watching.
|
||||
* Has the car reload whenever someone signs in or out, or the app goes offline or back, so
|
||||
* it never keeps showing "Sign in" (or someone else's music, or music it can't reach), and
|
||||
* keeps the heart in step with the track. Returns what stops watching.
|
||||
*/
|
||||
fun watch(session: MediaLibrarySession): () -> Unit {
|
||||
// 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 {
|
||||
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()
|
||||
.drop(1)
|
||||
.collect {
|
||||
@@ -203,8 +212,16 @@ class Library(private val context: Context, private val state: AppState, private
|
||||
pageSize: Int,
|
||||
params: LibraryParams?,
|
||||
): ListenableFuture<LibraryResult<ImmutableList<MediaItem>>> = future {
|
||||
val client = client() ?: return@future signedOut()
|
||||
val items = children(client, parentId) ?: return@future LibraryResult.ofError(SessionError.ERROR_BAD_VALUE)
|
||||
val client = client()
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -223,8 +240,12 @@ class Library(private val context: Context, private val state: AppState, private
|
||||
query: String,
|
||||
params: LibraryParams?,
|
||||
): ListenableFuture<LibraryResult<Void>> = future {
|
||||
val client = client() ?: return@future signedOut()
|
||||
val tracks = client.search(query, SearchKind.Tracks, 0).tracks
|
||||
val client = client()
|
||||
val tracks = when {
|
||||
client != null -> client.search(query, SearchKind.Tracks, 0).tracks
|
||||
offline() -> findDownloaded(state, query)
|
||||
else -> return@future signedOut()
|
||||
}
|
||||
val folder = SEARCH + query
|
||||
shown[folder] = tracks
|
||||
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(TRACK) -> {
|
||||
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)
|
||||
}
|
||||
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)),
|
||||
) + home.personal.map { playlist(it.playlist) }
|
||||
}
|
||||
COLLECTION -> listOf(
|
||||
COLLECTION -> listOfNotNull(
|
||||
folder(LIKED, context.getString(R.string.tab_liked_tracks)),
|
||||
folder(PLAYLISTS, context.getString(R.string.tab_playlists)),
|
||||
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)
|
||||
ALBUMS -> client.likedAlbums().filter { !it.isPodcast }.map(::album)
|
||||
else -> tracks(client, parent)?.let { tracks ->
|
||||
shown[parent] = tracks
|
||||
tracks.mapIndexed { i, t -> track(parent, i, t) }
|
||||
DOWNLOADS -> downloads()
|
||||
else -> tracks(client, parent)?.let { tracks -> trackItems(parent, tracks) }
|
||||
}
|
||||
|
||||
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. */
|
||||
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 == RECENT -> client.recentlyPlayed(RECENT_SHOWN)
|
||||
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)
|
||||
.setArtist(t.artistLine)
|
||||
.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)
|
||||
.setIsBrowsable(false)
|
||||
.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)
|
||||
|
||||
/** 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. */
|
||||
private fun <V : Any> signedOut(): LibraryResult<V> {
|
||||
val open = PendingIntent.getActivity(
|
||||
@@ -426,9 +482,26 @@ internal suspend fun awaitClient(state: AppState): YmClient? {
|
||||
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?) {
|
||||
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)
|
||||
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)
|
||||
}
|
||||
|
||||
/** 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 }
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
<string name="signin_open_page">Открыть страницу входа Яндекса</string>
|
||||
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
|
||||
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
|
||||
<string name="auto_offline">Нет интернета, а загруженной музыки нет.</string>
|
||||
<!-- Офлайн. -->
|
||||
<string name="downloads_title">Загрузки</string>
|
||||
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</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>
|
||||
<!-- 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>
|
||||
<!-- 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. -->
|
||||
<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>
|
||||
|
||||
Reference in new issue
Block a user