Add offline listening to the phone app

Albums, playlists and Liked tracks get a download button beside the heart,
and every track's menu offers Download or Remove download. Files are fetched
one at a time at the streaming quality, stored decrypted with their covers,
and play from the device even online. A downloaded album, playlist or Liked
tracks follows later changes to it. What's wanted is saved before it's
fetched, so a download cut short resumes when the connection returns or the
app next starts; a foreground service with a progress notification keeps it
going with the screen off.

Collection links to a Downloads page listing what's on the device, with
progress, failures and a retry. When Yandex can't be reached at launch and
something is downloaded, the app opens on that page with the player instead
of the "can't reach" screen, and reconnects by itself when the network
returns. Offline, menus and Now Playing hide what needs a connection, and
lyrics say they can't load instead of waiting forever. Settings shows the
space downloads take and can remove them all.

Another account signing in clears the previous one's downloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yuriy PanovandClaude Opus 5.5 committed 2026-10-23 14:12:34 +06:00
1 parent c13a4053ac
commit d3b3e139b5
31 files changed
+1451 -35

No files matched your search

+9
View File
@@ -6,6 +6,9 @@
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<!-- To carry on downloading, or reconnect from offline, when a connection comes back. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
@@ -52,6 +55,12 @@
</intent-filter>
</service>
<!-- Holds the app up while tracks download for offline listening. -->
<service
android:name=".DownloadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<!-- Covers for Android Auto, which can't load https itself. Read-only, Yandex hosts only. -->
<provider
android:name=".ArtworkProvider"
@@ -0,0 +1,106 @@
// Keeps the app running while downloads are under way, with a notification counting them off.
// The downloading itself happens in the app's Downloads; this only holds the process up and
// shows how far it has got, so a long playlist finishes with the screen off.
package it.panov.musyx.mobile
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
import androidx.core.content.ContextCompat
import it.panov.musyx.data.DownloadProgress
class DownloadService : Service() {
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
running = true
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val progress = latest
if (progress == null) {
stopSelf()
return START_NOT_STICKY
}
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC else 0
ServiceCompat.startForeground(this, NOTIFICATION, notification(this, progress), type)
return START_NOT_STICKY
}
/** Android 15 caps data sync at six hours a day; what's left carries on next time. */
override fun onTimeout(startId: Int, fgsType: Int) {
stopSelf()
}
override fun onDestroy() {
running = false
super.onDestroy()
}
companion object {
private const val CHANNEL = "downloads"
private const val NOTIFICATION = 2
private var running = false
private var latest: DownloadProgress? = null
/** Shows `progress`, starting the service for it; null stops it. */
fun update(context: Context, progress: DownloadProgress?) {
latest = progress
val intent = Intent(context, DownloadService::class.java)
if (progress == null) {
context.stopService(intent)
return
}
if (running) {
// Without the permission the service still runs; there's just nothing to update.
val allowed = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
if (allowed) NotificationManagerCompat.from(context).notify(NOTIFICATION, notification(context, progress))
return
}
try {
ContextCompat.startForegroundService(context, intent)
} catch (e: IllegalStateException) {
// From the background (a connection coming back) Android may refuse; the
// downloads go on while the app lives, and the service starts next time.
Log.w("Musyx", "download service: $e")
}
}
private fun notification(context: Context, p: DownloadProgress): android.app.Notification {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL, context.getString(R.string.notify_downloads_channel), NotificationManager.IMPORTANCE_LOW)
context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
val open = PendingIntent.getActivity(
context,
0,
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
return NotificationCompat.Builder(context, CHANNEL)
.setSmallIcon(R.drawable.ic_download)
.setContentTitle(context.getString(R.string.notify_downloading))
.setContentText(context.getString(R.string.notify_progress, p.done + 1, p.total, p.title.orEmpty()))
.setProgress(p.total, p.done, false)
.setContentIntent(open)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setSilent(true)
.build()
}
}
}
@@ -4,23 +4,33 @@ package it.panov.musyx.mobile
import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.core.os.ConfigurationCompat
import coil3.ImageLoader
import coil3.PlatformContext
import coil3.SingletonImageLoader
import coil3.disk.DiskCache
import coil3.disk.directory
import coil3.intercept.Interceptor
import coil3.memory.MemoryCache
import coil3.network.okhttp.OkHttpNetworkFetcherFactory
import coil3.request.ImageResult
import coil3.request.crossfade
import it.panov.musyx.api.Lrclib
import it.panov.musyx.data.CredentialStore
import it.panov.musyx.data.Downloads
import it.panov.musyx.data.SettingsStore
import it.panov.musyx.mobile.ui.components.COVER_LARGE
import it.panov.musyx.mobile.ui.components.COVER_SMALL
import it.panov.musyx.player.Buffering
import it.panov.musyx.state.AppState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class Musyx : Application(), SingletonImageLoader.Factory {
@@ -30,6 +40,21 @@ class Musyx : Application(), SingletonImageLoader.Factory {
override fun onCreate() {
super.onCreate()
Lrclib.agent = "Musyx/${BuildConfig.VERSION_NAME} (https://git.panov.it/panov/musyz-mobile)"
state.downloads.onProgress = { DownloadService.update(this, it) }
watchNetwork()
}
/** A connection coming back reconnects an offline session and resumes downloads. */
private fun watchNetwork() {
val request = NetworkRequest.Builder().addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
getSystemService(ConnectivityManager::class.java).registerNetworkCallback(
request,
object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
scope.launch { state.onNetworkAvailable() }
}
},
)
}
val state: AppState by lazy {
@@ -44,12 +69,16 @@ class Musyx : Application(), SingletonImageLoader.Factory {
},
// Mobile data slows and drops out: buffer whole tracks and preload the next one.
buffering = Buffering.Mobile,
coverSizes = listOf(COVER_SMALL, COVER_LARGE),
)
}
/** Covers: kept in memory and on disk so rows of cards open instantly the second time. */
override fun newImageLoader(context: PlatformContext): ImageLoader = ImageLoader.Builder(context)
.components { add(OkHttpNetworkFetcherFactory()) }
.components {
add(OfflineCovers { state.downloads })
add(OkHttpNetworkFetcherFactory())
}
.memoryCache { MemoryCache.Builder().maxSizePercent(context, 0.2).build() }
.diskCache {
DiskCache.Builder().directory(cacheDir.resolve("covers")).maxSizeBytes(COVER_CACHE_BYTES).build()
@@ -57,6 +86,15 @@ class Musyx : Application(), SingletonImageLoader.Factory {
.crossfade(true)
.build()
/** Downloaded music's covers come from the copies kept with it, so they show offline too. */
private class OfflineCovers(private val downloads: () -> Downloads) : Interceptor {
override suspend fun intercept(chain: Interceptor.Chain): ImageResult {
val url = chain.request.data as? String ?: return chain.proceed()
val file = downloads().coverFile(url) ?: return chain.proceed()
return chain.withRequest(chain.request.newBuilder().data(file).build()).proceed()
}
}
companion object {
private const val COVER_CACHE_BYTES = 200L * 1024 * 1024
@@ -9,6 +9,7 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
@@ -16,6 +17,7 @@ import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
@@ -28,6 +30,7 @@ import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.ui.Alignment
@@ -39,6 +42,7 @@ import it.panov.musyx.mobile.ui.components.MusyxIcon
import it.panov.musyx.mobile.ui.screens.AlbumScreen
import it.panov.musyx.mobile.ui.screens.ArtistScreen
import it.panov.musyx.mobile.ui.screens.ChartScreen
import it.panov.musyx.mobile.ui.screens.DownloadsScreen
import it.panov.musyx.mobile.ui.screens.CollectionScreen
import it.panov.musyx.mobile.ui.screens.GenreScreen
import it.panov.musyx.mobile.ui.screens.HoldingScreen
@@ -67,11 +71,14 @@ fun MusyxApp(state: AppState, onExit: () -> Unit) {
when (val s = state.session) {
Session.Restoring -> HoldingScreen(stringResource(R.string.session_checking))
is Session.Connecting -> HoldingScreen(stringResource(R.string.session_signing_in))
Session.Unreachable -> UnreachableScreen(state)
// Out of reach with music on the device: carry on with that.
Session.Unreachable -> if (state.downloads.hasAny) Shell(state, onExit, offline = true) else UnreachableScreen(state)
is Session.SignedOut -> SignInScreen(s.signIn)
is Session.SignedIn -> Shell(state, onExit)
}
if (state.session !is Session.SignedIn) ToastHost(state, Modifier.systemBarsPadding())
if (state.session !is Session.SignedIn && !(state.session == Session.Unreachable && state.downloads.hasAny)) {
ToastHost(state, Modifier.systemBarsPadding())
}
}
}
@@ -86,24 +93,27 @@ private val NAV = listOf(
NavItem(Route.Podcasts, R.string.nav_podcasts, R.drawable.ic_podcast),
)
/** The signed-in app; `offline`, only Downloads and the player, while Yandex is out of reach. */
@Composable
private fun Shell(state: AppState, onExit: () -> Unit) {
private fun Shell(state: AppState, onExit: () -> Unit, offline: Boolean = false) {
val route = state.nav.current
val pages = rememberSaveableStateHolder()
BackHandler { if (!state.back()) onExit() }
Scaffold(
containerColor = MusyxTheme.colors.bg,
topBar = { TopBar(state, route) },
topBar = { TopBar(state, route, offline) },
bottomBar = {
Column {
// The navigation bar keeps clear of the system's; offline, without it, the column does.
Column(if (offline) Modifier.navigationBarsPadding() else Modifier) {
if (state.playback.state.hasTrack) MiniPlayer(state)
NavBar(state.nav.section, state::navigate)
if (!offline) NavBar(state.nav.section, state::navigate)
}
},
) { padding ->
Box(Modifier.fillMaxSize().padding(padding)) {
pages.SaveableStateProvider(route.toString()) { Page(state, route) }
val page = if (offline && route !is Route.Downloads) Route.Downloads() else route
pages.SaveableStateProvider(page.toString()) { Page(state, page) }
ToastHost(state)
}
}
@@ -137,12 +147,16 @@ private fun Page(state: AppState, route: Route) {
is Route.Album -> AlbumScreen(state, route)
is Route.Artist -> ArtistScreen(state, route)
is Route.Playlist -> PlaylistScreen(state, route)
is Route.Downloads -> DownloadsScreen(state, route)
}
}
/** Back on pages under a section, the wordmark on the sections themselves; Settings on the right. */
/**
* Back on pages under a section, the wordmark on the sections themselves; Settings on the right,
* or offline, a note saying so and a way to reconnect.
*/
@Composable
private fun TopBar(state: AppState, route: Route) {
private fun TopBar(state: AppState, route: Route, offline: Boolean) {
Row(
Modifier.fillMaxWidth().statusBarsPadding().height(56.dp).padding(horizontal = 4.dp),
verticalAlignment = Alignment.CenterVertically,
@@ -153,7 +167,14 @@ private fun TopBar(state: AppState, route: Route) {
IconButton(onClick = { state.back() }) { MusyxIcon(R.drawable.ic_chevron_left) }
}
Spacer(Modifier.weight(1f))
if (route != Route.Settings) {
if (offline) {
val c = MusyxTheme.colors
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
MusyxIcon(R.drawable.ic_wifi_off, tint = c.muted, size = 18.dp)
Text(stringResource(R.string.offline_badge), style = MusyxTheme.type.meta, color = c.muted)
}
TextButton(onClick = state::restore) { Text(stringResource(R.string.action_try_again)) }
} else if (route != Route.Settings) {
IconButton(onClick = { state.navigate(Route.Settings) }) { MusyxIcon(R.drawable.ic_settings, tint = MusyxTheme.colors.muted) }
}
}
@@ -66,6 +66,7 @@ fun LazyListScope.trackItems(
track = track,
playing = state.playback.state.track?.id == track.id,
liked = state.liked.contains(track.id),
downloaded = state.downloads.isDone(track.id),
columns = columns,
shift = shifts?.getOrNull(i),
onPlay = { state.playTracks(tracks, i) },
@@ -85,6 +86,8 @@ fun TrackRow(
track: Track,
playing: Boolean,
liked: Boolean,
/** On the device, so it plays offline. */
downloaded: Boolean,
columns: Columns,
shift: Int?,
onPlay: () -> Unit,
@@ -124,7 +127,10 @@ fun TrackRow(
(if (columns.artist) track.artistsOrUnknown() else track.album?.title).takeIf { !it.isNullOrEmpty() },
clock(track.durationMs),
).joinToString(" · ")
Text(subtitle, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
if (downloaded) MusyxIcon(R.drawable.ic_download, tint = c.accent, size = 13.dp)
Text(subtitle, style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
if (onLike != null) {
IconButton(onClick = onLike) {
@@ -31,6 +31,7 @@ import it.panov.musyx.api.ArtistPage
import it.panov.musyx.api.PlaylistPage
import it.panov.musyx.api.PlaylistSummary
import it.panov.musyx.api.YmError
import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.COVER_LARGE
import it.panov.musyx.mobile.ui.components.Columns
@@ -123,7 +124,10 @@ private fun LazyListScope.albumPage(state: AppState, info: AlbumPage) {
}
item(key = "play") {
val liked = a.id in state.likes.albums
PlayBar(state, info.tracks) { LikeButton(liked) { state.likeAlbum(a.id, !liked) } }
PlayBar(state, info.tracks) {
LikeButton(liked) { state.likeAlbum(a.id, !liked) }
DownloadButton(state, Downloads.albumKey(a.id), a.fullTitle) { state.downloadAlbum(info) }
}
}
trackItems(state, info.tracks, Columns.ALBUM_PAGE, keyPrefix = "album")
}
@@ -220,6 +224,7 @@ private fun LazyListScope.playlistPage(state: AppState, info: PlaylistPage) {
val liked = p.id in state.likes.playlists
LikeButton(liked) { state.likePlaylist(p.id, !liked) }
}
DownloadButton(state, Downloads.playlistKey(p.id.key), p.title) { state.downloadPlaylist(info) }
}
}
trackItems(state, info.tracks, playlist = if (own) p.id else null, positions = info.positions, keyPrefix = "pl")
@@ -0,0 +1,249 @@
// What's on the device: downloaded albums, playlists and tracks, how far the downloads have
// got, and the button pages use to download or remove themselves. Offline, it's the app.
package it.panov.musyx.mobile.ui.screens
import android.text.format.Formatter
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import it.panov.musyx.data.OfflineSet
import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.MusyxIcon
import it.panov.musyx.mobile.ui.components.Note
import it.panov.musyx.mobile.ui.components.PlayBar
import it.panov.musyx.mobile.ui.components.ScreenTitle
import it.panov.musyx.mobile.ui.components.SectionTitle
import it.panov.musyx.mobile.ui.components.Thumb
import it.panov.musyx.mobile.ui.components.trackItems
import it.panov.musyx.mobile.ui.durationWords
import it.panov.musyx.mobile.ui.theme.MusyxTheme
import it.panov.musyx.mobile.ui.tracksWord
import it.panov.musyx.state.AppState
import it.panov.musyx.state.Route
import it.panov.musyx.state.Session
@Composable
fun DownloadsScreen(state: AppState, route: Route.Downloads) {
val key = route.set
if (key == null) AllDownloads(state) else DownloadedSet(state, key)
}
@Composable
private fun AllDownloads(state: AppState) {
val d = state.downloads
val space = MusyxTheme.space
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.downloads_title)) }
if (state.session == Session.Unreachable) item(key = "offline") { Note(stringResource(R.string.offline_note)) }
if (!d.hasAny) {
item(key = "empty") { Note(stringResource(R.string.downloads_empty)) }
return@PageColumn
}
status(state)
if (d.sets.isNotEmpty()) {
item(key = "sets-title") { SectionTitle(stringResource(R.string.downloads_sets), Modifier.padding(horizontal = space.gutter)) }
items(d.sets.asReversed(), key = { "set:${it.key}" }) { set -> SetRow(state, set) }
gap("tracks-gap")
}
val tracks = d.doneTracks
if (tracks.isNotEmpty()) {
item(key = "tracks-title") { SectionTitle(stringResource(R.string.downloads_tracks), Modifier.padding(horizontal = space.gutter)) }
item(key = "play") {
val size = Formatter.formatShortFileSize(LocalContext.current, d.bytes)
PlayBar(state, tracks, summary = "${tracksWord(tracks.size)} · ${durationWords(tracks.sumOf { it.durationMs })} · $size")
}
trackItems(state, tracks, keyPrefix = "dl", hearts = state.client != null)
}
}
}
/** How the downloads are getting on: the track on its way, what's left, what failed. */
private fun LazyListScope.status(state: AppState) {
val d = state.downloads
val queued = d.queued
val failed = d.failed.size
if (queued == 0 && failed == 0) return
item(key = "status") {
val c = MusyxTheme.colors
Column(
Modifier.fillMaxWidth().padding(horizontal = MusyxTheme.space.gutter),
verticalArrangement = Arrangement.spacedBy(MusyxTheme.space.s),
) {
val current = d.current
if (queued > 0) {
Text(
if (current != null) pluralStringResource(R.plurals.downloads_left, queued, queued) else stringResource(R.string.downloads_waiting),
style = MusyxTheme.type.meta,
color = c.muted,
)
if (current != null) {
LinearProgressIndicator(
progress = { current.second },
modifier = Modifier.fillMaxWidth(),
color = c.accent,
trackColor = c.raised,
)
}
}
if (failed > 0) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(pluralStringResource(R.plurals.downloads_failed, failed, failed), style = MusyxTheme.type.meta, color = c.like, modifier = Modifier.weight(1f))
if (state.client != null) TextButton(onClick = d::retry) { Text(stringResource(R.string.action_try_again)) }
}
}
}
}
}
@Composable
private fun SetRow(state: AppState, set: OfflineSet) {
val c = MusyxTheme.colors
val (done, total) = state.downloads.progressOf(set)
Row(
Modifier
.fillMaxWidth()
.clickable { state.navigate(Route.Downloads(set.key)) }
.padding(horizontal = MusyxTheme.space.gutter, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
Thumb(set.cover, set.hues, 56.dp)
Column(Modifier.weight(1f)) {
Text(setTitle(set), style = MusyxTheme.type.bodyMedium, color = c.fg, maxLines = 1, overflow = TextOverflow.Ellipsis)
val count = if (done < total) stringResource(R.string.downloads_set_progress, done, total) else tracksWord(total)
Text("${setKind(set)} · $count", style = MusyxTheme.type.meta, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
SetMark(done, total)
}
}
@Composable
private fun DownloadedSet(state: AppState, key: String) {
val d = state.downloads
val set = d.set(key)
PageColumn {
if (set == null) {
item(key = "gone") { Note(stringResource(R.string.downloads_gone)) }
return@PageColumn
}
val all = d.tracksOf(set)
// Offline only what's on the device plays; online the rest streams.
val tracks = if (state.session is Session.SignedIn) all else all.filter { d.isDone(it.id) }
item(key = "head") {
val c = MusyxTheme.colors
Row(
Modifier.fillMaxWidth().padding(horizontal = MusyxTheme.space.gutter),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Thumb(set.cover, set.hues, 112.dp)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(setKind(set), style = MusyxTheme.type.meta, color = c.muted, maxLines = 1)
Text(setTitle(set), style = MusyxTheme.type.displayS, color = c.fg, maxLines = 3, overflow = TextOverflow.Ellipsis)
val (done, total) = d.progressOf(set)
if (done < total) Text(stringResource(R.string.downloads_set_progress, done, total), style = MusyxTheme.type.meta, color = c.muted)
}
}
}
item(key = "play") {
PlayBar(state, tracks, summary = "${tracksWord(tracks.size)} · ${durationWords(tracks.sumOf { it.durationMs })}") {
DownloadButton(state, set.key, setTitle(set)) {}
}
}
trackItems(state, all, keyPrefix = "dls", hearts = state.client != null)
}
}
/**
* Downloads a page's tracks, shows how far that has got, and removes them again after asking.
* `download` is only called when nothing is downloaded yet.
*/
@Composable
fun DownloadButton(state: AppState, key: String, title: String, download: () -> Unit) {
val set = state.downloads.set(key)
var confirm by remember { mutableStateOf(false) }
val label = stringResource(if (set == null) R.string.action_download else R.string.action_downloaded)
IconButton(
onClick = { if (set == null) download() else confirm = true },
modifier = Modifier.size(44.dp).semantics { contentDescription = label },
) {
if (set == null) {
MusyxIcon(R.drawable.ic_download)
} else {
val (done, total) = state.downloads.progressOf(set)
SetMark(done, total)
}
}
if (confirm) {
AlertDialog(
onDismissRequest = { confirm = false },
title = { Text(stringResource(R.string.download_remove_title, title)) },
text = { Text(stringResource(R.string.download_remove_body)) },
confirmButton = {
TextButton(onClick = { confirm = false; state.removeDownloadSet(key) }) {
Text(stringResource(R.string.action_remove), color = MusyxTheme.colors.like)
}
},
dismissButton = { TextButton(onClick = { confirm = false }) { Text(stringResource(R.string.action_cancel)) } },
containerColor = MusyxTheme.colors.panel,
)
}
}
/** A ring filling up while a set downloads, then a tick. */
@Composable
private fun SetMark(done: Int, total: Int) {
val c = MusyxTheme.colors
Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {
if (done < total) {
CircularProgressIndicator(
progress = { done.toFloat() / total },
modifier = Modifier.size(20.dp),
color = c.accent,
trackColor = c.raised,
strokeWidth = 2.5.dp,
)
} else {
MusyxIcon(R.drawable.ic_circle_check, tint = c.accent)
}
}
}
@Composable
private fun setTitle(set: OfflineSet): String =
if (set.kind == OfflineSet.Kind.Liked) stringResource(R.string.tab_liked_tracks) else set.title
@Composable
private fun setKind(set: OfflineSet): String = stringResource(
when (set.kind) {
OfflineSet.Kind.Album -> R.string.kind_album
OfflineSet.Kind.Playlist, OfflineSet.Kind.Liked -> R.string.downloads_kind_playlist
},
)
@@ -18,6 +18,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import it.panov.musyx.data.Downloads
import it.panov.musyx.mobile.R
import it.panov.musyx.mobile.ui.components.CardGrid
import it.panov.musyx.mobile.ui.components.Failure
@@ -48,6 +49,17 @@ private fun tabLabel(tab: CollectionTab) = when (tab) {
fun CollectionScreen(state: AppState) {
PageColumn {
item(key = "title") { ScreenTitle(stringResource(R.string.nav_collection)) }
item(key = "downloads") {
val count = state.downloads.doneTracks.size
val label = stringResource(R.string.downloads_title)
Box(Modifier.padding(horizontal = MusyxTheme.space.gutter)) {
AssistChip(
onClick = { state.navigate(Route.Downloads()) },
label = { Text(if (count > 0) "$label $count" else label) },
leadingIcon = { MusyxIcon(R.drawable.ic_download, size = 18.dp) },
)
}
}
item(key = "tabs") {
val tabs = CollectionTab.entries
PrimaryScrollableTabRow(selectedTabIndex = tabs.indexOf(state.collectionTab), edgePadding = MusyxTheme.space.gutter) {
@@ -76,7 +88,9 @@ fun CollectionScreen(state: AppState) {
item(key = "empty") { Note(stringResource(R.string.empty_liked)) }
} else {
item(key = "play") {
PlayBar(state, liked.tracks, summary = "${tracksWord(liked.tracks.size)} · ${durationWords(liked.tracks.sumOf { it.durationMs })}")
PlayBar(state, liked.tracks, summary = "${tracksWord(liked.tracks.size)} · ${durationWords(liked.tracks.sumOf { it.durationMs })}") {
DownloadButton(state, Downloads.LIKED, stringResource(R.string.tab_liked_tracks), state::downloadLiked)
}
}
trackItems(state, liked.tracks, keyPrefix = "liked", hearts = false)
}
@@ -198,8 +198,11 @@ private fun TrackInfo(state: AppState, p: PlaybackState, track: Track) {
Text(noticeText(notice), style = MusyxTheme.type.meta, color = c.like, maxLines = 2)
}
}
IconButton(onClick = { state.likeTrack(track, !liked) }) {
MusyxIcon(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, tint = if (liked) c.like else c.fg)
// Offline there's no collection to change.
if (state.client != null) {
IconButton(onClick = { state.likeTrack(track, !liked) }) {
MusyxIcon(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, tint = if (liked) c.like else c.fg)
}
}
IconButton(onClick = { state.openSheet(Sheet.TrackMenu(track)) }) { MusyxIcon(R.drawable.ic_ellipsis) }
}
@@ -1,6 +1,7 @@
// Settings: account, streaming quality, appearance, font size, language, storage.
package it.panov.musyx.mobile.ui.screens
import android.text.format.Formatter
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
@@ -13,12 +14,19 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilterChip
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import it.panov.musyx.data.Appearance
@@ -110,6 +118,7 @@ fun SettingsScreen(state: AppState) {
MusyxIcon(R.drawable.ic_trash_2, size = 18.dp)
Text(stringResource(R.string.action_clear_covers), modifier = Modifier.padding(start = 8.dp))
}
Downloads(state)
}
}
item(key = "version") {
@@ -123,6 +132,39 @@ fun SettingsScreen(state: AppState) {
}
}
/** What downloads take, and a way to remove them all after asking. */
@Composable
private fun Downloads(state: AppState) {
val d = state.downloads
var confirm by remember { mutableStateOf(false) }
val size = Formatter.formatShortFileSize(LocalContext.current, d.bytes)
Text(
if (d.hasAny) stringResource(R.string.settings_downloads, size) else stringResource(R.string.settings_downloads_none),
style = MusyxTheme.type.meta,
color = MusyxTheme.colors.muted,
)
if (d.hasAny) {
OutlinedButton(onClick = { confirm = true }) {
MusyxIcon(R.drawable.ic_trash_2, size = 18.dp)
Text(stringResource(R.string.action_clear_downloads), modifier = Modifier.padding(start = 8.dp))
}
}
if (confirm) {
AlertDialog(
onDismissRequest = { confirm = false },
title = { Text(stringResource(R.string.clear_downloads_title)) },
text = { Text(stringResource(R.string.clear_downloads_body)) },
confirmButton = {
TextButton(onClick = { confirm = false; state.clearDownloads() }) {
Text(stringResource(R.string.action_remove), color = MusyxTheme.colors.like)
}
},
dismissButton = { TextButton(onClick = { confirm = false }) { Text(stringResource(R.string.action_cancel)) } },
containerColor = MusyxTheme.colors.panel,
)
}
}
@Composable
private fun Section(title: String, content: @Composable () -> Unit) {
val space = MusyxTheme.space
@@ -126,6 +126,8 @@ private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
val disliked = track.id in state.likes.dislikedTracks
// Where the menu was opened: no "go to" for the page already showing.
val here = state.nav.current
// Offline, only the queue and downloads work.
val online = state.client != null
Head(track.fullTitle, track.artistsOrUnknown().ifEmpty { null }) { Thumb(track.coverUrl(COVER_SMALL), track.hues, 48.dp) }
HorizontalDivider(color = MusyxTheme.colors.line)
Actions {
@@ -134,6 +136,12 @@ private fun TrackMenu(state: AppState, sheet: Sheet.TrackMenu) {
else Item(R.drawable.ic_skip_forward, stringResource(R.string.menu_play_next)) { state.playNext(track) }
}
item { Item(R.drawable.ic_list_music, stringResource(R.string.menu_add_to_queue)) { state.addToQueue(track) } }
if (state.downloads.isWanted(track.id)) {
item { Item(R.drawable.ic_trash_2, stringResource(R.string.menu_remove_download)) { state.removeDownload(track) } }
} else if (track.available && online) {
item { Item(R.drawable.ic_download, stringResource(R.string.menu_download)) { state.downloadTrack(track) } }
}
if (!online) return@Actions
item {
Item(if (liked) R.drawable.ic_heart_fill else R.drawable.ic_heart, stringResource(if (liked) R.string.menu_unlike else R.string.menu_like)) {
state.closeSheet()
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide circle-check (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 2 12 a 10 10 0 1 0 20 0 a 10 10 0 1 0 -20 0 Z"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 9 12 2 2 4 -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide download (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 21 15 v 4 a 2 2 0 0 1 -2 2 H 5 a 2 2 0 0 1 -2 -2 v -4"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 7 10 L 12 15 L 17 10"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 12 15 L 12 3"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Lucide wifi-off (ISC, assets/icons/LICENSE.txt). Generated by tool/svg_to_vector.py; tint it in code. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M 12 20 h 0.01"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 8.5 16.429 a 5 5 0 0 1 7 0"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 5 12.859 a 10 10 0 0 1 5.17 -2.69"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 19 12.859 a 10 10 0 0 0 -2.007 -1.523"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 2 8.82 a 15 15 0 0 1 4.177 -2.643"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="M 22 8.82 a 15 15 0 0 0 -11.288 -3.764"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<path
android:pathData="m 2 2 20 20"
android:strokeColor="@android:color/white"
android:strokeWidth="2"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
</vector>
@@ -4,4 +4,42 @@
<string name="signin_open_page">Открыть страницу входа Яндекса</string>
<string name="signin_phone_hint">Код копируется, когда открывается страница. Вставьте его там, подтвердите вход и вернитесь сюда — дальше всё произойдёт само.</string>
<string name="auto_sign_in">Войдите в Musyx, чтобы ваша музыка появилась здесь.</string>
<!-- Офлайн. -->
<string name="downloads_title">Загрузки</string>
<string name="downloads_empty">Здесь пока пусто. Скачайте альбом, плейлист или «Мне нравится» кнопкой загрузки на их странице, а трек — через его меню, и они будут играть без интернета.</string>
<string name="downloads_sets">Альбомы и плейлисты</string>
<string name="downloads_tracks">Треки</string>
<string name="downloads_waiting">Остальное скачается, когда появится интернет</string>
<string name="downloads_gone">Это больше не скачано.</string>
<string name="downloads_set_progress">Скачано %1$d из %2$d</string>
<string name="downloads_kind_playlist">Плейлист</string>
<plurals name="downloads_left">
<item quantity="one">Скачивается, остался %1$d трек</item>
<item quantity="few">Скачивается, осталось %1$d трека</item>
<item quantity="many">Скачивается, осталось %1$d треков</item>
<item quantity="other">Скачивается, осталось %1$d трека</item>
</plurals>
<plurals name="downloads_failed">
<item quantity="one">Не удалось скачать %1$d трек</item>
<item quantity="few">Не удалось скачать %1$d трека</item>
<item quantity="many">Не удалось скачать %1$d треков</item>
<item quantity="other">Не удалось скачать %1$d трека</item>
</plurals>
<string name="action_download">Скачать</string>
<string name="action_downloaded">Скачано</string>
<string name="action_remove">Удалить</string>
<string name="menu_download">Скачать</string>
<string name="menu_remove_download">Удалить загрузку</string>
<string name="download_remove_title">Удалить «%1$s» с устройства?</string>
<string name="download_remove_body">Чтобы снова послушать, понадобится интернет.</string>
<string name="offline_badge">Офлайн</string>
<string name="offline_note">Яндекс Музыка недоступна, поэтому играют только загрузки. Попробуйте ещё раз, когда появится интернет.</string>
<string name="settings_downloads">Загрузки занимают %1$s на устройстве.</string>
<string name="settings_downloads_none">Ничего не скачано.</string>
<string name="action_clear_downloads">Удалить все загрузки</string>
<string name="clear_downloads_title">Удалить все загрузки?</string>
<string name="clear_downloads_body">Все скачанные треки будут удалены с устройства. Ваша музыка в Яндексе останется как есть.</string>
<string name="notify_downloads_channel">Загрузки</string>
<string name="notify_downloading">Скачивание для прослушивания офлайн</string>
<string name="notify_progress">%1$d из %2$d · %3$s</string>
</resources>
@@ -6,4 +6,38 @@
<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>
<!-- 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>
<string name="downloads_sets">Albums and playlists</string>
<string name="downloads_tracks">Tracks</string>
<string name="downloads_waiting">Waiting for a connection to download the rest</string>
<string name="downloads_gone">This isn\'t downloaded any more.</string>
<string name="downloads_set_progress">Downloaded: %1$d of %2$d</string>
<string name="downloads_kind_playlist">Playlist</string>
<plurals name="downloads_left">
<item quantity="one">Downloading, %1$d track to go</item>
<item quantity="other">Downloading, %1$d tracks to go</item>
</plurals>
<plurals name="downloads_failed">
<item quantity="one">%1$d track couldn\'t be downloaded</item>
<item quantity="other">%1$d tracks couldn\'t be downloaded</item>
</plurals>
<string name="action_download">Download</string>
<string name="action_downloaded">Downloaded</string>
<string name="action_remove">Remove</string>
<string name="menu_download">Download</string>
<string name="menu_remove_download">Remove download</string>
<string name="download_remove_title">Remove “%1$s” from the device?</string>
<string name="download_remove_body">It will need a connection to play again.</string>
<string name="offline_badge">Offline</string>
<string name="offline_note">Yandex Music can\'t be reached, so only downloads play. Try again once you\'re connected.</string>
<string name="settings_downloads">Downloads take %1$s on this device.</string>
<string name="settings_downloads_none">Nothing is downloaded.</string>
<string name="action_clear_downloads">Remove all downloads</string>
<string name="clear_downloads_title">Remove all downloads?</string>
<string name="clear_downloads_body">Every downloaded track is deleted from this device. Your music on Yandex stays as it is.</string>
<string name="notify_downloads_channel">Downloads</string>
<string name="notify_downloading">Downloading for offline listening</string>
<string name="notify_progress">%1$d of %2$d · %3$s</string>
</resources>