Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
2.0.2-beta.6: update popup that shows promptly and stays reachable in About, Settings tabs, extensions Refresh that really refreshes, extensions from GitLab and Codeberg, Android Auto playback that keeps running, real crossfade for extension and downloaded songs, sharp covers in notification, lock screen and Auto (crash #77), Immersive queue reorder and uncut source line
kota-zoc8bcdceda059
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea44ff1f..509d1985 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@Each release on GitHub shows its section below. The app shows it too when it offers the update. Every detail: [docs/CHANGELOG-full.md](docs/CHANGELOG-full.md).+## 2.0.2-beta.6++- 🔔 **Update popup fixed**: it shows as soon as the app knows about the update, a stray tap no longer closes it, and after "Later" the update stays in Settings, About.+- 🗂️ **Settings in tabs** (classic look): Playback, Downloads, Appearance, Extensions, About. About shows your version and the update when there is one.+- 🧩 **Extensions**: Refresh really refreshes now (no stale cache, real errors, update check of installed extensions). Extensions are also found and installed from **GitLab** and **Codeberg** (topic `myspoti-extension`).+- 🚗 **Android Auto**: playback started from the car no longer stops after a few seconds, and the car's buttons keep working.+- 🔀 **Real crossfade** for songs played from extensions, downloads and device files (Settings, Playback). Spotify streams keep their fade out and in.+- 🖼️ **Sharp covers everywhere**: notification, lock screen, Android Auto, share card. Fixes a crash at playback start (#77).+- ✨ **Immersive look**: drag songs to reorder the queue, and the "playing from" source line is no longer cut off.+## 2.0.2-beta.5- ✨ **New Immersive look** (optional, Apple-Music-like): glass tab bar and mini player that fold away when you scroll, animated player and lyrics, grouped Settings, glass sheets (Spotify Connect, queue, quality…). Offered at the first open after the update; switch any time in Settings, Display. Classic stays the default.diff --git a/README.md b/README.mdindex 0fa63e85..8d732a89 100644--- a/README.md+++ b/README.md@@ -160,6 +160,7 @@ Every push builds and tests on GitHub Actions. A `v*` tag publishes a signed APK## Credits- UI derived from [Spotui](https://github.com/Spotui/Spotui) / [Metrolist](https://github.com/MetrolistGroup/Metrolist) (GPL-3.0); Spotui also gave the DASH-to-FLAC remux.+- The Immersive look (player, lyrics, queue, glass tab bar and pages) is ported from [BitChord](https://github.com/kushagrasinghx/BitChord) (GPL-3.0-or-later).- [NewPipeExtractor](https://github.com/TeamNewPipe/NewPipeExtractor) (GPL-3.0): music videos.- Lyrics: [LRCLIB](https://lrclib.net), LyricsPlus, lrc.red, Kugou and NetEase; song meanings: [Genius](https://genius.com).- [Material Icons](https://github.com/google/material-design-icons) (Apache 2.0) and the [Manrope](https://github.com/googlefonts/manrope) font (SIL OFL 1.1, see `base/licenses/`).diff --git a/base/app/src/main/java/com/music/spotui/App.kt b/base/app/src/main/java/com/music/spotui/App.ktindex fed3f163..881ef879 100644--- a/base/app/src/main/java/com/music/spotui/App.kt+++ b/base/app/src/main/java/com/music/spotui/App.kt@@ -274,7 +274,10 @@ private fun SupportDialog(supporter: Boolean, onSupport: () -> Unit, onSponsor:}}-/** "New version" dialog: checked a few seconds after launch (not on the startup path). */+/**+ * "New version" dialog: checked at launch (off the UI thread), shown as soon as the answer is+ * known. "Later" hides it; Settings > About offers the update again.+ */@Composableprivate fun UpdatePrompt() {val context = androidx.compose.ui.platform.LocalContext.current@@ -282,7 +285,7 @@ private fun UpdatePrompt() {androidx.compose.runtime.LaunchedEffect(Unit) {// Turned off in Settings: no check at launch. The manual check there still asks.if (!com.music.spotui.data.preferences.AutoUpdateCheckPref.on) return@LaunchedEffect- kotlinx.coroutines.delay(5_000)+ // At once: the request runs on the IO dispatcher, nothing waits for it.release = com.music.spotui.data.api.UpdateChecker.check(context)}updateCardOpen.value = release != null@@ -348,7 +351,11 @@ private fun UpdateDialog(version: String, notes: String, status: String?, progress: Float?, button: String,onUpdate: () -> Unit, onLater: () -> Unit,) {- androidx.compose.ui.window.Dialog(onDismissRequest = onLater) {+ // Only the buttons close it: a touch outside must not (the back gesture still means "Later").+ androidx.compose.ui.window.Dialog(+ onDismissRequest = onLater,+ properties = androidx.compose.ui.window.DialogProperties(dismissOnClickOutside = false),+ ) {androidx.compose.foundation.layout.Column(horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally,modifier = Modifierdiff --git a/base/app/src/main/java/com/music/spotui/data/api/UpdateChecker.kt b/base/app/src/main/java/com/music/spotui/data/api/UpdateChecker.ktindex 4fc6dfcb..522aeda0 100644--- a/base/app/src/main/java/com/music/spotui/data/api/UpdateChecker.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/UpdateChecker.kt@@ -22,12 +22,16 @@ object UpdateChecker {private const val INTERVAL_MS = 3 * 3_600_000Lprivate val http by lazy { OkHttpClient.Builder().callTimeout(10, TimeUnit.SECONDS).addInterceptor(com.music.spotui.data.DataSaver.interceptor).build() }- suspend fun check(context: Context): Release? = withContext(Dispatchers.IO) {+ /**+ * [manual]: asked from Settings. A release dismissed with "Later" is then offered again+ * (the launch check stays quiet about it).+ */+ suspend fun check(context: Context, manual: Boolean = false): Release? = withContext(Dispatchers.IO) {val repo = BuildConfig.UPDATE_REPOif (repo.isBlank()) return@withContext nullval prefs = context.getSharedPreferences("updates", Context.MODE_PRIVATE)val now = System.currentTimeMillis()- if (now - prefs.getLong("checked_at", 0L) < INTERVAL_MS) return@withContext pending(prefs)+ if (now - prefs.getLong("checked_at", 0L) < INTERVAL_MS) return@withContext pending(prefs, manual)val release = runCatching {// Stable builds follow "latest", which never includes pre-releases. A beta build// also takes the newer betas, then the release they lead to.@@ -46,14 +50,18 @@ object UpdateChecker {prefs.edit().putLong("checked_at", now).putString("version", release?.version).putString("url", release?.pageUrl).putString("notes", release?.notes).putString("apk", release?.apkUrl).apply()- pending(prefs)+ pending(prefs, manual)}- /** The latest release known, if newer than this build and not dismissed. */- private fun pending(prefs: android.content.SharedPreferences): Release? {+ /** The newer release last seen, dismissed or not (no request): what Settings > About shows. */+ fun known(context: Context): Release? =+ pending(context.getSharedPreferences("updates", Context.MODE_PRIVATE), true)++ /** The latest release known, if newer than this build and (unless [manual]) not dismissed. */+ private fun pending(prefs: android.content.SharedPreferences, manual: Boolean = false): Release? {val version = prefs.getString("version", null) ?: return nullval url = prefs.getString("url", null) ?: return null- if (prefs.getString("dismissed", null) == version) return null+ if (!manual && prefs.getString("dismissed", null) == version) return nullreturn Release(version, url, prefs.getString("notes", null).orEmpty(), prefs.getString("apk", null).orEmpty()).takeIf { isNewer(version, BuildConfig.VERSION_NAME) }}diff --git a/base/app/src/main/java/com/music/spotui/di/CrossfadeRamp.kt b/base/app/src/main/java/com/music/spotui/di/CrossfadeRamp.ktnew file mode 100644index 00000000..735c866d--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/CrossfadeRamp.kt@@ -0,0 +1,25 @@+package com.music.spotui.di++/**+ * Timing and volume curve of the real (overlapping) crossfade of [LocalPlayer], kept pure so it+ * is tested off-device. Equal-power: the two gains' squares add up to 1, so the loudness stays+ * level through the overlap.+ */+object CrossfadeRamp {+ /** The overlap for a song of [durationMs] and a setting of [seconds]: never over half the song. */+ fun fadeMs(seconds: Int, durationMs: Long): Long =+ if (seconds <= 0 || durationMs <= 0) 0L else minOf(seconds * 1000L, durationMs / 2)++ /** The fade starts once [remainingMs] of the song is left. */+ fun shouldStart(seconds: Int, durationMs: Long, positionMs: Long): Boolean {+ val fade = fadeMs(seconds, durationMs)+ return fade > 0 && positionMs >= 0 && durationMs - positionMs <= fade+ }++ /** Progress 0..1 of a fade of [fadeMs] when the incoming song is at [incomingPositionMs]. */+ fun progress(incomingPositionMs: Long, fadeMs: Long): Float =+ if (fadeMs <= 0) 1f else (incomingPositionMs.toFloat() / fadeMs).coerceIn(0f, 1f)++ fun incomingGain(t: Float): Float = Math.sin(t.coerceIn(0f, 1f) * Math.PI / 2).toFloat()+ fun outgoingGain(t: Float): Float = Math.cos(t.coerceIn(0f, 1f) * Math.PI / 2).toFloat()+}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 32a8f8bc..c816f9c4 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@@ -10,6 +10,7 @@ import androidx.media3.common.MediaMetadataimport androidx.media3.common.Playerimport androidx.media3.exoplayer.ExoPlayerimport com.music.spotui.data.local.LocalTrack+import com.music.spotui.data.preferences.CrossfadePref/*** Plays the device's own audio files (Local Files). While it plays, the Spotify engine is@@ -44,13 +45,18 @@ object LocalPlayer {private var exo: ExoPlayer? = null@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)- private fun player(): ExoPlayer = exo ?: ExoPlayer.Builder(Graph.app)- .setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(), true)- .setHandleAudioBecomingNoisy(true)+ private fun build(main: Boolean): ExoPlayer = ExoPlayer.Builder(Graph.app)+ // The fading-out copy of a crossfade owns neither the audio focus nor the noisy-audio pause:+ // the main player has them and the fade follows its play state.+ .setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(), main)+ .setHandleAudioBecomingNoisy(main)// Downloaded songs are encrypted files: the player reads them through the decrypting source..setMediaSourceFactory(androidx.media3.exoplayer.source.DefaultMediaSourceFactory(com.music.spotui.data.offline.OfflineCrypto.Factory(Graph.app)).setLoadErrorHandlingPolicy(NoAudioNotRetried))- .build().also { p ->+ .build()++ @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)+ private fun player(): ExoPlayer = exo ?: build(true).also { p ->p.addListener(object : Player.Listener {override fun onEvents(player: Player, events: Player.Events) = publish()@@ -59,17 +65,26 @@ object LocalPlayer {log("state ${stateName(state)} at ${p.currentPosition} ms, item ${p.currentMediaItemIndex + 1}/${p.mediaItemCount}")if (state == Player.STATE_ENDED) atEnd(p)}- override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) =+ override fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int) {log("playWhenReady $playWhenReady (${PLAY_WHEN_READY_REASONS.getOrElse(reason - 1) { "reason $reason" }})")- override fun onIsPlayingChanged(isPlaying: Boolean) =+ // A pause (or a lost focus) during a fade stops the fading-out song too.+ outgoing?.playWhenReady = playWhenReady+ }+ override fun onIsPlayingChanged(isPlaying: Boolean) {log("isPlaying $isPlaying at ${p.currentPosition} ms")+ if (isPlaying) tick.run()+ }override fun onPlaybackSuppressionReasonChanged(reason: Int) =log("suppressed: ${if (reason == Player.PLAYBACK_SUPPRESSION_REASON_NONE) "no" else "reason $reason"}")// The next song an extension streams is asked for as soon as this one starts: it then// starts at once instead of waiting for the extension when this one ends.// The last one starting asks what goes on after it (see continueIfLast).- override fun onMediaItemTransition(mediaItem: androidx.media3.common.MediaItem?, reason: Int) { prefetchNext(p); continueIfLast(p) }+ override fun onMediaItemTransition(mediaItem: androidx.media3.common.MediaItem?, reason: Int) {+ // Anything but the transition the fade itself makes (a skip, a tap in the queue) ends the fade.+ if (!startingFade) endFade()+ prefetchNext(p); continueIfLast(p)+ }// A song whose audio an extension did not give or that would not play (audio-source// hook) is never skipped silently: Spotify plays it, where it was, and goes on.@@ -152,6 +167,7 @@ object LocalPlayer {listName = context ?: Graph.app.getString(app.myspoti.engine.R.string.local_files_title)listUri = contextUriactive.value = true+ endFade()val p = player()p.shuffleModeEnabled = falsep.setMediaItems(list.map(::item), index.coerceIn(0, list.lastIndex), startMs.coerceAtLeast(0L))@@ -164,6 +180,7 @@ object LocalPlayer {/** Back to Spotify: stop and forget the local queue. */fun stop() {if (!active.value) return+ endFade()active.value = falseforgetRadio(); continues = falseexo?.let { it.stop(); it.clearMediaItems() }@@ -172,6 +189,88 @@ object LocalPlayer {SongPlayer.restoreEngineQueue()}++ // ── Crossfade (real overlap: every song of this player is a local-player one) ──+ // Near the end of a song, a second player takes over its last seconds (fading out) while the+ // main player moves on to the next item at once (fading in). The main player thus sees an+ // ordinary track change: session, notification, queue and play counting are untouched.+ private var outgoing: ExoPlayer? = null+ private var fadeMs = 0L+ private var startingFade = false+ private var preparingFade = false+ /** The item index whose end must not fade (the user sought into its tail, or the fade failed). */+ private var noFadeFor = -1+ private val handler = android.os.Handler(android.os.Looper.getMainLooper())++ private val tick: Runnable = object : Runnable {+ override fun run() {+ handler.removeCallbacks(this)+ val p = exo ?: return+ if (outgoing != null) {+ val t = CrossfadeRamp.progress(p.currentPosition, fadeMs)+ p.volume = CrossfadeRamp.incomingGain(t)+ outgoing?.volume = CrossfadeRamp.outgoingGain(t)+ if (t >= 1f) endFade() else handler.postDelayed(this, 40)+ return+ }+ if (!p.isPlaying) return+ if (!preparingFade && p.currentMediaItemIndex != noFadeFor && canFade(p) &&+ CrossfadeRamp.shouldStart(CrossfadePref.seconds, p.duration.takeIf { it > 0 } ?: 0L, p.currentPosition)) beginFade(p)+ handler.postDelayed(this, 200)+ }+ }++ private fun canFade(p: ExoPlayer): Boolean =+ CrossfadePref.seconds > 0 && p.repeatMode != Player.REPEAT_MODE_ONE && p.nextMediaItemIndex != C.INDEX_UNSET &&+ p.currentMediaItem != null && p.playWhenReady++ private fun beginFade(p: ExoPlayer) {+ val item = p.currentMediaItem ?: return+ val index = p.currentMediaItemIndex+ val remaining = (p.duration - p.currentPosition).coerceAtLeast(0)+ val fade = minOf(CrossfadeRamp.fadeMs(CrossfadePref.seconds, p.duration), remaining)+ if (fade < 500) return+ preparingFade = true+ val out = build(false)+ out.volume = 1f+ // The copy starts a little ahead of the main player: it is heard once it is ready.+ out.setMediaItem(item, p.currentPosition + 300)+ out.addListener(object : Player.Listener {+ override fun onPlaybackStateChanged(state: Int) {+ if (state != Player.STATE_READY || exo == null) return+ out.removeListener(this)+ preparingFade = false+ val main = exo ?: return out.release()+ if (!active.value || main.currentMediaItemIndex != index || !main.playWhenReady || !canFade(main)) return out.release()+ outgoing = out; fadeMs = fade+ out.play()+ startingFade = true+ main.volume = 0f+ main.seekToNextMediaItem()+ startingFade = false+ log("crossfade $fade ms")+ tick.run()+ }+ override fun onPlayerError(error: androidx.media3.common.PlaybackException) {+ // Could not start the copy: this song ends as usual.+ preparingFade = false; noFadeFor = index; out.release()+ }+ })+ out.prepare()+ // Not ready in time: no fade for this song.+ handler.postDelayed({+ if (preparingFade && outgoing == null) { preparingFade = false; noFadeFor = index; out.release() }+ }, 1500)+ }++ /** Ends a fade (done, or interrupted by a skip/seek/stop): the copy goes, the main player is at full volume. */+ private fun endFade() {+ handler.removeCallbacks(tick)+ outgoing?.let { it.stop(); it.release() }+ outgoing = null+ exo?.let { it.volume = 1f; if (it.isPlaying) handler.postDelayed(tick, 200) }+ }+/** A player stopped by an error (idle) is prepared again first: a play alone does nothing there. */fun resume() {val p = exo ?: return@@ -180,18 +279,27 @@ object LocalPlayer {}fun pause() { exo?.pause() }fun next() {+ endFade()exo?.let {if (it.hasNextMediaItem()) { com.music.spotui.extensions.Extensions.skipAsked("forward"); it.seekToNextMediaItem() }else if (atEnd(it)) com.music.spotui.extensions.Extensions.skipAsked("forward")}}fun previous() {+ endFade()exo?.let {if (it.currentPosition > 3000 || !it.hasPreviousMediaItem()) it.seekTo(0)else { com.music.spotui.extensions.Extensions.skipAsked("backward"); it.seekToPreviousMediaItem() }}}- fun seekTo(ms: Long) { exo?.seekTo(ms) }+ fun seekTo(ms: Long) {+ endFade()+ exo?.let { p ->+ // A seek into the tail of a song is the user's choice: that song then ends as usual.+ if (CrossfadeRamp.shouldStart(CrossfadePref.seconds, duration(), ms)) noFadeFor = p.currentMediaItemIndex+ p.seekTo(ms)+ }+ }/*** Shuffle reorders the songs after the current one (and off puts the list's order back),* so the queue shown is the order that really plays and can be edited like any list.@@ -228,6 +336,7 @@ object LocalPlayer {fun skipTo(index: Int) {val p = exo ?: returnif (index !in tracks.indices) return+ endFade()val (order, at) = LocalQueueOrder.skip(tracks.toList(), p.currentMediaItemIndex, index, isQueued)if (order != tracks) arrange(order)p.seekTo(at, 0L); p.play()diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.ktindex d5ac0b6c..d63db178 100644--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionStore.kt@@ -4,6 +4,7 @@ import app.myspoti.extensions.Catalogimport app.myspoti.extensions.Discoveryimport app.myspoti.extensions.ExtensionExceptionimport app.myspoti.extensions.GitHubAuth+import app.myspoti.extensions.CodeHostimport app.myspoti.extensions.Manifestimport app.myspoti.extensions.Ratingimport app.myspoti.extensions.Ranking@@ -51,12 +52,17 @@ object ExtensionStore {val urls = sources(userUrls)_repos.value = _repos.value.filterKeys { it in urls || it == Discovery.SOURCE }discover(force)+ if (force) scope.launch {+ // Refresh also re-reads the kill switch and looks for newer versions of the installed GitHub extensions.+ runCatching { ExtensionUpdates.refreshBlocks(force = true) }+ Extensions.registry.value.extensions.filter { it.origin != null }.forEach { runCatching { ExtensionUpdates.check(it.id, manual = false) } }+ }urls.forEach { url ->val now = _repos.value[url]if (now?.loading == true || (!force && now?.catalog != null)) return@forEach_repos.value = _repos.value + (url to (now ?: Repo(url)).copy(loading = true, error = null))scope.launch {- val r = runCatching { Extensions.catalog(url) }+ val r = runCatching { Extensions.catalog(url, fresh = force) }_repos.value = _repos.value + (url to Repo(url, r.getOrNull() ?: now?.catalog, r.exceptionOrNull()?.let { it.message ?: it.toString() }))}}@@ -87,8 +93,7 @@ object ExtensionStore {val downloads = MutableStateFlow<Map<String, Long>>(emptyMap())/**- * The repositories with the topic: one search (cached 6 hours, [force]: Refresh, still- * within the cache's age for GitHub's sake), their manifests from raw.githubusercontent.com+ * The repositories with the topic: one search (cached 6 hours; [force]: Refresh, bypasses the cache), their manifests from the hosts' raw file addresses* (8 at a time, cached alike), one search for the ratings issues. A repository whose manifest* is missing or refused is left out.*/@@ -97,26 +102,35 @@ object ExtensionStore {if (now?.loading == true || (!force && now?.catalog != null)) return_repos.value = _repos.value + (Discovery.SOURCE to (now ?: Repo(Discovery.SOURCE)).copy(loading = true, error = null))scope.launch {+ val failed = mutableListOf<String>()val r = runCatching {- val found = Discovery.parseSearch(ExtensionUpdates.cached(Discovery.SEARCH_URL, Discovery.CACHE_MS, MAX_SEARCH) ?: throw ExtensionException("GitHub search answered 404"))+ // One search per host: one failing (offline host, rate limit) leaves the others' results.+ val found = CodeHost.entries.flatMap { h ->+ runCatching {+ Discovery.parse(h, ExtensionUpdates.cached(Discovery.searchUrl(h), Discovery.CACHE_MS, MAX_SEARCH, force) ?: throw ExtensionException("${h.label} search answered 404"))+ }.getOrElse { failed += "${h.label}: ${it.message ?: it}"; emptyList() }+ }+ if (failed.size == CodeHost.entries.size) throw ExtensionException(failed.joinToString("; "))val gate = Semaphore(8)val entries = withContext(Dispatchers.IO) {found.map { f ->async {gate.withPermit {runCatching {- val text = f.manifestUrl()?.let { ExtensionUpdates.cached(it, Discovery.CACHE_MS) } ?: return@runCatching null+ val text = f.manifestUrl()?.let { ExtensionUpdates.cached(it, Discovery.CACHE_MS, force = force) } ?: return@runCatching nullManifest.parse(text).takeIf { it.problems().isEmpty() }?.let { Discovery.entry(f, it) }}.getOrNull()}}}.awaitAll().filterNotNull()}- runCatching { ExtensionUpdates.cached(Discovery.RATINGS_URL, Discovery.CACHE_MS, MAX_SEARCH) }.getOrNull()- ?.let { ratings.value = Discovery.parseRatings(it, found.map { f -> f.fullName }.toSet()) }- Catalog(name = "GitHub", extensions = entries.distinctBy { it.id })+ // Ratings are GitHub issues' reactions: GitHub's repositories only.+ runCatching { ExtensionUpdates.cached(Discovery.RATINGS_URL, Discovery.CACHE_MS, MAX_SEARCH, force) }.getOrNull()+ ?.let { ratings.value = Discovery.parseRatings(it, found.filter { f -> f.host == CodeHost.GITHUB }.map { f -> f.fullName }.toSet()) }+ Catalog(name = "Community", extensions = entries.distinctBy { it.id })}- _repos.value = _repos.value + (Discovery.SOURCE to Repo(Discovery.SOURCE, r.getOrNull() ?: now?.catalog, r.exceptionOrNull()?.let { it.message ?: it.toString() }))+ _repos.value = _repos.value + (Discovery.SOURCE to Repo(Discovery.SOURCE, r.getOrNull() ?: now?.catalog,+ r.exceptionOrNull()?.let { it.message ?: it.toString() } ?: failed.takeIf { it.isNotEmpty() }?.joinToString("; ")))}}diff --git a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUpdates.kt b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUpdates.ktindex bc402e0c..2856ad86 100644--- a/base/app/src/main/java/com/music/spotui/extensions/ExtensionUpdates.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/ExtensionUpdates.kt@@ -6,6 +6,7 @@ import app.myspoti.extensions.Catalogimport app.myspoti.extensions.ExtensionExceptionimport app.myspoti.extensions.ExtensionPackageimport app.myspoti.extensions.GitHub+import app.myspoti.extensions.Discoveryimport app.myspoti.extensions.GitHubRepoimport app.myspoti.extensions.Manifestimport app.myspoti.extensions.Origin@@ -65,6 +66,7 @@ object ExtensionUpdates {c.instanceFollowRedirects = followc.requestMethod = methodc.setRequestProperty("User-Agent", "Myspoti-Extensions/1")+ c.setRequestProperty("Cache-Control", "no-cache"); c.setRequestProperty("Pragma", "no-cache")accept?.let { c.setRequestProperty("Accept", it) }token?.let { c.setRequestProperty("Authorization", "Bearer $it") }try {@@ -102,6 +104,13 @@ object ExtensionUpdates {return GitHub.tagFromLocation(a.location) to GitHub.repoOf(a.location)}+ /** [ref], with `HEAD` turned into the default branch's name where the host's file addresses need one (Codeberg). */+ private fun concrete(repo: GitHubRepo, ref: String): String {+ if (ref != GitHubRepo.HEAD) return ref+ val api = repo.defaultBranchApi ?: return ref+ return runCatching { get(api, MAX_TEXT).body?.decodeToString()?.let(Discovery::parseDefaultBranch) }.getOrNull() ?: "main"+ }+private class SourceGone : ExtensionException("its GitHub repository is gone")/**@@ -118,15 +127,15 @@ object ExtensionUpdates {var asset = falsevar answer: Answer? = nullif (isTag && at != null) {- answer = get(repo.releaseAsset(at!!), GitHub.MAX_ARCHIVE).takeIf { it.status in 200..299 }+ answer = repo.releaseAsset(at!!)?.let { get(it, GitHub.MAX_ARCHIVE) }?.takeIf { it.status in 200..299 }asset = answer != null}if (answer == null) {- answer = get(repo.archive(at ?: GitHubRepo.HEAD, isTag), GitHub.MAX_ARCHIVE)+ answer = get(repo.archive(at ?: concrete(repo, GitHubRepo.HEAD), isTag), GitHub.MAX_ARCHIVE)if (answer.status == 404) throw SourceGone()- if (answer.status !in 200..299) throw ExtensionException("GitHub answered ${answer.status}")+ if (answer.status !in 200..299) throw ExtensionException("${repo.host.label} answered ${answer.status}")}- val raw = answer.body ?: throw ExtensionException("GitHub sent nothing")+ val raw = answer.body ?: throw ExtensionException("${repo.host.label} sent nothing")val zip = Archive.toPackage(raw)if (expectSha != null && ExtensionPackage.sha256(raw) != expectSha.lowercase() && ExtensionPackage.sha256(zip) != expectSha.lowercase())throw ExtensionException("the package is not the one the store lists (sha256 differs)")@@ -186,7 +195,7 @@ object ExtensionUpdates {// Where to look: the newest release when it came from one (or one appeared), else its branch.val (tag, movedTo) = latestTag(repo)val ref = tag ?: if (origin.tag) GitHubRepo.HEAD else origin.ref- val manifestAnswer = get(repo.raw(ref, "manifest.json"), MAX_TEXT)+ val manifestAnswer = get(repo.raw(concrete(repo, ref), "manifest.json"), MAX_TEXT)if (manifestAnswer.status == 404 && tag == null) throw SourceGone()val listed = manifestAnswer.body?.let { runCatching { Manifest.parse(it.decodeToString()) }.getOrNull() }if (e.sourceGone) Extensions.update { r -> r.find(id)?.let { r.put(it.copy(sourceGone = false)) } ?: r }@@ -307,14 +316,23 @@ object ExtensionUpdates {// ── A small cache of GitHub answers (the store's search, manifests, ratings) ──- /** [url]'s body, from the cache when younger than [maxAgeMs], else fetched and kept; null on 404. */- internal fun cached(url: String, maxAgeMs: Long, max: Int = MAX_TEXT): String? {+ /**+ * [url]'s body, from the cache when younger than [maxAgeMs], else fetched and kept; null on 404.+ * [force] (Refresh) skips the cache and reports a failure instead of falling back to the old copy.+ */+ internal fun cached(url: String, maxAgeMs: Long, max: Int = MAX_TEXT, force: Boolean = false): String? {val f = File(Extensions.dir, "cache/" + ExtensionPackage.sha256(url.toByteArray()).take(24))- if (f.isFile && System.currentTimeMillis() - f.lastModified() < maxAgeMs) return f.readText().ifEmpty { null }+ if (!force && f.isFile && System.currentTimeMillis() - f.lastModified() < maxAgeMs) return f.readText().ifEmpty { null }val a = runCatching { get(url, max, accept = if (url.startsWith("https://api.github.com/")) "application/vnd.github+json" else null) }- .getOrElse { if (f.isFile) return f.readText().ifEmpty { null } else throw it }+ .getOrElse { if (f.isFile && !force) return f.readText().ifEmpty { null } else throw it }if (a.status == 404) { writeAtomically(f, ""); return null }- if (a.status !in 200..299) { if (f.isFile) return f.readText().ifEmpty { null }; throw ExtensionException("GitHub answered ${a.status}") }+ if (a.status !in 200..299) {+ // A rate limit (403 / 429) keeps the old copy even on Refresh: hosts allow few searches a minute without an account.+ val limited = a.status == 403 || a.status == 429+ if (f.isFile && (!force || limited)) return f.readText().ifEmpty { null }+ val host = runCatching { java.net.URI(url).host }.getOrNull() ?: "the host"+ throw ExtensionException("$host answered ${a.status}" + if (limited) " (too many requests: try again in a few minutes)" else "")+ }val text = a.body?.decodeToString().orEmpty()writeAtomically(f, text)return textdiff --git a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt b/base/app/src/main/java/com/music/spotui/extensions/Extensions.ktindex 12e229b4..3c98ffcc 100644--- a/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt+++ b/base/app/src/main/java/com/music/spotui/extensions/Extensions.kt@@ -830,8 +830,10 @@ object Extensions {fun removeRepository(url: String) = update { r -> r.copy(repositories = r.repositories - url) }/** Reads a repository's index, and turns off what it blocks. */- suspend fun catalog(url: String): Catalog = withContext(Dispatchers.IO) {- val c = Catalog.parse(download(url, MAX_INDEX).decodeToString())+ suspend fun catalog(url: String, fresh: Boolean = false): Catalog = withContext(Dispatchers.IO) {+ // Refresh: a throwaway query makes the CDN in front of raw.githubusercontent.com (cached for minutes) answer anew.+ val at = if (fresh) url + (if ('?' in url) "&" else "?") + "t=" + System.currentTimeMillis() else url+ val c = Catalog.parse(download(at, MAX_INDEX).decodeToString())_registry.value.extensions.forEach { e ->c.blocks(e.id, e.sha256)?.let { b -> if (e.enabled) disable(e.id, "blocked by ${c.name}: ${b.reason.ifBlank { "no reason given" }}") }}@@ -873,6 +875,7 @@ object Extensions {val c = uri.toURL().openConnection() as HttpURLConnectionc.connectTimeout = 15_000; c.readTimeout = 20_000; c.useCaches = falsec.setRequestProperty("User-Agent", "Myspoti-Extensions/1")+ c.setRequestProperty("Cache-Control", "no-cache"); c.setRequestProperty("Pragma", "no-cache")try {if (c.responseCode !in 200..299) throw ExtensionException("the server answered ${c.responseCode}")val out = java.io.ByteArrayOutputStream()diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ShareCard.kt b/base/app/src/main/java/com/music/spotui/ui/components/ShareCard.ktindex 46855abf..0ade7eab 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/ShareCard.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/ShareCard.kt@@ -57,7 +57,7 @@ object ShareCard {private fun loadCover(context: Context, uri: String): Bitmap? {if (uri.isBlank()) return nullval bmp = runCatching {- Glide.with(context.applicationContext).asBitmap().load(uri).submit(1000, 1000).get()+ Glide.with(context.applicationContext).asBitmap().load(app.myspoti.host.android.Covers.large(uri)).submit(1000, 1000).get()}.getOrNull() ?: return nullreturn if (bmp.config == Bitmap.Config.HARDWARE) bmp.copy(Bitmap.Config.ARGB_8888, false) else bmp}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.ktindex 9d97f03e..9afb8591 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt@@ -1,5 +1,6 @@package com.music.spotui.ui.components+import app.myspoti.host.android.Covers as HostCoversimport com.music.spotui.ui.theme.toneimport com.music.spotui.ui.theme.AppTextimport com.music.spotui.ui.theme.AppMuted@@ -105,7 +106,7 @@ object SpotifyCode {runCatching {val app = context.applicationContextval code = Glide.with(app).asBitmap().load(imageUrl(target.uri, background, barsOn(background))).submit().get()- val cover = target.coverUri.takeIf { it.isNotBlank() }?.let { runCatching { Glide.with(app).asBitmap().load(it).submit(840, 840).get() }.getOrNull() }+ val cover = target.coverUri.takeIf { it.isNotBlank() }?.let { runCatching { Glide.with(app).asBitmap().load(HostCovers.large(it)).submit(840, 840).get() }.getOrNull() }val w = 1080; val side = 840; val pad = 120val codeH = side * code.height / code.width.coerceAtLeast(1)val h = pad + (if (cover != null) side + 60 else 0) + codeH + pad@@ -160,7 +161,7 @@ fun SpotifyCodeSheet(target: ShareTarget, onDismiss: () -> Unit) {modifier = Modifier.fillMaxWidth(0.82f).clip(RoundedCornerShape(16.dp)).background(background).padding(20.dp),) {if (target.coverUri.isNotBlank()) GlideImage(- model = target.coverUri, contentDescription = null, contentScale = ContentScale.Crop, transition = CrossFade,+ model = app.myspoti.host.android.Covers.large(target.coverUri), contentDescription = null, contentScale = ContentScale.Crop, transition = CrossFade,modifier = Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedCornerShape(6.dp)),)Text(target.title, color = text, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis,diff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.ktindex 8e72bbe5..c07a92e8 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/lyrics/ImmersiveQueuePanel.kt@@ -6,7 +6,8 @@* Changes: the sections (now playing, next in queue, next from the context), placement-only* item motion and the fading edges, over Myspoti's SongPlayer.engineQueue. A row is removed* by swiping it away, and shuffle and repeat sit in the header as in the queue sheet.- * Drag-to-reorder, history and the autoplay heading are left out for now.+ * A handle on each upcoming row drags it within its section (SongPlayer.reorder); history and+ * the autoplay heading are left out for now.*/package com.music.spotui.ui.immersive.lyrics@@ -15,6 +16,7 @@ import androidx.compose.animation.core.tweenimport androidx.compose.foundation.ExperimentalFoundationApiimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable+import androidx.compose.foundation.gestures.detectDragGesturesimport androidx.compose.foundation.interaction.MutableInteractionSourceimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Box@@ -37,6 +39,7 @@ import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.layout.Columnimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.rounded.Close+import androidx.compose.material.icons.rounded.DragHandleimport androidx.compose.material.icons.rounded.GraphicEqimport androidx.compose.material.icons.rounded.Repeatimport androidx.compose.material.icons.rounded.RepeatOne@@ -60,7 +63,16 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.snapshots.SnapshotStateMap+import androidx.compose.ui.zIndex+import kotlin.math.roundToIntimport androidx.compose.ui.input.nestedscroll.nestedScrollimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.platform.LocalLayoutDirection@@ -118,8 +130,12 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa// Rows swiped away, hidden at once: the queue takes a moment to report the removal.val removed = remember { mutableStateListOf<String>() }LaunchedEffect(queue) { removed.clear() }- val queued = queue.queued.dedupedKeys("q").filter { it.first !in removed }- val nextUp = queue.nextUp.dedupedKeys("n").filter { it.first !in removed }+ // Rows just dragged, shown in their new order until the queue reports it.+ val reordered = remember { mutableStateMapOf<String, List<String>>() }+ LaunchedEffect(queue) { reordered.clear() }+ val queued = queue.queued.dedupedKeys("q").filter { it.first !in removed }.inOrder(reordered["q"])+ val nextUp = queue.nextUp.dedupedKeys("n").filter { it.first !in removed }.inOrder(reordered["n"])+ val drag = remember { QueueDrag() }val listState = rememberLazyListState()val keepScroll = remember(listState) { keepScrollInList(listState) }@@ -186,7 +202,7 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVa)}}- queueSection(queued, removed)+ queueSection("q", queued, removed, reordered, drag)}if (nextUp.isNotEmpty()) {item(key = "heading-next") {@@ -199,7 +215,7 @@ fun ImmersiveQueuePanel(modifier: Modifier = Modifier, contentPadding: PaddingVamodifier = Modifier.padding(top = 16.dp, bottom = 6.dp).then(queueMotion()),)}- queueSection(nextUp, removed)+ queueSection("n", nextUp, removed, reordered, drag)}if (!hasCurrent && queued.isEmpty() && nextUp.isEmpty()) {item(key = "empty") {@@ -226,14 +242,42 @@ private fun List<SongPlayer.QueueItem>.dedupedKeys(prefix: String): List<Pair<St}}-/** One section's rows, each swiped away to remove it. */+private fun List<Pair<String, SongPlayer.QueueItem>>.inOrder(+ keys: List<String>?,+): List<Pair<String, SongPlayer.QueueItem>> {+ if (keys == null || keys.size != size) return this+ val byKey = associateBy { it.first }+ return keys.mapNotNull { byKey[it] }.takeIf { it.size == size } ?: this+}++/** The row being dragged by its handle: which one, and how far it is from its slot. */+private class QueueDrag {+ var key by mutableStateOf<String?>(null)+ var offset by mutableFloatStateOf(0f)+}++/** One section's rows, each swiped away to remove it or dragged by its handle to move it. */@OptIn(ExperimentalMaterial3Api::class)private fun LazyListScope.queueSection(+ section: String,rows: List<Pair<String, SongPlayer.QueueItem>>,removed: SnapshotStateList<String>,+ reordered: SnapshotStateMap<String, List<String>>,+ drag: QueueDrag,) {items(rows.size, key = { rows[it].first }) { index ->val (key, item) = rows[index]+ val rowPx = with(LocalDensity.current) { Immersive.RowHeight.toPx() }+ val from = rows.indexOfFirst { it.first == drag.key }+ val slot = if (from < 0) -1 else (from + (drag.offset / rowPx).roundToInt()).coerceIn(0, rows.lastIndex)+ // Rows the dragged one passes step aside by one slot.+ val shift = when {+ from < 0 || key == drag.key -> 0f+ index in (from + 1)..slot -> -rowPx+ index in slot until from -> rowPx+ else -> 0f+ }+ val dragged = key == drag.keyval dismiss = rememberSwipeToDismissBoxState(confirmValueChange = { value ->if (value == SwipeToDismissBoxValue.EndToStart) {removed += key@@ -246,7 +290,9 @@ private fun LazyListScope.queueSection(SwipeToDismissBox(state = dismiss,enableDismissFromStartToEnd = false,- modifier = queueMotion(),+ modifier = (if (dragged) Modifier else queueMotion())+ .zIndex(if (dragged) 1f else 0f)+ .graphicsLayer { translationY = if (dragged) drag.offset else shift },backgroundContent = {Box(Modifier.fillMaxSize().padding(end = 4.dp),@@ -268,6 +314,36 @@ private fun LazyListScope.queueSection(isCurrent = false,explicit = item.song.explicit,onClick = { SongPlayer.skipTo(item) },+ handle = {+ Icon(+ Icons.Rounded.DragHandle,+ contentDescription = stringResource(R.string.immersive_queue_reorder),+ tint = Immersive.TextSecondary,+ modifier = Modifier+ .size(40.dp)+ .padding(8.dp)+ .pointerInput(key) {+ detectDragGestures(+ onDragStart = { drag.key = key; drag.offset = 0f },+ onDragEnd = {+ val start = rows.indexOfFirst { it.first == key }+ val to = (start + (drag.offset / rowPx).roundToInt()).coerceIn(0, rows.lastIndex)+ drag.key = null+ drag.offset = 0f+ if (start >= 0 && to != start) {+ reordered[section] = rows.map { it.first }.toMutableList().apply { add(to, removeAt(start)) }+ SongPlayer.reorder(item, rows[to].second, after = to > start)+ }+ },+ onDragCancel = { drag.key = null; drag.offset = 0f },+ onDrag = { change, amount ->+ change.consume()+ drag.offset += amount.y+ },+ )+ },+ )+ },)}}@@ -339,6 +415,7 @@ private fun QueueRow(explicit: Boolean,onClick: () -> Unit,modifier: Modifier = Modifier,+ handle: (@Composable () -> Unit)? = null,) {Row(modifier = modifier@@ -384,6 +461,7 @@ private fun QueueRow()}}+ if (handle != null) handle()if (isCurrent) {Spacer(Modifier.width(10.dp))Icon(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 f23dc19d..46b7c284 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@@ -582,7 +582,7 @@ private fun AppPage(navController: NavController, back: () -> Unit) {if (!checking) {checking = truescope.launch {- val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx) }.getOrNull()+ val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx, manual = true) }.getOrNull()checking = false// The card is the app's one update UI: fill it, it shows itself.if (found != null) com.music.spotui.updateRelease.value = founddiff --git a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.ktindex 4929b481..4f339901 100644--- a/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt+++ b/base/app/src/main/java/com/music/spotui/ui/immersive/player/ImmersivePlayer.kt@@ -324,6 +324,11 @@ fun ImmersivePlayer(.dragToClose(),verticalAlignment = Alignment.CenterVertically,) {+ // The header is a fixed HEADER_HEIGHT: with a source line the three lines are+ // set tighter, so none is clipped at the bottom.+ val sourceLabel = com.music.spotui.ui.components.playingSourceLabel()+ val hasSource = sourceLabel.isNotBlank() && !state.adPlaying+ val lineH = if (hasSource) 22.sp else 24.spColumn(Modifier.weight(1f)@@ -338,7 +343,7 @@ fun ImmersivePlayer(Row(verticalAlignment = Alignment.CenterVertically) {Text(text = if (state.adPlaying) stringResource(R.string.immersive_player_ad) else state.title,- style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = 24.sp),+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = lineH),maxLines = 1,overflow = TextOverflow.Ellipsis,modifier = Modifier@@ -363,7 +368,7 @@ fun ImmersivePlayer(if (!state.adPlaying) {Text(text = state.artist,- style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = 24.sp, fontWeight = FontWeight.W500),+ style = Immersive.Title.copy(fontSize = 20.sp, lineHeight = lineH, fontWeight = FontWeight.W500),color = tint.copy(alpha = 0.55f),maxLines = 1,overflow = TextOverflow.Ellipsis,@@ -374,15 +379,13 @@ fun ImmersivePlayer(}// What the sound is when Myspoti's own player plays it (an extension's stream, a// download); a tap opens what plays and its quality. Same state as the Classic player.- val source = com.music.spotui.ui.components.playingSourceLabel()- if (source.isNotBlank() && !state.adPlaying) Text(- text = source,- style = Immersive.Caption,+ if (hasSource) Text(+ text = sourceLabel,+ style = Immersive.Caption.copy(lineHeight = 14.sp),color = tint.copy(alpha = 0.45f),maxLines = 1,overflow = TextOverflow.Ellipsis,modifier = Modifier- .padding(top = 2.dp).clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { showQuality = true },)}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.ktindex 8222d9b6..b35fdf52 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ExtensionsScreen.kt@@ -193,12 +193,13 @@ fun ExtensionsScreen(navController: NavController) {downloading = truescope.launch {// A GitHub repository's address: its newest release (or default branch), kept on the phone and updated from there.- val gitHub = app.myspoti.extensions.GitHubRepo.parse(url)?.takeIf { !url.endsWith(".zip") && (url.contains("github.com/") || !url.contains("://")) }+ // (GitHub, GitLab or Codeberg; `gitlab:group/name` and `codeberg:owner/name` work too.)+ val gitHub = app.myspoti.extensions.GitHubRepo.parse(url)?.takeIf { !url.endsWith(".zip") }runCatching {if (gitHub != null) com.music.spotui.extensions.ExtensionUpdates.fromGitHub(gitHub)else Extensions.downloadPackage(url).let { (zip, p) -> com.music.spotui.extensions.ExtensionUpdates.Fetched(zip, p, null) }}- .onSuccess { f -> offer(ctx, f.zip, f.origin?.let { "https://github.com/${it.repo}" } ?: url, f.origin) }+ .onSuccess { f -> offer(ctx, f.zip, f.origin?.page() ?: url, f.origin) }.onFailure { toastError(ctx, it) }downloading = false}diff --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 88e55d36..e8b6aff5 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@@ -34,6 +34,7 @@ import androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Iconimport androidx.compose.material3.IconButtonimport androidx.compose.material3.Text+import androidx.compose.material3.TabRowDefaults.tabIndicatorOffsetimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.remember@@ -70,7 +71,28 @@ fun SettingsScreen(navController: NavController) {}Text(stringResource(R.string.settings_title), color = AppText, fontSize = 20.sp, fontWeight = FontWeight.Bold)}+ // One tab per group, so the page is no longer one long list.+ var tab by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf(0) }+ val tabs = listOf(R.string.settings_section_playback, R.string.settings_section_downloads, R.string.settings_tab_appearance,+ R.string.extensions_title, R.string.settings_tab_about)+ androidx.compose.material3.ScrollableTabRow(+ selectedTabIndex = tab, containerColor = Color.Transparent, contentColor = AppText, edgePadding = 12.dp,+ indicator = { positions ->+ androidx.compose.material3.TabRowDefaults.SecondaryIndicator(+ Modifier.tabIndicatorOffset(positions[tab]), color = com.music.spotui.ui.theme.AppAccent)+ },+ divider = { HorizontalDivider(color = tone(0xFF2A2A2A)) },+ ) {+ tabs.forEachIndexed { i, title ->+ androidx.compose.material3.Tab(+ selected = tab == i, onClick = { tab = i },+ text = { Text(stringResource(title), fontSize = 14.sp, fontWeight = if (tab == i) FontWeight.Bold else FontWeight.Normal) },+ selectedContentColor = AppText, unselectedContentColor = AppMuted,+ )+ }+ }Column(Modifier.fillMaxWidth().weight(1f).verticalScroll(rememberScrollState()).navigationBarsPadding()) {+ if (tab == 0) {Section(R.string.settings_section_playback)StreamingQualityPicker(title = R.string.quality_streaming_wifi_title)StreamingQualityPicker(cellular = true, title = R.string.quality_streaming_cell_title)@@ -110,25 +132,6 @@ fun SettingsScreen(navController: NavController) {)Divider()- Section(R.string.settings_section_downloads)- DownloadQualityPicker()- // Where downloads come from: a download-source extension.- Column(- Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Extensions.route) }- .padding(horizontal = 20.dp, vertical = 10.dp),- ) {- Text(stringResource(R.string.downloads_source_row_title), color = AppText, fontSize = 16.sp)- Text(- stringResource(- if (com.music.spotui.extensions.Extensions.hasDownloadSource()) R.string.downloads_source_row_on- else R.string.downloads_source_row_off,- ),- color = AppMuted, fontSize = 12.sp,- )- }- if (com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty()) RemoveDownloadsRow()- Divider()-Section(R.string.settings_section_data)OptionRow(label = stringResource(R.string.energy_saver_title),@@ -156,7 +159,27 @@ fun SettingsScreen(navController: NavController) {else app.myspoti.power.BatteryExemption.request(ctx)},)- Divider()+ }+ if (tab == 1) {+ Section(R.string.settings_section_downloads)+ DownloadQualityPicker()+ // Where downloads come from: a download-source extension.+ Column(+ Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Extensions.route) }+ .padding(horizontal = 20.dp, vertical = 10.dp),+ ) {+ Text(stringResource(R.string.downloads_source_row_title), color = AppText, fontSize = 16.sp)+ Text(+ stringResource(+ if (com.music.spotui.extensions.Extensions.hasDownloadSource()) R.string.downloads_source_row_on+ else R.string.downloads_source_row_off,+ ),+ color = AppMuted, fontSize = 12.sp,+ )+ }+ if (com.music.spotui.data.offline.OfflineStore.tracks.isNotEmpty()) RemoveDownloadsRow()+ }+ if (tab == 2) {Section(R.string.settings_section_display)OptionRow(@@ -206,11 +229,21 @@ fun SettingsScreen(navController: NavController) {}OrientationRow()LanguageRow()- Divider()-+ }+ if (tab == 3) {ExtensionSettingsRows(navController)-+ // Third-party extensions: lyrics, a song's audio, scripts reacting to the music.+ Column(+ Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Extensions.route) }+ .padding(horizontal = 20.dp, vertical = 10.dp),+ ) {+ Text(stringResource(R.string.extensions_title), color = AppText, fontSize = 16.sp)+ Text(stringResource(R.string.extensions_row_detail), color = AppMuted, fontSize = 12.sp)+ }+ }+ if (tab == 4) {Section(R.string.settings_section_app)+ AboutRow()// A18: the launch check can be turned off; the manual check below keeps working.OptionRow(label = stringResource(R.string.settings_auto_update_title),@@ -219,14 +252,6 @@ fun SettingsScreen(navController: NavController) {onChecked = { com.music.spotui.data.preferences.AutoUpdateCheckPref.set(ctx, it) },)CheckUpdateRow()- // Third-party extensions: lyrics, a song's audio, scripts reacting to the music.- Column(- Modifier.fillMaxWidth().clickable { navController.navigate(com.music.spotui.ui.navigation.Routes.Extensions.route) }- .padding(horizontal = 20.dp, vertical = 10.dp),- ) {- Text(stringResource(R.string.extensions_title), color = AppText, fontSize = 16.sp)- Text(stringResource(R.string.extensions_row_detail), color = AppMuted, fontSize = 12.sp)- }// The hidden Web Player stuck or crashed: rebuild it without leaving the app.Column(Modifier.fillMaxWidth().clickable {@@ -252,6 +277,7 @@ fun SettingsScreen(navController: NavController) {Text(stringResource(R.string.diagnostic_export_title), color = AppText, fontSize = 16.sp)Text(stringResource(R.string.diagnostic_export_detail), color = AppMuted, fontSize = 12.sp)}+ }// Clear of the mini player and the navigation bar, as every other page (96 dp left the// last rows, "Restart the player" among them, under the mini player).Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace()))@@ -510,6 +536,27 @@ private fun OptionRow(label: String, detail: String, checked: Boolean,}}+/** The installed version and, when a newer one is known, the update on offer (its card opens on tap). */+@Composable+private fun AboutRow() {+ val ctx = androidx.compose.ui.platform.LocalContext.current+ // Also what "Later" put aside: the card in the app offers it again from here.+ val live = com.music.spotui.updateRelease.value+ val known = live ?: remember { com.music.spotui.data.api.UpdateChecker.known(ctx) }+ Column(+ Modifier.fillMaxWidth()+ .then(if (known != null) Modifier.clickable { com.music.spotui.updateRelease.value = known } else Modifier)+ .padding(horizontal = 20.dp, vertical = 10.dp),+ ) {+ Text(stringResource(R.string.settings_about_version, app.myspoti.engine.BuildConfig.VERSION_NAME), color = AppText, fontSize = 16.sp)+ if (known != null) {+ Text(stringResource(R.string.settings_update_available, known.version), color = com.music.spotui.ui.theme.AppAccent, fontSize = 14.sp,+ fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 2.dp))+ Text(stringResource(R.string.settings_update_available_detail), color = AppMuted, fontSize = 12.sp)+ }+ }+}+/** "Check for updates now": the launch check can be off; this one always asks. */@Composableprivate fun CheckUpdateRow() {@@ -521,7 +568,7 @@ private fun CheckUpdateRow() {if (checking) return@clickablechecking = truescope.launch {- val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx) }.getOrNull()+ val found = runCatching { com.music.spotui.data.api.UpdateChecker.check(ctx, manual = true) }.getOrNull()checking = false// The card is the app's one update UI: fill it, it shows itself.if (found != null) com.music.spotui.updateRelease.value = founddiff --git a/base/app/src/main/res/values-fr/extensions_strings.xml b/base/app/src/main/res/values-fr/extensions_strings.xmlindex 4c9879c1..9085788f 100644--- a/base/app/src/main/res/values-fr/extensions_strings.xml+++ b/base/app/src/main/res/values-fr/extensions_strings.xml@@ -158,7 +158,7 @@<string name="ext_welcome_ok">Compris</string><!-- GitHub : découverte, notes, signalements -->- <string name="extensions_github_title">Sur GitHub</string>+ <string name="extensions_github_title">Sur GitHub, GitLab et Codeberg</string><string name="extensions_github_note">Publiées par la communauté, non vérifiées par Myspoti. Chaque auteur est responsable de son extension.</string><string name="extensions_show_all">Tout afficher (%1$d masquées)</string><string name="extensions_show_less">Masquer les bloquées, signalées, mal notées et abandonnées</string>diff --git a/base/app/src/main/res/values-fr/immersive_lyrics_strings.xml b/base/app/src/main/res/values-fr/immersive_lyrics_strings.xmlindex a83e5d2c..6369196d 100644--- a/base/app/src/main/res/values-fr/immersive_lyrics_strings.xml+++ b/base/app/src/main/res/values-fr/immersive_lyrics_strings.xml@@ -6,6 +6,7 @@<string name="immersive_queue_now_playing">En cours de lecture</string><string name="immersive_queue_empty">La file d\'attente est vide</string><string name="immersive_queue_remove">Retirer de la file d\'attente</string>+ <string name="immersive_queue_reorder">Déplacer dans la file d\'attente</string><string name="immersive_queue_shuffle">Lecture aléatoire</string><string name="immersive_queue_repeat">Répéter</string></resources>diff --git a/base/app/src/main/res/values-fr/myspoti_strings.xml b/base/app/src/main/res/values-fr/myspoti_strings.xmlindex 6234d8c4..56f3a7ad 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -212,6 +212,11 @@<string name="settings_section_downloads">Téléchargements</string><string name="settings_section_data">Données et batterie</string><string name="settings_section_display">Affichage et langue</string>+ <string name="settings_tab_appearance">Apparence</string>+ <string name="settings_tab_about">À propos</string>+ <string name="settings_about_version">Version %1$s</string>+ <string name="settings_update_available">Version %1$s disponible</string>+ <string name="settings_update_available_detail">Touchez pour la télécharger et l\'installer</string><string name="settings_section_app">Application</string><string name="quality_streaming_title">Qualité du streaming</string><string name="quality_streaming_detail">Ce que le lecteur diffuse depuis Internet.</string>@@ -345,8 +350,8 @@<string name="share_as_image">Partager en image</string><string name="settings_autoplay_title">Lecture automatique</string><string name="settings_autoplay_detail">Quand votre musique se termine, continuer avec des titres similaires</string>- <string name="settings_crossfade_title">Fondu enchaîné (sans chevauchement)</string>- <string name="settings_crossfade_detail">Un morceau s\'efface sur ses dernières secondes, le suivant remonte. Les deux ne jouent jamais en même temps : un seul lecteur, un seul flux audio.</string>+ <string name="settings_crossfade_title">Fondu enchaîné</string>+ <string name="settings_crossfade_detail">Les morceaux issus d\'extensions, de téléchargements et de fichiers locaux se chevauchent : la fin de l\'un s\'efface pendant que le suivant monte. Les flux Spotify ne peuvent pas se chevaucher (un seul flux audio) : ils s\'effacent puis remontent seulement.</string><string name="settings_crossfade_off">Désactivé</string><string name="settings_crossfade_seconds">%1$d s</string><string name="settings_rotation_title">Rotation de l\'écran</string>diff --git a/base/app/src/main/res/values/extensions_strings.xml b/base/app/src/main/res/values/extensions_strings.xmlindex 22cc8581..05df4bcf 100644--- a/base/app/src/main/res/values/extensions_strings.xml+++ b/base/app/src/main/res/values/extensions_strings.xml@@ -158,7 +158,7 @@<string name="ext_welcome_ok">Got it</string><!-- GitHub: discovery, ratings, reports -->- <string name="extensions_github_title">On GitHub</string>+ <string name="extensions_github_title">On GitHub, GitLab and Codeberg</string><string name="extensions_github_note">Published by the community, not reviewed by Myspoti. Each author is responsible for their extension.</string><string name="extensions_show_all">Show all (%1$d hidden)</string><string name="extensions_show_less">Hide blocked, reported, low-rated and abandoned ones</string>diff --git a/base/app/src/main/res/values/immersive_lyrics_strings.xml b/base/app/src/main/res/values/immersive_lyrics_strings.xmlindex fe32920e..7696bc45 100644--- a/base/app/src/main/res/values/immersive_lyrics_strings.xml+++ b/base/app/src/main/res/values/immersive_lyrics_strings.xml@@ -6,6 +6,7 @@<string name="immersive_queue_now_playing">Now playing</string><string name="immersive_queue_empty">Nothing is queued</string><string name="immersive_queue_remove">Remove from queue</string>+ <string name="immersive_queue_reorder">Move in queue</string><string name="immersive_queue_shuffle">Shuffle</string><string name="immersive_queue_repeat">Repeat</string></resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 22930883..c3f5e47b 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -212,6 +212,11 @@<string name="settings_section_downloads">Downloads</string><string name="settings_section_data">Data and battery</string><string name="settings_section_display">Display and language</string>+ <string name="settings_tab_appearance">Appearance</string>+ <string name="settings_tab_about">About</string>+ <string name="settings_about_version">Version %1$s</string>+ <string name="settings_update_available">Version %1$s available</string>+ <string name="settings_update_available_detail">Tap to download and install it</string><string name="settings_section_app">App</string><string name="quality_streaming_title">Streaming quality</string><string name="quality_streaming_detail">What the player streams over the network.</string>@@ -345,8 +350,8 @@<string name="share_as_image">Share as image</string><string name="settings_autoplay_title">Autoplay</string><string name="settings_autoplay_detail">When your music ends, keep playing similar songs</string>- <string name="settings_crossfade_title">Crossfade (tracks fade, they do not overlap)</string>- <string name="settings_crossfade_detail">A track fades out over its last seconds, the next one fades in. They never play at once: one player, one audio stream.</string>+ <string name="settings_crossfade_title">Crossfade</string>+ <string name="settings_crossfade_detail">Songs from extensions, downloads and local files overlap: the end of one fades out while the next fades in. Spotify streams cannot overlap (one audio stream): they only fade out and in.</string><string name="settings_crossfade_off">Off</string><string name="settings_crossfade_seconds">%1$ds</string><string name="settings_rotation_title">Screen rotation</string>diff --git a/base/app/src/test/java/com/music/spotui/di/CrossfadeRampTest.kt b/base/app/src/test/java/com/music/spotui/di/CrossfadeRampTest.ktnew file mode 100644index 00000000..d6efc627--- /dev/null+++ b/base/app/src/test/java/com/music/spotui/di/CrossfadeRampTest.kt@@ -0,0 +1,32 @@+package com.music.spotui.di++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test++class CrossfadeRampTest {+ @Test fun fadeIsNeverOverHalfTheSong() {+ assertEquals(6000L, CrossfadeRamp.fadeMs(6, 200_000))+ assertEquals(5000L, CrossfadeRamp.fadeMs(12, 10_000))+ assertEquals(0L, CrossfadeRamp.fadeMs(0, 200_000))+ }++ @Test fun startsOnlyInTheLastSeconds() {+ assertFalse(CrossfadeRamp.shouldStart(6, 200_000, 100_000))+ assertTrue(CrossfadeRamp.shouldStart(6, 200_000, 194_000))+ assertFalse(CrossfadeRamp.shouldStart(0, 200_000, 199_000))+ assertFalse(CrossfadeRamp.shouldStart(6, 0, 1000))+ }++ @Test fun equalPowerKeepsLoudnessLevel() {+ for (i in 0..10) {+ val t = i / 10f+ val a = CrossfadeRamp.incomingGain(t); val b = CrossfadeRamp.outgoingGain(t)+ assertEquals(1f, a * a + b * b, 1e-4f)+ }+ assertEquals(0f, CrossfadeRamp.incomingGain(0f), 1e-6f)+ assertEquals(1f, CrossfadeRamp.incomingGain(1f), 1e-6f)+ assertEquals(1f, CrossfadeRamp.progress(9999, 5000), 0f)+ }+}diff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Discovery.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Discovery.ktindex 015ee520..69dbee3c 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Discovery.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Discovery.kt@@ -4,10 +4,11 @@ import kotlinx.serialization.SerialNameimport kotlinx.serialization.Serializable/**- * The store's discovery on GitHub: every public repository with the topic [TOPIC] is offered,- * along with the repositories' indexes. One search call per store visit, cached 6 hours (the- * API allows 10 searches a minute without an account); the manifests and packages then come- * from raw.githubusercontent.com and codeload.github.com, which have no such limit.+ * The store's discovery on GitHub, GitLab and Codeberg: every public repository with the topic+ * [TOPIC] is offered, along with the repositories' indexes. One search call per host and store+ * visit, cached 6 hours (GitHub's API allows 10 searches a minute without an account); the+ * manifests and packages then come from the hosts' file addresses, which have no such limit.+ * Ratings (issues' reactions) and download counts exist on GitHub only.*/object Discovery {const val TOPIC = "myspoti-extension"@@ -23,6 +24,19 @@ object Discovery {/** Up to 100 repositories with the topic, the most recently pushed first. */const val SEARCH_URL = "https://api.github.com/search/repositories?q=topic:$TOPIC+fork:true+archived:false&sort=updated&order=desc&per_page=100"+ /** Up to 100 public GitLab projects with the topic, the most recently active first. */+ const val GITLAB_SEARCH_URL = "https://gitlab.com/api/v4/projects?topic=$TOPIC&visibility=public&archived=false&order_by=last_activity_at&sort=desc&per_page=100"++ /** Up to 50 Codeberg repositories with the topic (`topic=true`: the query is matched against topics), the most recently updated first. */+ const val CODEBERG_SEARCH_URL = "https://codeberg.org/api/v1/repos/search?q=$TOPIC&topic=true&archived=false&sort=updated&order=desc&limit=50"++ /** The search address of [host]. */+ fun searchUrl(host: CodeHost) = when (host) {+ CodeHost.GITHUB -> SEARCH_URL+ CodeHost.GITLAB -> GITLAB_SEARCH_URL+ CodeHost.CODEBERG -> CODEBERG_SEARCH_URL+ }+/** Every open ratings issue (one search for all the store, filtered to the discovered repositories' owners). */const val RATINGS_URL = "https://api.github.com/search/issues?q=label:$RATINGS_LABEL+is:issue+is:open&per_page=100"@@ -45,8 +59,9 @@ object Discovery {@SerialName("stargazers_count") val stars: Int = 0,val archived: Boolean = false,val topics: List<String> = emptyList(),+ @kotlinx.serialization.Transient val host: CodeHost = CodeHost.GITHUB,) {- val repo: GitHubRepo? get() = GitHubRepo.parse(fullName)+ val repo: GitHubRepo? get() = GitHubRepo.of(host, fullName)/** Where its manifest is read, on the default branch. */fun manifestUrl(): String? = repo?.raw(defaultBranch, "manifest.json")@@ -57,6 +72,59 @@ object Discovery {fun parseSearch(text: String): List<Found> = ExtJson.decodeFromString(SearchAnswer.serializer(), text).items.filter { !it.archived && it.repo != null }+ @Serializable+ private data class GitLabProject(+ @SerialName("path_with_namespace") val path: String,+ val description: String? = null,+ @SerialName("web_url") val webUrl: String = "",+ @SerialName("default_branch") val defaultBranch: String? = null,+ @SerialName("last_activity_at") val lastActivityAt: String? = null,+ @SerialName("star_count") val stars: Int = 0,+ val archived: Boolean = false,+ val topics: List<String> = emptyList(),+ )++ /** GitLab's `/api/v4/projects` answer (a JSON array). */+ fun parseGitLab(text: String): List<Found> =+ ExtJson.decodeFromString(kotlinx.serialization.builtins.ListSerializer(GitLabProject.serializer()), text).map {+ Found(it.path, Owner(it.path.substringBeforeLast('/')), it.description, it.webUrl, it.defaultBranch ?: GitHubRepo.HEAD,+ it.lastActivityAt, it.lastActivityAt, it.stars, it.archived, it.topics, CodeHost.GITLAB)+ }.filter { !it.archived && it.repo != null }++ @Serializable+ private data class ForgejoRepo(+ @SerialName("full_name") val fullName: String,+ val description: String? = null,+ @SerialName("html_url") val htmlUrl: String = "",+ @SerialName("default_branch") val defaultBranch: String? = null,+ @SerialName("updated_at") val updatedAt: String? = null,+ @SerialName("stars_count") val stars: Int = 0,+ val archived: Boolean = false,+ val empty: Boolean = false,+ )++ @Serializable+ private data class ForgejoAnswer(val data: List<ForgejoRepo> = emptyList())++ /** Codeberg's (Forgejo/Gitea) `/api/v1/repos/search` answer. */+ fun parseCodeberg(text: String): List<Found> =+ ExtJson.decodeFromString(ForgejoAnswer.serializer(), text).data.filter { !it.empty }.map {+ Found(it.fullName, Owner(it.fullName.substringBefore('/')), it.description, it.htmlUrl, it.defaultBranch ?: GitHubRepo.HEAD,+ it.updatedAt, it.updatedAt, it.stars, it.archived, emptyList(), CodeHost.CODEBERG)+ }.filter { !it.archived && it.repo != null }++ /** [parseSearch], [parseGitLab] or [parseCodeberg] by [host]. */+ fun parse(host: CodeHost, text: String): List<Found> = when (host) {+ CodeHost.GITHUB -> parseSearch(text)+ CodeHost.GITLAB -> parseGitLab(text)+ CodeHost.CODEBERG -> parseCodeberg(text)+ }++ /** The default branch name out of Codeberg's repository API answer (null if absent). */+ fun parseDefaultBranch(text: String): String? = runCatching {+ (ExtJson.parseToJsonElement(text) as kotlinx.serialization.json.JsonObject)["default_branch"]?.let { (it as? kotlinx.serialization.json.JsonPrimitive)?.content }+ }.getOrNull()?.takeIf { it.isNotBlank() }+/*** The store entry of a discovered repository, from its [manifest]: installed from GitHub* ([Catalog.Entry.repo]), its package built when the user taps Install. No sha256: GitHubdiff --git a/base/extensions/src/main/kotlin/app/myspoti/extensions/Sources.kt b/base/extensions/src/main/kotlin/app/myspoti/extensions/Sources.ktindex 29709a20..56803794 100644--- a/base/extensions/src/main/kotlin/app/myspoti/extensions/Sources.kt+++ b/base/extensions/src/main/kotlin/app/myspoti/extensions/Sources.kt@@ -6,48 +6,95 @@ import java.io.ByteArrayOutputStreamimport java.net.URLEncoderimport java.util.zip.ZipInputStream+/** The code hosts an extension can be installed from. */+@Serializable+enum class CodeHost(val key: String, val domain: String, val label: String) {+ GITHUB("github", "github.com", "GitHub"),+ GITLAB("gitlab", "gitlab.com", "GitLab"),+ CODEBERG("codeberg", "codeberg.org", "Codeberg");++ companion object {+ fun ofDomain(d: String): CodeHost? = entries.firstOrNull { it.domain == d.lowercase().removePrefix("www.") }+ }+}+/**- * A GitHub repository an extension is installed from: `owner/name`. Everything is fetched from- * GitHub's file hosts (`raw.githubusercontent.com`, `codeload.github.com`, release downloads),- * never from its API, which allows 60 calls an hour without an account: the API is only used- * for the store's search (see [Discovery]), once per visit and cached.+ * A repository an extension is installed from, on [host]: [owner] and [name] (GitLab's owner may+ * be a group path, `group/sub`). Everything is fetched from the host's file addresses (GitHub:+ * `raw.githubusercontent.com`, `codeload.github.com`, release downloads; GitLab: `/-/raw`,+ * `/-/archive`; Codeberg: `/raw`, `/archive`), never from an API, except the store's search (see+ * [Discovery]), once per visit and cached. The [slug] is `owner/name` on GitHub (as it always was),+ * `gitlab:group/name` or `codeberg:owner/name` elsewhere. (Named after GitHub, where it began.)*/@Serializable-data class GitHubRepo(val owner: String, val name: String) {- val slug: String get() = "$owner/$name"+data class GitHubRepo(val owner: String, val name: String, val host: CodeHost = CodeHost.GITHUB) {+ val slug: String get() = if (host == CodeHost.GITHUB) "$owner/$name" else "${host.key}:$owner/$name"++ private val base: String get() = "https://${host.domain}/$owner/$name"/** A file of the repository at [ref] (a tag, a branch, or `HEAD` for the default branch). */- fun raw(ref: String, path: String) = "https://raw.githubusercontent.com/$owner/$name/$ref/$path"+ fun raw(ref: String, path: String) = when (host) {+ CodeHost.GITHUB -> "https://raw.githubusercontent.com/$owner/$name/$ref/$path"+ CodeHost.GITLAB -> "$base/-/raw/$ref/$path"+ CodeHost.CODEBERG -> "$base/raw/$ref/$path"+ }/** The whole repository at [ref], zipped: a tag when [tag], else a branch (`HEAD`: the default one). */- fun archive(ref: String, tag: Boolean) =- if (ref == HEAD) "https://codeload.github.com/$owner/$name/zip/HEAD"- else "https://codeload.github.com/$owner/$name/zip/refs/${if (tag) "tags" else "heads"}/$ref"+ fun archive(ref: String, tag: Boolean) = when (host) {+ CodeHost.GITHUB ->+ if (ref == HEAD) "https://codeload.github.com/$owner/$name/zip/HEAD"+ else "https://codeload.github.com/$owner/$name/zip/refs/${if (tag) "tags" else "heads"}/$ref"+ CodeHost.GITLAB -> "$base/-/archive/$ref/$name-${ref.replace('/', '-')}.zip"+ CodeHost.CODEBERG -> "$base/archive/$ref.zip"+ }/** Redirects to the newest release's page (`…/releases/tag/<tag>`); 404 without a release. */- val latestRelease: String get() = "https://github.com/$owner/$name/releases/latest"+ val latestRelease: String get() = when (host) {+ CodeHost.GITLAB -> "$base/-/releases/permalink/latest"+ else -> "$base/releases/latest"+ }++ /** The package attached to the release [tag], when the author attached one ([GitHub.ASSET]); GitLab's release links are not looked for. */+ fun releaseAsset(tag: String): String? = when (host) {+ CodeHost.GITLAB -> null+ else -> "$base/releases/download/$tag/${GitHub.ASSET}"+ }- /** The package attached to the release [tag], when the author attached one ([GitHub.ASSET]). */- fun releaseAsset(tag: String) = "https://github.com/$owner/$name/releases/download/$tag/${GitHub.ASSET}"+ val page: String get() = base- val page: String get() = "https://github.com/$owner/$name"+ /** Codeberg's file addresses want a branch name: its API tells the default one. */+ val defaultBranchApi: String? get() = if (host == CodeHost.CODEBERG) "https://codeberg.org/api/v1/repos/$owner/$name" else nullcompanion object {const val HEAD = "HEAD"private val PART = Regex("^[A-Za-z0-9_.-]{1,100}$")- /** `owner/name`, `github.com/owner/name` or `https://github.com/owner/name(.git)(/…)`; null otherwise. */+ /** A repository by its host's path (`group/sub/name`); null when it is not one. */+ fun of(host: CodeHost, path: String): GitHubRepo? {+ val parts = path.trim('/').split('/').map { it.removeSuffix(".git") }+ if (parts.size < 2 || parts.any { !PART.matches(it) || it == "." || it == ".." }) return null+ val usable = if (host == CodeHost.GITLAB) parts else parts.take(2)+ return GitHubRepo(usable.dropLast(1).joinToString("/"), usable.last(), host)+ }++ /**+ * `owner/name` (GitHub), `gitlab:group/name`, `codeberg:owner/name`, `github.com/owner/name`,+ * `https://gitlab.com/group/sub/name(.git)(/-/…)`, `https://codeberg.org/owner/name(/…)`; null otherwise.+ */fun parse(text: String): GitHubRepo? {var s = text.trim().removeSuffix("/")+ CodeHost.entries.firstOrNull { s.startsWith(it.key + ":") }?.let { return of(it, s.removePrefix(it.key + ":")) }s = s.removePrefix("https://").removePrefix("http://").removePrefix("www.")- if (s.startsWith("github.com/")) s = s.removePrefix("github.com/")- else if (s.contains("://") || s.contains('.') && s.substringBefore('/').contains('.')) return null+ val host = CodeHost.ofDomain(s.substringBefore('/'))+ if (host != null && s.contains('/')) {+ var path = s.substringAfter('/').substringBefore('?').substringBefore('#')+ if (host == CodeHost.GITLAB) path = path.substringBefore("/-/")+ return of(host, path)+ }+ if (s.contains("://") || s.contains('.') && s.substringBefore('/').contains('.')) return nullval parts = s.split('/')if (parts.size < 2) return null- val owner = parts[0]- val name = parts[1].removeSuffix(".git")- if (!PART.matches(owner) || !PART.matches(name) || name == "." || name == "..") return null- return GitHubRepo(owner, name)+ return of(CodeHost.GITHUB, parts[0] + "/" + parts[1])}}}@@ -67,6 +114,9 @@ data class Origin() {fun gitHub(): GitHubRepo? = GitHubRepo.parse(repo)+ /** The repository's page on its host. */+ fun page(): String? = gitHub()?.page+/** "v1.2.0 · 3f2a9c1" for the details. */fun label(): String = listOfNotNull(ref.takeIf { it != GitHubRepo.HEAD }, commit?.take(7)).joinToString(" · ").ifEmpty { ref }}@@ -88,9 +138,10 @@ object GitHub {/** The tag a `releases/latest` redirect points to (`…/releases/tag/v1.2.0` → `v1.2.0`); null otherwise. */fun tagFromLocation(location: String?): String? {val l = location ?: return null- val i = l.indexOf("/releases/tag/")- if (i < 0) return null- return java.net.URLDecoder.decode(l.substring(i + "/releases/tag/".length).substringBefore('?').substringBefore('#'), "UTF-8").takeIf { it.isNotBlank() }+ // GitHub and Codeberg: …/releases/tag/<tag>; GitLab: …/-/releases/<tag>.+ val marker = listOf("/releases/tag/", "/-/releases/").firstOrNull { l.contains(it) } ?: return null+ val tag = java.net.URLDecoder.decode(l.substring(l.indexOf(marker) + marker.length).substringBefore('?').substringBefore('#'), "UTF-8")+ return tag.takeIf { it.isNotBlank() && it != "permalink" && !it.startsWith("permalink/") }}/**@@ -100,6 +151,7 @@ object GitHub {*/fun repoOf(url: String?): String? {val u = runCatching { java.net.URI(url ?: return null) }.getOrNull() ?: return null+ if (u.host == "gitlab.com" || u.host == "codeberg.org") return GitHubRepo.parse("https://${u.host}${u.path.orEmpty()}")?.slugif (u.host !in setOf("github.com", "codeload.github.com", "raw.githubusercontent.com")) return nullval parts = u.path.orEmpty().trim('/').split('/')if (parts.size < 2) return null@@ -116,7 +168,7 @@ object GitHub {append("https://github.com/").append(OFFICIAL_REPO).append("/issues/new?template=report-extension.yml&labels=report")append("&title=").append(enc("Report: $id"))append("&extension=").append(enc(id)).append("&version=").append(enc(version))- repo?.let { append("&source=").append(enc("https://github.com/$it")) }+ repo?.let { append("&source=").append(enc(GitHubRepo.parse(it)?.page ?: "https://github.com/$it")) }sha256?.let { append("&sha256=").append(enc(it)) }}diff --git a/base/extensions/src/test/kotlin/app/myspoti/extensions/GitHubTest.kt b/base/extensions/src/test/kotlin/app/myspoti/extensions/GitHubTest.ktindex bfb619fa..0c877a30 100644--- a/base/extensions/src/test/kotlin/app/myspoti/extensions/GitHubTest.kt+++ b/base/extensions/src/test/kotlin/app/myspoti/extensions/GitHubTest.kt@@ -153,6 +153,16 @@ class GitHubTest {{ "number": 1, "user": { "login": "x" }, "repository_url": "https://api.github.com/repos/x/unknown", "reactions": { "+1": 5 } } ] }""", setOf("me/ext"))assertEquals(mapOf("me/ext" to Rating(12, 2, 3)), ratings)+ val gitlab = Discovery.parseGitLab("""[ { "path_with_namespace": "grp/ext", "description": "d", "web_url": "https://gitlab.com/grp/ext", "default_branch": "main",+ "last_activity_at": "2026-01-02T00:00:00Z", "star_count": 3, "archived": false, "topics": ["myspoti-extension"] },+ { "path_with_namespace": "grp/old", "archived": true } ]""").single()+ assertEquals("gitlab:grp/ext", gitlab.repo!!.slug)+ assertEquals("https://gitlab.com/grp/ext/-/raw/main/manifest.json", gitlab.manifestUrl())+ val codeberg = Discovery.parseCodeberg("""{ "ok": true, "data": [ { "full_name": "me/ext", "html_url": "https://codeberg.org/me/ext", "default_branch": "trunk",+ "updated_at": "2026-01-02T00:00:00Z", "stars_count": 1, "archived": false, "empty": false }, { "full_name": "me/none", "empty": true } ] }""").single()+ assertEquals("codeberg:me/ext", codeberg.repo!!.slug)+ assertEquals("https://codeberg.org/me/ext/raw/trunk/manifest.json", codeberg.manifestUrl())+ assertEquals("trunk", Discovery.parseDefaultBranch("""{ "default_branch": "trunk" }"""))assertEquals(41L, Discovery.parseDownloads("""{ "assets": [ { "name": "extension.zip", "download_count": 41 }, { "name": "other.zip", "download_count": 9 } ] }"""))assertEquals(9L, Discovery.parseDownloads("""{ "assets": [ { "name": "other.zip", "download_count": 9 } ] }"""))assertNull(Discovery.parseDownloads("""{ "assets": [] }"""))@@ -174,7 +184,21 @@ class GitHubTest {assertEquals("me/ext", GitHubRepo.parse("https://github.com/me/ext.git/")?.slug)assertEquals("me/ext", GitHubRepo.parse("github.com/me/ext/releases")?.slug)assertEquals("me/ext", GitHubRepo.parse("me/ext")?.slug)- assertNull(GitHubRepo.parse("https://gitlab.com/me/ext"))+ val gl = GitHubRepo.parse("https://gitlab.com/grp/sub/ext.git/-/tree/main")!!+ assertEquals("gitlab:grp/sub/ext", gl.slug)+ assertEquals("https://gitlab.com/grp/sub/ext/-/raw/v1/manifest.json", gl.raw("v1", "manifest.json"))+ assertEquals("https://gitlab.com/grp/sub/ext/-/archive/main/ext-main.zip", gl.archive("main", false))+ assertEquals(gl, GitHubRepo.parse(gl.slug))+ val cb = GitHubRepo.parse("https://codeberg.org/me/ext/src/branch/main")!!+ assertEquals("codeberg:me/ext", cb.slug)+ assertEquals("https://codeberg.org/me/ext/raw/main/manifest.json", cb.raw("main", "manifest.json"))+ assertEquals("https://codeberg.org/me/ext/archive/v1.zip", cb.archive("v1", true))+ assertEquals("https://codeberg.org/me/ext/releases/download/v1/extension.zip", cb.releaseAsset("v1"))+ assertNull(gl.releaseAsset("v1"))+ assertEquals("v2", GitHub.tagFromLocation("https://gitlab.com/grp/ext/-/releases/v2"))+ assertNull(GitHub.tagFromLocation("https://gitlab.com/grp/ext/-/releases/permalink/latest"))+ assertEquals("codeberg:me/ext", GitHub.repoOf("https://codeberg.org/me/ext/archive/main.zip"))+ assertNull(GitHubRepo.parse("https://example.com/me/ext"))assertNull(GitHubRepo.parse("https://example.com/ext.zip"))assertNull(GitHubRepo.parse("me"))assertEquals("v1.2.0", GitHub.tagFromLocation("https://github.com/me/ext/releases/tag/v1.2.0"))diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.ktindex 7cb734ff..a15d000a 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/PlaybackService.kt@@ -169,30 +169,62 @@ class PlaybackService : MediaBrowserServiceCompat() {/** A Spotify Connect device plays (the session's volume is that device's). */private var playingRemote = false+ /**+ * The car (Android Auto, Bluetooth) binds to this service without ever starting it. A bound-only+ * service cannot always promote itself to the foreground from the background (Android 12+), and+ * the app is then just a cached process the system freezes a few seconds into a song: playback+ * paused by itself and the car's buttons went dead. Every command that makes sound starts the+ * service for real (the media session's callback is allowed to, and [onStartCommand] goes+ * foreground at once), so it also outlives the car's binding.+ */+ private fun ensureStarted() {+ if (foreground) return+ runCatching { androidx.core.content.ContextCompat.startForegroundService(this, Intent(this, PlaybackService::class.java)) }+ .onFailure { android.util.Log.w("Myspoti", "service not started from a car command: ${it.message}") }+ }++ /** Runs a system command on the app's player; a command with nobody to take it is logged, not lost silently. */+ private inline fun command(name: String, wake: Boolean = true, run: PlaybackControls.() -> Unit) {+ Logbook.log("media session: $name")+ if (wake) ensureStarted()+ val c = controls+ if (c == null) android.util.Log.w("Myspoti", "media session: $name dropped, the player is not attached yet") else c.run()+ }+private val callback = object : MediaSessionCompat.Callback() {- override fun onPlay() { controls?.play() }- override fun onPause() { controls?.pause() }- override fun onSkipToNext() { controls?.next() }- override fun onSkipToPrevious() { controls?.previous() }- override fun onSeekTo(pos: Long) { controls?.seekTo(pos) }- override fun onStop() { controls?.pause() }- override fun onPlayFromMediaId(mediaId: String, extras: Bundle?) { controls?.playFromMediaId(mediaId) }- override fun onPlayFromSearch(query: String, extras: Bundle?) { controls?.playFromSearch(query) }+ override fun onPlay() = command("play") { play() }+ override fun onPrepare() { Logbook.log("media session: prepare") }+ override fun onPause() = command("pause", wake = false) { pause() }+ override fun onSkipToNext() = command("next") { next() }+ override fun onSkipToPrevious() = command("previous") { previous() }+ override fun onSeekTo(pos: Long) = command("seek", wake = false) { seekTo(pos) }+ override fun onStop() = command("stop", wake = false) { pause() }+ override fun onPlayFromMediaId(mediaId: String, extras: Bundle?) = command("play $mediaId") { playFromMediaId(mediaId) }+ override fun onPlayFromSearch(query: String, extras: Bundle?) = command("play from search") {+ // "Play music" with no words (Assistant, the car's voice button) is a plain play, not a search.+ if (query.isBlank()) play() else playFromSearch(query)+ }override fun onCustomAction(action: String, extras: Bundle?) {when (action) {- ACTION_LIKE -> controls?.setLiked(!(current?.liked ?: false))- ACTION_SHUFFLE -> controls?.setShuffle(!(current?.shuffle ?: false))+ ACTION_LIKE -> command("like", wake = false) { setLiked(!(current?.liked ?: false)) }+ ACTION_SHUFFLE -> command("shuffle", wake = false) { setShuffle(!(current?.shuffle ?: false)) }}}}- private fun apply(info: NowPlayingInfo) {+ private fun apply(raw: NowPlayingInfo) {+ // Every surface fed from here (notification, lock screen, car, Bluetooth) is large: the queue and+ // the lists hand over the 64/300 px id, whatever the caller did; also the key of the cover cache.+ val info = raw.coverUrl?.let { raw.copy(coverUrl = Covers.large(it)) } ?: raw+ // A bitmap recycled behind our back (issue #77: "cannot use a recycled source in createBitmap"+ // thrown by MediaMetadata.Builder.build) is dropped and fetched again, never handed to the session.+ if (cover?.isRecycled == true) { cover = null; lastCoverUrl = null }// Before the metadata: a cached cover is in it at once. A cover that failed (offline, Doze with the screen off, a 5xx) is asked again on the next// real state change: it used to stay bare until the next song.if (info.coverUrl != lastCoverUrl || (cover == null && !info.coverUrl.isNullOrBlank() && coverJob?.isActive != true)) {loadCover(info.coverUrl)}- session.setMetadata(MediaMetadataCompat.Builder()+ val metadata = fun(withArt: Boolean) = (MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, info.id).putString(MediaMetadataCompat.METADATA_KEY_TITLE, info.title).putString(MediaMetadataCompat.METADATA_KEY_ARTIST, info.artist)@@ -201,11 +233,15 @@ class PlaybackService : MediaBrowserServiceCompat() {.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, info.durationMs).apply {// Both keys: the lock screen, the shade, Bluetooth and the car do not read the same one.- val art = cover.takeIf { info.coverUrl == lastCoverUrl }+ val art = cover.takeIf { withArt && info.coverUrl == lastCoverUrl && it?.isRecycled == false }putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, art)putBitmap(MediaMetadataCompat.METADATA_KEY_ART, art)}.build())+ runCatching { session.setMetadata(metadata(true)) }.onFailure {+ android.util.Log.w("Myspoti", "session art rejected, metadata without it: $it")+ session.setMetadata(metadata(false))+ }val state = when {info.buffering && info.playing -> PlaybackStateCompat.STATE_BUFFERINGinfo.playing -> PlaybackStateCompat.STATE_PLAYING@@ -226,7 +262,7 @@ class PlaybackService : MediaBrowserServiceCompat() {private fun loadCover(url: String?) {coverJob?.cancel()lastCoverUrl = url- cover = url?.let { covers.get(it) }+ cover = url?.let { covers.get(it) }?.takeIf { !it.isRecycled }if (url.isNullOrBlank() || cover != null) returncoverJob = scope.launch {// Retried with a growing pause: a failed load used to be forgotten.@@ -427,7 +463,13 @@ class PlaybackService : MediaBrowserServiceCompat() {android.util.Log.w("Myspoti", "media browser: empty root for $clientPackageName")return BrowserRoot(EMPTY_ROOT_ID, null)}- return BrowserRoot(ROOT_ID, Bundle().apply { putBoolean("android.media.browse.SEARCH_SUPPORTED", true) })+ return BrowserRoot(ROOT_ID, Bundle().apply {+ putBoolean("android.media.browse.SEARCH_SUPPORTED", true)+ // Without this the car ignores the list / grid hints of the folders (AutoBrowser).+ putBoolean("android.media.browse.CONTENT_STYLE_SUPPORTED", true)+ putInt("android.media.browse.CONTENT_STYLE_BROWSABLE_HINT", 1)+ putInt("android.media.browse.CONTENT_STYLE_PLAYABLE_HINT", 1)+ })}override fun onLoadChildren(parentId: String, result: Result<MutableList<MediaBrowserCompat.MediaItem>>) {@@ -557,6 +599,8 @@ class PlaybackService : MediaBrowserServiceCompat() {) returnsvc.apply(info)svc.show(info)+ // Sound with no foreground service (bound by the car only, promotion refused): start it.+ if ((info.playing || info.buffering) && !svc.foreground) svc.ensureStarted()}/** Signed out: the notification and the media session go, nothing of the account stays. */