Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Live Radio from the Radio Browser directory, off until turned on in Settings: https streams only and no HLS, reconnects only on network drops with tries back after 30 s of steady play, favorites newest first by when saved, the station shared as its name and homepage instead of a Spotify Code, an Immersive page, the directory's errors said on screen
kota-zod4542e7a28b7
diff --git a/README.md b/README.mdindex e80d8144..bf731830 100644--- a/README.md+++ b/README.md@@ -86,6 +86,7 @@ Obtainium (add `https://github.com/kota-zo/myspoti`; the stable app and the beta**And also**- Your recap: your top songs, artists and albums, kept on your phone.+- **Live Radio**, off until you turn it on (Settings, Playback): internet radio from the free [Radio Browser](https://www.radio-browser.info) directory, https streams only, favorites kept on your phone. Searches go to Radio Browser, and each station's logo and stream come from that station's own server.- 69 languages and regional variants, following the phone or picked by hand.- Data saver, battery saver, AMOLED black, accent colour.@@ -130,7 +131,7 @@ Two looks, switched in Settings, Display.**Do downloads count in my Wrapped?** They always count in Myspoti's own recap. With **Sync downloaded songs with Spotify** (Settings → Playback, on by default), a downloaded song played online also plays muted on Spotify so your other devices see and control it; whether Spotify counts that play is up to Spotify and not guaranteed. Offline, or with the setting off, the file plays only from the phone and nothing is reported. Streamed songs and music videos count as usual.-**What leaves my phone?** Your plays go to Spotify. Lyrics are looked up on lyrics sites, song meanings on Genius, translations on Google Translate, music videos on YouTube, and downloads on the hosts your download-source extension names (shown before you install it). Nothing is sent to the developer.+**What leaves my phone?** Your plays go to Spotify. Lyrics are looked up on lyrics sites, song meanings on Genius, translations on Google Translate, music videos on YouTube, and downloads on the hosts your download-source extension names (shown before you install it). Live Radio, once turned on, searches [Radio Browser](https://www.radio-browser.info) and loads each station's logo and stream from that station's own server. Nothing is sent to the developer.## Not includeddiff --git a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.ktindex 83181e72..50e353d8 100644--- a/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt+++ b/base/app/src/main/java/com/music/spotui/data/local/LocalMusic.kt@@ -21,6 +21,14 @@ data class LocalTrack(val artUri: Uri,/** The file's folder on the phone, e.g. "Music/Album/" (MediaStore relative path). */val folder: String = "",+ /**+ * A Live Radio station (radio/ module) wrapped as a one-item "queue", not a file on this+ * phone: [id] is below both MediaStore's ids and the downloads' (see RadioPlayer.stableId)+ * and [uri] is the stream's address. This is how Radio shows in the mini player,+ * the full player, the notification and the lock screen exactly as a Local Files song does,+ * with no separate player or session of its own.+ */+ val isRadio: Boolean = false,)/** The device's music files, read through MediaStore (no file access beyond audio). */diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.ktindex 8f123b22..38939940 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCrypto.kt@@ -308,6 +308,13 @@ object OfflineCrypto {override fun getUri(): Uri? = if (usingOther) active.uri else uri+ // Without this, a station's "icy-metaint" response header never reaches the extractor+ // (BaseDataSource's default is an empty map): it can't tell the audio apart from the+ // station-title metadata the server interleaves into it every few kilobytes, so that+ // metadata gets decoded as if it were audio — a little glitch, right on the interval,+ // on every station that sends it (one that doesn't is unaffected either way).+ override fun getResponseHeaders(): Map<String, List<String>> = if (usingOther) active.responseHeaders else super.getResponseHeaders()+override fun close() {head = nulltransformed?.close(); transformed = nulldiff --git a/base/app/src/main/java/com/music/spotui/di/Graph.kt b/base/app/src/main/java/com/music/spotui/di/Graph.ktindex afe2ed4d..24c5cd8a 100644--- a/base/app/src/main/java/com/music/spotui/di/Graph.kt+++ b/base/app/src/main/java/com/music/spotui/di/Graph.kt@@ -36,6 +36,9 @@ object Graph {com.music.spotui.data.offline.PodcastDownloader.resumePending()// Installed extensions: each enabled one loads in its own sandbox, off the main thread.com.music.spotui.extensions.Extensions.init(application)+ // Live Radio: its own setting and favorites file (see com.music.spotui.radio).+ com.music.spotui.radio.RadioFeaturePref.init(application)+ com.music.spotui.radio.RadioFavoritesStore.init(application)}val api: Api by lazy { Api(app) }diff --git a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.ktindex 858fe5f8..b1f319cd 100644--- a/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/LocalPlayer.kt@@ -113,6 +113,9 @@ object LocalPlayer {// Casting: this player keeps the queue only, stopped; the song plays on the device.if (CastPlayback.active && state != Player.STATE_IDLE) { p.stop(); return }if (state == Player.STATE_READY) checkLength(p)+ // A station's server that closes the stream: a drop like any other, never "the end".+ val station = current()?.takeIf { it.isRadio }+ if (state == Player.STATE_ENDED && station != null) { reconnectRadio(p, station); return }if (state == Player.STATE_ENDED && !playAgain(p)) atEnd(p)}override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {@@ -135,6 +138,9 @@ object LocalPlayer {log("isPlaying $isPlaying at ${p.currentPosition} ms")if (isPlaying) errors.played()if (isPlaying) tick.run()+ // A station that plays on for a while has its reconnect tries back (see reconnectRadio).+ handler.removeCallbacks(radioSteady)+ if (isPlaying && current()?.isRadio == true) handler.postDelayed(radioSteady, RADIO_STEADY_MS)}override fun onPlaybackSuppressionReasonChanged(reason: Int) =log("suppressed: ${if (reason == Player.PLAYBACK_SUPPRESSION_REASON_NONE) "no" else "reason $reason"}")@@ -159,6 +165,8 @@ object LocalPlayer {// then Spotify plays it, where it was, and goes on; a queue that keeps failing stops.override fun onPlayerError(error: androidx.media3.common.PlaybackException) {log("error ${error.errorCodeName}: ${generic(error.cause?.toString() ?: error.message.orEmpty())}")+ val station = current()?.takeIf { it.isRadio }+ if (station != null) { radioError(p, station, error); return }val item = p.currentMediaItem?.localConfiguration?.uri ?: returnif (item.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME) com.music.spotui.extensions.Extensions.noteAttempt(item.lastPathSegment) { it.copy(error = "${error.errorCodeName}: ${error.cause ?: error.message.orEmpty()}") }// A file that is gone (a download deleted while the queue played): never left stopped on it.@@ -379,8 +387,11 @@ object LocalPlayer {}SongPlayer.pauseEngineForLocal()forgetRadio(); this.continues = continues+ // A station is a queue of its own: no Spotify songs after it, and its reconnect tries start afresh.+ val isStation = list.singleOrNull()?.isRadio == true+ radioRetries = 0; handler.removeCallbacks(radioSteady)// Spotify's queued songs (the account's: maybe queued on another device or install) play first.- val (all, fromSpotify) = QueueSync.withSpotifyQueue(list, index.coerceIn(0, list.lastIndex))+ val (all, fromSpotify) = if (isStation) list to emptyList<LocalTrack>() else QueueSync.withSpotifyQueue(list, index.coerceIn(0, list.lastIndex))tracks.clear(); tracks.addAll(all); unshuffled = null// An index kept from fading belonged to the list before: this one fades from its first song.noFadeFor = -1@@ -414,6 +425,7 @@ object LocalPlayer {// A page left muted by an extension's mirror must not stay silent once Spotify plays again.SongPlayer.unmuteMirror()forgetRadio(); continues = false; deletedDownloads.clear()+ handler.removeCallbacks(radioSteady)exo?.let { it.stop(); it.clearMediaItems() }tracks.clear(); unshuffled = nullqueued.clear(); playingQueued = null; radioSongs.clear()@@ -932,6 +944,51 @@ object LocalPlayer {com.music.spotui.data.offline.OfflineStore.byLocalId(t.id)?.trackId?: t.uri.takeIf { it.scheme == com.music.spotui.extensions.ExtensionAudio.SCHEME }?.lastPathSegment.orEmpty()+ /**+ * A live stream drops often (a weak connection, the server's own hiccup): reconnected instead+ * of left stopped, a few times with a growing pause between tries. The tries come back only+ * once a reconnect has played [RADIO_STEADY_MS] in a row ([radioSteady]): a stream that starts+ * and drops at once gives up after [RADIO_TRIES] instead of retrying every second for good.+ */+ private var radioRetries = 0+ private const val RADIO_TRIES = 5+ private const val RADIO_STEADY_MS = 30_000L+ private val radioSteady = Runnable { radioRetries = 0 }++ /** Only a network failure is worth a reconnect: a stream the player cannot read stays as it is the next time. */+ private fun radioError(p: ExoPlayer, t: LocalTrack, error: androidx.media3.common.PlaybackException) {+ val status = (error.cause as? androidx.media3.datasource.HttpDataSource.InvalidResponseCodeException)?.responseCode+ val network = when (error.errorCode) {+ androidx.media3.common.PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED,+ androidx.media3.common.PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT,+ androidx.media3.common.PlaybackException.ERROR_CODE_IO_UNSPECIFIED,+ androidx.media3.common.PlaybackException.ERROR_CODE_TIMEOUT -> true+ // The station's server busy or restarting (5xx), not a stream that is gone (404).+ androidx.media3.common.PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS -> status != null && status >= 500+ else -> false+ }+ if (network) return reconnectRadio(p, t)+ radioRetries = 0+ log("${t.title}: not reconnected, the stream itself failed (${error.errorCodeName})")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable, t.title), android.widget.Toast.LENGTH_LONG).show()+ }++ private fun reconnectRadio(p: ExoPlayer, t: LocalTrack) {+ if (radioRetries >= RADIO_TRIES) {+ radioRetries = 0+ log("${t.title}: gave up reconnecting after repeated failures")+ android.widget.Toast.makeText(Graph.app, Graph.app.getString(app.myspoti.engine.R.string.song_unavailable, t.title), android.widget.Toast.LENGTH_LONG).show()+ return+ }+ radioRetries+++ val delayMs = (1000L shl (radioRetries - 1)).coerceAtMost(16_000L)+ log("${t.title}: stream dropped, reconnecting in ${delayMs}ms (try $radioRetries/$RADIO_TRIES)")+ handler.postDelayed({+ // Paused meanwhile: it reconnects when the user plays it again, not by itself.+ if (exo === p && current() === t && p.playWhenReady) { p.setMediaItem(item(t)); p.prepare(); p.play() }+ }, delayMs)+ }+fun isPlaying() = if (CastPlayback.active) CastPlayback.isPlaying() else exo?.isPlaying == true/** Waiting for audio (a stream that does not keep up, a seek still loading). */fun isBuffering() = if (CastPlayback.active) CastPlayback.isBuffering() else exo?.playbackState == Player.STATE_BUFFERINGdiff --git a/base/app/src/main/java/com/music/spotui/radio/RadioBrowserApi.kt b/base/app/src/main/java/com/music/spotui/radio/RadioBrowserApi.ktnew file mode 100644index 00000000..80979b4e--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/RadioBrowserApi.kt@@ -0,0 +1,266 @@+package com.music.spotui.radio++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.jsonObject+import okhttp3.OkHttpClient+import okhttp3.Request+import java.util.concurrent.TimeUnit++/**+ * One station, as the public radio-browser.info directory (https://www.radio-browser.info,+ * API at https://api.radio-browser.info) describes it. Only the fields this module actually+ * shows are kept; the server sends many more.+ */+data class RadioStation(+ val stationUuid: String,+ val name: String,+ val streamUrl: String,+ val homepage: String,+ val favicon: String,+ val tags: List<String>,+ val country: String,+ val countryCode: String,+ val language: String,+ val codec: String,+ val bitrateKbps: Int,+ val votes: Int,+ val clickCount: Int,+ val lastCheckOk: Boolean,+)++data class RadioTag(val name: String, val stationCount: Int)++/**+ * A thin client for the radio-browser.info directory: a free, community-run index of public+ * internet radio streams (no account, no key). This module is the only place in the app that+ * talks to it, so it stays easy to replace or remove.+ *+ * The directory has no single server: a pool of community-hosted mirrors answers under+ * `all.api.radio-browser.info` (round-robin DNS). Resolving a hostname needs no extra+ * permission the app doesn't already have (INTERNET is granted), so the mirror list is read+ * once, shuffled, and tried in order; the first one that answers is kept for the session.+ */+object RadioBrowserApi {+ private const val DISCOVERY_HOST = "all.api.radio-browser.info"+ private const val MIRROR_SUFFIX = ".api.radio-browser.info"+ /** Used only if the DNS discovery above fails (a captive portal, a DNS block, …). */+ private val FALLBACK_HOSTS = listOf(+ "https://de1.api.radio-browser.info",+ "https://nl1.api.radio-browser.info",+ "https://at1.api.radio-browser.info",+ )+ private const val CURATED_PREFIX = "curated-"+ private const val USER_AGENT = "Myspoti/1.0 (Live Radio module; +https://github.com/kota-zo/myspoti)"++ private val json = Json { ignoreUnknownKeys = true }+ private val http by lazy { OkHttpClient.Builder().callTimeout(12, TimeUnit.SECONDS).build() }++ @Volatile private var resolvedHost: String? = null+ private val hostLock = Any()++ private suspend fun host(): String {+ resolvedHost?.let { return it }+ return withContext(Dispatchers.IO) {+ synchronized(hostLock) {+ resolvedHost?.let { return@withContext it }+ // DISCOVERY_HOST's round-robin DNS hands out bare IPs. A mirror's TLS cert is+ // issued for its real hostname (e.g. "de1.api.radio-browser.info"), not for that+ // IP, so calling "https://<ip>" directly fails hostname verification on every+ // request. A reverse (PTR) lookup on each IP recovers the real hostname first.+ // Only a name of the directory itself is kept: a reverse lookup answers whatever+ // its DNS says, and the app is not to be sent to some other https host by it.+ val found = runCatching { java.net.InetAddress.getAllByName(DISCOVERY_HOST) }+ .getOrNull()+ ?.mapNotNull { addr ->+ val canonical = addr.canonicalHostName.trimEnd('.')+ if (canonical.endsWith(MIRROR_SUFFIX) && canonical != addr.hostAddress) "https://$canonical" else null+ }+ ?.distinct()?.shuffled()+ val chosen = found?.firstOrNull() ?: FALLBACK_HOSTS.random()+ resolvedHost = chosen+ chosen+ }+ }+ }++ /** A mirror turned out unreachable: the next call resolves again instead of retrying it. */+ private fun forgetHost() { resolvedHost = null }++ /**+ * Stations matching [query] (name search) and/or [tag]; [limit] at most, ordered by vote+ * count (the directory's own measure of a station's popularity), broken streams and the+ * ones this app cannot play (see [playable]) left out. An empty [query] with a [tag] browses+ * that tag. Throws an [java.io.IOException] when no mirror of the directory answers.+ */+ suspend fun search(+ query: String = "",+ tag: String = "",+ limit: Int = 40,+ order: String = "votes",+ ): List<RadioStation> = withContext(Dispatchers.IO) {+ val params = buildString {+ append("hidebroken=true&is_https=true&limit=$limit&order=${enc(order)}&reverse=true")+ if (query.isNotBlank()) append("&name=${enc(query)}")+ if (tag.isNotBlank()) append("&tag=${enc(tag)}")+ }+ stations(getArray("/json/stations/search?$params"))+ }++ /** The directory's most-voted stations overall, for a starting screen with nothing searched yet. */+ suspend fun topStations(limit: Int = 30): List<RadioStation> = search(limit = limit, order = "votes")++ /** Every tag (genre, mood, format…) the directory knows, most used first. */+ suspend fun tags(limit: Int = 60): List<RadioTag> = withContext(Dispatchers.IO) {+ getArray("/json/tags?order=stationcount&reverse=true&limit=$limit").map {+ val o = it.jsonObject+ RadioTag(o.str("name").orEmpty(), o.int("stationcount") ?: 0)+ }.filter { it.name.isNotBlank() }+ }++ /**+ * Tells the directory a station was played (its "click count", how it ranks stations by+ * popularity). Best-effort: a station someone actually listens to should count even if this+ * single call fails, so errors are swallowed. The curated stations are not in the directory.+ */+ suspend fun reportClick(stationUuid: String) {+ if (stationUuid.isBlank() || stationUuid.startsWith(CURATED_PREFIX)) return+ withContext(Dispatchers.IO) { runCatching { get("/json/url/${enc(stationUuid)}") } }+ }++ /**+ * Whether this app can play [streamUrl]: https only (the app allows no cleartext traffic,+ * and a station is no reason to relax that), and no HLS, which the player is built without+ * (no media3-exoplayer-hls): an .m3u8 address would throw before it even starts.+ */+ internal fun playable(streamUrl: String, hls: Boolean = false): Boolean {+ if (hls) return false+ val uri = runCatching { java.net.URI(streamUrl.trim()) }.getOrNull() ?: return false+ return uri.scheme.equals("https", ignoreCase = true) && !uri.host.isNullOrBlank() &&+ !uri.path.orEmpty().endsWith(".m3u8", ignoreCase = true)+ }++ /** The directory's station list, without the ones [playable] turns down. */+ internal fun stations(array: JsonArray): List<RadioStation> = array.mapNotNull(::station)++ private fun station(e: JsonElement): RadioStation? {+ val o = e as? JsonObject ?: return null+ // url_resolved follows redirects already; url is the directory's raw entry.+ val streamUrl = o.str("url_resolved")?.takeIf { it.isNotBlank() } ?: o.str("url").orEmpty()+ if (!playable(streamUrl, hls = o.bool("hls") == true)) return null+ return RadioStation(+ stationUuid = o.str("stationuuid").orEmpty(),+ name = o.str("name").orEmpty().ifBlank { "?" },+ streamUrl = streamUrl,+ homepage = o.str("homepage").orEmpty(),+ favicon = o.str("favicon").orEmpty(),+ tags = o.str("tags").orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() },+ country = o.str("country").orEmpty(),+ countryCode = o.str("countrycode").orEmpty(),+ language = o.str("language").orEmpty(),+ codec = o.str("codec").orEmpty(),+ bitrateKbps = o.int("bitrate") ?: 0,+ votes = o.int("votes") ?: 0,+ clickCount = o.int("clickcount") ?: 0,+ lastCheckOk = o.bool("lastcheckok") ?: true,+ )+ }++ private suspend fun getArray(path: String): JsonArray =+ get(path) as? JsonArray ?: throw java.io.IOException("radio-browser.info: $path is not a list")++ /**+ * One GET, tried once more against a freshly resolved mirror if the first one fails; throws+ * the last failure when neither answers, so a screen can say the directory is unreachable.+ */+ private suspend fun get(path: String): JsonElement {+ var failure: Exception? = null+ repeat(2) {+ val base = host()+ val req = Request.Builder().url(base + path)+ .header("User-Agent", USER_AGENT)+ .header("Accept", "application/json")+ .build()+ try {+ http.newCall(req).execute().use { r ->+ if (!r.isSuccessful) throw java.io.IOException("HTTP ${r.code}")+ return json.parseToJsonElement(r.body.string())+ }+ } catch (e: java.io.IOException) {+ failure = e+ } catch (e: IllegalArgumentException) {+ // Not JSON (a captive portal's page): kotlinx' SerializationException is one.+ failure = e+ }+ forgetHost()+ }+ throw java.io.IOException("radio-browser.info did not answer", failure)+ }++ /**+ * A handful of well-known public-broadcaster stations, shown on "Popular" before (and+ * regardless of) any directory call: the screen has something to show the instant it opens,+ * and stays useful even if the directory or this device's network has a bad moment. Public+ * broadcaster streams rather than commercial ones, since their URLs change far less often.+ */+ val curatedPopular: List<RadioStation> = listOf(+ RadioStation(+ stationUuid = "${CURATED_PREFIX}de-bayern3", name = "Bayern 3",+ streamUrl = "https://dispatcher.rndfnk.com/br/br3/live/mp3/128/stream.mp3",+ homepage = "https://www.br.de/radio/bayern-3/", favicon = "", tags = listOf("pop"),+ country = "Germany", countryCode = "DE", language = "german", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ RadioStation(+ stationUuid = "${CURATED_PREFIX}de-wdr2", name = "WDR 2",+ streamUrl = "https://wdr-wdr2-rheinland.icecastssl.wdr.de/wdr/wdr2/rheinland/mp3/128/stream.mp3",+ homepage = "https://www1.wdr.de/radio/wdr2/", favicon = "", tags = listOf("pop"),+ country = "Germany", countryCode = "DE", language = "german", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ RadioStation(+ stationUuid = "${CURATED_PREFIX}de-ndr2", name = "NDR 2",+ streamUrl = "https://ndr-ndr2-niedersachsen.cast.addradio.de/ndr/ndr2/niedersachsen/mp3/128/stream.mp3",+ homepage = "https://www.ndr.de/ndr2/", favicon = "", tags = listOf("pop"),+ country = "Germany", countryCode = "DE", language = "german", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ RadioStation(+ stationUuid = "${CURATED_PREFIX}nl-radio2", name = "NPO Radio 2",+ streamUrl = "https://icecast.omroep.nl/radio2-bb-mp3",+ homepage = "https://www.nporadio2.nl/", favicon = "", tags = listOf("pop"),+ country = "Netherlands", countryCode = "NL", language = "dutch", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ RadioStation(+ stationUuid = "${CURATED_PREFIX}nl-3fm", name = "NPO 3FM",+ streamUrl = "https://icecast.omroep.nl/3fm-bb-mp3",+ homepage = "https://www.3fm.nl/", favicon = "", tags = listOf("alternative"),+ country = "Netherlands", countryCode = "NL", language = "dutch", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ RadioStation(+ stationUuid = "${CURATED_PREFIX}nl-radio1", name = "NPO Radio 1",+ streamUrl = "https://icecast.omroep.nl/radio1-bb-mp3",+ homepage = "https://www.nporadio1.nl/", favicon = "", tags = listOf("news"),+ country = "Netherlands", countryCode = "NL", language = "dutch", codec = "MP3",+ bitrateKbps = 128, votes = 0, clickCount = 0, lastCheckOk = true,+ ),+ )++ private fun enc(s: String) = java.net.URLEncoder.encode(s, "UTF-8")+ private fun JsonObject.str(name: String): String? = (this[name] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull+ private fun JsonObject.int(name: String): Int? = (this[name] as? kotlinx.serialization.json.JsonPrimitive)?.let {+ it.intOrNull ?: it.contentOrNull?.toIntOrNull()+ }+ private fun JsonObject.bool(name: String): Boolean? = (this[name] as? kotlinx.serialization.json.JsonPrimitive)?.let {+ it.booleanOrNull ?: it.contentOrNull?.let { s -> s == "true" || s == "1" }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/radio/RadioFavoritesStore.kt b/base/app/src/main/java/com/music/spotui/radio/RadioFavoritesStore.ktnew file mode 100644index 00000000..9ba20cb9--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/RadioFavoritesStore.kt@@ -0,0 +1,112 @@+package com.music.spotui.radio++import android.content.Context+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.snapshots.SnapshotStateMap+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import org.json.JSONArray+import org.json.JSONObject+import java.io.File++/** A saved station, with when it was saved (the order the favorites show in). */+data class RadioFavorite(val station: RadioStation, val addedAt: Long)++/**+ * Stations saved as favorites, kept on this phone only (radio-browser.info has no account to+ * sync them to). Same JSON-file-on-disk pattern as [com.music.spotui.data.local.LocalPlaylists].+ */+object RadioFavoritesStore {+ private const val VERSION = 1+ private var file: File? = null+ private val lock = Any()+ private var started = false++ /** stationUuid → the station, as it was when favorited (the directory's own copy may change). */+ val favorites: SnapshotStateMap<String, RadioFavorite> = mutableStateMapOf()++ fun init(context: Context) {+ if (started) return+ started = true+ val f = File(context.filesDir, "radio_favorites.json")+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { load(f) }+ }++ /** The favorites become [f]'s, and every change is saved to it from then on; [init] does it off the main thread. */+ internal fun load(f: File) {+ synchronized(lock) {+ favorites.clear()+ if (f.exists()) runCatching { read(f.readText()) }+ file = f+ }+ }++ fun isFavorite(stationUuid: String): Boolean = favorites.containsKey(stationUuid)++ fun toggle(station: RadioStation) {+ if (favorites.containsKey(station.stationUuid)) remove(station.stationUuid) else add(station)+ }++ /** A station this app cannot play (see [RadioBrowserApi.playable]) is not kept. */+ fun add(station: RadioStation, now: Long = System.currentTimeMillis()) {+ if (!RadioBrowserApi.playable(station.streamUrl)) return+ update { favorites[station.stationUuid] = RadioFavorite(station, now) }+ }++ fun remove(stationUuid: String) = update { favorites.remove(stationUuid) }++ /** Newest-added first (a SnapshotStateMap keeps no insertion order, so by when each was saved). */+ fun list(): List<RadioStation> = favorites.values.sortedByDescending { it.addedAt }.map { it.station }++ private fun update(change: () -> Unit) {+ synchronized(lock) {+ change()+ val f = file ?: return+ val tmp = File(f.parentFile, f.name + ".tmp")+ runCatching { tmp.writeText(write()); tmp.renameTo(f) }+ }+ }++ private fun favoriteJson(fav: RadioFavorite) = fav.station.let { s ->+ JSONObject()+ .put("uuid", s.stationUuid).put("name", s.name).put("url", s.streamUrl).put("homepage", s.homepage)+ .put("favicon", s.favicon).put("tags", JSONArray(s.tags)).put("country", s.country)+ .put("countrycode", s.countryCode).put("language", s.language).put("codec", s.codec)+ .put("bitrate", s.bitrateKbps).put("votes", s.votes).put("clicks", s.clickCount).put("ok", s.lastCheckOk)+ .put("added", fav.addedAt)+ }++ private fun favoriteOf(o: JSONObject): RadioFavorite {+ val tags = o.optJSONArray("tags")+ val station = RadioStation(+ stationUuid = o.getString("uuid"), name = o.optString("name"), streamUrl = o.optString("url"),+ homepage = o.optString("homepage"), favicon = o.optString("favicon"),+ tags = (0 until (tags?.length() ?: 0)).map { tags!!.getString(it) },+ country = o.optString("country"), countryCode = o.optString("countrycode"),+ language = o.optString("language"), codec = o.optString("codec"),+ bitrateKbps = o.optInt("bitrate"), votes = o.optInt("votes"), clickCount = o.optInt("clicks"),+ lastCheckOk = o.optBoolean("ok", true),+ )+ return RadioFavorite(station, o.optLong("added"))+ }++ internal fun write(): String {+ val arr = JSONArray()+ favorites.values.forEach { arr.put(favoriteJson(it)) }+ return JSONObject().put("version", VERSION).put("favorites", arr).toString()+ }++ /** Adds the favorites of [text]; one that is unreadable or no longer playable is left out. */+ internal fun read(text: String) {+ val o = JSONObject(text)+ if (o.optInt("version") != VERSION) return+ val arr = o.optJSONArray("favorites") ?: JSONArray()+ for (i in 0 until arr.length()) {+ runCatching { favoriteOf(arr.getJSONObject(i)) }.getOrNull()+ ?.takeIf { RadioBrowserApi.playable(it.station.streamUrl) }+ ?.let { favorites[it.station.stationUuid] = it }+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/radio/RadioFeaturePref.kt b/base/app/src/main/java/com/music/spotui/radio/RadioFeaturePref.ktnew file mode 100644index 00000000..1ed1eace--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/RadioFeaturePref.kt@@ -0,0 +1,34 @@+package com.music.spotui.radio++import android.content.Context+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValue++/**+ * "Live Radio" (Settings > Playback): on adds the pinned Library row under Local Files; off hides+ * it and stops anything playing. Off by default — an opt-in, not something that appears unasked.+ * Its own tiny prefs file, not [com.music.spotui.data.preferences.SettingsPref]'s, so the whole+ * `radio` package stays removable without touching the app's other data files.+ */+object RadioFeaturePref {+ private const val PREF = "live_radio_prefs"+ private const val KEY = "live_radio_enabled"++ /** The pinned Library row's sentinel id (parallel to Api.HomeCache.LOCAL_FILES_ID / DOWNLOADS_ID). */+ const val LIBRARY_ENTRY_ID = "live radio"++ private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)++ var on by androidx.compose.runtime.mutableStateOf(false)+ private set++ fun init(context: Context) {+ on = prefs(context).getBoolean(KEY, false)+ }++ fun set(context: Context, value: Boolean) {+ on = value+ prefs(context).edit().putBoolean(KEY, value).apply()+ if (!value) RadioPlayer.stop()+ }+}diff --git a/base/app/src/main/java/com/music/spotui/radio/RadioPlayer.kt b/base/app/src/main/java/com/music/spotui/radio/RadioPlayer.ktnew file mode 100644index 00000000..b3b12310--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/RadioPlayer.kt@@ -0,0 +1,79 @@+package com.music.spotui.radio++import android.content.Context+import android.content.Intent+import com.music.spotui.data.local.LocalTrack+import com.music.spotui.di.Graph+import com.music.spotui.di.LocalPlayer+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Starts a Live Radio station by handing it to [LocalPlayer] as a one-item "queue" (no duration,+ * no next/previous, no crossfade). From there it is simply a Local Files track as far as the+ * rest of the app is concerned — [LocalPlayer] already feeds the mini player, the full player,+ * the notification and the lock screen, and already pauses/resumes Spotify. No separate player,+ * session or notification exists here, so removing this file removes the feature cleanly.+ */+object RadioPlayer {+ private var started: RadioStation? = null++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ /** The station [LocalPlayer] is on (playing or paused) — null once anything else plays, or nothing does. */+ fun current(): RadioStation? {+ val station = started ?: return null+ return station.takeIf { LocalPlayer.current()?.let { it.isRadio && it.id == stableId(station) } == true }+ }++ /** Starts [station]: LocalPlayer.play pauses Spotify / whatever else was playing on its own. */+ fun play(station: RadioStation) {+ // A favorite saved before a stream was checked, say: never handed to a player that would fail on it.+ if (!RadioBrowserApi.playable(station.streamUrl)) return+ started = station+ LocalPlayer.play(+ listOf(track(station)), 0,+ context = Graph.app.getString(app.myspoti.engine.R.string.live_radio_title), contextUri = "",+ )+ scope.launch { RadioBrowserApi.reportClick(station.stationUuid) }+ }++ /** Leaves radio: only actually stops LocalPlayer if it is still on the station (not, say, a song since played). */+ fun stop() {+ if (LocalPlayer.current()?.isRadio == true) LocalPlayer.stop()+ started = null+ }++ /**+ * Shares the station playing as plain text, its name and homepage: not as a Spotify Code (its+ * image is drawn by Spotify's server, which would be sent the station), and never the stream+ * address itself.+ */+ fun share(context: Context) {+ val station = current() ?: return+ val homepage = station.homepage.takeIf { it.startsWith("https://") || it.startsWith("http://") }+ val text = listOfNotNull(station.name, homepage).joinToString("\n")+ val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, text)+ context.startActivity(Intent.createChooser(send, context.getString(app.myspoti.engine.R.string.action_share_label)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ }++ /** The synthetic song id LocalPlayer/SongPlayer show [station] under, to match against Graph.currentSongState. */+ fun songIdFor(station: RadioStation): Int = ("local:" + stableId(station)).hashCode() and 0x7fffffff++ private fun track(station: RadioStation) = LocalTrack(+ id = stableId(station), uri = android.net.Uri.parse(station.streamUrl),+ title = station.name, artist = station.tags.firstOrNull()?.ifBlank { null } ?: station.country,+ album = Graph.app.getString(app.myspoti.engine.R.string.live_radio_title), durationMs = 0L,+ artUri = station.favicon.takeIf { it.isNotBlank() }?.let(android.net.Uri::parse)+ ?: android.net.Uri.parse("android.resource://${Graph.app.packageName}/drawable/live_radio_cover"),+ isRadio = true,+ )++ /**+ * Below -2^32: out of the range MediaStore hands out (always >= 0) and of the downloads' own+ * negative ids (OfflineStore.localIdOf, -1 to -2^31), so it is never taken for either.+ */+ private fun stableId(station: RadioStation) = -(1L shl 32) - (station.stationUuid.hashCode().toLong() and 0x7fffffffL)+}diff --git a/base/app/src/main/java/com/music/spotui/radio/ui/ImmersiveLiveRadioScreen.kt b/base/app/src/main/java/com/music/spotui/radio/ui/ImmersiveLiveRadioScreen.ktnew file mode 100644index 00000000..b3f012d5--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/ui/ImmersiveLiveRadioScreen.kt@@ -0,0 +1,111 @@+package com.music.spotui.radio.ui++import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.Favorite+import androidx.compose.material.icons.rounded.FavoriteBorder+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.music.spotui.radio.RadioFavoritesStore+import com.music.spotui.radio.RadioPlayer+import com.music.spotui.radio.RadioStation+import com.music.spotui.ui.immersive.Immersive+import com.music.spotui.ui.immersive.components.ImmersiveListRow+import com.music.spotui.ui.immersive.components.ImmersiveMessageState+import com.music.spotui.ui.immersive.components.ImmersiveSearchField+import com.music.spotui.ui.immersive.components.SectionHeader+import com.music.spotui.ui.immersive.components.immersiveClickable+import com.music.spotui.ui.immersive.components.immersiveSongListSkeleton+import com.music.spotui.ui.immersive.pages.ImmersivePage+import com.music.spotui.ui.immersive.screens.ImmersiveChip+import com.music.spotui.ui.immersive.screens.ImmersiveChipRow++/**+ * The Live Radio screen of the Immersive look, on the same [LiveRadioState] as the Classic+ * [LiveRadioScreen]: the page scaffold with its large title, the search capsule, the genre pills+ * and the stations as list rows, the favorites first while nothing is searched.+ */+@Composable+fun ImmersiveLiveRadioScreen(navController: NavController) {+ val state = rememberLiveRadioState()+ val favorites = RadioFavoritesStore.list()+ ImmersivePage(+ title = stringResource(R.string.live_radio_title),+ subtitle = stringResource(R.string.live_radio_subtitle),+ onBack = { navController.popBackStack() },+ ) {+ item(key = "radio:search") {+ ImmersiveSearchField(+ query = state.query, onQueryChange = { state.query = it }, onSubmit = {},+ placeholder = stringResource(R.string.live_radio_search_hint),+ modifier = Modifier.padding(horizontal = Immersive.Gutter, vertical = 6.dp),+ )+ }+ if (state.genres.isNotEmpty()) item(key = "radio:genres") {+ ImmersiveChipRow {+ state.genres.forEach { g -> ImmersiveChip(g, selected = g == state.genre, onClick = { state.pick(g) }) }+ }+ }+ if (favorites.isNotEmpty() && state.browsing) {+ item(key = "radio:favorites") { SectionHeader(stringResource(R.string.live_radio_favorites)) }+ items(favorites, key = { "fav:" + it.stationUuid }) { StationRow(it) }+ }+ item(key = "radio:section") {+ SectionHeader(+ when {+ state.query.isNotBlank() -> stringResource(R.string.live_radio_search_results)+ state.genre.isNotBlank() -> state.genre.replaceFirstChar { it.uppercase() }+ else -> stringResource(R.string.live_radio_popular)+ },+ )+ }+ // Said even over the curated picks: what follows them is missing.+ if (state.error) item(key = "radio:error") { ImmersiveMessageState(stringResource(R.string.live_radio_error)) }+ val results = state.results+ when {+ state.loading && results == null -> immersiveSongListSkeleton(keyPrefix = "radio:skeleton")+ results?.isEmpty() == true && !state.error -> item(key = "radio:empty") {+ ImmersiveMessageState(stringResource(R.string.live_radio_no_results))+ }+ else -> items(results.orEmpty(), key = { it.stationUuid }) { StationRow(it) }+ }+ }+}++@Composable+private fun StationRow(station: RadioStation) {+ // The station LocalPlayer is on, by its synthetic song id, as the mini player shows it.+ val currentId by com.music.spotui.di.Graph.currentSongState.songId+ val current = currentId == RadioPlayer.songIdFor(station)+ val fav = RadioFavoritesStore.isFavorite(station.stationUuid)+ ImmersiveListRow(+ title = station.name,+ subtitle = stationSubtitle(station),+ imageUrl = station.favicon.ifBlank { null },+ round = false,+ onClick = { RadioPlayer.play(station) },+ playing = current && com.music.spotui.di.Graph.currentSongState.playingState.value,+ trailing = {+ Icon(+ if (fav) Icons.Rounded.Favorite else Icons.Rounded.FavoriteBorder,+ contentDescription = stringResource(if (fav) R.string.live_radio_unfavorite else R.string.live_radio_favorite),+ tint = if (fav) Immersive.Accent else Immersive.TextSecondary,+ modifier = Modifier+ .size(36.dp)+ .clip(CircleShape)+ .immersiveClickable(onClick = { RadioFavoritesStore.toggle(station) }, pressedScale = 0.9f)+ .padding(7.dp),+ )+ },+ )+}diff --git a/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioScreen.kt b/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioScreen.ktnew file mode 100644index 00000000..9523402f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioScreen.kt@@ -0,0 +1,204 @@+package com.music.spotui.radio.ui++import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+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.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.automirrored.filled.ArrowBack+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.navigation.NavController+import app.myspoti.engine.R+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.bumptech.glide.integration.compose.placeholder+import com.music.spotui.radio.RadioFavoritesStore+import com.music.spotui.radio.RadioPlayer+import com.music.spotui.radio.RadioStation+import com.music.spotui.ui.components.FindInListField+import com.music.spotui.ui.components.pressable+import com.music.spotui.ui.theme.AppAccent+import com.music.spotui.ui.theme.AppBackground+import com.music.spotui.ui.theme.AppMuted+import com.music.spotui.ui.theme.AppText+import com.music.spotui.ui.theme.headerTint++/**+ * The Live Radio screen of the Classic look ([ImmersiveLiveRadioScreen] is the Immersive one):+ * search the radio-browser.info directory, browse a handful of popular genres, and keep+ * favorites (see [LiveRadioState]). Deliberately its own small screen rather than reusing Library's+ * list/grid machinery — stations have no album, no artist, no duration, so little of that+ * machinery would apply.+ */+@Composable+fun LiveRadioScreen(navController: NavController) {+ val state = rememberLiveRadioState()+ val favorites = RadioFavoritesStore.list()++ Box(Modifier.fillMaxSize().background(AppBackground)) {+ LazyColumn(Modifier.fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(+ bottom = com.music.spotui.ui.components.bottomBarsSpace())) {+ item {+ Column(+ Modifier.fillMaxWidth()+ .background(Brush.verticalGradient(listOf(headerTint(Color(0xFF1C6E7A), 0f), AppBackground)))+ .statusBarsPadding().padding(horizontal = 16.dp),+ ) {+ Spacer(Modifier.height(56.dp))+ Image(+ painterResource(R.drawable.live_radio_cover), null,+ modifier = Modifier.align(Alignment.CenterHorizontally).size(120.dp).clip(RoundedCornerShape(6.dp)),+ )+ Text(stringResource(R.string.live_radio_title), color = AppText, fontSize = 26.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(top = 16.dp))+ Text(stringResource(R.string.live_radio_subtitle), color = AppMuted, fontSize = 13.sp, modifier = Modifier.padding(top = 4.dp))+ Spacer(Modifier.height(14.dp))+ FindInListField(state.query, { state.query = it }, stringResource(R.string.live_radio_search_hint), Modifier.fillMaxWidth())+ Spacer(Modifier.height(10.dp))+ }+ }++ if (favorites.isNotEmpty() && state.browsing) {+ item { SectionTitle(stringResource(R.string.live_radio_favorites)) }+ itemsIndexed(favorites, key = { _, s -> "fav-${s.stationUuid}" }) { _, s ->+ StationRow(s)+ }+ item { Spacer(Modifier.height(8.dp)) }+ }++ if (state.genres.isNotEmpty()) item {+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 4.dp),+ ) {+ for (g in state.genres) {+ val on = g == state.genre+ Text(+ g, color = if (on) Color.Black else AppText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,+ modifier = Modifier.clip(RoundedCornerShape(50))+ .background(if (on) AppAccent else com.music.spotui.ui.theme.tone(0xFF2A2A2A))+ .pressable(0.95f) { state.pick(g) }+ .padding(horizontal = 14.dp, vertical = 7.dp),+ )+ }+ }+ }++ item {+ SectionTitle(+ when {+ state.query.isNotBlank() -> stringResource(R.string.live_radio_search_results)+ state.genre.isNotBlank() -> state.genre.replaceFirstChar { it.uppercase() }+ else -> stringResource(R.string.live_radio_popular)+ },+ )+ }++ // Said even over the curated picks: what follows them is missing.+ if (state.error) item {+ Text(stringResource(R.string.live_radio_error), color = AppMuted, fontSize = 14.sp, textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 16.dp))+ }+ val results = state.results+ when {+ state.loading && results == null -> item {+ Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {+ CircularProgressIndicator(color = AppAccent)+ }+ }+ results?.isEmpty() == true && !state.error -> item {+ Text(stringResource(R.string.live_radio_no_results), color = AppMuted, fontSize = 14.sp,+ modifier = Modifier.fillMaxWidth().padding(32.dp), textAlign = TextAlign.Center)+ }+ else -> itemsIndexed(results.orEmpty(), key = { _, s -> s.stationUuid }) { _, s ->+ StationRow(s)+ }+ }+ }+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.statusBarsPadding().padding(12.dp).size(40.dp).clip(CircleShape)+ .background(AppBackground.copy(alpha = 0.4f)).pressable { navController.navigateUp() },+ ) {+ Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.accessibility_navigate_back), tint = AppText)+ }+ }+}++@Composable+private fun SectionTitle(text: String) {+ Text(text, color = AppText, fontSize = 17.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp))+}++@OptIn(ExperimentalGlideComposeApi::class)+@Composable+private fun StationRow(station: RadioStation) {+ // The station currently loaded in LocalPlayer (playing or paused on), by its synthetic song+ // id — the same signal the mini player, full player and notification already show.+ val currentId by com.music.spotui.di.Graph.currentSongState.songId+ val current = currentId == RadioPlayer.songIdFor(station)+ // Bars only while it is actually playing (not merely loaded/paused), same as any other row.+ val playing = current && com.music.spotui.di.Graph.currentSongState.playingState.value+ val fav = RadioFavoritesStore.favorites.containsKey(station.stationUuid)+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().pressable(0.97f) { RadioPlayer.play(station) }+ .padding(horizontal = 16.dp, vertical = 8.dp),+ ) {+ Box(Modifier.size(48.dp)) {+ GlideImage(+ transition = CrossFade,+ model = station.favicon, contentDescription = null, contentScale = ContentScale.Crop,+ loading = placeholder(R.drawable.live_radio_cover), failure = placeholder(R.drawable.live_radio_cover),+ modifier = Modifier.matchParentSize().clip(RoundedCornerShape(4.dp)),+ )+ // The same three dancing bars a playing song shows over its cover elsewhere in the app.+ if (playing) com.music.spotui.ui.immersive.components.ImmersivePlayingBars(Modifier.align(Alignment.Center))+ }+ Column(Modifier.padding(start = 12.dp).weight(1f)) {+ Text(station.name, color = if (current) AppAccent else AppText, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ val subtitle = stationSubtitle(station)+ if (subtitle.isNotBlank()) Text(subtitle, color = AppMuted, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ Icon(+ painterResource(if (fav) R.drawable.ic_favorite_filled else R.drawable.ic_favorite),+ contentDescription = stringResource(if (fav) R.string.live_radio_unfavorite else R.string.live_radio_favorite),+ tint = if (fav) AppAccent else AppText,+ modifier = Modifier.size(24.dp).pressable(0.9f) { RadioFavoritesStore.toggle(station) },+ )+ }+}diff --git a/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioState.kt b/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioState.ktnew file mode 100644index 00000000..e0397d29--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/radio/ui/LiveRadioState.kt@@ -0,0 +1,100 @@+package com.music.spotui.radio.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.Stable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.listSaver+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import com.music.spotui.radio.RadioBrowserApi+import com.music.spotui.radio.RadioStation+import kotlinx.coroutines.delay++/**+ * What the Live Radio screen shows, in either look: the search typed, the genre picked, and the+ * directory's answer to them. The two looks only draw it ([LiveRadioScreen], [ImmersiveLiveRadioScreen]).+ */+@Stable+internal class LiveRadioState(query: String = "", genre: String = "") {+ var query by mutableStateOf(query)+ var genre by mutableStateOf(genre)+ private set+ var genres by mutableStateOf<List<String>>(emptyList())+ private set+ var results by mutableStateOf<List<RadioStation>?>(null)+ private set+ var loading by mutableStateOf(false)+ private set+ /** The directory did not answer the last ask: said on the screen, even over the curated picks. */+ var error by mutableStateOf(false)+ private set++ /** Nothing searched or picked: the favorites and the popular stations show. */+ val browsing: Boolean get() = query.isBlank() && genre.isBlank()++ /** A genre chip tapped: picked (a search typed is cleared), or put down when it already was. */+ fun pick(tag: String) {+ genre = if (genre == tag) "" else tag+ query = ""+ }++ /** The genre chips; none when the directory does not answer (the stations' own ask says so). */+ suspend fun loadGenres() {+ genres = try { RadioBrowserApi.tags(limit = 16).map { it.name } } catch (e: java.io.IOException) { emptyList() }+ }++ /**+ * Asks the directory for what [query] and [genre] say, a little after the user stops typing+ * (a newer ask cancels this one: its caller is keyed on both).+ */+ suspend fun load() {+ val q = query; val g = genre+ error = false+ if (q.isBlank() && g.isBlank()) {+ // Curated picks show immediately, so "Popular" is never empty while the directory+ // call is in flight (or if it fails); the live top stations are appended after,+ // skipping any curated station the directory already returned.+ results = RadioBrowserApi.curatedPopular+ loading = true+ ask { RadioBrowserApi.topStations() }?.let { top ->+ val curatedNames = RadioBrowserApi.curatedPopular.map { it.name.lowercase() }.toSet()+ results = RadioBrowserApi.curatedPopular + top.filter { it.name.lowercase() !in curatedNames }+ }+ loading = false+ return+ }+ if (q.isNotBlank()) delay(400)+ loading = true+ results = ask { RadioBrowserApi.search(query = q, tag = g) }+ loading = false+ }++ /** [call]'s answer, or null with [error] set when the directory could not be reached. */+ private suspend fun <T> ask(call: suspend () -> T): T? =+ try { call() } catch (e: java.io.IOException) { error = true; null }++ companion object {+ val Saver = listSaver<LiveRadioState, String>(+ save = { listOf(it.query, it.genre) },+ restore = { LiveRadioState(it[0], it[1]) },+ )+ }+}++/** The screen's [LiveRadioState], kept across a rotation, with its asks to the directory running. */+@Composable+internal fun rememberLiveRadioState(): LiveRadioState {+ val state = rememberSaveable(saver = LiveRadioState.Saver) { LiveRadioState() }+ LaunchedEffect(Unit) { state.loadGenres() }+ LaunchedEffect(state.query, state.genre) { state.load() }+ return state+}++/** A station's line under its name, either look: its country, first genre and bitrate. */+internal fun stationSubtitle(station: RadioStation): String = listOfNotNull(+ station.country.takeIf { it.isNotBlank() },+ station.tags.firstOrNull()?.takeIf { it.isNotBlank() },+ station.bitrateKbps.takeIf { it > 0 }?.let { "$it kbps" },+).joinToString(" · ")diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.ktindex 5dd79f13..cbff0ea6 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SongOptionsSheet.kt@@ -141,6 +141,9 @@ fun SongOptionsSheet(return}val hasId = song.spotifyTrackId.isNotBlank()+ // A Live Radio station playing right now: no queue, album or artist page of its own, but+ // (unlike a track with no Spotify id) a name and homepage worth sharing.+ val isRadio = nowPlaying && com.music.spotui.radio.RadioPlayer.current() != null// An episode is keyed by its url ("episode:<id>") and has no track id: the Download row// (and only it) follows that key, everything else in this menu stays on the track id.val episodeKey = com.music.spotui.data.offline.episodeKeyOf(song)@@ -208,7 +211,7 @@ fun SongOptionsSheet(onDismiss()}} else if (onOpenQueue != null) {- MenuRow(Icons.AutoMirrored.Filled.QueueMusic, stringResource(R.string.context_menu_go_to_queue)) {+ MenuRow(Icons.AutoMirrored.Filled.QueueMusic, stringResource(R.string.context_menu_go_to_queue), enabled = !isRadio) {onDismiss()onOpenQueue()}@@ -260,11 +263,11 @@ fun SongOptionsSheet(navigate = { route -> navController.navigate(route) },onFailed = { toast(context.getString(R.string.song_radio_failed)) })}- MenuRow(Icons.Default.Album, stringResource(R.string.context_menu_browse_album), enabled = song.album.isNotBlank() || song.albumId.isNotBlank()) {+ MenuRow(Icons.Default.Album, stringResource(R.string.context_menu_browse_album), enabled = !isRadio && (song.album.isNotBlank() || song.albumId.isNotBlank())) {onDismiss()navController.navigate(albumRoute(song.album, song.singer, song.albumId))}- MenuRow(Icons.Outlined.Person, stringResource(R.string.context_menu_browse_artist), enabled = song.singer.isNotBlank()) {+ MenuRow(Icons.Outlined.Person, stringResource(R.string.context_menu_browse_artist), enabled = !isRadio && song.singer.isNotBlank()) {onDismiss()playerViewModel.goToArtist(song.spotifyTrackId, song.singer) { route -> navController.navigate(route) }}@@ -334,8 +337,10 @@ fun SongOptionsSheet(navController.navigate(com.music.spotui.ui.navigation.Routes.Equalizer.route)}}- MenuRow(Icons.Outlined.Share, stringResource(R.string.context_menu_share), enabled = hasId) {- SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))+ MenuRow(Icons.Outlined.Share, stringResource(R.string.context_menu_share), enabled = hasId || isRadio) {+ // A station has no Spotify uri: shared as plain text, never through a Spotify Code.+ if (isRadio) com.music.spotui.radio.RadioPlayer.share(context)+ else SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))onDismiss()}if (nowPlaying) {diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.ktindex 238c1af9..a864bae2 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/pages/ImmersiveSettingsScreen.kt@@ -276,6 +276,15 @@ private fun PlaybackPage(navController: NavController, open: (SettingsPage) -> Udetail = stringResource(R.string.settings_connect_mirror_detail),)}+ // Live Radio: adds the pinned Library row under Local Files (see com.music.spotui.radio).+ row {+ ImmersiveSwitchRow(+ stringResource(R.string.live_radio_settings_title),+ checked = com.music.spotui.radio.RadioFeaturePref.on,+ onChecked = { com.music.spotui.radio.RadioFeaturePref.set(ctx, it) },+ detail = stringResource(R.string.live_radio_settings_detail),+ )+ }// Downloaded songs, played from their files online, played by Spotify too (unheard), as an extension's.row {ImmersiveSwitchRow(diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.ktindex 1d78040e..44e2d28a 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/screens/ImmersiveLibraryScreen.kt@@ -309,7 +309,10 @@ fun ImmersiveLibraryScreen(navController: NavController) {}/** The library rows that hold songs rather than a playlist, for [LibraryChips.apply]. */-private val LIBRARY_SONG_IDS = setOf(Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID)+private val LIBRARY_SONG_IDS = setOf(+ Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID,+ com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID,+)/** The collapse fraction (0..1) of a grid page, as [rememberTopBarCollapse] gives a list's. */@Composable@@ -335,11 +338,14 @@ private fun libraryEntries(entries: Response<List<LibraryEntry>>): Pair<List<Libval downloadsName = stringResource(R.string.collection_downloaded)val localSubtitle = stringResource(R.string.assisted_curation_search_playlist) + " • " + stringResource(R.string.local_playlist_subtitle)val likedName = stringResource(R.string.collection_liked_songs_title)+ val radioName = stringResource(R.string.live_radio_title)val packageName = LocalContext.current.packageNameval hasDownloads = com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty() ||com.music.spotui.data.offline.OfflineDownloader.requests.isNotEmpty()+ val radioOn = com.music.spotui.radio.RadioFeaturePref.onval base = (entries as? Response.Success)?.data ?: emptyList()- val rootPinned = base.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 + (if (hasDownloads) 1 else 0)+ val rootPinned = base.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 ++ (if (radioOn) 1 else 0) + (if (hasDownloads) 1 else 0)val all = base.map {if (it.spotifyId == Api.HomeCache.LIKED_SONGS_ID) it.copy(name = likedName, subtitle = "") else it}.let { list ->@@ -347,6 +353,11 @@ private fun libraryEntries(entries: Response<List<LibraryEntry>>): Pair<List<LibspotifyId = Api.HomeCache.LOCAL_FILES_ID, name = localName, subtitle = "",coverUri = "android.resource://$packageName/drawable/local_files_cover", isPlaylist = true,)+ // Live Radio, right under Local Files — behind the Settings > Playback toggle.+ val radio = LibraryEntry(+ spotifyId = com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID, name = radioName, subtitle = "",+ coverUri = "android.resource://$packageName/drawable/live_radio_cover", isPlaylist = true,+ )val downloads = LibraryEntry(spotifyId = Api.HomeCache.DOWNLOADS_ID, name = downloadsName, subtitle = "", coverUri = "", isPlaylist = true,)@@ -358,7 +369,8 @@ private fun libraryEntries(entries: Response<List<LibraryEntry>>): Pair<List<Libsubtitle = localSubtitle, coverUri = "", isPlaylist = true,)}- list.take(at) + local + (if (hasDownloads) listOf(downloads) else emptyList()) + localLists + list.drop(at)+ list.take(at) + local + (if (radioOn) listOf(radio) else emptyList()) ++ (if (hasDownloads) listOf(downloads) else emptyList()) + localLists + list.drop(at)}.let { list ->LibraryOrder.versionLibraryOrder.arrange(list, LibraryOrder.sort, LibraryOrder.custom(LibraryOrder.ROOT), rootPinned)@@ -446,6 +458,7 @@ internal fun Modifier.immersiveBleed(inset: Dp): Modifier = layout { measurable,private fun prefetchLibraryEntry(entry: LibraryEntry) = when {entry.isFolder || entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) || entry.spotifyId.startsWith(Api.HomeCache.SHOW_PREFIX) -> Unitentry.spotifyId == Api.HomeCache.LOCAL_FILES_ID || entry.spotifyId == Api.HomeCache.DOWNLOADS_ID || entry.spotifyId == Api.HomeCache.EPISODES_ID || entry.spotifyId == Api.HomeCache.NEW_EPISODES_ID -> Unit+ entry.spotifyId == com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID -> Unitentry.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> ContextViewModel.prefetch("liked", "")entry.isPlaylist -> ContextViewModel.prefetch("playlist", entry.spotifyId)else -> ContextViewModel.prefetch("album", entry.spotifyId)@@ -457,6 +470,7 @@ private fun openLibraryEntry(entry: LibraryEntry, navController: NavController)else if (entry.spotifyId.startsWith(Api.HomeCache.SHOW_PREFIX)) navController.navigate(showRoute(entry.spotifyId.removePrefix(Api.HomeCache.SHOW_PREFIX), entry.name))else if (entry.spotifyId == Api.HomeCache.DOWNLOADS_ID) navController.navigate(Routes.Downloads.route)else if (entry.spotifyId == Api.HomeCache.LOCAL_FILES_ID) navController.navigate(Routes.LocalFiles.route)+ else if (entry.spotifyId == com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID) navController.navigate(Routes.LiveRadio.route)else if (entry.spotifyId == Api.HomeCache.LIKED_SONGS_ID) navController.navigate(Routes.Liked.route)else if (entry.spotifyId == Api.HomeCache.EPISODES_ID) navController.navigate(Routes.Episodes.route)else if (entry.spotifyId == Api.HomeCache.NEW_EPISODES_ID) navController.navigate(Routes.NewEpisodes.route)diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.ktindex f05dabd5..aa6a5e6c 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/sheets/ImmersiveSongOptionsSheet.kt@@ -112,6 +112,9 @@ fun ImmersiveSongOptionsSheet(if (showSleep) { SleepTimerSheet(onDismiss = { showSleep = false; onDismiss() }); return }val hasId = song.spotifyTrackId.isNotBlank()+ // A Live Radio station playing right now: no queue, album or artist page of its own, but+ // (unlike a track with no Spotify id) a name and homepage worth sharing.+ val isRadio = nowPlaying && com.music.spotui.radio.RadioPlayer.current() != nullval episodeKey = com.music.spotui.data.offline.episodeKeyOf(song)val downloadKey = episodeKey ?: song.spotifyTrackIdfun toast(text: String) = Toast.makeText(context, text, Toast.LENGTH_SHORT).show()@@ -152,7 +155,7 @@ fun ImmersiveSongOptionsSheet(onDismiss()}} else if (onOpenQueue != null) {- ImmersiveSheetRow(Icons.AutoMirrored.Rounded.QueueMusic, stringResource(R.string.context_menu_go_to_queue)) {+ ImmersiveSheetRow(Icons.AutoMirrored.Rounded.QueueMusic, stringResource(R.string.context_menu_go_to_queue), enabled = !isRadio) {onDismiss()onOpenQueue()}@@ -200,11 +203,11 @@ fun ImmersiveSongOptionsSheet(navigate = { route -> navController.navigate(route) },onFailed = { toast(context.getString(R.string.song_radio_failed)) })}- ImmersiveSheetRow(Icons.Rounded.Album, stringResource(R.string.context_menu_browse_album), enabled = song.album.isNotBlank() || song.albumId.isNotBlank()) {+ ImmersiveSheetRow(Icons.Rounded.Album, stringResource(R.string.context_menu_browse_album), enabled = !isRadio && (song.album.isNotBlank() || song.albumId.isNotBlank())) {onDismiss()navController.navigate(albumRoute(song.album, song.singer, song.albumId))}- ImmersiveSheetRow(Icons.Rounded.Person, stringResource(R.string.context_menu_browse_artist), enabled = song.singer.isNotBlank()) {+ ImmersiveSheetRow(Icons.Rounded.Person, stringResource(R.string.context_menu_browse_artist), enabled = !isRadio && song.singer.isNotBlank()) {onDismiss()playerViewModel.goToArtist(song.spotifyTrackId, song.singer) { route -> navController.navigate(route) }}@@ -316,8 +319,10 @@ fun ImmersiveSongOptionsSheet(navController.navigate(com.music.spotui.ui.navigation.Routes.Equalizer.route)}}- ImmersiveSheetRow(Icons.Rounded.Share, stringResource(R.string.context_menu_share), enabled = hasId) {- SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))+ ImmersiveSheetRow(Icons.Rounded.Share, stringResource(R.string.context_menu_share), enabled = hasId || isRadio) {+ // A station has no Spotify uri: shared as plain text, never through a Spotify Code.+ if (isRadio) com.music.spotui.radio.RadioPlayer.share(context)+ else SpotifyCode.show(ShareTarget("spotify:track:${song.spotifyTrackId}", song.title, song.singer, song.coverUri))onDismiss()}if (nowPlaying) {diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.ktindex c725e26b..b47968c7 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/MyNavHost.kt@@ -100,6 +100,11 @@ fun MyNavHost(if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveLocalFilesScreen(navHostController) else com.music.spotui.ui.screens.LocalFilesScreen(navHostController)}+ // Live Radio (see com.music.spotui.radio): plays through LocalPlayer, as a Local Files song does.+ page(Routes.LiveRadio.route){+ if (isImmersive()) com.music.spotui.radio.ui.ImmersiveLiveRadioScreen(navHostController) else com.music.spotui.radio.ui.LiveRadioScreen(navHostController)+ }+page(Routes.Downloads.route){if (isImmersive()) com.music.spotui.ui.immersive.pages.ImmersiveDownloadsScreen(navHostController) else com.music.spotui.ui.screens.DownloadsScreen(navHostController)}diff --git a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.ktindex 268e89be..11a6893e 100644--- a/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt+++ b/base/app/src/main/java/com/music/spotui/ui/navigation/Routes.kt@@ -23,6 +23,8 @@ sealed class Routes(object Queue : Routes(0, "Queue", "queue")object Liked : Routes(0, "Liked", "liked")object LocalFiles : Routes(0, "LocalFiles", "localfiles")+ /** Live Radio (radio/ module): search radio-browser.info, favorites, playback. */+ object LiveRadio : Routes(0, "LiveRadio", "liveradio")object Downloads : Routes(0, "Downloads", "downloads")object HiddenSongs : Routes(0, "HiddenSongs", "hiddensongs")object Equalizer : Routes(0, "Equalizer", "equalizer")diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.ktindex 0fa92412..430c6956 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryScreeen.kt@@ -299,8 +299,10 @@ fun LibraryScreen(navController: NavController) {// Liked Songs, Local Files and Downloaded stay on top; the rest follows the// chosen sort. "Récents" is not here: it lives on the profile panel, as in the// official app (it is the account's history, not a library folder).+ val radioOn = com.music.spotui.radio.RadioFeaturePref.on+ val radioName = stringResource(R.string.live_radio_title)val rootPinned = ((entries as? Response.Success)?.data ?: emptyList())- .indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 + (if (hasDownloads) 1 else 0)+ .indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 2 + (if (hasDownloads) 1 else 0) + (if (radioOn) 1 else 0)val allEntries = ((entries as? Response.Success)?.data ?: emptyList()).map {if (it.spotifyId == Api.HomeCache.LIKED_SONGS_ID) it.copy(name = likedName, subtitle = "") else it}.let { list ->@@ -309,6 +311,11 @@ fun LibraryScreen(navController: NavController) {spotifyId = Api.HomeCache.LOCAL_FILES_ID, name = localName, subtitle = "",coverUri = "android.resource://${LocalContext.current.packageName}/drawable/local_files_cover", isPlaylist = true,)+ // Live Radio, right under Local Files — behind the Settings > Playback toggle.+ val radio = com.music.spotui.data.entity.LibraryEntry(+ spotifyId = com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID, name = radioName, subtitle = "",+ coverUri = "android.resource://${LocalContext.current.packageName}/drawable/live_radio_cover", isPlaylist = true,+ )// "Downloaded" right after it, once something was downloaded.val downloads = com.music.spotui.data.entity.LibraryEntry(spotifyId = Api.HomeCache.DOWNLOADS_ID, name = downloadsName, subtitle = "", coverUri = "", isPlaylist = true,@@ -321,7 +328,8 @@ fun LibraryScreen(navController: NavController) {subtitle = localSubtitle, coverUri = "", isPlaylist = true,)}- list.take(at) + local + (if (hasDownloads) listOf(downloads) else emptyList()) + localLists + list.drop(at)+ list.take(at) + local + (if (radioOn) listOf(radio) else emptyList()) ++ (if (hasDownloads) listOf(downloads) else emptyList()) + localLists + list.drop(at)}.let { list ->LibraryOrder.versionLibraryOrder.arrange(list, LibraryOrder.sort, LibraryOrder.custom(LibraryOrder.ROOT), rootPinned)@@ -330,7 +338,8 @@ fun LibraryScreen(navController: NavController) {val myId = com.music.spotui.data.api.ProfileCache.name?.let { com.music.spotui.data.api.ProfileCache.id }val (chipEntries, chipArtists) = com.music.spotui.data.local.LibraryChips.apply(chip, allEntries, followedArtists,- setOf(Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID),+ setOf(Api.HomeCache.LIKED_SONGS_ID, Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID,+ com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID),myId, followedShows, setOf(Api.HomeCache.EPISODES_ID),)val filteredEntries = if (searchQuery.isBlank()) chipEntries@@ -600,6 +609,7 @@ fun LibraryEntryCover(entry: LibraryEntry, modifier: Modifier) {val drawn = when {entry.spotifyId == Api.HomeCache.DOWNLOADS_ID -> R.drawable.downloads_coverentry.spotifyId == Api.HomeCache.LOCAL_FILES_ID || entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> R.drawable.local_files_cover+ entry.spotifyId == com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID -> R.drawable.live_radio_coverentry.isFolder -> R.drawable.folder_coverelse -> 0}@@ -615,6 +625,7 @@ private fun prefetchLibraryEntry(entry: LibraryEntry) = when {LibraryEdits.isPending(entry.spotifyId) -> Unitentry.isFolder || entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) || entry.spotifyId.startsWith(Api.HomeCache.SHOW_PREFIX) -> Unitentry.spotifyId == Api.HomeCache.LOCAL_FILES_ID || entry.spotifyId == Api.HomeCache.DOWNLOADS_ID || entry.spotifyId == Api.HomeCache.EPISODES_ID || entry.spotifyId == Api.HomeCache.NEW_EPISODES_ID -> Unit+ entry.spotifyId == com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID -> Unitentry.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> ContextViewModel.prefetch("liked", "")entry.isPlaylist -> ContextViewModel.prefetch("playlist", entry.spotifyId)else -> ContextViewModel.prefetch("album", entry.spotifyId)@@ -628,6 +639,7 @@ private fun openLibraryEntry(entry: LibraryEntry, navController: NavController)else if (entry.spotifyId.startsWith(Api.HomeCache.SHOW_PREFIX)) navController.navigate(showRoute(entry.spotifyId.removePrefix(Api.HomeCache.SHOW_PREFIX), entry.name))else if (entry.spotifyId == Api.HomeCache.DOWNLOADS_ID) navController.navigate(Routes.Downloads.route)else if (entry.spotifyId == Api.HomeCache.LOCAL_FILES_ID) navController.navigate(Routes.LocalFiles.route)+ else if (entry.spotifyId == com.music.spotui.radio.RadioFeaturePref.LIBRARY_ENTRY_ID) navController.navigate(Routes.LiveRadio.route)else if (entry.spotifyId == Api.HomeCache.LIKED_SONGS_ID) navController.navigate(Routes.Liked.route)else if (entry.spotifyId == Api.HomeCache.EPISODES_ID) navController.navigate(Routes.Episodes.route)else if (entry.spotifyId == Api.HomeCache.NEW_EPISODES_ID) navController.navigate(Routes.NewEpisodes.route)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.ktindex 33326bee..6cb3cf62 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/PlayerScreen.kt@@ -505,6 +505,10 @@ fun PlayerScreen(navController: NavController) {// Immersive: the artwork fills the screen instead of sitting in a square.modifier = if (immersive) Modifier.fillMaxSize()else Modifier.fillMaxWidth().aspectRatio(1f),+ // A Live Radio station is a "queue" of one with nothing to swipe to: without this the+ // artwork could be dragged onto a page falling back to the very same cover.+ // (Read again each time np changes, which a station starting does.)+ userScrollEnabled = com.music.spotui.radio.RadioPlayer.current() == null,) { page ->val cover = when (page) {0 -> np.prev?.coverUridiff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.ktindex eb644ce5..6d5423d4 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SettingsScreen.kt@@ -169,6 +169,13 @@ fun SettingsScreen(navController: NavController) {checked = com.music.spotui.data.preferences.ConnectMirrorPref.on,onChecked = { com.music.spotui.data.preferences.ConnectMirrorPref.set(ctx, it) },)+ // Live Radio: adds the pinned Library row under Local Files (see com.music.spotui.radio).+ OptionRow(+ label = stringResource(R.string.live_radio_settings_title),+ detail = stringResource(R.string.live_radio_settings_detail),+ checked = com.music.spotui.radio.RadioFeaturePref.on,+ onChecked = { com.music.spotui.radio.RadioFeaturePref.set(ctx, it) },+ )// Downloaded songs, played from their files online, played by Spotify too (unheard), as an extension's.OptionRow(label = stringResource(R.string.settings_download_sync_title),diff --git a/base/app/src/main/res/drawable/live_radio_cover.xml b/base/app/src/main/res/drawable/live_radio_cover.xmlnew file mode 100644index 00000000..4b3433b7--- /dev/null+++ b/base/app/src/main/res/drawable/live_radio_cover.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- "Live Radio" cover: a white radio set on blue/teal (Material "radio", Apache 2.0), matching+ the style of local_files_cover.xml / downloads_cover.xml so the pinned folder row looks native. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="64dp" android:height="64dp"+ android:viewportWidth="64" android:viewportHeight="64">+ <path android:fillColor="#FF1C6E7A" android:pathData="M0,0h64v64h-64z" />+ <group android:translateX="12" android:translateY="12" android:scaleX="1.65" android:scaleY="1.65">+ <path android:fillColor="#FFFFFFFF" android:pathData="M3.24,6.15L13,2L14,4L5.6,7.59L3.24,6.15zM20,8H5L3,11.5V20c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2v-10c0,-1.1 -0.9,-2 -2,-2zM7,17c-1.1,0 -2,-0.9 -2,-2s0.9,-2 2,-2 2,0.9 2,2 -0.9,2 -2,2zM20,20H5v-7h15v7z" />+ </group>+</vector>diff --git a/base/app/src/main/res/values-de/radio_strings.xml b/base/app/src/main/res/values-de/radio_strings.xmlnew file mode 100644index 00000000..a2c82153--- /dev/null+++ b/base/app/src/main/res/values-de/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Live Radio</string>+ <string name="live_radio_subtitle">Internetradiosender aus dem kostenlosen Verzeichnis radio-browser.info</string>+ <string name="live_radio_search_hint">Sender suchen</string>+ <string name="live_radio_popular">Beliebte Sender</string>+ <string name="live_radio_search_results">Suchergebnisse</string>+ <string name="live_radio_favorites">Favoriten</string>+ <string name="live_radio_favorite">Zu Favoriten hinzufügen</string>+ <string name="live_radio_unfavorite">Aus Favoriten entfernen</string>+ <string name="live_radio_no_results">Keine Sender gefunden</string>+ <string name="live_radio_error">Das Radioverzeichnis ist nicht erreichbar. Prüfe deine Verbindung und versuche es erneut.</string>+ <string name="live_radio_settings_title">Live Radio</string>+ <string name="live_radio_settings_detail">Fügt deiner Mediathek unter Lokale Dateien einen Live Radio-Ordner hinzu. Suchen gehen an das Verzeichnis radio-browser.info; Logo und Stream eines Senders kommen von dessen eigenem Server.</string>+</resources>diff --git a/base/app/src/main/res/values-el/radio_strings.xml b/base/app/src/main/res/values-el/radio_strings.xmlnew file mode 100644index 00000000..e3598f81--- /dev/null+++ b/base/app/src/main/res/values-el/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Ζωντανό ραδιόφωνο</string>+ <string name="live_radio_subtitle">Διαδικτυακοί ραδιοφωνικοί σταθμοί, από τον δωρεάν κατάλογο radio-browser.info</string>+ <string name="live_radio_search_hint">Αναζήτηση σταθμών</string>+ <string name="live_radio_popular">Δημοφιλείς σταθμοί</string>+ <string name="live_radio_search_results">Αποτελέσματα αναζήτησης</string>+ <string name="live_radio_favorites">Αγαπημένα</string>+ <string name="live_radio_favorite">Προσθήκη στα αγαπημένα</string>+ <string name="live_radio_unfavorite">Αφαίρεση από τα αγαπημένα</string>+ <string name="live_radio_no_results">Δεν βρέθηκαν σταθμοί</string>+ <string name="live_radio_error">Δεν ήταν δυνατή η πρόσβαση στον κατάλογο ραδιοφώνου. Έλεγξε τη σύνδεσή σου και δοκίμασε ξανά.</string>+ <string name="live_radio_settings_title">Ζωντανό ραδιόφωνο</string>+ <string name="live_radio_settings_detail">Προσθέτει έναν φάκελο Ζωντανού ραδιοφώνου στη Βιβλιοθήκη σου, κάτω από τα Τοπικά αρχεία. Οι αναζητήσεις πηγαίνουν στον κατάλογο radio-browser.info· το λογότυπο και η ροή κάθε σταθμού έρχονται από τον δικό του διακομιστή.</string>+</resources>diff --git a/base/app/src/main/res/values-es/radio_strings.xml b/base/app/src/main/res/values-es/radio_strings.xmlnew file mode 100644index 00000000..c61fb86c--- /dev/null+++ b/base/app/src/main/res/values-es/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Radio en directo</string>+ <string name="live_radio_subtitle">Emisoras de radio por internet, del directorio gratuito radio-browser.info</string>+ <string name="live_radio_search_hint">Buscar emisoras</string>+ <string name="live_radio_popular">Emisoras populares</string>+ <string name="live_radio_search_results">Resultados de búsqueda</string>+ <string name="live_radio_favorites">Favoritas</string>+ <string name="live_radio_favorite">Añadir a favoritas</string>+ <string name="live_radio_unfavorite">Quitar de favoritas</string>+ <string name="live_radio_no_results">No se encontraron emisoras</string>+ <string name="live_radio_error">No se pudo contactar con el directorio de radio. Comprueba tu conexión e inténtalo de nuevo.</string>+ <string name="live_radio_settings_title">Radio en directo</string>+ <string name="live_radio_settings_detail">Añade una carpeta Radio en directo a Tu biblioteca, bajo Archivos locales. Las búsquedas van al directorio radio-browser.info; el logo y la emisión de cada emisora vienen de su propio servidor.</string>+</resources>diff --git a/base/app/src/main/res/values-fr/radio_strings.xml b/base/app/src/main/res/values-fr/radio_strings.xmlnew file mode 100644index 00000000..cf3dc80a--- /dev/null+++ b/base/app/src/main/res/values-fr/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Radio en direct</string>+ <string name="live_radio_subtitle">Stations de radio internet, depuis l’annuaire gratuit radio-browser.info</string>+ <string name="live_radio_search_hint">Rechercher des stations</string>+ <string name="live_radio_popular">Stations populaires</string>+ <string name="live_radio_search_results">Résultats de recherche</string>+ <string name="live_radio_favorites">Favoris</string>+ <string name="live_radio_favorite">Ajouter aux favoris</string>+ <string name="live_radio_unfavorite">Retirer des favoris</string>+ <string name="live_radio_no_results">Aucune station trouvée</string>+ <string name="live_radio_error">L’annuaire radio est inaccessible. Vérifiez votre connexion et réessayez.</string>+ <string name="live_radio_settings_title">Radio en direct</string>+ <string name="live_radio_settings_detail">Ajoute un dossier Radio en direct à Votre bibliothèque, sous Fichiers locaux. Les recherches vont à l’annuaire radio-browser.info ; le logo et le flux de chaque station viennent de son propre serveur.</string>+</resources>diff --git a/base/app/src/main/res/values-it/radio_strings.xml b/base/app/src/main/res/values-it/radio_strings.xmlnew file mode 100644index 00000000..d00eadf9--- /dev/null+++ b/base/app/src/main/res/values-it/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Radio dal vivo</string>+ <string name="live_radio_subtitle">Stazioni radio internet, dal catalogo gratuito radio-browser.info</string>+ <string name="live_radio_search_hint">Cerca stazioni</string>+ <string name="live_radio_popular">Stazioni popolari</string>+ <string name="live_radio_search_results">Risultati di ricerca</string>+ <string name="live_radio_favorites">Preferiti</string>+ <string name="live_radio_favorite">Aggiungi ai preferiti</string>+ <string name="live_radio_unfavorite">Rimuovi dai preferiti</string>+ <string name="live_radio_no_results">Nessuna stazione trovata</string>+ <string name="live_radio_error">Impossibile raggiungere il catalogo radio. Controlla la connessione e riprova.</string>+ <string name="live_radio_settings_title">Radio dal vivo</string>+ <string name="live_radio_settings_detail">Aggiunge una cartella Radio dal vivo a La tua libreria, sotto File locali. Le ricerche vanno alla directory radio-browser.info; logo e flusso di ogni stazione arrivano dal suo server.</string>+</resources>diff --git a/base/app/src/main/res/values-pl/radio_strings.xml b/base/app/src/main/res/values-pl/radio_strings.xmlnew file mode 100644index 00000000..0ad43965--- /dev/null+++ b/base/app/src/main/res/values-pl/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Radio na żywo</string>+ <string name="live_radio_subtitle">Stacje radiowe z internetu, z darmowego katalogu radio-browser.info</string>+ <string name="live_radio_search_hint">Szukaj stacji</string>+ <string name="live_radio_popular">Popularne stacje</string>+ <string name="live_radio_search_results">Wyniki wyszukiwania</string>+ <string name="live_radio_favorites">Ulubione</string>+ <string name="live_radio_favorite">Dodaj do ulubionych</string>+ <string name="live_radio_unfavorite">Usuń z ulubionych</string>+ <string name="live_radio_no_results">Nie znaleziono stacji</string>+ <string name="live_radio_error">Nie można połączyć się z katalogiem radiowym. Sprawdź połączenie i spróbuj ponownie.</string>+ <string name="live_radio_settings_title">Radio na żywo</string>+ <string name="live_radio_settings_detail">Dodaje folder Radio na żywo do Twojej biblioteki, pod Plikami lokalnymi. Wyszukiwania trafiają do katalogu radio-browser.info; logo i strumień stacji pochodzą z jej własnego serwera.</string>+</resources>diff --git a/base/app/src/main/res/values-pt-rBR/radio_strings.xml b/base/app/src/main/res/values-pt-rBR/radio_strings.xmlnew file mode 100644index 00000000..1ec2f417--- /dev/null+++ b/base/app/src/main/res/values-pt-rBR/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Rádio ao vivo</string>+ <string name="live_radio_subtitle">Estações de rádio pela internet, do diretório gratuito radio-browser.info</string>+ <string name="live_radio_search_hint">Pesquisar estações</string>+ <string name="live_radio_popular">Estações populares</string>+ <string name="live_radio_search_results">Resultados da pesquisa</string>+ <string name="live_radio_favorites">Favoritas</string>+ <string name="live_radio_favorite">Adicionar aos favoritos</string>+ <string name="live_radio_unfavorite">Remover dos favoritos</string>+ <string name="live_radio_no_results">Nenhuma estação encontrada</string>+ <string name="live_radio_error">Não foi possível acessar o diretório de rádio. Verifique sua conexão e tente novamente.</string>+ <string name="live_radio_settings_title">Rádio ao vivo</string>+ <string name="live_radio_settings_detail">Adiciona uma pasta Rádio ao vivo à Sua Biblioteca, abaixo de Arquivos locais. As pesquisas vão para o diretório radio-browser.info; o logo e o stream de cada estação vêm do servidor dela.</string>+</resources>diff --git a/base/app/src/main/res/values-pt-rPT/radio_strings.xml b/base/app/src/main/res/values-pt-rPT/radio_strings.xmlnew file mode 100644index 00000000..7df6806e--- /dev/null+++ b/base/app/src/main/res/values-pt-rPT/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Rádio ao vivo</string>+ <string name="live_radio_subtitle">Estações de rádio pela internet, do diretório gratuito radio-browser.info</string>+ <string name="live_radio_search_hint">Pesquisar estações</string>+ <string name="live_radio_popular">Estações populares</string>+ <string name="live_radio_search_results">Resultados da pesquisa</string>+ <string name="live_radio_favorites">Favoritas</string>+ <string name="live_radio_favorite">Adicionar aos favoritos</string>+ <string name="live_radio_unfavorite">Remover dos favoritos</string>+ <string name="live_radio_no_results">Nenhuma estação encontrada</string>+ <string name="live_radio_error">Não foi possível contactar o diretório de rádio. Verifica a tua ligação e tenta novamente.</string>+ <string name="live_radio_settings_title">Rádio ao vivo</string>+ <string name="live_radio_settings_detail">Adiciona uma pasta Rádio ao vivo à tua Biblioteca, em Ficheiros locais. As pesquisas vão para o diretório radio-browser.info; o logótipo e a emissão de cada estação vêm do servidor dela.</string>+</resources>diff --git a/base/app/src/main/res/values-pt/radio_strings.xml b/base/app/src/main/res/values-pt/radio_strings.xmlnew file mode 100644index 00000000..1ec2f417--- /dev/null+++ b/base/app/src/main/res/values-pt/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Rádio ao vivo</string>+ <string name="live_radio_subtitle">Estações de rádio pela internet, do diretório gratuito radio-browser.info</string>+ <string name="live_radio_search_hint">Pesquisar estações</string>+ <string name="live_radio_popular">Estações populares</string>+ <string name="live_radio_search_results">Resultados da pesquisa</string>+ <string name="live_radio_favorites">Favoritas</string>+ <string name="live_radio_favorite">Adicionar aos favoritos</string>+ <string name="live_radio_unfavorite">Remover dos favoritos</string>+ <string name="live_radio_no_results">Nenhuma estação encontrada</string>+ <string name="live_radio_error">Não foi possível acessar o diretório de rádio. Verifique sua conexão e tente novamente.</string>+ <string name="live_radio_settings_title">Rádio ao vivo</string>+ <string name="live_radio_settings_detail">Adiciona uma pasta Rádio ao vivo à Sua Biblioteca, abaixo de Arquivos locais. As pesquisas vão para o diretório radio-browser.info; o logo e o stream de cada estação vêm do servidor dela.</string>+</resources>diff --git a/base/app/src/main/res/values-ru/radio_strings.xml b/base/app/src/main/res/values-ru/radio_strings.xmlnew file mode 100644index 00000000..644d88d2--- /dev/null+++ b/base/app/src/main/res/values-ru/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">Прямой эфир радио</string>+ <string name="live_radio_subtitle">Интернет-радиостанции из бесплатного каталога radio-browser.info</string>+ <string name="live_radio_search_hint">Поиск станций</string>+ <string name="live_radio_popular">Популярные станции</string>+ <string name="live_radio_search_results">Результаты поиска</string>+ <string name="live_radio_favorites">Избранное</string>+ <string name="live_radio_favorite">Добавить в избранное</string>+ <string name="live_radio_unfavorite">Удалить из избранного</string>+ <string name="live_radio_no_results">Станции не найдены</string>+ <string name="live_radio_error">Не удалось подключиться к каталогу радиостанций. Проверьте соединение и повторите попытку.</string>+ <string name="live_radio_settings_title">Радио в эфире</string>+ <string name="live_radio_settings_detail">Добавляет папку «Радио в эфире» в вашу медиатеку, рядом с Локальными файлами. Поиск идёт в каталог radio-browser.info; логотип и поток станции загружаются с её собственного сервера.</string>+</resources>diff --git a/base/app/src/main/res/values-zh/radio_strings.xml b/base/app/src/main/res/values-zh/radio_strings.xmlnew file mode 100644index 00000000..d00a4128--- /dev/null+++ b/base/app/src/main/res/values-zh/radio_strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="live_radio_title">实时电台</string>+ <string name="live_radio_subtitle">来自免费电台目录 radio-browser.info 的网络电台</string>+ <string name="live_radio_search_hint">搜索电台</string>+ <string name="live_radio_popular">热门电台</string>+ <string name="live_radio_search_results">搜索结果</string>+ <string name="live_radio_favorites">收藏</string>+ <string name="live_radio_favorite">添加到收藏</string>+ <string name="live_radio_unfavorite">从收藏中移除</string>+ <string name="live_radio_no_results">未找到电台</string>+ <string name="live_radio_error">无法连接电台目录,请检查网络连接后重试。</string>+ <string name="live_radio_settings_title">实时电台</string>+ <string name="live_radio_settings_detail">在“你的资料库”中本地文件下方添加一个实时电台文件夹。搜索会发送到 radio-browser.info 目录;每个电台的标志和音频流来自该电台自己的服务器。</string>+</resources>diff --git a/base/app/src/main/res/values/radio_strings.xml b/base/app/src/main/res/values/radio_strings.xmlnew file mode 100644index 00000000..6cf7276a--- /dev/null+++ b/base/app/src/main/res/values/radio_strings.xml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Live Radio (radio/ package): internet radio via the free radio-browser.info directory. -->+<resources>+ <string name="live_radio_title">Live Radio</string>+ <string name="live_radio_subtitle">Internet radio stations, from the free radio-browser.info directory</string>+ <string name="live_radio_search_hint">Search stations</string>+ <string name="live_radio_popular">Popular stations</string>+ <string name="live_radio_search_results">Search results</string>+ <string name="live_radio_favorites">Favorites</string>+ <string name="live_radio_favorite">Add to favorites</string>+ <string name="live_radio_unfavorite">Remove from favorites</string>+ <string name="live_radio_no_results">No stations found</string>+ <string name="live_radio_error">The radio directory could not be reached. Check your connection and try again.</string>+ <string name="live_radio_settings_title">Live Radio</string>+ <string name="live_radio_settings_detail">Adds a Live Radio folder to Your Library, under Local Files. Searches go to the radio-browser.info directory; each station\'s logo and stream come from that station\'s own server.</string>+</resources>diff --git a/base/app/src/test/java/com/music/spotui/radio/RadioFavoritesStoreTest.kt b/base/app/src/test/java/com/music/spotui/radio/RadioFavoritesStoreTest.ktnew file mode 100644index 00000000..03a6cb1f--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/radio/RadioFavoritesStoreTest.kt@@ -0,0 +1,72 @@+package com.music.spotui.radio++import org.json.JSONArray+import org.json.JSONObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.File+import java.nio.file.Files++class RadioFavoritesStoreTest {+ private fun station(id: String, url: String = "https://radio.example.com/$id.mp3") = RadioStation(+ stationUuid = id, name = "Station $id", streamUrl = url, homepage = "https://radio.example.com",+ favicon = "", tags = listOf("jazz", "news"), country = "France", countryCode = "FR", language = "french",+ codec = "MP3", bitrateKbps = 128, votes = 3, clickCount = 4, lastCheckOk = true,+ )++ private fun file() = File(Files.createTempDirectory("radio").toFile(), "radio_favorites.json")++ private fun ids() = RadioFavoritesStore.list().map { it.stationUuid }++ @Test fun favoritesAreReadBackNewestFirst() {+ val f = file()+ RadioFavoritesStore.load(f)+ RadioFavoritesStore.add(station("a"), now = 1_000)+ RadioFavoritesStore.add(station("c"), now = 3_000)+ RadioFavoritesStore.add(station("b"), now = 2_000)+ RadioFavoritesStore.load(f)+ assertEquals(listOf("c", "b", "a"), ids())+ assertEquals(station("a"), RadioFavoritesStore.favorites["a"]?.station)+ }++ @Test fun aRemovedFavoriteStaysRemoved() {+ val f = file()+ RadioFavoritesStore.load(f)+ RadioFavoritesStore.add(station("a"), now = 1_000)+ RadioFavoritesStore.add(station("b"), now = 2_000)+ RadioFavoritesStore.toggle(station("a"))+ RadioFavoritesStore.load(f)+ assertEquals(listOf("b"), ids())+ assertFalse(RadioFavoritesStore.isFavorite("a"))+ }++ @Test fun aStationThatCannotPlayIsNeverKept() {+ RadioFavoritesStore.load(file())+ RadioFavoritesStore.add(station("cleartext", "http://radio.example.com/live"))+ assertTrue(ids().isEmpty())+ // One in the file all the same (written before the check): left out, the others kept.+ val f = file()+ val saved = JSONArray()+ .put(JSONObject().put("uuid", "x").put("url", "http://radio.example.com/x").put("added", 9))+ .put(JSONObject().put("uuid", "y").put("url", "https://radio.example.com/y").put("added", 5))+ .put(JSONObject().put("uuid", "z").put("url", "https://radio.example.com/z.m3u8").put("added", 7))+ .put(JSONObject().put("name", "no uuid").put("url", "https://radio.example.com/n"))+ f.writeText(JSONObject().put("version", 1).put("favorites", saved).toString())+ RadioFavoritesStore.load(f)+ assertEquals(listOf("y"), ids())+ }++ @Test fun aDamagedFileOrAnotherVersionReadsAsNoFavorite() {+ val f = file()+ RadioFavoritesStore.load(f)+ RadioFavoritesStore.add(station("a"))+ f.writeText("{oops")+ RadioFavoritesStore.load(f)+ assertTrue(ids().isEmpty())+ f.writeText(JSONObject().put("version", 2).put("favorites", JSONArray()).toString())+ RadioFavoritesStore.load(f)+ assertTrue(ids().isEmpty())+ }+}diff --git a/base/app/src/test/java/com/music/spotui/radio/RadioStationFilterTest.kt b/base/app/src/test/java/com/music/spotui/radio/RadioStationFilterTest.ktnew file mode 100644index 00000000..bf7a7cb4--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/radio/RadioStationFilterTest.kt@@ -0,0 +1,44 @@+package com.music.spotui.radio++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class RadioStationFilterTest {+ @Test fun onlyHttpsStreamsThatAreNotHlsPlay() {+ assertTrue(RadioBrowserApi.playable("https://icecast.example.com/live.mp3"))+ assertTrue(RadioBrowserApi.playable("HTTPS://icecast.example.com:8443/stream"))+ assertFalse(RadioBrowserApi.playable("http://icecast.example.com/live.mp3"))+ assertFalse(RadioBrowserApi.playable("https://cdn.example.com/live/index.m3u8"))+ assertFalse(RadioBrowserApi.playable("https://cdn.example.com/live/master.M3U8?token=1"))+ assertFalse(RadioBrowserApi.playable("https://cdn.example.com/live", hls = true))+ assertFalse(RadioBrowserApi.playable("rtsp://cdn.example.com/live"))+ assertFalse(RadioBrowserApi.playable("https:///no-host"))+ assertFalse(RadioBrowserApi.playable(""))+ }++ @Test fun theDirectoryListKeepsOnlyPlayableStations() {+ val list = Json.parseToJsonElement(+ """+ [+ {"stationuuid": "a", "name": "A", "url": "http://a.example.com/raw", "url_resolved": "https://a.example.com/live", "hls": 0},+ {"stationuuid": "b", "name": "B", "url": "https://b.example.com/raw", "url_resolved": "http://b.example.com/live"},+ {"stationuuid": "c", "name": "C", "url": "https://c.example.com/live", "url_resolved": ""},+ {"stationuuid": "d", "name": "D", "url_resolved": "https://d.example.com/live", "hls": 1},+ {"stationuuid": "e", "name": "E", "url_resolved": "https://e.example.com/playlist.m3u8"},+ "not a station"+ ]+ """,+ ).jsonArray+ val kept = RadioBrowserApi.stations(list)+ assertEquals(listOf("a", "c"), kept.map { it.stationUuid })+ assertEquals("https://a.example.com/live", kept[0].streamUrl)+ }++ @Test fun theCuratedStationsAllPlay() {+ assertTrue(RadioBrowserApi.curatedPopular.all { RadioBrowserApi.playable(it.streamUrl) })+ }+}