Native Android client for Spotify, built with Jetpack Compose
Kotlin ad-freeadblockandroidjetpack-composekotlinlyricsmusic-playermusic-videomyspotispotifyspotify-adblockerspotify-clientspotify-connectspotui
Word-by-word lyrics from more sources, Genius meanings, clips with their own sound, collaborative playlists, an add-songs screen, Spotify Codes, a new welcome screen and README
kota-zo8bca14946bcd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6159596e..74e17476 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,18 @@ Each release on GitHub shows its section below. The app shows it too when it off## Unreleased+- **Word-by-word lyrics from more sources** (Apple Music timing through LyricsPlus, lrc.red, Kugou), lined up with Spotify's own, words lit whole as they are sung; a setting picks word by word or line by line.+- **Song meanings from Genius**: the light bulb opens the story of the song; underlined lines open their explanation with a long press, best-liked first, translated into your language as they arrive.+- **Music videos with their own sound**: "Sound: clip" plays the clip's audio while the song keeps playing silently on Spotify (it still counts). Clips in 1080p on Wi-Fi, fewer freezes, the full-screen button in the clip's corner, the right cover after the clip, and label uploads found when Spotify itself has the video.+- **Add songs to a playlist** from a Spotify search right under its cover, with suggestions.+- **Collaborative playlists**: invite with a link, members' faces in the header, who added each song, and collaborators can add and remove songs.+- **Share as a Spotify Code**, with the link under it.+- **Queue**: a line shows where a dragged song will land, and a song moved into or out of the queue no longer gets stuck.+- **Smart Shuffle**: suggested songs are marked and can be kept with +, and they light up when they play.+- **Shared links open the page** (playlist, album, artist, show) instead of starting it.+- **Fixed**: a crash when typing or deleting in a playlist's search while music plays, a skip when a clip went full screen, the status bar over the login page, the + of a song played from your own playlist, and lyrics hard to read on some colours.+- **A crash or a freeze now shows in the next diagnostic report.**+- **A new welcome screen** and a smoother setup.- **Smoother player, lighter on the battery**: the hidden player page was redrawn with every frame the app drew (and kept animating its own UI underneath), and the progress bar redrew the whole player 15 times a second. The page now stays out of the app's drawing and the bar redraws only itself, as often as it actually moves. Measured on the player screen: 0 late frames instead of 86 %, about a third less CPU — and a tap on a song or "next" is heard ~150 ms sooner.- **The player recovers from a page that fails to load**: when Spotify answered an error to a reload (seen: 504), the app stayed on it, refusing every command until restarted. The page is now loaded again, sooner first, then every minute.- **"Next" that does nothing**: when the player page answered "ok" to a skip but stayed on the song (the sound dipped, then nothing), the song after it is now asked for by name.diff --git a/README.md b/README.mdindex 98c7c12b..f3df99b9 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@[](LICENSE)[](https://discord.gg/jXKnGVFnGS)-**Spotify on Android, free account, no ads.** A native Jetpack Compose client with synced lyrics and official music videos.+**Spotify without ads, with downloads, on a free account.** Your own Spotify account, playlists and Wrapped, in a native Android app that blocks the ads and lets you download your music in lossless quality.<p align="center"><img src="docs/screenshots/banner.jpg" alt="Myspoti: home, player, artist and album screens" width="100%">@@ -14,37 +14,82 @@<a href="https://github.com/kota-zo/myspoti/releases/latest"><b>⬇ Download the latest APK</b></a></p>-The official Spotify Web Player runs in a hidden WebView and does the actual playback, with the phone's DRM and Spotify's own reporting. The native UI drives it, so plays count on your account exactly as they do in a browser. You always sign in yourself, on Spotify's own login page.-<p align="center"><a href="https://ko-fi.com/kotazo"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" alt="Support Myspoti on Ko-fi" height="56"></a><a href="https://github.com/sponsors/kota-zo"><img src="https://img.shields.io/badge/Sponsor_on_GitHub-%E2%9D%A4-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="Sponsor kota-zo on GitHub" height="56"></a></p>-## Features+## Why Myspoti-- **No ads.** The ad audio is refused, so the player skips each ad within a second. It works with a free account: no Premium, no patched Spotify app, and the DRM is left untouched.-- Home (with Music, Podcasts and Audiobooks filters), search (songs, artists, albums, playlists, podcasts, episodes), **New releases**, Spotify's real **Browse** categories, library (folders, sorting, drag to reorder), artist, album and playlist pages, with Spotify's official labels.-- **Podcasts and audiobooks**: shows, episodes, chapters, Your Episodes, playback speed.-- **Jam**: join a Jam with an invite link.-- Synced lyrics: Spotify first, then [LRCLIB](https://lrclib.net); optionally Apple Music (word by word), NetEase and Genius.-- **Your recap**: your top tracks, artists and albums, counting Spotify, downloads and local files. It stays on your phone.-- Official music videos, when one exists. The video plays muted, in sync with the song. The app only uses YouTube videos marked as official clips, and shows nothing when no clip exists.-- Spotify Connect, media notification, lock screen, Bluetooth and Android Auto.-- **Offline downloads.** Download a song, an album, a playlist or your Liked Songs, then play them without a connection. The audio comes lossless (FLAC, 16-bit or 24-bit hi-res when it exists), or as Tidal's own AAC for the smallest files: the very recording, found on Tidal (or Qobuz) by its exact ISRC, through the same signed servers as [SpotiFLAC Mobile](https://github.com/zarzet/SpotiFLAC-Mobile)'s extensions, after a one-off verification in Settings. Each file is checked against the recording's official preview (looked up by ISRC), so a live take, a remix or a cover is rejected. Files stay in Myspoti's private storage.-- **Sound quality and Settings.** Streaming quality (Automatic, Low, Normal, High) and download quality are picked at the first start and kept in one Settings page, with data saver, battery, display and language.-- **Connect with your headphones.** Their name shows instead of "This phone", one tap sends the sound back to the speaker, and a quality badge shows what plays now. The music pauses when headphones or Bluetooth go away.-- English, French and Italian.+### 🚫 Spotify with no ads, on a free account+No audio ads, no video ads, no banners, and no 30-second break between songs. Myspoti switches off the ad breaks of Spotify's own player, so a free account plays like Premium: pick any song, skip as much as you want. No Premium, no modified Spotify app, nothing to root.-## How it works+### ⬇️ Download your music, in lossless+Download a song, an album, a playlist or all your Liked Songs, and listen with no connection: on the plane, in the metro, with no data. The audio is better than Spotify's own: **lossless FLAC** (CD quality, or 24-bit hi-res when it exists), or small AAC files if you prefer. Each song is the very same recording, found by its ISRC on Tidal or Qobuz and checked before it is kept (after a one-off verification in Settings). Downloaded playlists stay in step: songs you add on Spotify download by themselves.-The app is split in two:+### ✨ And everything you expect from Spotify, and more+Your home, search, library, playlists, podcasts, Spotify Connect and Android Auto, plus **word-by-word lyrics**, **official music videos** and **song meanings from Genius**.-- **`:api`** is the contract the UI talks to: plain Kotlin models and interfaces (player, search, catalog, library, playlists, home, podcasts, users, lyrics, devices, Jam).-- **`:api-spotify`** implements it on Spotify's Web Player. Playback stays in the official player, in a hidden WebView (`:host-android`), driven by a small bridge script. Catalog, search and library calls go straight to Spotify's servers, which is faster. When Spotify ships a new Web Player, the app reads its new operation list from the public files by itself.-- **`:host-cdp`** runs the same API on desktop Chrome: the whole API is tested against the real Web Player, without a phone.+## What is it?++Myspoti is a Spotify app for Android that you install yourself. You sign in with your usual Spotify account, on Spotify's own login page: Myspoti never sees your password. A free account is enough.++Under the hood, the official Spotify Web Player plays the music, hidden inside the app, with your phone's DRM. Myspoti draws its own screens on top and drives it. Your plays are reported to Spotify exactly as in a browser: they count for the artists, in your history and in your Wrapped.++## Get started++1. Download the APK from the [latest release](https://github.com/kota-zo/myspoti/releases/latest) and open it (Android 10 or later). Android asks once to allow installs from your browser or file manager.+2. Tap **Log in with Spotify** and sign in.+3. Pick the sound quality, allow what you want (notifications, Bluetooth, local files…), and you are in.++New versions are offered inside the app: one tap downloads and installs them.++## What you get++**Listening**+- No ads (see above).+- Home, search, Browse, New releases, Your Library with folders, artist, album, playlist and profile pages, with Spotify's own content.+- Pick any song: shuffle, Smart Shuffle, the queue (drag to reorder), repeat, crossfade, sleep timer.+- Podcasts and audiobooks, with their own player (speed, ±15 s, mark as played).+- Spotify Connect, Jam, Bluetooth with your headphones' name, lock screen, notification, widget and Android Auto.-Details for developers: [`base/api-spotify/README.md`](base/api-spotify/README.md) and [`docs/api`](docs/api).+**Lyrics and videos**+- Synced lyrics, word by word when a source has the timing (or line by line, your choice in Settings), with translation.+- **Song meanings from Genius**: a light bulb for the story of the song, and a long press on an underlined line for its explanation, translated into your language.+- **Official music videos**, in sync with the song, in full screen if you like. Play them silently over the song, or hear the clip's own sound while the song keeps counting on Spotify.++**Your playlists**+- Create, edit (name, description, cover), sort, make public, private or collaborative.+- **Add songs** from a Spotify search inside the playlist, with suggestions.+- **Collaborative playlists**: invite friends with a link, see who is in, and who added each song.+- Share any song, album, artist or playlist as a **Spotify Code** (scannable in the Spotify app) or a link.++**Offline**+- Download songs, albums, playlists and Liked Songs, in **lossless FLAC** (CD or hi-res) or small AAC. The very recording is found by its ISRC on Tidal or Qobuz and checked before it is kept.+- Downloads are encrypted and stay in Myspoti. Lists you downloaded stay in step with Spotify.+- Your local audio files too.++**And also**+- Your recap: your top songs, artists and albums, kept on your phone.+- 7 languages: English, French, German, Spanish, Italian, Portuguese and Greek.+- Data saver, battery saver, AMOLED black, accent colour.++## New since 1.1++Version 2.0 is a new app, rebuilt from the ground up.++- 🚀 **A new engine**: faster screens, quicker skips, and playback that recovers by itself when Spotify's player stumbles.+- 🚫 **Ads stopped at the source** instead of skipped.+- 🎧 **Lossless downloads** (FLAC, hi-res) instead of YouTube audio, encrypted on your phone.+- 🎤 **Word-by-word lyrics**, from more sources, with **Genius song meanings**.+- 🎬 **Music videos with their own sound**, in full screen, in better quality.+- 👥 **Collaborative playlists**, an **Add songs** screen, and full playlist editing.+- 🔀 **Smart Shuffle**, a draggable queue, crossfade.+- 🎙️ **Podcasts and audiobooks** are back, with their own player and downloads.+- 📷 **Spotify Codes** to share, and profiles, Recents, Browse and New releases.+- 🌍 **Four new languages**, in-app updates and a diagnostic report you can send in one tap.++Every change is in the [changelog](CHANGELOG.md).## Screenshots@@ -52,38 +97,44 @@ Details for developers: [`base/api-spotify/README.md`](base/api-spotify/README.m|:---:|:---:|:---:|:---:|| <img src="docs/screenshots/home.jpg" width="200" alt="Home"> | <img src="docs/screenshots/player.jpg" width="200" alt="Player"> | <img src="docs/screenshots/artist.jpg" width="200" alt="Artist"> | <img src="docs/screenshots/album.jpg" width="200" alt="Album"> |-## Not included+## Questions-- No DRM circumvention. No Amazon stream decryption.-- No Spotify audio download. Offline downloads are resolved from lossless catalogues through the open-backends community of SpotiFLAC; a track with no lossless source is simply marked unavailable.-- Downloaded songs played on the phone are not reported to Spotify: they do not count in Wrapped or in artists' play counts. They are kept in Myspoti's own Recap only. No ad is marked as heard.+**Is it safe for my account?** Myspoti talks to Spotify the way its web player does, and you sign in on Spotify's own page. Blocking ads is still against Spotify's Terms of Use (see the disclaimer below).-## Credits+**"Spotify refused to play this"?** Some new or free accounts get refused by Spotify. Settings → **Export a diagnostic report** and send it on [Discord](https://discord.gg/jXKnGVFnGS) or in an [issue](https://github.com/kota-zo/myspoti/issues): it holds the app's recent log (what Spotify answered) and your phone's model, never your password or your login tokens.-- [SpotiFLAC](https://github.com/spotbye/SpotiFLAC) (MIT) — the lossless resolving idea, its community backend protocol and the gated-session flow.-- [Spotui](https://github.com/Spotui/Spotui) (GPL-3.0) — the Kotlin port of the resolver, the signed-session verification screen and the DASH-to-FLAC remux that Myspoti builds on.-- [SpotiFLAC Mobile](https://github.com/zarzet/SpotiFLAC-Mobile) (MIT) and its [extensions](https://github.com/zarzet/SpotiFLAC-Extension) (Apache-2.0) — the signed download sessions and the Tidal / Qobuz download requests.+**Do downloads count in my Wrapped?** No. Songs played from a download are not reported to Spotify; they count in Myspoti's own recap only. Streamed songs and music videos count as usual.-Full notices: [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).+**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 Tidal or Qobuz sources. Nothing is sent to the developer.++## Not included++- No DRM circumvention, and no Spotify audio download: offline songs come from lossless catalogues, and a song with no lossless source is marked unavailable.+- No ad is ever marked as heard.## DisclaimerBlocking ads goes against Spotify's Terms of Use, and Spotify may suspend accounts that do it. Use this app at your own risk. If you can, support artists with Premium or by buying their music.+Not affiliated with or endorsed by Spotify. Spotify is a trademark of Spotify AB.+## Support-Myspoti is free, has no ads and is made in my spare time. If you enjoy it, you can support it on [Ko-fi](https://ko-fi.com/kotazo) or [GitHub Sponsors](https://github.com/sponsors/kota-zo), also from **About** in the app's profile menu. Nothing in the app is locked behind a donation.+Myspoti is free, has no ads and is made in my spare time. If you enjoy it, you can support it on [Ko-fi](https://ko-fi.com/kotazo) or [GitHub Sponsors](https://github.com/sponsors/kota-zo), also from **About** in the app. Nothing is locked behind a donation.-<p align="center">- <a href="https://ko-fi.com/kotazo"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" alt="Support Myspoti on Ko-fi" height="56"></a>- <a href="https://github.com/sponsors/kota-zo"><img src="https://img.shields.io/badge/Sponsor_on_GitHub-%E2%9D%A4-ea4aaa?style=for-the-badge&logo=githubsponsors&logoColor=white" alt="Sponsor kota-zo on GitHub" height="56"></a>-</p>+News, help and ideas: the [Discord server](https://discord.gg/jXKnGVFnGS). Bugs and requests: [GitHub issues](https://github.com/kota-zo/myspoti/issues).++## For developers-News, help and ideas: join the [Discord server](https://discord.gg/jXKnGVFnGS). Bugs and requests are also welcome in [GitHub issues](https://github.com/kota-zo/myspoti/issues).+The Android project is in `base/`, split in two:++- **`:api`** is the contract the UI talks to: plain Kotlin models and interfaces (player, search, catalog, library, playlists, home, podcasts, users, lyrics, devices, Jam).+- **`:api-spotify`** implements it on Spotify's Web Player. Playback stays in the official player, in a hidden WebView (`:host-android`), driven by a small bridge script. Catalog, search and library calls go straight to Spotify's servers. When Spotify ships a new Web Player, the app reads its new operation list by itself.+- **`:host-cdp`** runs the same API on desktop Chrome, so the whole API is tested against the real Web Player without a phone.-## Build+More: [`base/api-spotify/README.md`](base/api-spotify/README.md) and [`docs/api`](docs/api).-The Android project is in `base/`. Requirements: JDK 17+ and the Android SDK (compileSdk 37).+Requirements: JDK 17+ and the Android SDK (compileSdk 37).```bashcd base@@ -98,17 +149,19 @@ google-chrome --user-data-dir="$HOME/.myspoti-chrome" --remote-debugging-port=92./gradlew :host-cdp:test -Pcdp=http://localhost:9222```-Every push builds and tests on GitHub Actions. A `v*` tag publishes a signed APK in Releases; the app finds it, downloads it and installs it through Android's installer.+Every push builds and tests on GitHub Actions. A `v*` tag publishes a signed APK in Releases.## Credits-- UI derived from [Spotui](https://github.com/Spotui/Spotui) / [Metrolist](https://github.com/MetrolistGroup/Metrolist) (GPL-3.0).-- [NewPipeExtractor](https://github.com/TeamNewPipe/NewPipeExtractor) (GPL-3.0).-- [Material Icons](https://github.com/google/material-design-icons) (Apache 2.0).-- [Figtree](https://github.com/erikdkennedy/figtree) font (SIL OFL 1.1, see `base/licenses/`).+- UI derived from [Spotui](https://github.com/Spotui/Spotui) / [Metrolist](https://github.com/MetrolistGroup/Metrolist) (GPL-3.0); Spotui also gave the Kotlin port of the lossless resolver, the verification screen and the DASH-to-FLAC remux.+- [SpotiFLAC](https://github.com/spotbye/SpotiFLAC) (MIT): the lossless resolving idea and its community backend protocol.+- [SpotiFLAC Mobile](https://github.com/zarzet/SpotiFLAC-Mobile) (MIT) and its [extensions](https://github.com/zarzet/SpotiFLAC-Extension) (Apache-2.0): the signed download sessions and the Tidal / Qobuz requests.+- [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 [Figtree](https://github.com/erikdkennedy/figtree) font (SIL OFL 1.1, see `base/licenses/`).++Full notices: [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).## LicenseGPL-3.0.--Not affiliated with or endorsed by Spotify. Spotify is a trademark of Spotify AB.diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.ktindex ef980562..bc42a5dc 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/Mappers.kt@@ -44,6 +44,7 @@ internal fun track(d: JsonElement?, uid: String? = null): Track? {explicit = d.str("contentRating.label") == "EXPLICIT",playable = d.bool("playability.playable") ?: true,uid = uid,+ hasVideo = (d.long("associationsV3.videoAssociations.totalCount") ?: 0) > 0,)}@@ -103,6 +104,7 @@ internal fun playlist(d: JsonElement?): Playlist? {ownerUri = d.str("ownerV2.data.uri"),ownerImages = images(d.list("ownerV2.data.avatar.sources")),followers = d.long("followers"),+ isBlend = d.str("format") == "blend",)}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.ktindex cb60c22d..707d0905 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyApi.kt@@ -62,6 +62,7 @@ class SpotifyApi(override val extras = SpotifyTrackExtras(gql, bridge, this.http)override val devices = SpotifyDevices(bridge)override val jam = SpotifyJam(bridge)+ override val blends = SpotifyBlends(this.http)override val recents = SpotifyRecents(gql)/** Escape hatch to the 179 GraphQL operations and 89 page services, for what is not typed yet. */@@ -98,6 +99,8 @@ class SpotifyApi(/** True when the page's token belongs to a signed-in user (the cached one is reused). */suspend fun isSignedIn(): Boolean = http.isSignedIn()+ /** What the token in hand says, without asking the page (null: none yet); for logs. */+ fun signedInHint(): Boolean? = http.signedInHint()suspend fun awaitReady() { ready.first { it } }}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyBlends.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyBlends.ktnew file mode 100644index 00000000..231484a5--- /dev/null+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyBlends.kt@@ -0,0 +1,118 @@+package app.myspoti.spotify++import app.myspoti.api.BlendGroup+import app.myspoti.api.BlendInvitation+import app.myspoti.api.BlendInvitationState+import app.myspoti.api.BlendInvite+import app.myspoti.api.BlendMember+import app.myspoti.api.BlendStory+import app.myspoti.api.Blends+import app.myspoti.api.Uri+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.gql.GqlException+import app.myspoti.spotify.gql.HttpException+import app.myspoti.spotify.gql.SpotifyHttp+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put++/**+ * Blends over Spotify's own `blend-invitation` and `blend-writer` services (spclient): the Web+ * Player's Blend routes call generate, view-invitation and join; the Blend page's members, its+ * taste-match card, renaming and leaving are the calls the mobile apps make for the same page.+ * There is no GraphQL operation and no page service for it.+ * An invitation made with [invite] shows as a placeholder in the library of its maker until+ * someone joins; only then does the Blend playlist exist on Spotify's side.+ */+class SpotifyBlends(private val http: SpotifyHttp) : Blends {+ private companion object {+ const val BASE = "https://spclient.wg.spotify.com/blend-invitation"+ const val WRITER = "https://spclient.wg.spotify.com/blend-writer"+ /** The link's path: `/blend/taste-match/{id}` (what the page generates) or `/blend/invitation/{id}`. */+ val LINK_ID = Regex("""/blend/(?:taste-match|invitation)/([A-Za-z0-9]+)""")+ val BARE_ID = Regex("""[A-Za-z0-9]{8,}""")+ }++ override suspend fun invite(): BlendInvite {+ val body = send("POST", "$BASE/v1/generate")+ val link = body.str("invite") ?: throw GqlException("blend-invitation", "no invite link")+ return BlendInvite(idOf(link), link)+ }++ override suspend fun invitation(linkOrId: String): BlendInvitation =+ parseInvitation(send("GET", "$BASE/v3/view-invitation/${idOf(linkOrId)}"))++ /** The `view-invitation` answer, as the page's three Blend screens read it. */+ internal fun parseInvitation(v: JsonElement): BlendInvitation {+ fun member(m: JsonElement?) = m.str("username")?.let { BlendMember(it, m.str("name") ?: it, m.str("image_url")) }+ return BlendInvitation(+ state = when (v.str("page_type")) {+ "PENDING_INVITATION" -> BlendInvitationState.WAITING+ "READY_TO_JOIN_EMPTY_BLEND", "READY_TO_JOIN_ALREADY_CREATED_BLEND" -> BlendInvitationState.JOINABLE+ "MAX_MEMBERS" -> BlendInvitationState.FULL+ "ALREADY_JOINED" -> BlendInvitationState.JOINED+ "DELETED" -> BlendInvitationState.DELETED+ else -> BlendInvitationState.UNKNOWN+ },+ title = v.str("title"), subtitle = v.str("subtitle"),+ inviter = member(v.at("recipient")),+ members = v.list("members").mapNotNull { member(it) },+ playlist = v.str("playlist_uri"),+ )+ }++ override suspend fun join(linkOrId: String): Uri {+ val r = send("PUT", "$BASE/v2/join/${idOf(linkOrId)}")+ return r.str("playlist_uri") ?: throw GqlException("blend-invitation", "no playlist after joining")+ }++ override suspend fun group(playlist: Uri): BlendGroup = parseGroup(send("GET", "$BASE/v3/get-invitation/${idOfPlaylist(playlist)}"))++ internal fun parseGroup(v: JsonElement) = BlendGroup(+ title = v.str("title"), inviteLabel = v.str("button_text"), link = v.str("invitation_link"),+ members = v.list("members").mapNotNull { m -> m.str("username")?.let { BlendMember(it, m.str("name") ?: it, m.str("image_url")?.takeIf { u -> u.isNotBlank() }) } },+ )++ override suspend fun story(playlist: Uri): BlendStory? = parseStory(send("GET", "$BASE/v3/data-stories/${idOfPlaylist(playlist)}"))++ /** The intro card (the match score) with the first story's line on the song that brings them together. */+ internal fun parseStory(v: JsonElement): BlendStory? {+ val intro = v.at("intro_story")+ val first = v.list("stories").firstOrNull()+ val title = intro.at("title1").str("text") ?: first.at("subtitle").str("text") ?: return null+ return BlendStory(+ title = title,+ subtitle = intro.at("subtitle1").str("text"),+ detail = first.at("body").str("text"),+ background = intro.str("background_color") ?: first.str("background_color"),+ titleColor = intro.at("title1").str("text_color"),+ textColor = intro.at("subtitle1").str("text_color") ?: first.at("body").str("text_color"),+ image = first.str("image"),+ )+ }++ override suspend fun rename(playlist: Uri, name: String) {+ send("PUT", "$WRITER/v1/rename/${idOfPlaylist(playlist)}", buildJsonObject { put("name", name) }.toString())+ }++ override suspend fun leave(playlist: Uri) {+ send("PUT", "$BASE/v1/leave", buildJsonObject { put("playlist_uri", playlist) }.toString())+ }++ private fun idOfPlaylist(playlist: Uri) = playlist.substringAfterLast(':')++ /** The invitation id inside a pasted link, or the text itself when it is already an id. */+ internal fun idOf(linkOrId: String): String {+ val t = linkOrId.trim()+ return LINK_ID.find(t)?.groupValues?.get(1)+ ?: t.takeIf { BARE_ID.matches(it) }+ ?: throw IllegalArgumentException("not a Blend invitation: $t")+ }++ private suspend fun send(method: String, url: String, body: String? = null): JsonElement {+ val (code, text) = http.send(method, url, body)+ if (code !in 200..299) throw HttpException(code, text.take(200))+ return if (text.isBlank()) JsonNull else Bridge.json.parseToJsonElement(text)+ }+}diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.ktindex 9cbb1438..3bafc1d3 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyLibrary.kt@@ -9,6 +9,8 @@ import app.myspoti.api.MediaKindimport app.myspoti.api.Pageimport app.myspoti.api.Playlistimport app.myspoti.api.PlaylistAccess+import app.myspoti.api.PlaylistMember+import app.myspoti.api.RowAdderimport app.myspoti.api.PlaylistSortimport app.myspoti.api.Playlistsimport app.myspoti.api.SavedTrack@@ -166,6 +168,8 @@ class SpotifyLibrary(private val bridge: Bridge, private val gql: Gql) : Library}}+private const val ADDED_BY_PAGE = 300+class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, private val http: SpotifyHttp) : Playlists {override suspend fun playlist(uri: Uri): Playlist =playlist(gql.query("fetchPlaylist", vars(@@ -195,7 +199,10 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, privateowner = item.str("owner.displayName") ?: item.str("owner.name"),images = item.list("images").mapNotNull { i -> i.str("url")?.let { Image(it, i.int("width"), i.int("height")) } },trackCount = item.int("totalLength") ?: 0,- editable = item.bool("isOwnedBySelf") ?: item.bool("canAdd") ?: false,+ // Owned, or open to this account (a collaborator: not the owner, yet can add).+ // `isOwnedBySelf ?: canAdd` never read canAdd for a collaborator (false is not+ // null): the playlist they joined stayed read-only in the app (reported).+ editable = item.bool("isOwnedBySelf") == true || item.bool("canAdd") == true,)}}@@ -270,6 +277,62 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, privatebridge.service("RootlistAPI", "remove", json(listOf(mapOf("uri" to uri))))}+ /**+ * The page's `claimPermissions` (spclient `POST playlist-permission/v1/playlist/{id}/permission-grant/token/{pt}/claim`,+ * no body, answers `{userPermission:{permissionLevel,revision},capabilities}`); open.spotify.com does the same when+ * it is opened with `?pt=`. Claiming does not say whether the playlist is in the rootlist, so it is followed when not.+ */+ override suspend fun join(uri: Uri, invitationToken: String): PlaylistAccess {+ val claimed = bridge.service("PlaylistPermissionsAPI", "claimPermissions", JsonPrimitive(uri), JsonPrimitive(invitationToken))+ val inLibrary = (bridge.service("RootlistAPI", "contains", JsonArray(listOf(JsonPrimitive(uri)))) as? JsonArray)+ ?.firstOrNull()?.jsonPrimitive?.boolean == true+ if (!inLibrary) follow(uri)+ return PlaylistAccess.of(claimed.str("userPermission.permissionLevel"))+ }++ /**+ * The page's `getPermissionGrant(uri, "CONTRIBUTOR")` (spclient `POST playlist-permission/v1/playlist/{id}/permission-grant`,+ * `{"permission":{"permissionLevel":"CONTRIBUTOR"},"ttlMs":604800000}`, answers `{token, permissionGrantOptions, createdAt}`):+ * what the web player's "Invite collaborators" shares as `open.spotify.com/playlist/{id}?pt={token}`.+ */+ override suspend fun collaboratorInvite(uri: Uri): String {+ val grant = bridge.service("PlaylistPermissionsAPI", "getPermissionGrant", JsonPrimitive(uri), JsonPrimitive("CONTRIBUTOR"))+ val token = grant.str("token")?.takeIf { it.isNotBlank() } ?: error("no invitation token")+ return "https://open.spotify.com/playlist/${uri.substringAfterLast(':')}?pt=$token"+ }++ /**+ * The page's `getMembers(uri)`: `{members:[{permissionLevel, isOwner, user:{displayName, images:[{url}],+ * uri, username}, songsAdded}]}` — the faces shown on a collaborative playlist.+ */+ override suspend fun members(uri: Uri): List<PlaylistMember> =+ bridge.service("PlaylistPermissionsAPI", "getMembers", JsonPrimitive(uri)).list("members").mapNotNull { m ->+ val username = m.str("user.username") ?: return@mapNotNull null+ PlaylistMember(username, m.str("user.displayName") ?: username,+ m.list("user.images").firstNotNullOfOrNull { it.str("url") }, m.bool("isOwner") == true)+ }.sortedByDescending { it.isOwner }++ /**+ * The page's `PlaylistAPI.getContents(uri, {offset, limit})`: each row carries `uid` and+ * `addedBy {username}`. Read a page at a time to the end (a few hundred rows a request).+ */+ override suspend fun addedBy(uri: Uri): List<RowAdder> {+ val out = ArrayList<RowAdder>()+ var offset = 0+ while (offset < 10_000) {+ val page = bridge.service("PlaylistAPI", "getContents", JsonPrimitive(uri),+ json(mapOf("offset" to offset, "limit" to ADDED_BY_PAGE)))+ val items = page.list("items")+ items.forEach { r ->+ val who = r.str("addedBy.username") ?: return@forEach+ out += RowAdder(r.str("uid").orEmpty(), r.str("uri").orEmpty(), who)+ }+ if (items.size < ADDED_BY_PAGE) break+ offset += items.size+ }+ return out+ }+/** Pages through the whole playlist (100 rows a request), then sorts it on the client. */override suspend fun sortedTracks(uri: Uri, sort: PlaylistSort, descending: Boolean): List<Track> {val all = mutableListOf<Track>()@@ -300,9 +363,12 @@ class SpotifyPlaylists(private val gql: Gql, private val bridge: Bridge, privategql.query("moveItemsInPlaylist", vars("playlistUri" to uri, "uids" to uids, "newPosition" to position))}- /** The "Recommended songs" list under an own playlist (playlistextender). */- override suspend fun recommended(uri: Uri, limit: Int): List<Track> {- val body = json(mapOf("playlistURI" to uri, "trackSkipIDs" to emptyList<String>(), "numResults" to limit)).toString()+ /**+ * The "Recommended songs" list under an own playlist (playlistextender). An empty playlist+ * gets some too, from its name (checked live). [skip]: tracks not to suggest again.+ */+ override suspend fun recommended(uri: Uri, limit: Int, skip: List<Uri>): List<Track> {+ val body = json(mapOf("playlistURI" to uri, "trackSkipIDs" to skip.map { it.substringAfterLast(':') }, "numResults" to limit)).toString()val (code, text) = http.send("POST", "https://spclient.wg.spotify.com/playlistextender/extendp/", body, contentType = "application/json")if (code != 200) throw app.myspoti.spotify.gql.HttpException(code, text.take(200))return Bridge.json.parseToJsonElement(text).list("recommendedTracks").mapNotNull { t ->diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.ktindex 68b8d205..ef74fde0 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/SpotifyPlayer.kt@@ -11,8 +11,11 @@ import app.myspoti.spotify.bridge.serviceimport app.myspoti.spotify.bridge.Bridgeimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Job+import kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.delay+import kotlinx.coroutines.flow.collectLatestimport kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNullimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow@@ -31,9 +34,10 @@ import kotlinx.serialization.json.putJsonArray* The Web Player's own player, driven through the bridge.** Ads: hosts refuse the ad audio they know. Such an ad then stays current, buffering at- * 0:00, and the page never moves on by itself: after [AD_STUCK_MS] the song after the last- * one is played. An ad that "plays" (it came without a file, or from another market's ad- * server) is muted at once and, as it refuses skips, the page is reloaded after+ * 0:00, and the page never moves on by itself; it refuses every skip and play ("ad_disallow").+ * After [AD_STUCK_MS] the page is reloaded (a new device, which the ad does not follow) and the+ * song after the last one is played. An ad that "plays" (it came without a file, or from+ * another market's ad server) is muted at once and got past the same way after* [AD_PLAYING_SKIP_MS]; if the page still holds on to it after that reload, it stays muted* until it ends. [adPlaying] says an ad is* on; ads are never exposed in [state] (the last song stays there, buffering).@@ -66,8 +70,6 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var adStateAt = 0L/** The page's own ad managers were switched off for this break (see [BridgeHost]). */@Volatile private var adsOffSent = false- /** The page's in-stream ad manager was asked to end this break (a lighter lever than a reload). */- @Volatile private var adSkipped = false/** How many times the ad mute was sent this break: the media element may appear late. */@Volatile private var adMuteTries = 0/** A pause asked through [pause]; it holds until playback is asked for again, never expires. */@@ -79,8 +81,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop@Volatile private var wantedVolume: Double? = null/** The last [play] sent: (context, track, when), for a refused command's retry. */@Volatile private var lastPlay: Triple<Uri, Uri?, Long>? = null- /** The play an ad came in place of (see [onState]), asked again when the ad is over. */- @Volatile private var pickBeforeAd: Triple<Uri, Uri?, Long>? = null+ /**+ * A song the user picked: the list, the song (null: the list from its start), when, and the+ * order given with it (a sorted list or a smart shuffle plays as that order, not as the list).+ */+ private data class Pick(val context: Uri, val track: Uri?, val at: Long, val order: List<Uri>?, val positionMs: Long? = null)+ /**+ * The pick an ad came in place of, or one made during the ad (the page refuses every play+ * then): asked again when the ad is over (see [onState]).+ */+ @Volatile private var pickBeforeAd: Pick? = null+ /** When the user last played, skipped or picked: what an ad-avoiding skip started earlier must not undo. */+ @Volatile private var userMoveAt = 0L+ /** The last play sent was the user's: only its refusal walks [onRefused]'s steps. */+ @Volatile private var lastPlayRefusable = false/** How far down [onRefused]'s steps the current play went (0: not refused). */@Volatile private var refusalStep = 0@Volatile private var refusalTransferring = false@@ -123,10 +137,17 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopscope.launch { watchStalls() }// One collector, so a mute and the unmute after it never run out of order.scope.launch { _adPlaying.collect { if (it) muteForAd() else unmuteAfterAd() } }+ // An ad on both ways on from the song now playing: the next song is played just before+ // it ends, so the page never reaches the ad (see AdBlock.adAhead).+ scope.launch { app.myspoti.spotify.bridge.AdBlock.ahead.collectLatest { a -> if (a != null) playBeforeAd(a) } }// A reloaded page starts on "auto": the chosen quality is set again.scope.launch {bridge.ready.collect {if (!it) {+ // The ad ahead belonged to the page that went: the new one registers a new+ // device, which that ad does not follow (seen: a play "before the ad" sent to a+ // page still reloading, and refused).+ app.myspoti.spotify.bridge.AdBlock.ahead.value = null// The page went away (reloaded by Android, the WebView or the host): what// played then is picked up again once the new page is there.// A page that unloads reports "nothing plays" first: the song before that counts.@@ -229,8 +250,10 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopresume()if (kotlin.math.abs(s.positionMs - at) > 5_000) seek(at)} else {- val ctx = lost.contextUri ?: uri- play(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = at, order = lastOrder?.takeIf { it.first == ctx }?.second)+ // A state without a list would play the song alone, and Spotify then goes on+ // with its own autoplay: the list of the song before it is the next best.+ val ctx = lost.contextUri ?: lastSong?.contextUri ?: uri+ playNow(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = at, order = lastOrder?.takeIf { it.first == ctx }?.second)}}.onFailure { bridge.logger?.invoke("restore attempt $attempt failed: ${it.message}") }// The play just sent is ours, not the user's.@@ -330,7 +353,13 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop// app in the background (seen: "freezing <renderer pid>" in the system log, then// a reload every minute that could not help). Nothing is lost while paused: the// page is only marked, and the next resume loads it again at once ([resume]).- if (quiet) { pageSuspect = true; frozenMisses = 0; key = null; silentSince = 0L; continue }+ if (quiet) {+ // One missed read proves little (a busy main thread misses one too), and a+ // suspect page makes the next resume ping first: it is marked only after+ // [FROZEN_MISSES] in a row, as a playing page is. Any answer clears it below.+ if (++frozenMisses >= FROZEN_MISSES) pageSuspect = true+ key = null; silentSince = 0L; continue+ }// One silent page is not a dead one: a busy main thread (a long render, a reload// still settling, an ad break starting) also holds the bridge for seconds, and// reloading on the first miss turned a short hiccup into a full page reload — the@@ -359,9 +388,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (tick % VOLUME_CHECK_TICKS == 0) guardVolume(s, media)if (_adPlaying.value) {val ad = adState- // The break just started: the page's own ad managers are switched off, so the- // *next* break never starts (SpotX's adsEnabled patch, done at runtime instead of- // by patching the bundle). The bridge repeats it on every state push.+ // The break just started: the page's own ad managers are switched off once more+ // (the bridge also does it on every state push). This does not keep the server from+ // queueing the next audio ad; the host leaves those out (AdBlock.withoutAds).if (!adsOffSent) {adsOffSent = truerunCatching { bridge.call("ads.off") }@@ -396,33 +425,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval videoAd = ad?.item?.mediaType == "video"val playing = ad != null && !refused && (videoAd || now - adSince > AD_PLAYING_SKIP_MS) && !adReloadedval stuck = refused || playing || now - adSince > AD_BREAK_MAX_MS- // The page's in-stream ad manager can end its own break. Asked once per break,- // before the skip/reload recovery, because that recovery is what the user sees: a- // "Test ad" used to cost a full reload of the page. The recovery below still runs- // if the ad is still there on the next turn.- if (stuck && !adSkipped) {- adSkipped = true- val lever = runCatching { bridge.call("ads.skip") }.getOrNull()- bridge.logger?.invoke("ad ${ad?.item?.name}: asked the page to end the break ($lever)")- adSince = System.currentTimeMillis()- key = null; silentSince = 0L- continue- }+ // Measured on 20/10 (desktop, free account, a real ad with its audio refused): the+ // page now keeps a refused ad current for good (20 min, buffering at 0:00), and+ // neither the in-stream manager's skipToNext nor playing the next song moves it+ // (every skip and play is refused with "ad_disallow"). Only a reload leaves it: the+ // new page registers a new device, which the ad does not follow, and the song after+ // it plays within a second. So the first try is the reload, at once; going through+ // the other levers first cost ~20 s of silence. If an ad is still there after+ // that, playing on is tried, then the reload again.if (stuck) {adAttempts++val last = lastTrackState- // Playing on can land on the same refused ad again: after a few tries the- // page itself is reloaded, which drops the ad break. An ad that "plays" (it- // has no file: silence on the page's clock) refuses every skip ("Skipping is- // not allowed with current content"): straight to the reload.- if (playing) adAttempts = AD_SKIPS_BEFORE_RELOAD + 1if (adRecovery(adAttempts) == "next") {bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: playing the next song (attempt $adAttempts)")last?.let { runCatching { playOn(it) } }} else {- adAttempts = 0adReloaded = true- bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: reloading the player")+ bridge.logger?.invoke("ad stuck on ${ad?.item?.name}: reloading the player (attempt $adAttempts)")if (reloadHost != null) reloadAndPlayOn(last) else last?.let { runCatching { playOn(it) } }}adSince = System.currentTimeMillis()@@ -512,6 +531,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval last = lastPlay ?: returnval now = System.currentTimeMillis()if (now - last.third > REFUSED_WINDOW_MS) return+ // A play of ours (an ad recovery, a reload restore): refused during an ad, and the steps+ // below would replay the list from its start and turn shuffle on, which nobody asked for.+ if (!lastPlayRefusable) { bridge.logger?.invoke("play refused by Spotify: not the user's, left alone"); return }// The step's own transfer refused: the step is judged by the play that follows it.if (refusalTransferring) returnval ctx = last.first@@ -519,8 +541,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopif (step == 1 && last.second == null) step = ++refusalStep// Each step's own play may be refused in its turn: it opens a new window.lastPlay = last.copy(third = now)+ // The list as it was picked: a sorted list or a smart shuffle keeps its order.+ val order = lastOrder?.takeIf { it.first == ctx }?.secondsuspend fun playCtx(track: Uri?) = bridge.call("player.play", buildJsonObject {put("contextUri", ctx)+ order?.let { uris -> putJsonArray("order") { uris.forEach { add(kotlinx.serialization.json.JsonPrimitive(it)) } } }track?.let { put("trackUri", it) }}, timeoutMs = PLAY_TIMEOUT_MS)when (step) {@@ -631,8 +656,8 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopbridge.logger?.invoke("playing the song the skips pointed at: ${i.item.name}")val ctx = i.contextrunCatching {- if (ctx != null) play(ctx, trackUri = uri, order = lastOrder?.takeIf { it.first == ctx }?.second)- else play(uri)+ if (ctx != null) playNow(ctx, trackUri = uri, order = lastOrder?.takeIf { it.first == ctx }?.second)+ else playNow(uri)}.onFailure { bridge.logger?.invoke("intent not played: ${it.message}") }}// The page on it, or the user skipped again (then that song is played).@@ -647,17 +672,103 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}}+ /**+ * Plays [a]'s next song [AD_AHEAD_LEAD_MS] before the song [a] names ends, unless another song+ * plays by then (a skip, a pick). Waits while it is paused or buffering.+ */+ private suspend fun playBeforeAd(a: app.myspoti.spotify.bridge.AdBlock.AdAhead) {+ fun isThat(item: NowPlaying?) = item != null && ((a.songUid != null && item.uid == a.songUid) || item.uri == a.songUri)+ // The reply comes as the song starts: its state may come a moment later.+ withTimeoutOrNull(AD_AHEAD_WAIT_MS) { _state.first { isThat(it?.item) } } ?: return+ // A pick or a skip made from here on is the user's: this song's end is no longer the one+ // to avoid the ad at (the page has not reported the new song yet, so the state alone+ // would still say "that song" and the pick would be overridden by the old queue's next).+ val movedAt = userMoveAt+ while (true) {+ if (!bridge.ready.value || userMoveAt != movedAt) return+ val s = _state.value ?: return+ if (!isThat(s.item)) return+ if (s.isPaused || s.isBuffering) {+ _state.first { it == null || !isThat(it.item) || (!it.isPaused && !it.isBuffering) }+ continue+ }+ val left = s.item!!.durationMs - s.positionAt(System.currentTimeMillis())+ if (left <= AD_AHEAD_LEAD_MS) break+ // Re-read now and then: a seek or a late state moves the end.+ delay((left - AD_AHEAD_LEAD_MS).coerceAtMost(AD_AHEAD_CHECK_MS))+ }+ val ctx = _state.value?.contextUri ?: return+ if (userMoveAt != movedAt) return+ // Clearing the flow below cancels this very block (collectLatest): what follows must+ // finish, or the skip is sent and its put-back never is.+ withContext(NonCancellable) {+ app.myspoti.spotify.bridge.AdBlock.ahead.compareAndSet(a, null)+ bridge.logger?.invoke("ad after this song: ${a.nextUri} played before its end")+ if (skipPastAd(a)) return@withContext+ runCatching { playNow(ctx, trackUri = a.nextUri, order = lastOrder?.takeIf { it.first == ctx }?.second) }+ .onFailure { bridge.logger?.invoke("play before the ad refused: ${it.message}") }+ }+ }++ @Volatile private var adRestore: Job? = null++ /**+ * Skips within the current queue to [a]'s next song, which a new play would reshuffle (measured+ * 21/10, desktop, free account, shuffle on: a new `player.play` in a shuffled context+ * reshuffles the queue, songs vanish from what comes next). With an ad due, `queue.skipTo`+ * leaves the order alone but makes the ad current for ~180 ms (its MP3 is refused by the host),+ * then the page moves on by itself to the song AFTER the target: the target is lost. So it is+ * put back first in the user queue once the page plays on ([restoreAfterAd]).+ * False (nothing done): the target is not in the queue or the skip was refused; the caller plays it.+ */+ private suspend fun skipPastAd(a: app.myspoti.spotify.bridge.AdBlock.AdAhead): Boolean {+ val target = adTargetIn(upcoming(), a.nextUri) ?: return false+ val ok = runCatching { withFade { command("queue.skipTo", ref(target)) } }+ .onFailure { bridge.logger?.invoke("skip past the ad refused (${it.message}): playing ${target.name}") }+ .isSuccess+ if (!ok) return false+ adRestore?.cancel()+ adRestore = scope.launch { restoreAfterAd(a, target) }+ return true+ }++ /**+ * Waits for the song after the ad ([AD_RESTORE_WAIT_MS] at most), then queues [target] first,+ * unless the page plays it itself. `queue.insert` before the first queued item puts it ahead of+ * the user's own queue ([playNext]); with an empty user queue, `queue.add` does (the user queue+ * plays before the context).+ */+ private suspend fun restoreAfterAd(a: app.myspoti.spotify.bridge.AdBlock.AdAhead, target: NowPlaying) {+ val now = withTimeoutOrNull(AD_RESTORE_WAIT_MS) { _state.first { adSkipSettled(it?.item, a) }?.item }+ if (now != null && now.uri == target.uri) { bridge.logger?.invoke("skip past the ad: ${target.name} plays, nothing to put back"); return }+ runCatching { playNext(listOf(target.uri)) }+ .onSuccess { bridge.logger?.invoke("skip past the ad: ${target.name} put back to play next (page on ${now?.name ?: "nothing yet"})") }+ .onFailure { bridge.logger?.invoke("skip past the ad: ${target.name} not put back: ${it.message}") }+ }+private suspend fun playOn(s: PlayerState) {// The user skipped meanwhile: their song, not the one after the last state seen.if (playIntent()) return+ // Or picked one during the ad that is being got past: that one, in the order it was picked.+ pickBeforeAd?.takeIf { System.currentTimeMillis() - it.at < PICK_REPLAY_MS }?.let { pick ->+ pickBeforeAd = null+ bridge.logger?.invoke("playing the song picked during the ad: ${pick.track ?: pick.context}")+ playNow(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order, refusable = true)+ return+ }val ctx = s.contextUrival target = onwardTarget(s, _queue.value?.nextUp.orEmpty())+ // A new play reshuffles a shuffled list (measured 21/10) and does not find a song the user+ // queued in the list: both go on within the queue the page has, as a skip would.+ val inQueue = target?.let { t -> upcoming().firstOrNull { it.uri == t } }+ if (inQueue != null && (s.shuffle || inQueue.provider == "queue") &&+ runCatching { command("queue.skipTo", ref(inQueue), timeoutMs = PLAY_TIMEOUT_MS) }.isSuccess) returnwhen {- ctx != null && target != null -> play(ctx, trackUri = target, order = lastOrder?.takeIf { it.first == ctx }?.second)+ ctx != null && target != null -> playNow(ctx, trackUri = target, order = lastOrder?.takeIf { it.first == ctx }?.second)target != null -> next()// Nothing after it: a song is started again (the page's own end-of-context behaviour);// an episode is left finished rather than replayed from the start.- ctx != null && s.item?.kind == ItemKind.TRACK -> play(ctx, trackUri = s.item?.uri)+ ctx != null && s.item?.kind == ItemKind.TRACK -> playNow(ctx, trackUri = s.item?.uri)}}@@ -683,9 +794,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopadMuteTries = 0// A song picked a moment ago and not playing yet: the ad came in its place.val p = lastPlay- pickBeforeAd = p?.takeIf {+ val came = p?.takeIf {adSince - it.third < PICK_AD_MS && it.second != null && lastTrackState?.item?.uri != it.second- }+ }?.let { Pick(it.first, it.second, it.third, lastOrder?.takeIf { o -> o.first == it.first }?.second) }+ // A pick held from an earlier break stays until it was played or went stale.+ pickBeforeAd = came ?: pickBeforeAd}adState = sadStateAt = System.currentTimeMillis()@@ -703,13 +816,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScoppickBeforeAd = null// Reported (beta.9): a song picked in another playlist, an ad, then the old queue went// on and the song had to be picked again. Not on it after the ad: asked for again.- if (s?.item?.uri != pick.second && System.currentTimeMillis() - pick.third < PICK_REPLAY_MS && liveIntent() == null) {+ // A pick of a whole list (no song) has landed when the page plays that list.+ val landed = if (pick.track != null) s?.item?.uri == pick.track else s?.contextUri == pick.context+ if (!landed && System.currentTimeMillis() - pick.at < PICK_REPLAY_MS && liveIntent() == null) {bridge.logger?.invoke("song picked before the ad not played: asked again")- scope.launch { runCatching { play(pick.first, trackUri = pick.second) } }+ // With the order it was picked in: a sorted list or a smart shuffle is not the list's own.+ scope.launch { runCatching { play(pick.context, trackUri = pick.track, positionMs = pick.positionMs, order = pick.order) } }}}+ shufflePending?.takeIf { System.currentTimeMillis() - it.second < PICK_REPLAY_MS }?.let { (on, _) ->+ if (adJustEnded && s?.shuffle != on) scope.launch { runCatching { setShuffle(on) } }+ }adsOffSent = false- adSkipped = falseadMuteTries = 0// A real song is playing: the fallback after a refusal (play the list without picking the// song) is armed again for the next command, not held once per five seconds for all of them.@@ -774,7 +892,7 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopfadeBackTo = targetfadeBack?.cancel()// The ramp runs in the page, so it goes down while the command is already on its way.- runCatching { fade(FADE_STEPS.map { it * target }) }+ runCatching { fade(FADE_OUT_STEPS.map { it * target }, ms = FADE_OUT_STEP_MS) }try {block()} finally {@@ -788,13 +906,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}val back = fadeBackTo ?: target// Ends on the page player's own volume: a volume change during the fade is kept.- runCatching { fade(FADE_STEPS.reversed().drop(1).map { it * back }, restore = true) }+ runCatching { fade(FADE_IN_STEPS.map { it * back }, restore = true) }.onFailure { runCatching { restoreLevel() } }fadeBackTo = null}}}+ /**+ * The song unheard on this phone while it keeps playing (the music video's own sound is heard+ * instead, see the app's clip sound). Sent again on each new song: the element can change.+ */+ suspend fun setHushed(on: Boolean): Int =+ runCatching { bridge.call("media.hush", buildJsonObject { put("on", on) }).toString().trim('"').toIntOrNull() ?: 0 }.getOrDefault(0)+private suspend fun muteForAd() = runCatching {adMuted = trueadMutedAt = System.currentTimeMillis()@@ -961,11 +1086,37 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}.onFailure { runCatching { restoreLevel() } }}+ /**+ * The user's play (a pick, a list started). The page refuses every play while an ad is on+ * ("ad_disallow", measured 20/10), and each refusal walks [onRefused]'s steps, which play the+ * list from its start and turn shuffle on: the pick is held instead and played, in the order it+ * was given, when the ad is over (see [onState]) or when the ad recovery plays on ([playOn]).+ */override suspend fun play(contextUri: Uri, trackUri: Uri?, index: Int?, positionMs: Long?, order: List<Uri>?) {+ userMoveAt = System.currentTimeMillis()+ // The ad due after the song that played before: a new play brings its own queue, and the+ // put-back of an earlier ad skip would queue that old song after the pick.+ adRestore?.cancel()+ app.myspoti.spotify.bridge.AdBlock.ahead.value = null+ if (_adPlaying.value && index == null) {+ if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = null+ lastOrder = order?.let { contextUri to it }+ pausedByUser = false+ pickBeforeAd = Pick(contextUri, trackUri, System.currentTimeMillis(), order, positionMs)+ bridge.logger?.invoke("pick during an ad: ${trackUri ?: contextUri} held until the ad is over")+ return+ }+ pickBeforeAd = null+ playNow(contextUri, trackUri, index, positionMs, order, refusable = true)+ }++ /** A play sent to the page; [refusable]: the user's own, whose refusal walks [onRefused]'s steps. */+ private suspend fun playNow(contextUri: Uri, trackUri: Uri? = null, index: Int? = null, positionMs: Long? = null, order: List<Uri>? = null, refusable: Boolean = false) {// A new song picked (or the intent itself played): any earlier skip is over.if (trackUri == null || trackUri != liveIntent()?.item?.uri) intent = nulllastOrder = order?.let { contextUri to it }lastPlay = Triple(contextUri, trackUri, System.currentTimeMillis())+ lastPlayRefusable = refusablerefusalStep = 0pausedByUser = falsewithFade {@@ -1057,9 +1208,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopfadeBackTo = lastMedia?.own?.takeIf { it > 0.01 } ?: 1.0fadeBack?.cancel()bridge.logger?.invoke("resume: rising from silence over $RISE_MS ms once the sound starts")- runCatching {- bridge.call("media.rise", buildJsonObject { put("ms", RISE_MS); put("wait", RISE_WAIT_MS) },- timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ // The rise is not waited for: it answers only once the sound has risen, and the resume+ // waited behind that answer. Started undispatched, its call is already on its way to the+ // page (ahead of the resume) when the launch returns; the page arms the silence and then+ // waits for the element's clock, as when it was awaited.+ scope.launch(start = kotlinx.coroutines.CoroutineStart.UNDISPATCHED) {+ runCatching {+ bridge.call("media.rise", buildJsonObject { put("ms", RISE_MS); put("wait", RISE_WAIT_MS) },+ timeoutMs = LEVEL_TIMEOUT_MS, quiet = true)+ }}try {command("player.resume")@@ -1076,7 +1233,21 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun next() {pausedByUser = falsepickBeforeAd = null+ userMoveAt = System.currentTimeMillis()+ adRestore?.cancel()if (skipsHeld) { stepIntent(1); return }+ // An ad is due right after this song: Spotify sends its skip to the ad too, and a page that+ // steps onto an ad that way stays on it (its audio refused). Going to the next song by name+ // gets past it within a second (measured 20/10, desktop), as at the end of the song.+ // Played as a skip within the queue now, not a new play (that reshuffles; see [skipPastAd]).+ val due = app.myspoti.spotify.bridge.AdBlock.ahead.value+ val ctx = _state.value?.contextUri+ if (due != null && ctx != null && adDueFor(due, _state.value?.item)) {+ app.myspoti.spotify.bridge.AdBlock.ahead.compareAndSet(due, null)+ bridge.logger?.invoke("next with an ad due: ${due.nextUri} skipped to instead of a plain skip")+ if (!skipPastAd(due)) playNow(ctx, trackUri = due.nextUri, order = lastOrder?.takeIf { it.first == ctx }?.second)+ return+ }// Remembered: should the page go into an ad break instead, this song comes after it.val base = lastWithSong()val after = base?.next?.takeIf { it.kind == ItemKind.TRACK || it.kind == ItemKind.EPISODE }@@ -1115,8 +1286,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun previous() {pausedByUser = falsepickBeforeAd = null+ userMoveAt = System.currentTimeMillis()+ adRestore?.cancel()if (skipsHeld) { stepIntent(-1); return }intent = null+ // Spotify points skip_prev of a song with an ad due at the ad as well (measured 21/10), so+ // a step back would land on the ad: the song starts over, the ad stays due for its end.+ val due = app.myspoti.spotify.bridge.AdBlock.ahead.value+ if (adDueFor(due, _state.value?.item)) {+ bridge.logger?.invoke("previous with an ad due: song restarted instead of a step back onto the ad")+ seek(0)+ return+ }withFade {val s = _state.valuerunCatching { command("player.previous") }.onFailure { e ->@@ -1129,11 +1310,23 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopval before = s?.previous?.takeIf { it.kind == ItemKind.TRACK }?.urival ctx = s?.contextUribridge.logger?.invoke("previous refused (${e.message}): ${if (pos > 3_000 || before == null || ctx == null) "song restarted" else "song before played"}")- if (pos > 3_000 || before == null || ctx == null) seek(0) else play(ctx, trackUri = before, order = lastOrder?.takeIf { it.first == ctx }?.second)+ if (pos > 3_000 || before == null || ctx == null) seek(0) else playNow(ctx, trackUri = before, order = lastOrder?.takeIf { it.first == ctx }?.second)}}}- override suspend fun setShuffle(on: Boolean) { bridge.call("player.setShuffle", buildJsonObject { put("on", on) }) }+ /** A shuffle setting the page refused (during an ad), and when: set again once the ad is over. */+ @Volatile private var shufflePending: Pair<Boolean, Long>? = null++ override suspend fun setShuffle(on: Boolean) {+ shufflePending = null+ try {+ command("player.setShuffle", buildJsonObject { put("on", on) })+ } catch (e: app.myspoti.spotify.bridge.BridgeException) {+ if (!_adPlaying.value) throw e+ shufflePending = on to System.currentTimeMillis()+ bridge.logger?.invoke("shuffle ${if (on) "on" else "off"} refused during an ad: set again when it is over")+ }+ }override suspend fun setRepeat(mode: Repeat) {bridge.call("player.setRepeat", buildJsonObject { put("mode", mode.ordinal) })@@ -1160,6 +1353,9 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopoverride suspend fun skipTo(item: NowPlaying) {pausedByUser = false+ userMoveAt = System.currentTimeMillis()+ adRestore?.cancel()+ pickBeforeAd = nullval base = lastWithSong()if (skipsHeld) { setIntent(base?.contextUri, item, base?.item?.uri); return }if (base?.item?.kind != ItemKind.AD) intent = Intent(base?.contextUri, item, base?.item?.uri, System.currentTimeMillis())@@ -1221,8 +1417,16 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop}companion object {+ /** How long before the end of the song before an ad its next song is played. */+ const val AD_AHEAD_LEAD_MS = 1_000L+ /** The song an [app.myspoti.spotify.bridge.AdBlock.AdAhead] names, awaited that long. */+ const val AD_AHEAD_WAIT_MS = 30_000L+ /** While waiting for that song's end, the end is computed again at least that often. */+ const val AD_AHEAD_CHECK_MS = 5_000L+ /** After a skip past an ad, the song after the ad is awaited that long before the target is put back. */+ const val AD_RESTORE_WAIT_MS = 6_000L/** A refused ad left current that long: the page will not move on by itself. */- const val AD_STUCK_MS = 4_000L+ const val AD_STUCK_MS = 3_000L/*** An ad mute that old is lifted. The page never reports the end of a break, so a lost* unmute used to leave the phone silent until the app was restarted; longer than any ad@@ -1261,10 +1465,20 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopconst val PRELOAD_AFTER_MS = 2_000L/** Longer than any ad break: the page is stuck in it. */const val AD_BREAK_MAX_MS = 4 * 60_000L- /** Volume steps of a fade (down; reversed to come back). */+ /**+ * Volume steps of the fade before a skip, [FADE_OUT_STEP_MS] apart: about 220 ms down to+ * -40 dB in even decibel steps, which the ear hears as one smooth bow-out. The 36 ms+ * three-step fade before it sounded like a cut. The command goes out while it runs, so+ * the next song is not delayed by it.+ */// Never 0: Chromium pauses a hidden page's media that (re)starts at volume 0 (a// "previous" that restarts the song stayed paused); the bridge keeps a floor.- val FADE_STEPS = listOf(0.35, 0.08, 0.002)+ val FADE_OUT_STEPS: List<Double> = (1..13).map { Math.pow(10.0, -40.0 * it / 13 / 20) } + 0.002+ const val FADE_OUT_STEP_MS = 16L+ /** The way back on the next song: only enough not to click, it is the song's start. */+ val FADE_IN_STEPS = listOf(0.08, 0.35)+ /** All fade levels, for the floor check. */+ val FADE_STEPS = FADE_OUT_STEPS + FADE_IN_STEPSconst val FADE_STEP_MS = 12L/** The sound always comes back after that long, whatever the page does. */const val FADE_BACK_MAX_MS = 2_500L@@ -1323,8 +1537,11 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopprivate const val AD_MUTE_TRIES = 2/** The volume is checked every that many ticks. */const val VOLUME_CHECK_TICKS = 3- /** An ad that plays (silent, muted) is got past after that long. */- const val AD_PLAYING_SKIP_MS = 1_000L+ /**+ * An ad that plays (silent, muted) is got past after that long. Not sooner: an ad at the+ * start of a new play, its audio refused, moves on by itself within about a second.+ */+ const val AD_PLAYING_SKIP_MS = 3_000Lconst val STUCK_MS = 8_000L/** A song over with nothing after it: where an ad was left out. Next song quickly. */const val END_STUCK_MS = 1_000L@@ -1333,11 +1550,15 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScopprivate const val WATCH_IDLE_TICK_MS = 4_000L/** Buffering longer than this on one song is a stall, not a slow network. */const val BUFFERING_STALL_MS = 25_000L- /** Stuck ads skipped by playing on before the page is reloaded. */- const val AD_SKIPS_BEFORE_RELOAD = 2+ /** An ad still there after a reload: tries at playing on before the next reload. */+ const val AD_SKIPS_AFTER_RELOAD = 2- /** What the [attempt]-th try on a stuck ad does: "next" (play on) or "reload". */- fun adRecovery(attempt: Int): String = if (attempt <= AD_SKIPS_BEFORE_RELOAD) "next" else "reload"+ /**+ * What the [attempt]-th try on a stuck ad does: "reload" first (the only lever a refused+ * ad yields to, see [watchStalls]), then "next" (play on) before reloading again.+ */+ fun adRecovery(attempt: Int): String =+ if (attempt == 1 || attempt > 1 + AD_SKIPS_AFTER_RELOAD) "reload" else "next"/*** Why [s] looks stalled at [now], or null. A song is stalled when its clock ran past@@ -1349,6 +1570,18 @@ class SpotifyPlayer(private val bridge: Bridge, private val scope: CoroutineScop* episode counts too; with tracks only, an episode stuck at its end found no target and* was played again from 0:00.*/+ /** [due] is the ad due right after [playing]. */+ fun adDueFor(due: app.myspoti.spotify.bridge.AdBlock.AdAhead?, playing: NowPlaying?): Boolean =+ due != null && playing != null && ((due.songUid != null && playing.uid == due.songUid) || playing.uri == due.songUri)++ /** The queue entry (with its uid, for `queue.skipTo`) of the song [uri], or null. */+ fun adTargetIn(upcoming: List<NowPlaying>, uri: String): NowPlaying? = upcoming.firstOrNull { it.uri == uri }++ /** [item] is a real song or episode other than the one the ad was due after: the skip past the ad has landed. */+ fun adSkipSettled(item: NowPlaying?, due: app.myspoti.spotify.bridge.AdBlock.AdAhead): Boolean =+ item != null && (item.kind == ItemKind.TRACK || item.kind == ItemKind.EPISODE) &&+ !((due.songUid != null && item.uid == due.songUid) || item.uri == due.songUri)+fun onwardTarget(s: PlayerState, nextUp: List<NowPlaying>): String? {val playable = { k: ItemKind -> k == ItemKind.TRACK || k == ItemKind.EPISODE }return s.next?.takeIf { playable(it.kind) }?.uri ?: nextUp.firstOrNull { playable(it.kind) }?.uridiff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.ktindex 60c16414..0b670ab3 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/bridge/BridgeHost.kt@@ -1,6 +1,7 @@package app.myspoti.spotify.bridgeimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonObject@@ -32,11 +33,11 @@ object BridgeScript {}/**- * Audio ads. Spotify's server puts them in the player's queue (track-playback state machine),- * each with an audio file in a format of its own. The player registers itself without those- * formats ([withoutAdFormats]), so an ad comes with nothing to play; the ad audio host is- * refused as well. The player then halts at the end of the song before the ad, and- * [app.myspoti.spotify.SpotifyPlayer] starts the next song.+ * Audio ads. Spotify's server puts them in the player's queue: the track-playback state machine+ * it sends to the page about three minutes ahead, where the song before the ad `advance`s to an+ * ad state at its end. [withoutAds] sends that end to the song after the ad instead, before the+ * page sees the machine, so the page never reaches an ad. The ad audio host is refused as well,+ * and [app.myspoti.spotify.SpotifyPlayer] reloads the page if an ad still becomes current.*/object AdBlock {/**@@ -73,6 +74,94 @@ object AdBlock {return blockedPaths.any { path.startsWith(it) }}+ /**+ * A track-playback reply (a state machine) with its ads left out, or null when it leads to no+ * ad. Measured on 20/10 (desktop, free account): a refused ad now stays current for good, and+ * every skip or play is refused while it is ("ad_disallow"); only a reload left it. Spotify's+ * state machine ties the ad to the song before it: that song's `advance` (its natural end)+ * goes to the ad, and then `advance` is sent where its `skip_next` goes, so the page plays the+ * next song at the end of this one, as after a skip. Measured: the next song started 60 ms+ * after the end, and Spotify accepted every state the page reported (200). When `skip_next`+ * leads to the ad as well (an ad already left out once), nothing here can help and the reply+ * is left as it is; an ad that is already the current state cannot be left out either.+ */+ fun withoutAds(body: String): Pair<String, List<String>>? {+ if ("\"AD\"" !in body) return null+ val root = runCatching { Json.parseToJsonElement(body).jsonObject }.getOrNull() ?: return null+ val notes = mutableListOf<String>()+ val out = root.toMutableMap()+ for (key in listOf("state_machine", "previous_state_machine")) {+ val machine = root[key] as? JsonObject ?: continue+ machineWithoutAds(machine, notes)?.let { out[key] = it }+ }+ if (out == root) return null+ return JsonObject(out).toString() to notes+ }++ /**+ * A song whose two ways on — its end and its skip — both lead to an ad: Spotify does that once+ * an ad was left out by [withoutAds]. [nextUri] (the song the page shows as next) is then+ * played just before the song ends: a plain play command, which Spotify answers with a new+ * queue the ad is no longer reached from. Measured on 20/10 (desktop, free account): played+ * 1 s before the end, the next song started at once, every report was answered 200, and the+ * songs after it went on without an ad.+ */+ data class AdAhead(val songUid: String?, val songUri: String?, val nextUri: String)++ /** The last [AdAhead] the host saw in Spotify's replies; the player plays on and clears it. */+ val ahead = MutableStateFlow<AdAhead?>(null)++ /** The [AdAhead] in a track-playback reply (after [withoutAds]), or null. */+ fun adAhead(body: String): AdAhead? = runCatching {+ if ("\"AD\"" !in body) return null+ val root = Json.parseToJsonElement(body).jsonObject+ val machine = root["state_machine"] as? JsonObject ?: return null+ val tracks = machine["tracks"] as? JsonArray ?: return null+ val states = machine["states"] as? JsonArray ?: return null+ fun index(o: JsonObject?, key: String) = (o?.get(key) as? JsonPrimitive)?.contentOrNull?.toIntOrNull()+ fun trackOf(state: Int) = index(states.getOrNull(state) as? JsonObject, "track")?.let { tracks.getOrNull(it) as? JsonObject }+ fun isAd(state: Int) = (trackOf(state)?.get("content_type") as? JsonPrimitive)?.contentOrNull == "AD"+ fun uriOf(state: Int) = ((trackOf(state)?.get("metadata") as? JsonObject)?.get("uri") as? JsonPrimitive)?.contentOrNull+ val current = index(root["updated_state_ref"] as? JsonObject, "state_index") ?: return null+ if (isAd(current)) return null+ val state = states.getOrNull(current) as? JsonObject ?: return null+ val transitions = state["transitions"] as? JsonObject ?: return null+ fun to(key: String) = index(transitions[key] as? JsonObject, "state_index")+ val end = to("advance") ?: return null+ if (!isAd(end) || to("skip_next")?.let { !isAd(it) } == true) return null+ val next = to("show_next")?.takeIf { !isAd(it) }?.let(::uriOf) ?: return null+ AdAhead((state["track_uid"] as? JsonPrimitive)?.contentOrNull, uriOf(current), next)+ }.getOrNull()++ private fun machineWithoutAds(machine: JsonObject, notes: MutableList<String>): JsonObject? {+ val tracks = machine["tracks"] as? JsonArray ?: return null+ val states = machine["states"] as? JsonArray ?: return null+ fun trackOf(state: Int) = ((states.getOrNull(state) as? JsonObject)?.get("track") as? JsonPrimitive)+ ?.contentOrNull?.toIntOrNull()?.let { tracks.getOrNull(it) as? JsonObject }+ fun isAd(state: Int) = (trackOf(state)?.get("content_type") as? JsonPrimitive)?.contentOrNull == "AD"+ fun nameOf(state: Int) = ((trackOf(state)?.get("metadata") as? JsonObject)?.get("name") as? JsonPrimitive)?.contentOrNull+ fun indexOf(transition: JsonObject) = (transition["state_index"] as? JsonPrimitive)?.contentOrNull?.toIntOrNull()+ var changed = false+ val rewritten = states.mapIndexed { i, element ->+ val state = element as? JsonObject ?: return@mapIndexed element+ val transitions = state["transitions"] as? JsonObject ?: return@mapIndexed element+ if (isAd(i)) return@mapIndexed element+ // Only a skip is a state the server knows: `show_next` points at a display-only state,+ // and a page sent there had every report refused (502 unknown_state_ref) and stopped.+ val target = (transitions["skip_next"] as? JsonObject)?.takeIf { t -> indexOf(t)?.let { !isAd(it) } == true }+ val next = transitions.toMutableMap()+ for (key in listOf("advance", "skip_next")) {+ val t = transitions[key] as? JsonObject ?: continue+ if (indexOf(t)?.let(::isAd) != true) continue+ if (target == null) { notes += "$key after ${nameOf(i)}: an ad, and no song to send it to"; continue }+ next[key] = JsonObject(target.toMutableMap().apply { t["paused"]?.let { put("paused", it) } })+ notes += "$key after ${nameOf(i)}: ${indexOf(target)?.let(::nameOf)} instead of an ad"+ }+ if (next == transitions) element else { changed = true; JsonObject(state.toMutableMap().apply { put("transitions", JsonObject(next)) }) }+ }+ return if (changed) JsonObject(machine.toMutableMap().apply { put("states", JsonArray(rewritten)) }) else null+ }+/** The player's registration (POST track-playback/v1/devices), to rewrite with [withDeviceName]. */fun isDeviceRegistration(method: String, url: String): Boolean =method.equals("POST", ignoreCase = true) && url.substringBefore('?').endsWith("/track-playback/v1/devices")diff --git a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.ktindex 7f641742..3b954390 100644--- a/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt+++ b/base/api-spotify/src/main/kotlin/app/myspoti/spotify/gql/Gql.kt@@ -83,7 +83,8 @@ class SpotifyHttp(*/private val deviceId: String = java.util.UUID.randomUUID().toString(),) {- private data class WebToken(val access: String, val expiresAtMs: Long, val clientId: String, val appVersion: String, val anonymous: Boolean)+ private data class WebToken(val access: String, val expiresAtMs: Long, val clientId: String, val appVersion: String, val anonymous: Boolean,+ val fetchedAtMs: Long = System.currentTimeMillis())private data class ClientToken(val value: String, val expiresAtMs: Long)private val lock = Mutex()@@ -98,8 +99,17 @@ class SpotifyHttp(* Asks the page, never the cached token: a token cached before a logout (valid up to an hour)* said "signed in" while the user was still on the e-mail code step, the sign-in page was put* away under them and the code was lost (log seen). A fresh answer also refreshes the cache.+ * "Fresh" is a few seconds: several checks at once (startup asks five times within five+ * seconds) share one answer, and every request waits behind this lock while the page answers+ * (0.3 to 2 s each, measured at startup).*/- suspend fun isSignedIn(): Boolean = lock.withLock { web = null; !webToken().anonymous }+ suspend fun isSignedIn(): Boolean = lock.withLock {+ if (web?.let { System.currentTimeMillis() - it.fetchedAtMs < SIGNED_IN_FRESH_MS } != true) web = null+ !webToken().anonymous+ }++ /** What the token in hand says (null: none yet), without asking the page; for logs only. */+ fun signedInHint(): Boolean? = web?.let { !it.anonymous }/** The account's token, fetched again only when the cached one is missing or stale. */private suspend fun webToken(): WebToken {@@ -186,6 +196,8 @@ class SpotifyHttp(}companion object {+ /** How long a signed-in check answers from the token just fetched (see isSignedIn). */+ const val SIGNED_IN_FRESH_MS = 10_000Lconst val JSON_TYPE = "application/json;charset=UTF-8"const val USER_AGENT ="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"diff --git a/base/api-spotify/src/main/resources/bridge/player-bridge.js b/base/api-spotify/src/main/resources/bridge/player-bridge.jsindex 1e739646..81bb22cc 100644--- a/base/api-spotify/src/main/resources/bridge/player-bridge.js+++ b/base/api-spotify/src/main/resources/bridge/player-bridge.js@@ -277,10 +277,12 @@// web player to force `adsEnabled` off; the very same managers are reachable at runtime through// the service registry, so they are turned off here instead of patching a bundle we do not ship.//- // `disable` alone is not enough: the page re-arms its managers at every ad opportunity (a- // "Test ad" still came through on a free account, 19/10 02:29). `enable`/`disable` sit on the- // prototype and `enabled` is a plain field, so the instance is shadowed here: after this, the- // page cannot arm an ad again for the life of the page.+ // `enable`/`disable` sit on the prototype and `enabled` is a plain field, so the instance is+ // shadowed here: after this, the page cannot arm its own managers again for the life of the page.+ // This does not stop audio ads: Spotify's server puts those in the queue itself (measured on+ // 20/10, desktop, free account: one ad after ~17 min with this latch on, as without it). Those+ // are left out of the queue by the host (AdBlock.withoutAds). The "Test ad" once taken for an+ // ad that came through was tools/playback_test.py's own fake.let adsLatched = false;const adsOff = () => {if (!services) return 'not ready';@@ -304,9 +306,8 @@};/**- * Ends the ad the in-stream ad manager owns, its own way (a skip of the ad break, not of the- * song). The app asks for this before it falls back to reloading the page, which is what a- * "Test ad" used to cost: a visible reload of the whole player.+ * Asks the in-stream ad manager to end its break. Kept for diagnosis only: on a real ad whose+ * audio was refused it did nothing (20/10), the server holds the ad ("ad_disallow").*/const adsSkip = () => {if (!services) return 'not ready';@@ -408,6 +409,26 @@return els.size;},+ // "Clip sound": the music video's own soundtrack is heard instead of the song. The song keeps+ // playing here (still Spotify's play of it, counted as one), only unheard, at the same+ // unheard volume as above. Held against the page's own volume sets (a new song, a fade, a+ // volume change) by a listener on each element; an ad's mute keeps the upper hand. {on} -> elements.+ 'media.hush': async a => {+ window.__mspHushed = !!a.on;+ const player = await localPlayer().catch(() => null);+ const els = new Set([...(window.__mspMedia || []), ...document.querySelectorAll('audio, video'), ...await playerMedia()]);+ for (const el of els) {+ if (!el.__mspHush) {+ el.__mspHush = () => { if (window.__mspHushed && !window.__mspMuted && el.volume > SILENT) el.volume = SILENT; };+ el.addEventListener('volumechange', el.__mspHush);+ el.addEventListener('playing', el.__mspHush);+ }+ if (a.on) { cancelFade(); el.muted = false; el.volume = SILENT; }+ else if (!window.__mspMuted) el.volume = player && el === player._player ? ownLevel(player) : 1;+ }+ return els.size;+ },+// The page player's own media element now: what is really heard, whatever the state says.// active: this page is Spotify Connect's active device (else the state is another device's).// level: the element's volume (0..1), which local fades move; own: the level the page@@ -562,11 +583,16 @@},};+ // Inside one of the app's own commands (see traceSkips).+ let calling = 0;const call = async (id, method, args) => {try {const fn = commands[method];if (!fn) throw new Error(`unknown method ${method}`);- const value = await fn(args || {});+ let pending;+ calling++;+ try { pending = fn(args || {}); } finally { calling--; }+ const value = await pending;const out = value === undefined ? null : value;post({ type: 'result', id, ok: true, value: out });return out;@@ -600,6 +626,41 @@events.addListener('queue_update', pushQueue);// Ads off from the first moment: a break queued before the bridge attached never starts.try { adsOff(); } catch (e) { /* no service yet */ }+ traceSkips();+ };++ // Diagnosis (read-only): who asks the page for another song. A tester's song changed with no+ // command from the app (the clip going full screen); the caller's stack, a key or a media+ // session action says where it came from.+ const stackTop = () => String(new Error().stack || '').split('\n').slice(2, 8).map(l => l.trim()).join(' < ').slice(0, 400);+ const traceSkips = () => {+ try {+ const p = services.player;+ for (const name of ['skipToNext', 'skipToPrevious', 'seekTo']) {+ const own = p[name];+ if (typeof own !== 'function' || own.__mspTraced) continue;+ const traced = function (...args) {+ if (!calling) post({ type: 'skip', by: name, stack: stackTop() });+ return own.apply(this, args);+ };+ traced.__mspTraced = true;+ p[name] = traced;+ }+ } catch (e) { /* left as it is */ }+ try {+ const ms = navigator.mediaSession;+ if (ms && !ms.__mspTraced) {+ const set = ms.setActionHandler.bind(ms);+ ms.setActionHandler = (action, handler) => set(action, handler && ((...a) => {+ post({ type: 'skip', by: 'mediaSession.' + action });+ return handler(...a);+ }));+ ms.__mspTraced = true;+ }+ } catch (e) { /* no media session */ }+ window.addEventListener('keydown', e => {+ if (/Arrow|Media|Key[NPJL]/.test(e.code)) post({ type: 'skip', by: 'key ' + e.code + (e.ctrlKey ? '+ctrl' : '') + (e.shiftKey ? '+shift' : '') });+ }, true);};// --- boot -----------------------------------------------------------------diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PickDuringAdTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PickDuringAdTest.ktnew file mode 100644index 00000000..1e19fd5a--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/PickDuringAdTest.kt@@ -0,0 +1,130 @@+package app.myspoti.spotify++import app.myspoti.spotify.bridge.AdBlock+import app.myspoti.spotify.bridge.Bridge+import app.myspoti.spotify.bridge.BridgeHost+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.runBlocking+import org.junit.jupiter.api.AfterEach+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.BeforeEach+import org.junit.jupiter.api.Test+import java.util.concurrent.CopyOnWriteArrayList++/**+ * A pick made while an ad is on or due must reach the page after the ad, in its order (reported+ * on build 2022: the old queue went on and the song had to be picked again).+ */+class PickDuringAdTest {+ private class FakeHost : BridgeHost {+ override val messages = MutableSharedFlow<String>(extraBufferCapacity = 64)+ /** Every call the player made: method to its arguments (json text). */+ val calls = CopyOnWriteArrayList<Pair<String, String>>()+ override suspend fun evaluate(script: String) {+ val m = Regex("""Myspoti\.call\((\d+), "([^"]+)", (.*)\)\.catch""", RegexOption.DOT_MATCHES_ALL).find(script) ?: return+ calls += m.groupValues[2] to m.groupValues[3]+ messages.emit("""{"type":"result","id":${m.groupValues[1]},"ok":true,"value":null}""")+ }+ suspend fun post(json: String) = messages.emit(json)+ }++ private lateinit var scope: CoroutineScope+ private lateinit var host: FakeHost+ private lateinit var player: SpotifyPlayer++ @BeforeEach fun up() {+ AdBlock.ahead.value = null+ scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+ host = FakeHost()+ player = SpotifyPlayer(Bridge(host, scope), scope)+ }++ @AfterEach fun down() {+ AdBlock.ahead.value = null+ scope.cancel()+ }++ private fun track(name: String, ms: Long = 200_000) =+ """{"kind":"track","uri":"spotify:track:$name","uid":"u$name","name":"$name","durationMs":$ms}"""++ private fun state(item: String, next: String? = null, ctx: String = "spotify:playlist:C") =+ """{"type":"state","state":{"track":$item,"contextUri":"$ctx","next":${next ?: "null"},"isPaused":false,"isBuffering":false,+ |"positionMs":0,"timestamp":${System.currentTimeMillis()},"restrictions":{}}}""".trimMargin()++ private val ad = """{"kind":"ad","uri":"spotify:ad:1","name":"ad","durationMs":30000}"""++ private fun waitFor(what: String, ms: Long = 3_000, cond: () -> Boolean) = runBlocking {+ val end = System.currentTimeMillis() + ms+ while (!cond()) {+ check(System.currentTimeMillis() < end) { "timed out: $what" }+ delay(20)+ }+ }++ private fun plays() = host.calls.filter { it.first == "player.play" }.map { it.second }++ @Test fun `a pick during an ad is held and played in its order once the ad is over`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A"), track("B")))+ host.post(state(ad))+ waitFor("ad flag") { player.adPlaying.value }+ player.play("spotify:playlist:C", trackUri = "spotify:track:P", order = listOf("spotify:track:P", "spotify:track:Q"))+ delay(300)+ assertTrue(plays().isEmpty(), "a play during an ad is refused by the page: nothing sent, got ${plays()}")+ host.post(state(track("B"), track("C2")))+ waitFor("the held pick played") { plays().isNotEmpty() }+ val sent = plays().single()+ assertTrue("spotify:track:P" in sent && "spotify:track:Q" in sent, "pick and its order sent: $sent")+ }++ @Test fun `a pick on a song the page already plays after the ad is not played twice`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A"), track("B")))+ host.post(state(ad))+ waitFor("ad flag") { player.adPlaying.value }+ player.play("spotify:playlist:C", trackUri = "spotify:track:P")+ host.post(state(track("P"), track("Q")))+ delay(400)+ assertTrue(plays().isEmpty(), "P plays by itself: ${plays()}")+ }++ @Test fun `a pick outside an ad is sent at once`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A"), track("B")))+ waitFor("state") { player.state.value != null }+ player.play("spotify:playlist:C", trackUri = "spotify:track:P")+ waitFor("play sent") { plays().isNotEmpty() }+ assertEquals(1, plays().size)+ }++ @Test fun `a pick while the ad-avoiding play is waiting for the song's end is not overridden`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A", ms = 1_500), track("B")))+ waitFor("state") { player.state.value != null }+ AdBlock.ahead.value = AdBlock.AdAhead("uA", "spotify:track:A", "spotify:track:B")+ delay(150)+ player.play("spotify:playlist:C", trackUri = "spotify:track:P")+ // The page has not reported P yet when A's last second comes.+ delay(1_800)+ assertEquals(1, plays().size, "only the pick is played: ${host.calls.map { it.first }}")+ assertTrue("spotify:track:P" in plays().single())+ assertTrue(host.calls.none { it.first == "queue.skipTo" }, "no skip to the old queue's next song")+ }++ @Test fun `the fallback after a refused pick keeps the order it was picked in`() = runBlocking {+ host.post("""{"type":"ready"}""")+ host.post(state(track("A"), track("B")))+ waitFor("state") { player.state.value != null }+ player.play("spotify:playlist:C", trackUri = "spotify:track:P", order = listOf("spotify:track:P", "spotify:track:Q"))+ host.post("""{"type":"refused"}""")+ waitFor("fallback play") { plays().size == 2 }+ val fallback = plays()[1]+ assertTrue("spotify:track:Q" in fallback && "trackUri" !in fallback, "the list from its start, same order: $fallback")+ }+}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.ktindex db392e00..6a71c389 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/SpotifyWritesTest.kt@@ -129,4 +129,105 @@ class SpotifyWritesTest {assertEquals(listOf("u0", "u1", "u2"), playlists.sortedTracks("spotify:playlist:p").map { it.uid })assertEquals(listOf("u2", "u1", "u0"), playlists.sortedTracks("spotify:playlist:p", PlaylistSort.CUSTOM, true).map { it.uid })}++ @Test fun `the same song twice in a playlist keeps two row ids, and removing one sends only its id`() = runBridge({ JsonNull }) { _, bridge ->+ fun row(uid: String) = """{"uid":"$uid","addedAt":{"isoString":"2026-01-01T00:00:00Z"},"itemV2":{"__typename":"TrackResponseWrapper","data":+ {"__typename":"Track","uri":"spotify:track:same","name":"Same","duration":{"totalMilliseconds":1000},+ "artists":{"items":[{"uri":"spotify:artist:a","profile":{"name":"Artist"}}]},+ "albumOfTrack":{"uri":"spotify:album:b","name":"Album"}}}}"""+ val gql = FakeGql { name, _ ->+ if (name == "fetchPlaylistContents")+ Bridge.json.parseToJsonElement("""{"data":{"playlistV2":{"__typename":"Playlist","content":{"totalCount":2,"items":[${row("u1")},${row("u2")}]}}}}""")+ else JsonNull+ }+ val playlists = SpotifyPlaylists(gql, bridge, SpotifyHttp(OkHttpClient(), bridge))+ val rows = playlists.tracks("spotify:playlist:p", 0, 100).items+ assertEquals(listOf("spotify:track:same", "spotify:track:same"), rows.map { it.uri })+ assertEquals(listOf("u1", "u2"), rows.map { it.uid })+ playlists.removeTracks("spotify:playlist:p", listOf(rows[1].uid!!))+ val removal = gql.variables.last()+ assertEquals("""["u2"]""", removal["uids"]!!.jsonArray.toString())+ assertEquals("spotify:playlist:p", removal["playlistUri"]!!.jsonPrimitive.content)+ }++ @Test fun `making a listed playlist private takes it off the profile before the base permission`() = runBridge({ call ->+ if (call.method() == "getPublishedState") kotlinx.serialization.json.JsonPrimitive("true") else JsonNull+ }) { host, bridge ->+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))+ playlists.setAccess("spotify:playlist:p", app.myspoti.api.PlaylistAccess.PRIVATE)+ val writes = host.calls.filter { it.method() == "setPublishedState" || it.method() == "setBasePermission" }+ assertEquals(listOf("setPublishedState", "setBasePermission"), writes.map { it.method() })+ assertEquals("""["spotify:playlist:p",false]""", writes[0].args())+ assertEquals("""["spotify:playlist:p","BLOCKED"]""", writes[1].args())+ }++ @Test fun `public and collaborative leave the profile listing alone`() = runBridge({ JsonNull }) { host, bridge ->+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))+ playlists.setAccess("spotify:playlist:p", app.myspoti.api.PlaylistAccess.COLLABORATIVE)+ playlists.setAccess("spotify:playlist:p", app.myspoti.api.PlaylistAccess.PUBLIC)+ assertEquals(listOf("setBasePermission", "setBasePermission"), host.calls.map { it.method() })+ }++ @Test fun `a playlist created in a folder is placed after that folder and its uri is returned`() = runBridge({ call ->+ if (call.method() == "createPlaylist") kotlinx.serialization.json.JsonPrimitive("spotify:playlist:new") else JsonNull+ }) { host, bridge ->+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))+ assertEquals("spotify:playlist:new", playlists.create("Mine", "spotify:user:u:folder:abc"))+ assertEquals("""["Mine",{"after":{"uri":"spotify:user:u:folder:abc"}}]""", host.calls.single().args())+ }++ @Test fun `joining with an invitation token claims it on the page, then follows the playlist when it is not in the library`() = runBridge({ call ->+ when (call.method()) {+ "claimPermissions" -> Bridge.json.parseToJsonElement("""{"userPermission":{"revision":"b3du","permissionLevel":"CONTRIBUTOR"},"capabilities":{"canEditItems":true}}""")+ "contains" -> Bridge.json.parseToJsonElement("[false]")+ else -> JsonNull+ }+ }) { host, bridge ->+ val playlists = SpotifyPlaylists(FakeGql { _, _ -> JsonNull }, bridge, SpotifyHttp(OkHttpClient(), bridge))+ assertEquals(app.myspoti.api.PlaylistAccess.COLLABORATIVE, playlists.join("spotify:playlist:p", "tok123"))+ assertEquals(listOf("claimPermissions", "contains", "add"), host.calls.map { it.method() })+ assertEquals("""["spotify:playlist:p","tok123"]""", host.calls[0].args())+ }++ @Test fun `a Blend invitation id is read from the link the page generates, or given bare`() {+ val blends = SpotifyBlends(SpotifyHttp(OkHttpClient(), Bridge(RecordingHost { JsonNull }, scope)))+ assertEquals("f6c3d87d8beb9a3f", blends.idOf("https://open.spotify.com/blend/taste-match/f6c3d87d8beb9a3f?si=DJpS4omqRFOjF4es_Fnm8A&fallback=getapp&blendDecoration=5f9c38d2"))+ assertEquals("f6c3d87d8beb9a3f", blends.idOf(" f6c3d87d8beb9a3f "))+ org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException::class.java) { blends.idOf("https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M") }+ }++ @Test fun `a pending invitation of this account reads as waiting, a joined one carries its playlist`() {+ val blends = SpotifyBlends(SpotifyHttp(OkHttpClient(), Bridge(RecordingHost { JsonNull }, scope)))+ // Both bodies are what the live service answered.+ val waiting = blends.parseInvitation(Bridge.json.parseToJsonElement("""{"page_type":"PENDING_INVITATION","members":null,+ "recipient":{"name":"Sam","username":"user0002","image_url":null,"hash":"7370"},"playlist_uri":null,+ "title":"Invite is pending","subtitle":"Invite someone else while you wait!","members_title":null,"button_text":"Invite","footnote":null}"""))+ assertEquals(app.myspoti.api.BlendInvitationState.WAITING, waiting.state)+ assertEquals("Sam", waiting.inviter?.name)+ assertEquals(emptyList<app.myspoti.api.BlendMember>(), waiting.members)+ val joined = blends.parseInvitation(Bridge.json.parseToJsonElement("""{"page_type":"ALREADY_JOINED","members":null,"recipient":null,+ "playlist_uri":"spotify:playlist:37i9dQZF1EJMv6aMStShzx","title":null,"subtitle":null,"members_title":null,"button_text":null,"footnote":null}"""))+ assertEquals(app.myspoti.api.BlendInvitationState.JOINED, joined.state)+ assertEquals("spotify:playlist:37i9dQZF1EJMv6aMStShzx", joined.playlist)+ }++ @Test fun `a Blend's members and its taste-match card read as the live service gives them`() {+ val blends = SpotifyBlends(SpotifyHttp(OkHttpClient(), Bridge(RecordingHost { JsonNull }, scope)))+ // Shortened from what the live service answered for a two-person Blend.+ val group = blends.parseGroup(Bridge.json.parseToJsonElement("""{"title":"Other Blend members (2)","button_text":"Invite more people",+ "invitation_link":"https://open.spotify.com/blend/taste-match/98ad2d0287420131?si=x","members":[+ {"name":"Alex","image_url":"https://i.scdn.co/image/a","hash":"9","username":"user0001"},+ {"name":"Sam","image_url":"","hash":"7","username":"user0002"}]}"""))+ assertEquals(listOf("Alex", "Sam"), group.members.map { it.name })+ assertEquals(null, group.members[1].imageUrl)+ assertEquals("https://open.spotify.com/blend/taste-match/98ad2d0287420131?si=x", group.link)+ val story = blends.parseStory(Bridge.json.parseToJsonElement("""{"wrapped_mode_enabled":false,"playlist_uri":"spotify:playlist:37i9dQZF1EJEqgDMQbDle1",+ "intro_story":{"title1":{"text":"You're a 98% match","text_color":"#191414"},"subtitle1":{"text":"A friendship the world envies.","text_color":"#2F6F56"},+ "background_color":"#F5F3E4"},"stories":[{"story_type":"standard_two_user:blend","subtitle":{"text":"98% taste match","text_color":"#2F6F56"},+ "body":{"text":"The song that brings you together is X","text_color":"#2F6F56"},"image":"https://i.scdn.co/image/b","background_color":"#F5F3E4"}]}"""))+ assertEquals("You're a 98% match", story?.title)+ assertEquals("The song that brings you together is X", story?.detail)+ assertEquals("#F5F3E4", story?.background)+ assertEquals(null, blends.parseStory(Bridge.json.parseToJsonElement("""{"intro_story":null,"stories":[]}""")))+ }}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.ktindex 9648510a..04584b37 100644--- a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/StallTest.kt@@ -37,12 +37,29 @@ class StallTest {assertEquals(nextEpisode.uri, SpotifyPlayer.onwardTarget(state(199_500, 0, next = null).copy(item = episode), listOf(ad, nextEpisode)))@Test fun `an ad is never a target`() = assertNull(SpotifyPlayer.onwardTarget(state(199_500, 0, next = ad), listOf(ad)))- @Test fun `a stuck ad is skipped twice, then the page reloads`() {- assertEquals("next", SpotifyPlayer.adRecovery(1))+ @Test fun `a stuck ad reloads the page first, then plays on twice before reloading again`() {+ assertEquals("reload", SpotifyPlayer.adRecovery(1))assertEquals("next", SpotifyPlayer.adRecovery(2))- assertEquals("reload", SpotifyPlayer.adRecovery(3))+ assertEquals("next", SpotifyPlayer.adRecovery(3))+ assertEquals("reload", SpotifyPlayer.adRecovery(4))}// Chromium pauses a hidden page's media that (re)starts at volume 0.@Test fun `a fade never reaches volume 0`() = SpotifyPlayer.FADE_STEPS.forEach { assertEquals(true, it > 0.0) }++ // The skip past an ad due (measured 21/10): the target is found in the queue, the ad's own song is recognised.+ private val due = app.myspoti.spotify.bridge.AdBlock.AdAhead("uid-a", "spotify:track:a", "spotify:track:b")+ @Test fun `an ad is due after the song with that uid`() = assertEquals(true, SpotifyPlayer.adDueFor(due, song.copy(uid = "uid-a", uri = "spotify:track:z")))+ @Test fun `an ad is due after the song with that uri`() = assertEquals(true, SpotifyPlayer.adDueFor(due.copy(songUid = null), song))+ @Test fun `no ad due after another song`() = assertEquals(false, SpotifyPlayer.adDueFor(due, after.copy(uid = "uid-b")))+ @Test fun `no ad due when none is announced`() = assertEquals(false, SpotifyPlayer.adDueFor(null, song))+ @Test fun `the target is found by uri with its uid`() =+ assertEquals("uid-b", SpotifyPlayer.adTargetIn(listOf(song, after.copy(uid = "uid-b")), "spotify:track:b")?.uid)+ @Test fun `a target missing from the queue is null`() = assertNull(SpotifyPlayer.adTargetIn(listOf(song), "spotify:track:b"))+ @Test fun `the skip has landed on another real song`() = assertEquals(true, SpotifyPlayer.adSkipSettled(after, due))+ @Test fun `the skip has not landed on the song before or on the ad`() {+ assertEquals(false, SpotifyPlayer.adSkipSettled(song, due))+ assertEquals(false, SpotifyPlayer.adSkipSettled(song.copy(kind = ItemKind.AD, uri = "spotify:ad:1"), due))+ assertEquals(false, SpotifyPlayer.adSkipSettled(null, due))+ }}diff --git a/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.ktnew file mode 100644index 00000000..4b22b04e--- /dev/null+++ b/base/api-spotify/src/test/kotlin/app/myspoti/spotify/bridge/AdQueueTest.kt@@ -0,0 +1,89 @@+package app.myspoti.spotify.bridge++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.int+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.junit.jupiter.api.Test+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertNull+import org.junit.jupiter.api.Assertions.assertTrue++/** The two shapes of ad-bearing state machines seen on 20/10, with made-up names and ids. */+class AdQueueTest {+ private fun track(type: String, name: String) =+ """{"content_type":"$type","metadata":{"uri":"spotify:${type.lowercase()}:${name.replace(' ', '-')}","name":"$name"},"manifest":{}}"""++ private fun go(to: Int?) = if (to == null) "null" else """{"state_index":$to,"paused":false,"active_alias":null}"""++ private fun state(track: Int, advance: Int? = null, next: Int? = null, show: Int? = null) =+ """{"state_id":"s$track","track":$track,"transitions":{"skip_next":${go(next)},"skip_prev":null,"show_next":${go(show)},"show_prev":null,"advance":${go(advance)}}}"""++ private fun reply(tracks: List<String>, states: List<String>, current: Int) =+ """{"state_machine":{"state_machine_id":"m","tracks":[${tracks.joinToString(",")}],"states":[${states.joinToString(",")}],"attributes":{}},"updated_state_ref":{"state_index":$current,"paused":false}}"""++ private fun transitions(body: String, state: Int): JsonObject =+ Json.parseToJsonElement(body).jsonObject["state_machine"]!!.jsonObject["states"]!!.jsonArray[state].jsonObject["transitions"]!!.jsonObject++ private fun index(t: JsonObject, key: String) = t[key]!!.jsonObject["state_index"]!!.jsonPrimitive.int++ // First shape: the song's end goes to the ad, its skip to the next song.+ private val first = reply(+ listOf(track("AD", "An ad"), track("TRACK", "Before"), track("TRACK", "Playing"), track("TRACK", "After")),+ listOf(state(0), state(1), state(2, advance = 0, next = 4, show = 4), state(2), state(3)),+ current = 2,+ )++ // Second shape, the try after a left-out ad: skip and end both go to the ad, only the shown+ // next song does not.+ private val second = reply(+ listOf(track("AD", "An ad"), track("TRACK", "After"), track("TRACK", "Before"), track("TRACK", "Playing")),+ listOf(state(0), state(0), state(3, advance = 0, next = 1, show = 4), state(0), state(1), state(2)),+ current = 2,+ )++ @Test fun `the end of the song before an ad goes to the song after it`() {+ val (body, notes) = AdBlock.withoutAds(first)!!+ val t = transitions(body, 2)+ assertEquals(4, index(t, "advance"))+ assertEquals(4, index(t, "skip_next"))+ assertEquals(listOf("advance after Playing: After instead of an ad"), notes)+ }++ @Test fun `when the skip goes to the ad too, the reply is left as it is`() =+ // show_next is a display-only state: the server refuses a page sent there (502).+ assertNull(AdBlock.withoutAds(second))++ @Test fun `everything else in the reply is kept`() {+ val (body, _) = AdBlock.withoutAds(first)!!+ val root = Json.parseToJsonElement(body).jsonObject+ assertEquals(2, root["updated_state_ref"]!!.jsonObject["state_index"]!!.jsonPrimitive.int)+ assertEquals(4, root["state_machine"]!!.jsonObject["tracks"]!!.jsonArray.size)+ assertTrue("\"AD\"" in body, "the ad stays listed, it is only never reached")+ }++ @Test fun `an ad on both ways on names the song to play before the end`() {+ val a = AdBlock.adAhead(second)!!+ assertEquals("spotify:track:Playing", a.songUri)+ assertEquals("spotify:track:After", a.nextUri)+ }++ @Test fun `no play before the end when the end can be sent to the next song`() {+ assertNull(AdBlock.adAhead(first))+ assertNull(AdBlock.adAhead(AdBlock.withoutAds(first)!!.first))+ }++ @Test fun `a reply without an ad is left alone`() {+ val plain = reply(listOf(track("TRACK", "A"), track("TRACK", "B")), listOf(state(0, advance = 1, next = 1), state(1)), current = 0)+ assertNull(AdBlock.withoutAds(plain))+ }++ @Test fun `an ad already playing is not touched`() {+ val playing = reply(listOf(track("AD", "An ad"), track("TRACK", "B")), listOf(state(0), state(1)), current = 0)+ assertNull(AdBlock.withoutAds(playing))+ }++ @Test fun `an unreadable reply is left alone`() = assertNull(AdBlock.withoutAds("""{"x":"AD" """))+}diff --git a/base/api/src/main/kotlin/app/myspoti/api/Api.kt b/base/api/src/main/kotlin/app/myspoti/api/Api.ktindex f7ea85e9..aa1abff0 100644--- a/base/api/src/main/kotlin/app/myspoti/api/Api.kt+++ b/base/api/src/main/kotlin/app/myspoti/api/Api.kt@@ -16,6 +16,8 @@ interface MyspotiApi {val extras: TrackExtrasval devices: Devicesval jam: Jam+ /** Blends ("Mix à plusieurs"): playlists made of several people's taste, joined through an invitation link. */+ val blends: Blends/** The account's "Recently played", as Spotify's own list has it. */val recents: Recents@@ -152,13 +154,32 @@ interface Playlists {suspend fun delete(uri: Uri)suspend fun follow(uri: Uri)suspend fun unfollow(uri: Uri)+ /**+ * Joins a collaborative playlist through the `pt` token of its invitation link+ * (`open.spotify.com/playlist/{id}?si=…&pt={token}`): the account becomes a member with the+ * level the token grants and the playlist is put in the library when it is not there yet.+ * Fails (HTTP 400) when the token is wrong or has expired. Returns the level granted.+ */+ suspend fun join(uri: Uri, invitationToken: String): PlaylistAccess++ /**+ * The invitation link of a collaborative playlist (owner): whoever opens it becomes a+ * collaborator ([join]). A plain link only lets people see the playlist. Valid 7 days.+ */+ suspend fun collaboratorInvite(uri: Uri): String++ /** The owner and the collaborators of a playlist (just the owner when it is not shared). */+ suspend fun members(uri: Uri): List<PlaylistMember>++ /** Who added each row of a playlist (shown on collaborative ones). */+ suspend fun addedBy(uri: Uri): List<RowAdder>suspend fun addTracks(uri: Uri, trackUris: List<Uri>)/** Rows are addressed by [Track.uid]. */suspend fun removeTracks(uri: Uri, uids: List<String>)suspend fun moveTracks(uri: Uri, uids: List<String>, beforeUid: String?)/** Tracks Spotify suggests adding at the bottom of the playlist. */- suspend fun recommended(uri: Uri, limit: Int = 10): List<Track>+ suspend fun recommended(uri: Uri, limit: Int = 10, skip: List<Uri> = emptyList()): List<Track>}interface Home {@@ -242,6 +263,27 @@ interface Jam {suspend fun setParticipantVolumeControl(on: Boolean)}+/**+ * Spotify Blend. A Blend starts as an invitation link; the Blend playlist itself only exists+ * once someone else has joined through it. An existing Blend is an ordinary playlist+ * ([Playlist.isBlend]), opened with [Playlists].+ */+interface Blends {+ /** Makes a new invitation. */+ suspend fun invite(): BlendInvite+ /** What an invitation (its link or its bare id) leads to for this account. */+ suspend fun invitation(linkOrId: String): BlendInvitation+ /** Joins through an invitation; the uri of the Blend playlist. */+ suspend fun join(linkOrId: String): Uri+ /** Who is in the Blend [playlist], and the link to invite more people. */+ suspend fun group(playlist: Uri): BlendGroup+ /** The Blend's taste-match card, or null when Spotify has none for it. */+ suspend fun story(playlist: Uri): BlendStory?+ suspend fun rename(playlist: Uri, name: String)+ /** Leaves the Blend: it goes from the library, the others keep it. */+ suspend fun leave(playlist: Uri)+}+interface Recents {/*** What the account played lately, newest first, as the Web Player lists it: context rowsdiff --git a/base/api/src/main/kotlin/app/myspoti/api/Models.kt b/base/api/src/main/kotlin/app/myspoti/api/Models.ktindex f2f7193b..83facba5 100644--- a/base/api/src/main/kotlin/app/myspoti/api/Models.kt+++ b/base/api/src/main/kotlin/app/myspoti/api/Models.kt@@ -25,6 +25,8 @@ data class Track(val uid: String? = null,/** When it was added to the playlist (ISO 8601), for playlist rows. */val addedAt: String? = null,+ /** Spotify knows a music video of it (its own "switch to video"), when the answer says. */+ val hasVideo: Boolean = false,)data class Album(@@ -58,6 +60,8 @@ data class Playlist(val ownerUri: Uri? = null,val ownerImages: List<Image> = emptyList(),val followers: Long? = null,+ /** A Spotify Blend (a playlist shared by taste between people). */+ val isBlend: Boolean = false,)/**@@ -168,3 +172,64 @@ data class ArtistPage(val appearsOn: List<Album>,val related: List<Artist>,)++/** A Blend invitation just made: [link] is what to send, [id] what the link carries. */+data class BlendInvite(val id: String, val link: String)++data class BlendMember(val username: String, val name: String, val imageUrl: String?)++/** Who put a row in a playlist ([rowUid]: the row; [trackUri]: its song). */+data class RowAdder(val rowUid: String, val trackUri: String, val username: String)++/** Someone who can change a playlist: its owner, or a collaborator who joined it. */+data class PlaylistMember(val username: String, val name: String, val imageUrl: String?, val isOwner: Boolean)++/** Where an invitation stands for the signed-in account. */+enum class BlendInvitationState {+ /** Made by this account, nobody has joined yet. */+ WAITING,+ /** Someone else's invitation, open to join. */+ JOINABLE,+ /** The Blend is full. */+ FULL,+ /** This account is in the Blend already ([BlendInvitation.playlist] opens it). */+ JOINED,+ /** The invitation or the Blend was deleted. */+ DELETED,+ UNKNOWN,+}++/** Who is in a Blend, as its page lists them, and the link that invites more people. */+data class BlendGroup(+ /** Spotify's heading for the list ("Other Blend members (2)"), translated. */+ val title: String?,+ /** Spotify's words for the invite button, translated. */+ val inviteLabel: String?,+ val link: String?,+ val members: List<BlendMember>,+)++/** The Blend's taste-match card: how close the members' tastes are, in Spotify's words and colours. */+data class BlendStory(+ val title: String,+ val subtitle: String?,+ /** The song that brings the members together, as Spotify says it. */+ val detail: String?,+ /** "#RRGGBB" colours, as Spotify gives them. */+ val background: String?,+ val titleColor: String?,+ val textColor: String?,+ val image: String?,+)++data class BlendInvitation(+ val state: BlendInvitationState,+ val title: String?,+ val subtitle: String?,+ /** Who made the invitation. */+ val inviter: BlendMember?,+ /** Who is in the Blend already. */+ val members: List<BlendMember>,+ /** The Blend playlist, once there is one. */+ val playlist: Uri?,+)diff --git a/base/app/src/main/AndroidManifest.xml b/base/app/src/main/AndroidManifest.xmlindex c39520ce..fe6579c8 100644--- a/base/app/src/main/AndroidManifest.xml+++ b/base/app/src/main/AndroidManifest.xml@@ -88,9 +88,10 @@<category android:name="android.intent.category.DEFAULT" /></intent-filter><!-- No autoVerify: these are Spotify's domains, verification can never- pass for this app. spotify.link is not claimed: the id is only in the- redirect target, so the browser resolves it to open.spotify.com,- which is claimed and parsed. -->+ pass for this app. spotify.link / spoti.fi short links (how the official+ apps share a collaborative playlist invitation) are offered too: the id and+ the invitation token (pt) are only in the redirect target, which the app+ resolves itself (InviteLinks). --><intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" />@@ -107,6 +108,12 @@<dataandroid:scheme="https"android:host="play.spotify.com" />+ <data+ android:scheme="https"+ android:host="spotify.link" />+ <data+ android:scheme="https"+ android:host="spoti.fi" /></intent-filter></activity>diff --git a/base/app/src/main/java/app/myspoti/MainActivity.kt b/base/app/src/main/java/app/myspoti/MainActivity.ktindex 8dcf0dbe..edf5b04f 100644--- a/base/app/src/main/java/app/myspoti/MainActivity.kt+++ b/base/app/src/main/java/app/myspoti/MainActivity.kt@@ -115,6 +115,7 @@ class MainActivity : AppCompatActivity() {// The clip player follows the app on screen: paused with its side jobs in the background.override fun onStart() {+ app.myspoti.host.android.MainThreadWatch.start()super.onStart()com.music.spotui.video.MusicVideoController.onForeground()// Asked for over adb (TestControlReceiver's "screenon"): One UI ignores the huge@@ -125,6 +126,7 @@ class MainActivity : AppCompatActivity() {override fun onStop() {super.onStop()+ app.myspoti.host.android.MainThreadWatch.stop()if (!isChangingConfigurations) com.music.spotui.video.MusicVideoController.onBackground()}@@ -174,6 +176,10 @@ class MainActivity : AppCompatActivity() {MyspotiRuntime.host.url.collect { url ->val backOnPlayer = url.startsWith("https://open.spotify.com") && !url.contains("/login")if (!(showingLogin && backOnPlayer)) return@collect+ // Spotify's desktop player is not shown while the session is confirmed: the app's+ // waiting screen is, behind the page made transparent (reported: it flashed).+ connecting = true+ MyspotiRuntime.host.veil(true)// The address is not a session — and it comes back to open.spotify.com as soon as the// user leaves the app to read the sign-in e-mail. Hiding the page here showed an// anonymous player: an app that looked signed in with nothing playable (reported).@@ -195,6 +201,7 @@ class MainActivity : AppCompatActivity() {android.util.Log.d(LOG, "no session ${SESSION_WAIT_MS / 1000}s after the player came back: sign-in page restored")// The page may now be the anonymous player: send it back to the e-mail step so the// user is not left where nothing plays.+ connecting = falseif (!showingLogin) showLogin() else MyspotiRuntime.host.openLogin()}}@@ -277,7 +284,17 @@ class MainActivity : AppCompatActivity() {}when (intent.action) {Intent.ACTION_VIEW -> {- val uri = spotifyUri(intent.data?.toString() ?: return) ?: return+ val link = intent.data?.toString() ?: return+ // A collaborative-playlist invitation (…?pt=) or a spotify.link short link: kept / resolved there.+ if (com.music.spotui.data.api.InviteLinks.handle(link)) return+ val uri = spotifyUri(link) ?: return+ // A shared list (or artist, podcast) opens on its page, as in the official app+ // (reported: a shared playlist started playing and was never shown). A song or an+ // episode still plays.+ if (uri.split(':').getOrNull(1) in setOf("playlist", "album", "artist", "show")) {+ com.music.spotui.data.api.InviteLinks.page.value = uri+ return+ }lifecycleScope.launch {MyspotiRuntime.api.ready.first { it }runCatching { MyspotiRuntime.api.player.play(uri) }diff --git a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt b/base/app/src/main/java/app/myspoti/MyspotiApplication.ktindex 30d3682e..ebefe6e0 100644--- a/base/app/src/main/java/app/myspoti/MyspotiApplication.kt+++ b/base/app/src/main/java/app/myspoti/MyspotiApplication.kt@@ -15,6 +15,8 @@ import kotlinx.coroutines.launchclass MyspotiApplication : Application() {override fun onCreate() {super.onCreate()+ // A crash or a freeze of the last run, back in this run's diagnostic report.+ app.myspoti.host.android.LastExit.install(this)app.myspoti.power.EnergySettings.init(this)// Spotify session (hidden Web Player + API), caches, downloads, data saver.Graph.init(this)diff --git a/base/app/src/main/java/com/music/spotui/App.kt b/base/app/src/main/java/com/music/spotui/App.ktindex 2c11d7a7..fed88c90 100644--- a/base/app/src/main/java/com/music/spotui/App.kt+++ b/base/app/src/main/java/com/music/spotui/App.kt@@ -21,6 +21,7 @@ import androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValue+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchimport androidx.compose.runtime.setValueimport androidx.compose.runtime.mutableStateOf@@ -53,6 +54,53 @@ fun App() {UpdatePrompt()SupportPrompt()+ // The playlists at the top of the library, fetched ahead on Wi-Fi (see PagePrefetch).+ LaunchedEffect(Unit) { com.music.spotui.data.api.PagePrefetch.start() }++ // A collaborative-playlist invitation was opened (see InviteLinks): its playlist page offers "Join".+ val invite by com.music.spotui.data.api.InviteLinks.pending.collectAsState()+ LaunchedEffect(invite) {+ val i = invite?.takeIf { !it.opened } ?: return@LaunchedEffect+ app.myspoti.host.android.MyspotiRuntime.api.ready.first { it }+ i.opened = true+ navController.navigate(com.music.spotui.ui.navigation.playlistRoute(i.playlistId))+ }++ // A Blend invitation was opened (see InviteLinks): who invites, and "Join", over the app.+ val blendLink by com.music.spotui.data.api.InviteLinks.blend.collectAsState()+ blendLink?.let { link ->+ com.music.spotui.ui.screens.BlendInviteSheet(link, navController) {+ if (com.music.spotui.data.api.InviteLinks.blend.value === link) com.music.spotui.data.api.InviteLinks.blend.value = null+ }+ }++ // Genius's explanations of the song playing, read while it starts: ready when the lyrics open.+ val geniusLang = com.music.spotui.ui.components.readerLanguage()+ val playingUri = com.music.spotui.di.SongPlayer.nowPlaying.value.uri+ LaunchedEffect(playingUri) {+ if (!playingUri.startsWith("spotify:track:")) return@LaunchedEffect+ kotlinx.coroutines.delay(2_000) // the song's own loads first+ val st = com.music.spotui.di.Graph.currentSongState+ com.music.spotui.data.api.GeniusMeaning.prefetch(playingUri.substringAfterLast(':'), st.title.value, st.singer.value, geniusLang)+ }+ // A shared link to a list / artist / podcast: its page, over whatever was open.+ val pageLink by com.music.spotui.data.api.InviteLinks.page.collectAsState()+ LaunchedEffect(pageLink) {+ val uri = pageLink ?: return@LaunchedEffect+ com.music.spotui.data.api.InviteLinks.page.value = null+ val id = uri.substringAfterLast(':')+ com.music.spotui.ui.navigation.PlayerSheet.close()+ runCatching {+ navController.navigate(when (uri.split(':')[1]) {+ "playlist" -> com.music.spotui.ui.navigation.playlistRoute(id)+ "album" -> com.music.spotui.ui.navigation.albumRoute("", "", id)+ "artist" -> com.music.spotui.ui.navigation.artistRoute("artist", id)+ else -> com.music.spotui.ui.navigation.showRoute(id)+ })+ }+ }+ val shareTarget by com.music.spotui.ui.components.SpotifyCode.request.collectAsState()+ shareTarget?.let { t -> com.music.spotui.ui.components.SpotifyCodeSheet(t) { com.music.spotui.ui.components.SpotifyCode.request.value = null } }androidx.compose.foundation.layout.Box(Modifier.fillMaxSize()) {Scaffold(diff --git a/base/app/src/main/java/com/music/spotui/data/api/Api.kt b/base/app/src/main/java/com/music/spotui/data/api/Api.ktindex f5c81665..fb628e10 100644--- a/base/app/src/main/java/com/music/spotui/data/api/Api.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/Api.kt@@ -153,6 +153,7 @@ class Api constructor(durationMs = t.durationMs.toInt(),addedAt = t.addedAt.orEmpty(),playable = t.playable,+ rowUid = t.uid.orEmpty(),)return SongsModel(id = stableId("track:$id"),@@ -168,6 +169,7 @@ class Api constructor(addedAt = t.addedAt.orEmpty(),playable = t.playable,artistIds = t.artists.map { it.uri.substringAfterLast(':') },+ rowUid = t.uid.orEmpty(),)}@@ -822,6 +824,7 @@ class Api constructor(ownerAvatar = cover(pl.ownerImages),ownerUri = pl.ownerUri.orEmpty(),metaLine = saves,+ isBlend = pl.isBlend,)// The first page gives the total: the rest is asked for PLAYLIST_PARALLEL pages at a time// and shown in order as it lands, at most every PLAYLIST_EMIT_MS. One page after the@@ -888,7 +891,7 @@ class Api constructor(emit(Response.Success(songs.toList()))offset = page.nextOffset ?: break}- if (songs.isEmpty()) emit(Response.Error("Couldn't load this playlist"))+ if (songs.isEmpty()) emit(Response.Error(context.getString(R.string.page_load_failed)))}// ── Library ──@@ -943,7 +946,7 @@ class Api constructor(HomeCache.libraryRoot?.let { emit(Response.Success(it)) } ?: emit(Response.Loading())if (!ready()) { if (HomeCache.libraryRoot == null) emit(Response.Error(notSignedIn())); return@flow }runCatching { listOf(likedEntry()) + libraryLevel(null).mapNotNull(::entryOf) }.fold(- onSuccess = { HomeCache.libraryRoot = it; ScreenCache.libraryRoot.write(it); emit(Response.Success(it)) },+ onSuccess = { HomeCache.libraryRoot = it; ScreenCache.libraryRoot.write(it); PagePrefetch.schedule(it); emit(Response.Success(it)) },onFailure = { Log.e("Api", "getLibraryRoot failed", it); if (HomeCache.libraryRoot == null) emit(Response.Error(it.message ?: "error")) },)}@@ -991,7 +994,7 @@ class Api constructor(LikedCache.tracks = songsemit(Response.Success(songs))},- onFailure = { emit(Response.Error("Couldn't load Liked Songs")) },+ onFailure = { emit(Response.Error(context.getString(R.string.couldnt_load, context.getString(R.string.collection_liked_songs_title)))) },)}diff --git a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.ktindex d6ad1b58..e54f6d49 100644--- a/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/EditablePlaylists.kt@@ -20,6 +20,17 @@ data class EditablePlaylist(}object EditablePlaylists {+ /** Ids of the playlists this account can change, read at most every [IDS_TTL_MS]. */+ @Volatile private var ids: Set<String>? = null+ @Volatile private var idsAt = 0L+ private const val IDS_TTL_MS = 5 * 60_000L++ suspend fun ids(): Set<String> {+ val now = System.currentTimeMillis()+ ids?.takeIf { now - idsAt < IDS_TTL_MS }?.let { return it }+ return runCatching { load().mapTo(HashSet()) { it.id } }.getOrNull()?.also { ids = it; idsAt = now } ?: ids.orEmpty()+ }+/** The user's own and collaborative playlists, in library order, folders flattened. */suspend fun load(): List<EditablePlaylist> =runCatching { MyspotiRuntime.api.playlists.editable() }.getOrDefault(emptyList()).map {diff --git a/base/app/src/main/java/com/music/spotui/data/api/GeniusMeaning.kt b/base/app/src/main/java/com/music/spotui/data/api/GeniusMeaning.ktnew file mode 100644index 00000000..f28be0f5--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/api/GeniusMeaning.kt@@ -0,0 +1,184 @@+package com.music.spotui.data.api++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch+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.contentOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import okhttp3.OkHttpClient+import okhttp3.Request+import java.text.Normalizer+import java.util.concurrent.TimeUnit++/**+ * What a song means, from Genius: its "About" text and the explanations written on its lines.+ * Read from the JSON genius.com's own pages use (no key needed): a song search, then the song+ * and its annotations. The last few songs asked for are kept in memory (small texts).+ */+object GeniusMeaning {+ data class Note(val fragment: String, val explanation: String, val votes: Int = 0)+ data class Meaning(val url: String, val title: String, val artist: String, val about: String?, val notes: List<Note>) {+ val isEmpty get() = about.isNullOrBlank() && notes.isEmpty()+ }++ private const val BASE = "https://genius.com/api"+ private const val KEEP = 12+ private val json = Json { ignoreUnknownKeys = true }+ private val http by lazy { OkHttpClient.Builder().callTimeout(12, TimeUnit.SECONDS).build() }+ /** title|artist → the meaning, or null when Genius has none (not asked again this session). */+ private val recent = java.util.Collections.synchronizedMap(object : LinkedHashMap<String, Meaning?>(KEEP, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Meaning?>?) = size > KEEP+ })++ fun cached(title: String, artist: String): Meaning? = recent[key(title, artist)]++ /** null: no song on Genius matches, or it says nothing about it. Throws when Genius can't be reached. */+ suspend fun find(title: String, artist: String): Meaning? = withContext(Dispatchers.IO) {+ val k = key(title, artist)+ if (recent.containsKey(k)) return@withContext recent[k]+ val cleanTitle = clean(title)+ val artists = artist.split(',', '&').map { norm(it) }.filter { it.isNotBlank() }+ val q = "$cleanTitle ${artist.substringBefore(',')}"+ val hits = get("$BASE/search/song?per_page=5&q=${java.net.URLEncoder.encode(q, "UTF-8")}")+ ?.obj("response")?.get("sections")?.jsonArray?.firstOrNull()?.jsonObject?.get("hits")?.jsonArray.orEmpty()+ // The right song: one of its artists, and its title (without "feat." / "Remastered" asides).+ val song = hits.map { it.jsonObject.obj("result") }.firstOrNull { r ->+ r ?: return@firstOrNull false+ val names = norm(r.str("artist_names").orEmpty())+ val t = norm(clean(r.str("title").orEmpty()))+ artists.any { names.contains(it) } && (t == norm(cleanTitle) || t.startsWith(norm(cleanTitle)) || norm(cleanTitle).startsWith(t))+ } ?: run { recent[k] = null; return@withContext null }+ val id = song.str("id") ?: run { recent[k] = null; return@withContext null }+ val meaning = coroutineScope {+ val about = async { get("$BASE/songs/$id?text_format=plain")?.obj("response")?.obj("song")?.obj("description")?.str("plain") }+ val notes = async {+ get("$BASE/referents?song_id=$id&text_format=plain&per_page=50")?.obj("response")?.get("referents")?.jsonArray.orEmpty()+ .mapNotNull { e ->+ val r = e.jsonObject+ // Genius's own "?" (empty) and the song-wide notes are left out: lines only.+ val fragment = r.str("fragment")?.trim().orEmpty()+ // The best liked explanation of the line; one voted down (negative) is never shown.+ val best = r["annotations"]?.jsonArray.orEmpty().map { it.jsonObject }+ .map { a -> a.obj("body")?.str("plain")?.trim().orEmpty() to (a.str("votes_total")?.toIntOrNull() ?: 0) }+ .filter { (body, votes) -> body.isNotBlank() && body != "?" && votes >= 0 }+ .maxByOrNull { it.second }+ if (fragment.isBlank() || best == null) null else Note(fragment, best.first, best.second)+ }+ }+ Meaning(+ url = song.str("url").orEmpty(),+ title = song.str("title").orEmpty(),+ artist = song.str("artist_names").orEmpty(),+ about = about.await()?.trim()?.takeIf { it.isNotBlank() && it != "?" },+ notes = notes.await(),+ )+ }.takeUnless { it.isEmpty }+ recent[k] = meaning+ meaning+ }++ // ── Ready before it is asked for: the song playing, and its translation ──++ /** The meaning of the song playing (its track id), looked up as soon as it starts. */+ val current = androidx.compose.runtime.mutableStateOf<Pair<String, Meaning>?>(null)+ private val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)+ private var prefetchJob: kotlinx.coroutines.Job? = null+ @Volatile private var prefetchFor = ""++ /**+ * [trackId] started: its Genius page is read in the background (and translated, on Wi-Fi), so+ * the light bulb and the underlined lines are there the moment the lyrics open.+ */+ fun prefetch(trackId: String, title: String, artist: String, lang: String) {+ if (trackId.isBlank() || title.isBlank() || current.value?.first == trackId) return+ if (prefetchFor == trackId && prefetchJob?.isActive == true) return+ prefetchFor = trackId+ prefetchJob?.cancel()+ prefetchJob = scope.launch {+ val m = runCatching { find(title, artist) }.getOrNull() ?: return@launch+ current.value = trackId to m+ if (!com.music.spotui.data.DataSaver.metered) pretranslate(m, lang)+ }+ }++ /** Translations already done ("lang|text" → text), shown as each one arrives. */+ private val translated = androidx.compose.runtime.mutableStateMapOf<String, String>()+ /** Meanings (url|lang) Genius wrote in the reader's own language: nothing to translate. */+ private val sameLanguage = androidx.compose.runtime.mutableStateMapOf<String, Boolean>()+ private val inFlight = androidx.compose.runtime.mutableStateMapOf<String, Boolean>()+ private val translateSlots = Dispatchers.IO.limitedParallelism(4)++ /** null: in the reader's language already. true/false: translation known to be needed (or not yet known). */+ fun isSameLanguage(m: Meaning, lang: String): Boolean? = sameLanguage["${m.url}|$lang"]++ /** [text] in [lang] when its translation has arrived; null until then. */+ fun translation(text: String, lang: String): String? = translated["$lang|$text"]++ /**+ * Asks for [text] in [lang] now (the one on screen goes first); the answer lands in+ * [translation]. The first answer for [m] also says whether Genius wrote it in [lang] already.+ */+ fun requestTranslation(m: Meaning, text: String, lang: String) {+ scope.launch(translateSlots) { translateNow(m, text, lang) }+ }++ /** Whether [text] is being translated into [lang] right now. */+ fun isTranslating(text: String, lang: String): Boolean = inFlight["$lang|$text"] == true++ private fun translateNow(m: Meaning, text: String, lang: String) {+ val k = "$lang|$text"+ synchronized(inFlight) {+ if (translated.containsKey(k) || sameLanguage["${m.url}|$lang"] == true || inFlight[k] == true) return+ inFlight[k] = true+ }+ try {+ val r = LyricTranslate.translateLines(text.split('\n'), lang) ?: return+ val same = r.sourceLanguage?.substringBefore('-')?.equals(lang.substringBefore('-'), ignoreCase = true) == true+ if (sameLanguage["${m.url}|$lang"] == null) sameLanguage["${m.url}|$lang"] = same+ if (!same) translated[k] = r.lines.joinToString("\n")+ } finally { inFlight.remove(k) }+ }++ /** Everything of [m] translated in the background, the "About" first, then the lines in order. */+ fun pretranslate(m: Meaning, lang: String) {+ val texts = listOfNotNull(m.about) + m.notes.map { it.explanation }+ scope.launch(translateSlots) {+ // The first answer says the language: nothing more is sent when it is the reader's.+ translateNow(m, texts.firstOrNull() ?: return@launch, lang)+ if (sameLanguage["${m.url}|$lang"] == false) texts.drop(1).forEach { requestTranslation(m, it, lang) }+ }+ }++ private fun get(url: String): JsonObject? {+ val req = Request.Builder().url(url)+ .header("User-Agent", "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36")+ .header("Accept", "application/json").build()+ http.newCall(req).execute().use { r ->+ if (!r.isSuccessful) { if (r.code == 404) return null; error("Genius ${r.code}") }+ return json.parseToJsonElement(r.body.string()).jsonObject+ }+ }++ private fun key(title: String, artist: String) = "$title|$artist"+ private fun JsonObject.obj(name: String): JsonObject? = (this[name] as? JsonObject)+ private fun JsonObject.str(name: String): String? = (this[name] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull+ private fun JsonArray?.orEmpty(): List<JsonElement> = this ?: emptyList()++ /** The title without its asides: "(feat. …)", "- Remastered 2011", "[Live]". */+ private fun clean(title: String) = title+ .replace(Regex("""\s*[(\[](feat|ft|with|prod)[^)\]]*[)\]]""", RegexOption.IGNORE_CASE), "")+ .replace(Regex("""\s+-\s+.*(remaster|version|edit|live|mix|mono|stereo).*$""", RegexOption.IGNORE_CASE), "")+ .trim()++ /** Lower case, no accents, letters and digits only: "Beyoncé" and "beyonce" match. */+ private fun norm(s: String) = Normalizer.normalize(s, Normalizer.Form.NFD)+ .replace(Regex("\\p{Mn}+"), "").lowercase().replace(Regex("[^\\p{L}\\p{N}]+"), "")+}diff --git a/base/app/src/main/java/com/music/spotui/data/api/InviteLinks.kt b/base/app/src/main/java/com/music/spotui/data/api/InviteLinks.ktnew file mode 100644index 00000000..eb333bc6--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/api/InviteLinks.kt@@ -0,0 +1,121 @@+package com.music.spotui.data.api++import android.content.Context+import android.util.Log+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.entity.ContextPageModel+import com.music.spotui.data.entity.LibraryEntry+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Collaborative-playlist invitations: `open.spotify.com/playlist/{id}?si=…&pt={token}`, as the+ * official apps share them (or a spotify.link short link that redirects to it). `pt` is the+ * permission-grant token; claiming it makes the account a collaborator. The link is kept here+ * until the user taps "Join" on the playlist page (see [join]). Blend invitations+ * (`/blend/taste-match/{id}`) are kept as [blend] and answered from a sheet.+ */+object InviteLinks {+ private const val TAG = "InviteLinks"++ /** A new object for every link opened, so the same link opened twice navigates twice. */+ class Invite(val playlistId: String, val token: String) {+ val uri get() = "spotify:playlist:$playlistId"+ /** The playlist page has been opened on it (not again when the screen is rebuilt). */+ @Volatile var opened = false+ }++ /** The invitation waiting for the user's answer; cleared once joined. */+ val pending = MutableStateFlow<Invite?>(null)++ /** A Blend invitation (`open.spotify.com/blend/taste-match/{id}`), a new object per link opened. */+ class BlendLink(val id: String)++ /** The Blend invitation opened, shown as a sheet over the app until answered (see BlendInviteSheet). */+ val blend = MutableStateFlow<BlendLink?>(null)++ /** A shared playlist / album / artist / podcast link: its page, opened by App.kt (not played). */+ val page = MutableStateFlow<String?>(null)++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val http by lazy { okhttp3.OkHttpClient.Builder().followRedirects(true).build() }++ private val PLAYLIST = Regex("""(?:open|www|play)\.spotify\.com/(?:intl-[a-z-]+/)?playlist/([A-Za-z0-9]{22})([^\s"'<>]*)""")+ private val TOKEN = Regex("""[?&]pt=([A-Za-z0-9_-]+)""")+ private val BLEND = Regex("""spotify\.com/(?:intl-[a-z-]+/)?blend/(?:taste-match|invitation)/([A-Za-z0-9]+)""")+ private val SHORT = Regex("""https?://(?:spotify\.link|spoti\.fi)/[^\s"'<>]+""")++ /** The invitation inside [link] (a playlist link carrying `pt`), or null. */+ fun parse(link: String): Invite? {+ val m = PLAYLIST.find(link.replace("&", "&").replace("\\u0026", "&")) ?: return null+ val token = TOKEN.find(m.groupValues[2])?.groupValues?.get(1) ?: return null+ return Invite(m.groupValues[1], token)+ }++ /**+ * An incoming link. True when it is taken here: a playlist invitation (kept as [pending], the+ * playlist page opens on it) or a short link (resolved on a background thread, then handled as+ * the link it leads to; one that is not an invitation plays like any Spotify link).+ */+ fun handle(link: String): Boolean {+ parse(link)?.let { pending.value = it; return true }+ BLEND.find(link)?.let { blend.value = BlendLink(it.groupValues[1]); return true }+ val short = SHORT.find(link)?.value ?: return false+ scope.launch {+ val target = resolve(short) ?: return@launch+ val invite = parse(target)+ if (invite != null) { pending.value = invite; return@launch }+ BLEND.find(target)?.let { blend.value = BlendLink(it.groupValues[1]); return@launch }+ // Not an invitation: the item the short link leads to is played, as a direct link is.+ val m = Regex("""spotify\.com/(?:intl-[a-z-]+/)?(track|album|playlist|artist|show|episode)/([A-Za-z0-9]{22})""").find(target) ?: return@launch+ runCatching {+ MyspotiRuntime.api.ready.first { it }+ MyspotiRuntime.api.player.play("spotify:${m.groupValues[1]}:${m.groupValues[2]}")+ }+ }+ return true+ }++ /** Where a short link leads: its final URL, or the playlist link inside the page it answers with. */+ private suspend fun resolve(link: String): String? = withContext(Dispatchers.IO) {+ runCatching {+ http.newCall(okhttp3.Request.Builder().url(link).header("user-agent", "Mozilla/5.0").build()).execute().use { r ->+ val final = r.request.url.toString()+ if (PLAYLIST.containsMatchIn(final) && TOKEN.containsMatchIn(final) || BLEND.containsMatchIn(final)) final+ else {+ val body = r.body.string().replace("\\/", "/")+ PLAYLIST.find(body.replace("&", "&").replace("\\u0026", "&"))?.value?.let { "https://$it" } ?: final+ }+ }+ }.onFailure { Log.w(TAG, "short link not resolved: ${it.message}") }.getOrNull()+ }++ /**+ * Joins the playlist of [invite] ([page] is that playlist's page, for the library row shown at+ * once): claims the token, follows the playlist when needed, and has the library read again.+ * A refused token (wrong or expired link) undoes the row and says so.+ */+ fun join(context: Context, invite: Invite, page: ContextPageModel, onDone: (Boolean) -> Unit = {}) {+ val app = context.applicationContext+ val edit = LibraryEdits.Add(null, LibraryEntry(+ spotifyId = invite.playlistId, name = page.name,+ subtitle = app.getString(R.string.assisted_curation_search_playlist) + page.ownerName.takeIf { it.isNotBlank() }?.let { " • $it" }.orEmpty(),+ coverUri = page.coverUri, isPlaylist = true, uri = invite.uri,+ addedAt = java.time.Instant.now().toString(),+ ))+ LibraryEdits.run(app, edit, write = {+ MyspotiRuntime.api.playlists.join(invite.uri, invite.token)+ Api.HomeCache.libraryRoot = null+ Api.HomeCache.folders.clear()+ }, onDone = { ok ->+ if (ok && pending.value === invite) pending.value = null+ onDone(ok)+ })+ }+}diff --git a/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt b/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.ktnew file mode 100644index 00000000..3429c7ab--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/api/LibraryEdits.kt@@ -0,0 +1,155 @@+package com.music.spotui.data.api++import android.content.Context+import android.util.Log+import android.widget.Toast+import app.myspoti.engine.R+import com.music.spotui.data.entity.LibraryEntry+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableSharedFlow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharedFlow+import kotlinx.coroutines.launch+import java.util.concurrent.CopyOnWriteArrayList++/**+ * Library changes shown before Spotify has them. Spotify's library list (libraryV3) trails a+ * write by several seconds, so a list read right after "delete" still held the playlist and a+ * reload put it back. Each edit is applied on top of whatever list the server gave, until the+ * server has had time to catch up; a refused write drops its edit, which restores the list.+ *+ * The screens keep the server's list as it came and show [applyTo] of it: a rollback is then+ * just "apply without this edit". Every edit is idempotent, so a server list that already+ * has the change is left as it is.+ */+object LibraryEdits {+ private const val TAG = "LibraryEdits"+ /** How long a written edit keeps covering the list: past this Spotify's list is right. */+ private const val SETTLE_MS = 25_000L+ /** An edit whose write never answers does not hide the server's list for ever. */+ private const val MAX_WRITE_MS = 120_000L++ abstract class Edit {+ /** [level] is the library folder's uri, null for the top level. */+ abstract fun apply(level: String?, list: List<LibraryEntry>): List<LibraryEntry>+ }++ /** A playlist or folder leaves the library (deleted, unfollowed, or moved elsewhere). */+ class Remove(val uri: String) : Edit() {+ override fun apply(level: String?, list: List<LibraryEntry>) = list.filterNot { it.matches(uri) }+ }++ class Rename(private val uri: String, private val name: String) : Edit() {+ override fun apply(level: String?, list: List<LibraryEntry>) =+ list.map { if (it.matches(uri) && it.name != name) it.copy(name = name) else it }+ }++ class Pin(private val uri: String, private val pinned: Boolean) : Edit() {+ override fun apply(level: String?, list: List<LibraryEntry>) =+ list.map { if (it.matches(uri) && it.pinned != pinned) it.copy(pinned = pinned) else it }+ }++ /**+ * A new playlist or folder in [level]. It first shows with a placeholder id (the real one is+ * known when Spotify has answered); [resolve] then swaps in the real entry.+ */+ class Add(private val level: String?, entry: LibraryEntry) : Edit() {+ @Volatile var entry: LibraryEntry = entry+ internal set+ override fun apply(level: String?, list: List<LibraryEntry>) = if (level == this.level) insertOnce(level, list, entry) else list+ }++ /** [entry] moves to [to] (a folder uri, null: the top level) and leaves every other level. */+ class Move(private val entry: LibraryEntry, private val to: String?) : Edit() {+ override fun apply(level: String?, list: List<LibraryEntry>) =+ if (level == to) insertOnce(level, list, entry) else list.filterNot { it.matches(entry.uri) }+ }++ /** After Liked Songs at the top level (it stays pinned there), first in a folder. */+ private fun insertOnce(level: String?, list: List<LibraryEntry>, e: LibraryEntry): List<LibraryEntry> {+ if (list.any { it.matches(e.uri) }) return list+ val at = if (level == null) list.indexOfFirst { it.spotifyId == Api.HomeCache.LIKED_SONGS_ID } + 1 else 0+ return list.toMutableList().apply { add(at.coerceIn(0, size), e) }+ }++ private class Pending(val edit: Edit, @Volatile var until: Long)++ private val pending = CopyOnWriteArrayList<Pending>()+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++ /** Counts every change to the set of edits: the screens show their list again when it moves. */+ val version = MutableStateFlow(0)++ /** Asks the screens to read the library again (the write is in; Spotify's list may have caught up). */+ private val _reloads = MutableSharedFlow<Unit>(extraBufferCapacity = 4)+ val reloads: SharedFlow<Unit> = _reloads++ fun applyTo(level: String?, list: List<LibraryEntry>): List<LibraryEntry> {+ val now = System.currentTimeMillis()+ if (pending.removeAll { it.until < now }) version.value+++ var out = list+ for (p in pending) out = p.edit.apply(level, out)+ return out+ }++ /** The row [edit] added now has its real uri. */+ fun resolve(edit: Add, real: LibraryEntry) {+ edit.entry = real+ version.value+++ }++ private fun find(edit: Edit) = pending.firstOrNull { it.edit === edit }++ /** Shows [edit] at once. */+ fun begin(edit: Edit) {+ // A playlist deleted right after it was made must not come back from its own Add.+ if (edit is Remove) pending.removeAll { p -> (p.edit as? Add)?.entry?.let { edit.apply(null, listOf(it)).isEmpty() } == true }+ pending.add(Pending(edit, System.currentTimeMillis() + MAX_WRITE_MS))+ version.value+++ }++ /** The write went through: the edit keeps covering the list while Spotify's list catches up. */+ fun confirm(edit: Edit) {+ find(edit)?.until = System.currentTimeMillis() + SETTLE_MS+ reloadSoon()+ }++ /** A change written elsewhere (a Blend joined): the library is read again a few times, the first read can still be the old one. */+ fun reloadSoon() {+ scope.launch { for (wait in longArrayOf(1_500, 3_500, 7_000)) { delay(wait); _reloads.tryEmit(Unit) } }+ }++ /** The write failed: the list goes back to what it was. */+ fun cancel(edit: Edit) {+ if (pending.removeAll { it.edit === edit }) version.value+++ }++ /**+ * Shows [edit] (when given), then writes it in the app's own scope, so leaving the screen+ * that asked does not cancel it. A refused write undoes the edit and says so.+ */+ fun run(context: Context, edit: Edit?, write: suspend () -> Unit, onDone: (Boolean) -> Unit = {}) {+ val app = context.applicationContext+ if (edit != null) begin(edit)+ scope.launch {+ val failure = runCatching { write() }.exceptionOrNull()+ if (failure is kotlinx.coroutines.CancellationException) throw failure+ if (failure == null) { edit?.let(::confirm) }+ else {+ Log.w(TAG, "library write refused: ${failure.message}")+ edit?.let(::cancel)+ Toast.makeText(app, app.getString(R.string.library_change_undone), Toast.LENGTH_SHORT).show()+ }+ onDone(failure == null)+ }+ }++ private fun LibraryEntry.matches(uri: String) = uri.isNotBlank() && (this.uri == uri || folderUri == uri)++ /** A row shown for something Spotify is still creating: it cannot be opened yet. */+ const val PENDING_PREFIX = "pending:"+ fun isPending(id: String) = id.startsWith(PENDING_PREFIX)+}diff --git a/base/app/src/main/java/com/music/spotui/data/api/LibraryFolders.kt b/base/app/src/main/java/com/music/spotui/data/api/LibraryFolders.ktindex 74b00c2a..322bbd39 100644--- a/base/app/src/main/java/com/music/spotui/data/api/LibraryFolders.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/LibraryFolders.kt@@ -1,22 +1,53 @@package com.music.spotui.data.api+import android.content.Context+import app.myspoti.engine.Rimport app.myspoti.host.android.MyspotiRuntime+import com.music.spotui.data.entity.LibraryEntry/*** Library folders: real Spotify folders, synced to the account (the public Web API has none).+ * Each change shows in the library at once ([LibraryEdits]) and is written in the app's own+ * scope; a refusal takes it back with a short message.*/object LibraryFolders {- /** Creates a folder at the top of the library; its uri, or null when Spotify refused. */- suspend fun create(name: String): String? =- runCatching { MyspotiRuntime.api.library.createFolder(name.trim()) }.getOrNull()?.also { changed() }+ private val pendingIds = java.util.concurrent.atomic.AtomicInteger()- /** Renames a folder; false when Spotify refused. */- suspend fun rename(uri: String, name: String): Boolean =- runCatching { MyspotiRuntime.api.library.renameFolder(uri, name.trim()) }.isSuccess.also { if (it) changed() }+ /** Creates a folder at the top of the library. */+ fun create(context: Context, name: String, onDone: (Boolean) -> Unit = {}) {+ val title = name.trim()+ if (title.isBlank()) { onDone(false); return }+ val app = context.applicationContext+ val placeholder = LibraryEdits.PENDING_PREFIX + "folder" + pendingIds.incrementAndGet()+ val edit = LibraryEdits.Add(null, LibraryEntry(+ spotifyId = placeholder, name = title, subtitle = app.getString(R.string.create_menu_item_folder_title),+ coverUri = "", isPlaylist = false, folderUri = placeholder, uri = placeholder,+ addedAt = java.time.Instant.now().toString(),+ ))+ LibraryEdits.run(context, edit, write = {+ val uri = MyspotiRuntime.api.library.createFolder(title)+ LibraryEdits.resolve(edit, edit.entry.copy(spotifyId = uri, folderUri = uri, uri = uri))+ changed()+ }, onDone = onDone)+ }++ /** Renames a folder. */+ fun rename(context: Context, uri: String, name: String, onDone: (Boolean) -> Unit = {}) {+ val title = name.trim()+ if (title.isBlank()) { onDone(false); return }+ LibraryEdits.run(context, LibraryEdits.Rename(uri, title), write = {+ MyspotiRuntime.api.library.renameFolder(uri, title)+ changed()+ }, onDone = onDone)+ }- /** Deletes a folder (its playlists go to the level above); false when Spotify refused. */- suspend fun delete(uri: String): Boolean =- runCatching { MyspotiRuntime.api.library.deleteFolder(uri) }.isSuccess.also { if (it) changed() }+ /** Deletes a folder (its playlists go to the level above). */+ fun delete(context: Context, uri: String, onDone: (Boolean) -> Unit = {}) {+ LibraryEdits.run(context, LibraryEdits.Remove(uri), write = {+ MyspotiRuntime.api.library.deleteFolder(uri)+ changed()+ }, onDone = onDone)+ }/** The library changed: the next load must come from Spotify, not from the caches. */fun changed() {diff --git a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.ktindex a6bfea3f..5b60c963 100644--- a/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/LyricsApi.kt@@ -56,6 +56,15 @@ object LyricsApi {/** Set by the settings: also ask NetEase and Genius when nothing better is found. */@Volatile var extraSources: Boolean = false+ /** Set by the settings: lyrics timed word by word first (karaoke), line by line otherwise. */+ @Volatile var wordSync: Boolean = true++ /** How long a word-synced source is waited for before the line-synced ones answer instead. */+ private const val WORD_WAIT_MS = 4_000L++ /** Lyrics to show while better ones are looked for (track key → Spotify's line-timed lyrics). */+ val early = kotlinx.coroutines.flow.MutableStateFlow<Pair<String, Lyrics>?>(null)+fun cached(track: Track): Lyrics? = cache[track.key] as? Lyrics@@ -71,6 +80,9 @@ object LyricsApi {fun forget(track: Track) { cache.remove(track.key) }+ /** A setting changed what is looked for: every song is read again when next shown. */+ fun forgetAll() { cache.clear() }+suspend fun fetch(track: Track): Lyrics? {when (val c = cache[track.key]) {is Lyrics -> return c@@ -91,7 +103,72 @@ object LyricsApi {}private suspend fun resolve(track: Track): Lyrics? {- val result = fromSpotify(track) ?: coroutineScope {+ val result = if (wordSync) wordFirst(track) else fromSpotify(track) ?: lineFallbacks(track)+ cache[track.key] = result ?: Miss()+ Log.d("LyricsApi", "${track.title}: ${result?.let { "${it.lines.size} lines from ${it.provider}, synced=${it.synced}, words=${it.wordSynced}" } ?: "none"}")+ return result+ }++ /**+ * "Word by word" (the setting): the sources with each word's time come first — Spotify's own+ * when it has them, then LyricsPlus, lrc.red and Kugou, asked together; the line-synced+ * chain after them. Spotify's colours are kept whoever gives the words.+ */+ private suspend fun wordFirst(track: Track): Lyrics? = coroutineScope {+ // The catalogues are asked with the full title: "Old Town Road - Remix" cut down to+ // "Old Town Road" found the original (1:53), refused for its length (reported: lyrics+ // not complete). The comparison still uses the title without its asides.+ val asked = track.title.trim()+ val title = cleanTitle(track.title)+ val artist = track.artist.substringBefore(",").trim()+ val durationMs = track.durationMs+ val spotify = async { fromSpotify(track) }+ val plus = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { fromLyricsPlus(asked, title, artist, durationMs) } }+ val red = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { fromLrcRed(asked, title, artist, durationMs) } }+ val kugou = async { kotlinx.coroutines.withTimeoutOrNull(WORD_WAIT_MS) { fromKugou(title, artist, durationMs) } }+ val sp = spotify.await()+ if (sp != null && sp.wordSynced && sp.uncapped) return@coroutineScope sp.also { plus.cancel(); red.cancel(); kugou.cancel() }+ // Shown at once while the word timings are looked for (reported: lyrics slow to come).+ if (sp != null) early.value = track.key to sp+ val words = (plus.await() ?: red.await() ?: kugou.await())?.takeIf { it.wordSynced }+ when {+ words != null -> alignTo(words, sp).copy(colors = sp?.colors)+ sp != null -> sp+ else -> lineFallbacks(track)+ }+ }++ /**+ * Word timings come from another recording's catalogue (Apple Music, Kugou): its intro can be+ * a little longer or shorter than Spotify's (reported: "mal synchro"). When Spotify times the+ * same lines, the words are moved by the usual gap between the two (the median of the lines+ * found in both, in order), so they follow Spotify's own audio.+ */+ private fun alignTo(words: Lyrics, spotify: Lyrics?): Lyrics {+ if (spotify == null || !spotify.synced) return words+ val theirs = spotify.lines.filter { it.timeMs > 0 && matchKey(it.text).length >= 6 }+ val gaps = ArrayList<Long>()+ var from = 0+ for (l in words.lines) {+ val k = matchKey(l.text)+ if (k.length < 6) continue+ val i = (from until theirs.size).firstOrNull { matchKey(theirs[it].text) == k } ?: continue+ gaps += theirs[i].timeMs - l.timeMs+ from = i + 1+ }+ if (gaps.size < 3) return words+ val shift = gaps.sorted()[gaps.size / 2]+ if (kotlin.math.abs(shift) < 60) return words+ Log.d("LyricsApi", "${words.provider}: moved by $shift ms to Spotify's timing (${gaps.size} lines)")+ return words.copy(lines = words.lines.map { l ->+ l.copy(timeMs = (l.timeMs + shift).coerceAtLeast(0), words = l.words?.map { w ->+ w.copy(startMs = (w.startMs + shift).coerceAtLeast(0), endMs = if (w.endMs > 0) (w.endMs + shift).coerceAtLeast(0) else 0)+ })+ })+ }++ /** Nothing from Spotify: LRCLIB, then (opt-in) NetEase and Genius, then Kugou. */+ private suspend fun lineFallbacks(track: Track): Lyrics? = coroutineScope {val title = cleanTitle(track.title)val artist = track.artist.substringBefore(",").trim()val durationSec = (track.durationMs / 1000).toInt()@@ -106,12 +183,8 @@ object LyricsApi {when {lrclib != null && lrclib.synced -> lrclibne != null && ne.synced -> ne- else -> lrclib ?: ne ?: genius?.await()+ else -> fromKugou(title, artist, track.durationMs) ?: lrclib ?: ne ?: genius?.await()}- }- cache[track.key] = result ?: Miss()- Log.d("LyricsApi", "${track.title}: ${result?.let { "${it.lines.size} lines from ${it.provider}, synced=${it.synced}, words=${it.wordSynced}" } ?: "none"}")- return result}// ── 1. Spotify color-lyrics ──@@ -234,6 +307,151 @@ object LyricsApi {return Lyrics(plain.split("\n").map { LyricLine(0L, it) }, synced = false, provider = "LRCLIB")}+ // ── Word by word: LyricsPlus (Apple Music's timing, by title / artist / length) ──+ private val LYRICS_PLUS = listOf("https://lyricsplus.binimum.org", "https://lyricsplus.prjktla.my.id")++ private fun fromLyricsPlus(asked: String, title: String, artist: String, durationMs: Long): Lyrics? {+ val q = "title=${enc(asked)}&artist=${enc(artist)}" + if (durationMs > 0) "&duration=${durationMs / 1000}" else ""+ for (base in LYRICS_PLUS) {+ val body = httpGet("$base/v2/lyrics/get?$q", timeoutMs = 5000) ?: continue+ val o = runCatching { JSONObject(body) }.getOrNull() ?: continue+ val meta = o.optJSONObject("metadata")+ if (meta != null && !sameSong(meta.optString("title"), meta.optString("artist"), parseClock(meta.optString("totalDuration")), title, artist, durationMs)) return null+ val arr = o.optJSONArray("lyrics") ?: continue+ val lines = ArrayList<LyricLine>()+ for (i in 0 until arr.length()) {+ val l = arr.optJSONObject(i) ?: continue+ val syl = l.optJSONArray("syllabus")+ val words = syl?.let { s ->+ (0 until s.length()).mapNotNull { j -> s.optJSONObject(j) }+ .filterNot { it.optBoolean("isBackground") }+ .map { w -> val t = w.optLong("time"); LyricWord(t, t + w.optLong("duration"), w.optString("text")) }+ }?.takeIf { it.isNotEmpty() }+ val text = words?.joinToString("") { it.text }?.trim() ?: l.optString("text").trim()+ if (text.isNotEmpty()) lines += LyricLine(l.optLong("time"), text, words)+ }+ if (lines.isEmpty()) continue+ val source = meta?.optString("source").orEmpty()+ return Lyrics(lines, synced = true, language = meta?.optString("language")?.takeIf { it.isNotBlank() },+ provider = if (source.contains("apple", true)) "Apple Music · LyricsPlus" else "LyricsPlus")+ }+ return null+ }++ // ── Word by word: lrc.red (Apple Music TTML, found by ISRC) ──+ private fun fromLrcRed(asked: String, title: String, artist: String, durationMs: Long): Lyrics? {+ val search = httpGet("https://lrc.red/search.json?q=${enc("$asked $artist")}", timeoutMs = 5000) ?: return null+ val hits = runCatching { JSONObject(search).optJSONArray("hits") }.getOrNull() ?: return null+ val hit = (0 until hits.length()).mapNotNull { hits.optJSONObject(it) }.firstOrNull {+ sameSong(it.optString("title"), it.optString("artist"), (it.optDouble("duration", 0.0) * 1000).toLong(), title, artist, durationMs)+ } ?: return null+ val isrc = hit.optString("isrc").takeIf { it.isNotBlank() } ?: return null+ val ttml = httpGet("https://lrc.red/s/${enc(isrc)}.ttml", timeoutMs = 6000) ?: return null+ val lines = parseTtml(ttml) ?: return null+ return Lyrics(lines, synced = true, provider = "Apple Music · lrc.red")+ }++ /** Apple Music's TTML: a <p> per line, a timed <span> per word (background voices left out). */+ internal fun parseTtml(xml: String): List<LyricLine>? = runCatching {+ val p = android.util.Xml.newPullParser()+ p.setFeature(org.xmlpull.v1.XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)+ p.setInput(java.io.StringReader(xml))+ val lines = ArrayList<LyricLine>()+ var lineStart = -1L+ var words: MutableList<LyricWord>? = null+ var plain = StringBuilder()+ var wordStart = -1L; var wordEnd = 0L; var word = StringBuilder()+ var skipDepth = 0+ var inBody = false+ while (true) {+ when (p.next()) {+ org.xmlpull.v1.XmlPullParser.END_DOCUMENT -> break+ org.xmlpull.v1.XmlPullParser.START_TAG -> when {+ p.name == "body" -> inBody = true+ !inBody -> {}+ skipDepth > 0 -> skipDepth+++ p.getAttributeValue(null, "ttm:role")?.startsWith("x-") == true -> skipDepth = 1+ p.name == "p" -> { lineStart = clock(p.getAttributeValue(null, "begin")); words = ArrayList(); plain = StringBuilder() }+ p.name == "span" && words != null -> {+ wordStart = clock(p.getAttributeValue(null, "begin")); wordEnd = clock(p.getAttributeValue(null, "end")); word = StringBuilder()+ }+ }+ org.xmlpull.v1.XmlPullParser.TEXT -> if (inBody && skipDepth == 0 && words != null) {+ val t = p.text+ if (wordStart >= 0) word.append(t)+ // Text between two words (a space): it belongs to the word before it.+ else if (words!!.isNotEmpty()) words!![words!!.lastIndex] = words!!.last().let { it.copy(text = it.text + t) }+ plain.append(t)+ }+ org.xmlpull.v1.XmlPullParser.END_TAG -> when {+ skipDepth > 0 -> skipDepth--+ p.name == "span" && wordStart >= 0 -> { words?.add(LyricWord(wordStart, wordEnd, word.toString())); wordStart = -1 }+ p.name == "p" && words != null -> {+ val text = plain.toString().replace(Regex("\\s+"), " ").trim()+ if (text.isNotEmpty() && lineStart >= 0) lines += LyricLine(lineStart, text, words!!.takeIf { it.isNotEmpty() })+ words = null+ }+ }+ }+ }+ lines.takeIf { it.isNotEmpty() }+ }.getOrNull()++ /** TTML times: "11.859", "1:02.345" or "00:01:02.345" → ms. */+ private fun clock(v: String?): Long {+ if (v.isNullOrBlank()) return -1+ val parts = v.trim().removeSuffix("s").split(':')+ var ms = 0.0+ for (part in parts) ms = ms * 60 + (part.toDoubleOrNull() ?: return -1)+ return (ms * 1000).toLong()+ }+ private fun parseClock(v: String?): Long = clock(v).coerceAtLeast(0)++ // ── Word by word: Kugou (its own catalogue, strong in Asian music; KRC, encrypted) ──+ private val KRC_KEY = intArrayOf(64, 71, 97, 119, 94, 50, 116, 71, 81, 54, 49, 45, 206, 210, 110, 105)+ private val krcLine = Regex("""^\[(\d+),(\d+)](.*)$""")+ private val krcWord = Regex("""<(\d+),(\d+),\d+>([^<]*)""")++ private fun fromKugou(title: String, artist: String, durationMs: Long): Lyrics? {+ val search = httpGet("https://lyrics.kugou.com/search?ver=1&man=yes&client=pc&keyword=${enc("$artist - $title")}" ++ (if (durationMs > 0) "&duration=$durationMs" else ""), timeoutMs = 5000) ?: return null+ val cands = runCatching { JSONObject(search).optJSONArray("candidates") }.getOrNull() ?: return null+ val c = (0 until cands.length()).mapNotNull { cands.optJSONObject(it) }.firstOrNull {+ sameSong(it.optString("song"), it.optString("singer"), it.optLong("duration"), title, artist, durationMs)+ } ?: return null+ val dl = httpGet("https://lyrics.kugou.com/download?ver=1&client=pc&id=${c.optString("id")}&accesskey=${c.optString("accesskey")}&fmt=krc&charset=utf8", timeoutMs = 5000) ?: return null+ val content = runCatching { JSONObject(dl).optString("content") }.getOrNull()?.takeIf { it.isNotBlank() } ?: return null+ val krc = runCatching {+ val raw = android.util.Base64.decode(content, android.util.Base64.DEFAULT)+ val x = ByteArray(raw.size - 4) { i -> (raw[i + 4].toInt() xor KRC_KEY[i % KRC_KEY.size]).toByte() }+ java.util.zip.InflaterInputStream(x.inputStream()).readBytes().decodeToString()+ }.getOrNull() ?: return null+ val lines = krc.lines().mapNotNull { raw ->+ val m = krcLine.find(raw.trim()) ?: return@mapNotNull null+ val start = m.groupValues[1].toLong()+ val words = krcWord.findAll(m.groupValues[3]).map { w ->+ val s = start + w.groupValues[1].toLong(); LyricWord(s, s + w.groupValues[2].toLong(), w.groupValues[3])+ }.toList()+ val text = words.joinToString("") { it.text }.trim()+ // Kugou opens with credit lines ("作词:…"): not lyrics.+ if (text.isEmpty() || text.contains(':')) null else LyricLine(start, text, words.takeIf { it.isNotEmpty() })+ }+ if (lines.size < 3) return null+ return Lyrics(lines, synced = true, provider = "Kugou")+ }++ /**+ * The same song for the word-timed sources: one of its artists is ours, the title is ours+ * (asides left out, either may be longer), and the length is within 4 s when both are known.+ */+ private fun sameSong(candTitle: String, candArtist: String, candDurationMs: Long, title: String, artist: String, durationMs: Long): Boolean {+ val a = matchKey(artist)+ if (a.isEmpty() || candArtist.split(',', '&', '、', '/').none { matchKey(it) == a }) return false+ val t = matchKey(title); val ct = matchKey(cleanTitle(candTitle))+ if (t.isEmpty() || !(ct == t || ct.startsWith(t) || t.startsWith(ct))) return false+ return durationMs <= 0 || candDurationMs <= 0 || kotlin.math.abs(candDurationMs - durationMs) <= 4_000+ }+// ── Matching ──// Strip the noise Spotify puts in titles that other catalogues don't have:// "Song - 2011 Remaster", "Song (feat. X)", "Song [Bonus Track]".diff --git a/base/app/src/main/java/com/music/spotui/data/api/PagePrefetch.kt b/base/app/src/main/java/com/music/spotui/data/api/PagePrefetch.ktnew file mode 100644index 00000000..e0a9b978--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/data/api/PagePrefetch.kt@@ -0,0 +1,76 @@+package com.music.spotui.data.api++import com.music.spotui.data.entity.LibraryEntry+import com.music.spotui.di.Graph+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++/**+ * The playlists at the top of the library, fetched ahead on Wi-Fi while the app sits idle and+ * kept on storage (not in memory): opening one shows it whole at once, after a restart too, and+ * the network only refreshes it behind. A few pages, refreshed at most every half hour, the+ * oldest deleted; nothing on mobile data or under the data saver.+ */+object PagePrefetch {+ private const val COUNT = 4+ /** Pages kept on storage: the prefetched ones plus a few the user opened since. */+ const val KEEP = 8+ private const val IDLE_MS = 20_000L+ private const val FRESH_MS = 30 * 60_000L+ private const val MIN_GAP_MS = 10 * 60_000L+ /** A bigger playlist is left to the network: its file would be large for one open. */+ private const val MAX_TRACKS = 1_000++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ @Volatile private var lastRun = 0L++ /**+ * At startup, once the player is ready: the library as last saved, so the prefetch does not+ * wait for the Library tab to be opened.+ */+ fun start() {+ scope.launch {+ if (kotlinx.coroutines.withTimeoutOrNull(60_000) { app.myspoti.host.android.MyspotiRuntime.api.ready.first { it } } == null) return@launch+ val root = Api.HomeCache.libraryRoot ?: ScreenCache.libraryRoot.read() ?: return@launch+ schedule(root)+ }+ }++ /** Called with the library's first level each time it is read; runs at most every 10 minutes. */+ fun schedule(entries: List<LibraryEntry>) {+ val now = System.currentTimeMillis()+ if (now - lastRun < MIN_GAP_MS) return+ lastRun = now+ val ids = entries.asSequence()+ .filter { it.isPlaylist && it.uri.startsWith("spotify:playlist:") }+ .map { it.uri.substringAfterLast(':') }+ .take(COUNT).toList()+ if (ids.isEmpty()) return+ scope.launch {+ delay(IDLE_MS)+ for (id in ids) {+ if (com.music.spotui.data.DataSaver.metered) return@launch+ val saved = ScreenCache.pageSavedAt(id)+ if (saved != null && System.currentTimeMillis() - saved < FRESH_MS) continue+ val page = runCatching {+ Graph.api.getPlaylistPage(id).first { it is Response.Success && it.data.complete || it is Response.Error }+ }.getOrNull()+ val kept = (page as? Response.Success)?.data?.takeIf { it.tracks.isNotEmpty() && it.tracks.size <= MAX_TRACKS }+ kept?.let { ScreenCache.page(id).write(it) }+ android.util.Log.d("Myspoti", "prefetch playlist ${id.take(6)}…: ${kept?.tracks?.size?.let { "$it songs kept on storage" } ?: "not kept"}")+ delay(1_500) // one after the other, gently+ }+ ScreenCache.prunePages(KEEP)+ }+ }++ /** A page just read whole from the network: its copy on storage, when it has one, follows. */+ fun refreshed(id: String, page: com.music.spotui.data.entity.ContextPageModel) {+ if (!page.complete || page.tracks.size > MAX_TRACKS || ScreenCache.pageSavedAt(id) == null) return+ ScreenCache.page(id).write(page)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt b/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.ktindex d00594d4..1d7886de 100644--- a/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/ScreenCache.kt@@ -16,7 +16,7 @@ import kotlinx.serialization.json.Jsonimport java.io.File/**- * The last home feed, library and Liked Songs, kept on disk: after a restart the screens+ * The last home feed, library and Liked Songs (and a few playlist pages), kept on disk: after a restart the screens* show them at once, while the hidden Web Player is still starting, then refresh.* Private app storage; cleared on logout ([clear]).*/@@ -34,6 +34,20 @@ object ScreenCache {val libraryRoot = Entry("library_root", ListSerializer(LibraryEntry.serializer()))val liked = Entry("liked", ListSerializer(SongsModel.serializer()))+ /** A playlist page fetched ahead (see PagePrefetch), one file per playlist. */+ fun page(id: String) = Entry("page_$id", com.music.spotui.data.entity.ContextPageModel.serializer())++ /** When the page of [id] was last saved; null when there is none. */+ fun pageSavedAt(id: String): Long? = File(dir, "page_$id.json").takeIf { it.exists() }?.lastModified()++ /** Keeps the [keep] most recent pages on storage and deletes the others. */+ fun prunePages(keep: Int) {+ io.launch {+ dir.listFiles { f -> f.name.startsWith("page_") && f.name.endsWith(".json") }+ ?.sortedByDescending { it.lastModified() }?.drop(keep)?.forEach { it.delete() }+ }+ }+class Entry<T>(private val name: String, private val serializer: KSerializer<T>) {private val file get() = AtomicFile(File(dir, "$name.json"))diff --git a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.ktindex a6ad4f5f..ede5ce5d 100644--- a/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt+++ b/base/app/src/main/java/com/music/spotui/data/api/SpotifySync.kt@@ -7,6 +7,10 @@ import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import app.myspoti.engine.R+import com.music.spotui.data.entity.LibraryEntryimport java.util.concurrent.ConcurrentHashMap/**@@ -37,11 +41,35 @@ object SpotifySync {val ok = runCatching { api.playlists.addTracks("spotify:playlist:$playlistId", listOf("spotify:track:$trackId")) }.onFailure { Log.w(TAG, "add $trackId to $playlistId failed: ${it.message}") }.isSuccessif (ok) membershipCache[playlistId]?.add(trackId)+ if (ok) com.music.spotui.data.offline.OfflineCollections.refreshOne(context.applicationContext, "spotify:playlist:$playlistId")onDone(ok)}}- /** Removes every occurrence of a track from one of the user's playlists. */+ /**+ * Takes one row out of a playlist, named by its row id (not by its song: the same song twice+ * in a playlist is two rows, and removing "the song" took both). Without a row id (an old+ * cache) the first row of that song goes, never all of them.+ */+ fun removeRowFromPlaylist(context: Context, playlistId: String, trackId: String, rowUid: String, onDone: (Boolean) -> Unit = {}) {+ if (playlistId.isBlank() || (trackId.isBlank() && rowUid.isBlank())) { onDone(false); return }+ scope.launch {+ val ok = runCatching {+ val uri = "spotify:playlist:$playlistId"+ val uid = rowUid.ifBlank { allTracks(uri).firstOrNull { it.uri == "spotify:track:$trackId" }?.uid }+ checkNotNull(uid) { "track not in playlist" }+ api.playlists.removeTracks(uri, listOf(uid))+ }.onFailure { Log.w(TAG, "remove row $rowUid ($trackId) from $playlistId failed: ${it.message}") }.isSuccess+ // The song may still be in the playlist through another row: read it again when asked.+ if (ok) membershipCache.remove(playlistId)+ onDone(ok)+ }+ }++ /**+ * Removes every occurrence of a track from one of the user's playlists: the "Saved in"+ * sheet's switch means "this song is not in that playlist any more".+ */fun removeTrackFromPlaylist(context: Context, playlistId: String, trackId: String, onDone: (Boolean) -> Unit = {}) {if (playlistId.isBlank() || trackId.isBlank()) { onDone(false); return }scope.launch {@@ -56,23 +84,64 @@ object SpotifySync {}}- /** Creates a playlist (and adds the track when given). */- fun createPlaylistWithTrack(context: Context, name: String, trackId: String, folderUri: String? = null, onDone: (Boolean) -> Unit = {}) {- if (name.isBlank()) { onDone(false); return }+ // Visibility taps are written one at a time, in the order they were made.+ private val visibilityWrites = Mutex()++ /** Who may see or change a playlist (public, private, collaborative), as chosen. [onDone] gets whether Spotify took it. */+ fun setPlaylistAccess(uri: String, access: app.myspoti.api.PlaylistAccess, onDone: (Boolean) -> Unit = {}) {scope.launch {- val ok = runCatching {- val uri = api.playlists.create(name.trim(), folderUri)- if (trackId.isNotBlank()) {- api.playlists.addTracks(uri, listOf("spotify:track:$trackId"))- membershipCache[uri.substringAfterLast(':')] = ConcurrentHashMap.newKeySet<String>().apply { add(trackId) }- }- }.onFailure { Log.w(TAG, "create playlist '$name' failed: ${it.message}") }.isSuccess- Api.HomeCache.libraryRoot = null- folderUri?.let { Api.HomeCache.folders.remove(it) }+ val ok = visibilityWrites.withLock {+ runCatching { api.playlists.setAccess(uri, access) }+ .onFailure { Log.w(TAG, "access of $uri to $access refused: ${it.message}") }.isSuccess+ }onDone(ok)}}+ /** Whether the playlist is listed on the user's profile. */+ fun setPlaylistPublished(uri: String, published: Boolean, onDone: (Boolean) -> Unit = {}) {+ scope.launch {+ val ok = visibilityWrites.withLock {+ runCatching { api.playlists.setPublished(uri, published) }+ .onFailure { Log.w(TAG, "profile listing of $uri to $published refused: ${it.message}") }.isSuccess+ }+ onDone(ok)+ }+ }++ private val pendingIds = java.util.concurrent.atomic.AtomicInteger()++ /**+ * Creates a playlist (and adds the track when given). In the library it shows at once as a+ * row that cannot be opened yet, and becomes the real playlist when Spotify has answered;+ * a refused creation takes the row away again.+ */+ fun createPlaylistWithTrack(context: Context, name: String, trackId: String, folderUri: String? = null, onDone: (Boolean) -> Unit = {}) {+ val title = name.trim()+ if (title.isBlank()) { onDone(false); return }+ val app = context.applicationContext+ val placeholderId = LibraryEdits.PENDING_PREFIX + pendingIds.incrementAndGet()+ val edit = LibraryEdits.Add(folderUri, LibraryEntry(+ spotifyId = placeholderId, name = title,+ subtitle = app.getString(R.string.assisted_curation_search_playlist) + ProfileCache.name?.let { " • $it" }.orEmpty(),+ coverUri = "", isPlaylist = true, uri = placeholderId,+ addedAt = java.time.Instant.now().toString(),+ ))+ var trackAdded = true+ LibraryEdits.run(context, edit, write = {+ val uri = api.playlists.create(title, folderUri)+ LibraryEdits.resolve(edit, edit.entry.copy(spotifyId = uri.substringAfterLast(':'), uri = uri))+ Api.HomeCache.libraryRoot = null+ folderUri?.let { Api.HomeCache.folders.remove(it) }+ if (trackId.isNotBlank()) {+ // The playlist exists now: a refused track must not take its row away again.+ trackAdded = runCatching { api.playlists.addTracks(uri, listOf("spotify:track:$trackId")) }+ .onFailure { Log.w(TAG, "add $trackId to new playlist '$title' failed: ${it.message}") }.isSuccess+ if (trackAdded) membershipCache[uri.substringAfterLast(':')] = ConcurrentHashMap.newKeySet<String>().apply { add(trackId) }+ }+ }, onDone = { ok -> onDone(ok && trackAdded) })+ }+private suspend fun allTracks(uri: String): List<app.myspoti.api.Track> {val out = ArrayList<app.myspoti.api.Track>()var offset = 0diff --git a/base/app/src/main/java/com/music/spotui/data/entity/ContextPageModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/ContextPageModel.ktindex 63ea72b4..fb2ef34c 100644--- a/base/app/src/main/java/com/music/spotui/data/entity/ContextPageModel.kt+++ b/base/app/src/main/java/com/music/spotui/data/entity/ContextPageModel.kt@@ -1,6 +1,7 @@package com.music.spotui.data.entity/** Everything the album / playlist page shows, loaded by Spotify id. */data class ContextPageModel(val uri: String,val type: String, // "album" | "playlist"@@ -14,4 +15,6 @@ data class ContextPageModel(val explicit: Boolean = false,val tracks: List<SongsModel> = emptyList(),val complete: Boolean = true,+ /** A Spotify Blend: its page shows the members and the taste match. */+ val isBlend: Boolean = false,)diff --git a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.ktindex e7a65520..d62f80f6 100644--- a/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt+++ b/base/app/src/main/java/com/music/spotui/data/entity/SongsModel.kt@@ -37,6 +37,12 @@ data class SongsModel(val playedPositionMs : Long = 0L,/** Raw Spotify id of the show the episode belongs to. */val showId : String = "",+ /**+ * This row's own id in a Spotify playlist. The same song twice in a playlist has the same+ * [id] and [spotifyTrackId] but two row ids, and a removal must name the row, not the song.+ * Empty outside playlists and in older caches.+ */+ val rowUid : String = "",){constructor() : this(-1 ,"" ,"" ,"" ,"" ,"", "")diff --git a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.ktindex d281611f..5d725757 100644--- a/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt+++ b/base/app/src/main/java/com/music/spotui/data/offline/OfflineCollections.kt@@ -154,6 +154,21 @@ object OfflineCollections {}}+ /**+ * One downloaded list changed from the app (a song added to it): read again and synced at+ * once, so the new song is on the phone without opening the list (Wi-Fi rule as above).+ */+ fun refreshOne(context: Context, uri: String) {+ val c = collections[uri] ?: return+ scope.launch {+ delay(1_500) // Spotify's own copy of the list catches up first.+ if (!OfflineStore.isOnline(context)) return@launch+ if (com.music.spotui.data.DataSaver.metered) { waitForWifi(); return@launch }+ val page = withTimeoutOrNull(60_000) { loadComplete(c) } ?: return@launch+ withContext(Dispatchers.Main) { sync(page) }+ }+ }+private suspend fun loadComplete(c: OfflineCollection): ContextPageModel? {val api = Graph.apival id = c.uri.substringAfterLast(":")diff --git a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.ktindex 72071a2d..485cdc83 100644--- a/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt+++ b/base/app/src/main/java/com/music/spotui/data/preferences/SettingsPref.kt@@ -17,6 +17,10 @@ private const val KEY_CROSSFADE = "crossfade_seconds"fun isLyricsExtraSources(c: Context): Boolean = prefs(c).getBoolean(KEY_LYRICS_EXTRA, false)fun setLyricsExtraSources(c: Context, v: Boolean) = prefs(c).edit().putBoolean(KEY_LYRICS_EXTRA, v).apply()+/** Lyrics timed word by word first (karaoke); off: line by line, Spotify's first. */+fun isLyricsWordSync(c: Context): Boolean = prefs(c).getBoolean("lyrics_word_sync", true)+fun setLyricsWordSync(c: Context, v: Boolean) = prefs(c).edit().putBoolean("lyrics_word_sync", v).apply()+private fun prefs(c: Context) = c.getSharedPreferences(PREF, Context.MODE_PRIVATE)/** The bottom bar: fading into the list (the default), or solid black. Read by the bar as state. */diff --git a/base/app/src/main/java/com/music/spotui/di/OutputLag.kt b/base/app/src/main/java/com/music/spotui/di/OutputLag.ktnew file mode 100644index 00000000..5dc1967e--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/di/OutputLag.kt@@ -0,0 +1,28 @@+package com.music.spotui.di++import android.os.SystemClock++/**+ * How late the sound is heard after the player plays it: Bluetooth delays it (~150-250 ms with+ * SBC / AAC / LDAC). What is shown in time with the song (clip, lyrics) follows what is heard.+ */+object OutputLag {+ private const val CHECK_MS = 3_000L+ /** One figure for every Bluetooth codec: close enough for lines and words. */+ private const val BLUETOOTH_MS = 200L++ @Volatile private var lag = 0L+ @Volatile private var checkedAt = 0L++ fun ms(): Long {+ val now = SystemClock.elapsedRealtime()+ if (now - checkedAt > CHECK_MS) {+ checkedAt = now+ val route = com.music.spotui.ui.components.AudioRoute.current(Graph.app)+ val l = if (route.kind == com.music.spotui.ui.components.AudioRoute.Kind.BLUETOOTH) BLUETOOTH_MS else 0L+ if (l != lag) app.myspoti.host.android.Logbook.log("sound heard $l ms late (${route.kind.name.lowercase()}): clip and lyrics follow")+ lag = l+ }+ return lag+ }+}diff --git a/base/app/src/main/java/com/music/spotui/di/Palette.kt b/base/app/src/main/java/com/music/spotui/di/Palette.ktindex 248df757..1375c7cf 100644--- a/base/app/src/main/java/com/music/spotui/di/Palette.kt+++ b/base/app/src/main/java/com/music/spotui/di/Palette.kt@@ -11,6 +11,8 @@ import com.bumptech.glide.request.transition.Transitionclass Palette {companion object {+ /** The tint when a cover gives none (none loaded). */+ val NEUTRAL = Color(0xFF2A2A2A)// Cover colours already computed (process-wide): a screen opening on a known// cover gets its colour in the first frame instead of popping in afterwards.private val colors = java.util.Collections.synchronizedMap(object : java.util.LinkedHashMap<String, Color>(64, 0.75f, true) {@@ -48,7 +50,9 @@ class Palette {.into(object : CustomTarget<Bitmap>() {override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {Palette.from(resource).generate { palette ->- val dominantColor = palette?.darkVibrantSwatch?.rgb+ // Not every cover has a dark vibrant swatch: without one the colour of the song+ // before stayed (reported: the tint "doesn't change" between some songs).+ val dominantColor = palette?.let { it.darkVibrantSwatch ?: it.darkMutedSwatch ?: it.dominantSwatch ?: it.vibrantSwatch }?.rgbdominantColor?.let {// Convert RGB color integer to ARGB color integer with full opacityval argbColor = Color(it or (0xFF shl 24))@@ -60,6 +64,9 @@ class Palette {override fun onLoadCleared(placeholder: Drawable?) {// Handle cleanup here if necessary}++ // No cover (failed load): a neutral tint, never the song before's.+ override fun onLoadFailed(errorDrawable: Drawable?) { onColorExtracted(NEUTRAL) }})}fun extractSecondColorFromCoverUrl(context: Context, imageUrl: String, onColorExtracted: (Color) -> Unit) {@@ -78,7 +85,7 @@ class Palette {Palette.from(scaledBitmap).generate { palette ->- val lightVibrantColor = palette?.mutedSwatch?.rgb+ val lightVibrantColor = palette?.let { it.mutedSwatch ?: it.darkMutedSwatch ?: it.dominantSwatch ?: it.vibrantSwatch }?.rgblightVibrantColor?.let {// Convert RGB color integer to ARGB color integer with full opacityval argbColor = Color(it or (0xFF shl 24))@@ -90,6 +97,9 @@ class Palette {override fun onLoadCleared(placeholder: Drawable?) {// Handle cleanup here if necessary}++ // No cover (failed load): a neutral tint, never the song before's.+ override fun onLoadFailed(errorDrawable: Drawable?) { onColorExtracted(NEUTRAL) }})}}\ No newline at end of filediff --git a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt b/base/app/src/main/java/com/music/spotui/di/SongPlayer.ktindex 464700ea..f2d37a63 100644--- a/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/di/SongPlayer.kt@@ -38,6 +38,10 @@ object SongPlayer {private const val END_OF_TRACK_MARGIN_MS = 600L/** How often the state is read again while another device plays. */private const val REMOTE_REFRESH_MS = 3_000L+ /** How often the state is read again while this phone plays (the page pushes its changes). */+ private const val LOCAL_REFRESH_MS = 15_000L+ /** A song this far past its end with no new state from the page: the state is read at once. */+ private const val SONG_END_GRACE_MS = 1_500L/** A transport command that has not answered by then is given up (the next one runs). */private const val TRANSPORT_TIMEOUT_MS = 15_000L/** How long a play has to show up in the page's state before it is sent again. */@@ -46,6 +50,10 @@ object SongPlayer {private const val EPISODE_RESUME_CHECK_MS = 2_500L/** "Next" taps closer than this are sent as one jump. */private const val SKIP_BURST_MS = 350L+ /** Skip commands are at least this far apart; taps in between add up (see [next]). */+ private const val MIN_SKIP_GAP_MS = 2_000L+ /** An ad break shorter than this is never shown (see the adPlaying collector). */+ private const val AD_SHOW_AFTER_MS = 2_000L/** After a local file starts, engine states this recent still predate the pause. */private const val LOCAL_GRACE_MS = 2500Lprivate const val TAG = "MspPlayer"@@ -144,25 +152,60 @@ object SongPlayer {boundState = statecom.music.spotui.data.api.LyricsApi.extraSources =com.music.spotui.data.preferences.isLyricsExtraSources(Graph.app)+ com.music.spotui.data.api.LyricsApi.wordSync =+ com.music.spotui.data.preferences.isLyricsWordSync(Graph.app)restoreLastTrack(state)scope.launch { api.player.state.collect { s -> if (acceptsSessionUpdates()) applyState(s) } }- // Another device plays (the phone as a remote), or the app sits in the background while the- // page's own reports go quiet: the state is read again every few seconds so the- // notification, the mini player and the slider keep up. Reported: the notification stopped- // refreshing in the background — this loop waited for _activeDevice, which only a pull-back- // sets, so an app started in the background never ran it.+ // Another device plays (the phone as a remote): the state is read again every few seconds+ // so the notification, the mini player and the slider keep up. Reported: the notification+ // stopped refreshing in the background — this loop waited for _activeDevice, which only a+ // pull-back sets, so an app started in the background never ran it.+ // This phone plays: the page pushes every change itself (it is never throttled, see+ // AwakeWebView), so reading the whole state and queue every 3 s only kept both processes+ // awake, screen off. It is read every LOCAL_REFRESH_MS as a safety net, and at once when+ // the song should have ended without the page saying what came next.scope.launch {+ var lastRead = 0Lwhile (true) {kotlinx.coroutines.delay(REMOTE_REFRESH_MS)- if (_activeDevice.value == null && !PlaybackService.isRunning) continue+ val remote = _activeDevice.value != null+ if (!remote && !PlaybackService.isRunning) continue+ val now = SystemClock.elapsedRealtime()+ val overdue = playing && !isBuffering && durationMs > 0 &&+ positionMs + (now - positionAt) > durationMs + SONG_END_GRACE_MS+ if (!remote && !overdue && now - lastRead < LOCAL_REFRESH_MS) continue+ lastRead = nowrunCatching { MyspotiRuntime.spotify.player.refresh() }}}scope.launch { api.player.queue.collect { q -> if (acceptsSessionUpdates()) applyQueue(q) } }+ // Smart shuffle plays a mixed order as the list and leaves Spotify's own shuffle off, so+ // turning it off sends no shuffle command at all (the button finds shuffle already off):+ // the list's own order comes back here.+ scope.launch {+ var was = com.music.spotui.ui.screens.SmartShuffle.on.value+ androidx.compose.runtime.snapshotFlow { com.music.spotui.ui.screens.SmartShuffle.on.value }.collect { now ->+ val ended = was.takeIf { now == null }+ was = now+ if (ended != null) endSmartShuffle(ended)+ }+ }scope.launch { api.library.changes.collect { refreshCurrentLiked() } }// T4: the player keeps the ad out of [api.player.state] on purpose (the last song stays- // there, buffering); its own flag is collected here so the UI can say an ad is on.- scope.launch { MyspotiRuntime.spotify.player.adPlaying.collect(::onAdPlaying) }+ // there, buffering); its own flag is collected here so the UI can say an ad is on. Only an+ // ad that is still on after AD_SHOW_AFTER_MS is shown: a blocked ad is gone within a second+ // (its audio is refused, the page moves on), and showing it only made the screens blink.+ scope.launch {+ MyspotiRuntime.spotify.player.adPlaying.collectLatest { on ->+ if (on) {+ kotlinx.coroutines.delay(AD_SHOW_AFTER_MS)+ // Spotify limiting playback holds every repair, the ad's too: the limit is what+ // the user is told (its toast), not an ad for as long as it lasts (50 s seen).+ while (MyspotiRuntime.host.licenseLimited()) kotlinx.coroutines.delay(1_000)+ }+ onAdPlaying(on)+ }+ }scope.launch {MyspotiRuntime.spotify.player.refused.collect {android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.play_refused, android.widget.Toast.LENGTH_LONG).show()@@ -375,7 +418,7 @@ object SongPlayer {_nowPlaying.value = NowPlaying(contextUri = s.contextUri.orEmpty(),contextName = s.contextName.orEmpty(),- provider = "",+ provider = item?.provider.orEmpty(),uri = uri,explicit = item?.explicit == true,albumUri = item?.album?.uri.orEmpty(),@@ -424,6 +467,15 @@ object SongPlayer {if (!isBuffering && playing && mv.inForeground && app.myspoti.power.EnergySettings.state.value.policy.allowBackgroundLookups) {com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(song))_nowPlaying.value.next?.let { com.music.spotui.data.api.LyricsApi.prefetch(lyricsTrack(it)) }+ // The next song's clip is looked up now, so its button is there when it starts. The+ // controller itself stays off under the data saver; a Spotify limit holds it too, as+ // it holds every other request. Only for someone who has the player open or wants+ // the clip: a lookup downloads ~145 s of audio, too much data and battery to spend on+ // every song for a user who never looks at the player.+ if ((mv.wantVideo || mv.hasPlayerScreen) && !MyspotiRuntime.host.licenseLimited()) _nowPlaying.value.next?.takeIf { it.spotifyTrackId.isNotBlank() && it.durationMs > 0 }?.let {+ // Without the song's length the match could not be checked, so nothing is cached for it.+ mv.prefetch(it.spotifyTrackId, it.title, it.singer, it.durationMs.toLong())+ }}}@@ -500,7 +552,13 @@ object SongPlayer {* [waitReady]: wait for the page when it is loading. Skips do not once a state was seen:* the player keeps them for after the reload (the song the taps point at plays then).*/- private fun transport(pullBack: Boolean = true, waitReady: Boolean = true, block: suspend (isLatest: () -> Boolean) -> Unit) {+ /**+ * [checkAfter]: when this phone was the one playing, the device check runs after the command+ * instead of before it, so the tap does not wait on a server round trip. A takeover it finds+ * then is pulled back as before; with another device known to be active, the check still+ * comes first, since the pull-back has to happen before the command.+ */+ private fun transport(pullBack: Boolean = true, waitReady: Boolean = true, checkAfter: Boolean = false, block: suspend (isLatest: () -> Boolean) -> Unit) {val gen = transportGen.incrementAndGet()scope.launch {transportLock.withLock {@@ -512,7 +570,8 @@ object SongPlayer {return@withLock}if (gen != transportGen.get()) return@withLock- if (pullBack && api.ready.value) takeBackPlayback()+ val checkLater = pullBack && checkAfter && _activeDevice.value == null+ if (pullBack && !checkLater && api.ready.value) takeBackPlayback()// A cancellation of the caller is never swallowed (it must unwind); only the// transport's own timeout and a real failure are logged here.try {@@ -524,6 +583,7 @@ object SongPlayer {} catch (e: Exception) {Log.w(TAG, "transport failed: ${e.message}")}+ if (checkLater && gen == transportGen.get() && api.ready.value) takeBackPlayback()}}}@@ -591,13 +651,22 @@ object SongPlayer {return}LocalPlayer.stop()+ cancelBurst()val episodeId = song.removePrefix("episode:").takeIf { song.startsWith("episode:") }val trackId = episodeId ?: spotifyTrackIdForPlayback(song) ?: returnval itemUri = if (episodeId != null) "spotify:episode:$episodeId" else SPOTIFY_TRACK_PREFIX + trackIdval ctx = contextUri ?: contextRegistry[song]+ // What a smart shuffle ending brings back: the order of the last play that was not one.+ if (ctx != null) {+ val sent = order?.takeIf { ctx == contextUri }+ playedOrder = ctx to sent+ if (com.music.spotui.ui.screens.SmartShuffle.on.value != ctx) { plainOrder = ctx to sent; smartPlayed = null }+ else if (sent != null) smartPlayed = ctx+ }markPending(if (episodeId != null) "" else trackId, itemUri)transport { isLatest ->playChecked(itemUri, isLatest) {+ Log.d(TAG, "playing $itemUri in ${ctx ?: "no context"}: ${queueTag()}")if (ctx != null) api.player.play(ctx, trackUri = itemUri, positionMs = positionMs, order = order?.takeIf { ctx == contextUri })else api.player.play(itemUri)}@@ -606,11 +675,13 @@ object SongPlayer {fun play() {if (LocalPlayer.active.value) { Haptics.click(); LocalPlayer.resume(); return }+ // Smart shuffle was turned off while paused: the list's order comes back as it plays on.+ plainOrderDue?.let { if (restorePlainOrder(it)) return }Haptics.click(); intendPlaying(); playing = true; positionAt = SystemClock.elapsedRealtime()// Tapped on the restored mini player while the Web Player is still loading.if (!stateSeen) resumeWhenReady = trueval uri = _nowPlaying.value.uri- transport { api.player.resume() }+ transport(checkAfter = true) { api.player.resume() }// An episode ignored by a plain resume (the page's element stays paused, which is what// "the podcast stopped and the play button does nothing" was — B11) is asked for again// by its uri, where it was. Music keeps the plain resume: it never showed that.@@ -620,13 +691,15 @@ object SongPlayer {if (!playing || LocalPlayer.active.value) return@launchval s = api.player.state.valueif (s?.item?.uri == uri && s.isPaused) {- Log.i(TAG, "episode resume not taken: playing $uri again")- runCatching { api.player.play(uri, positionMs = getCurrentPosition()) }+ Log.i(TAG, "episode resume not taken: playing $uri again (${queueTag()})")+ // In its show: played alone, Spotify goes on with its own autoplay after the episode.+ val ctx = _nowPlaying.value.contextUri.ifBlank { uri }+ runCatching { api.player.play(ctx, trackUri = uri.takeIf { ctx != it }, positionMs = getCurrentPosition()) }}}}- fun pause() { Haptics.click(); pauseSilently() }+ fun pause() { Haptics.click(); cancelBurst(); pauseSilently() }private fun pauseSilently() {if (LocalPlayer.active.value) { LocalPlayer.pause(); return }@@ -640,26 +713,46 @@ object SongPlayer {Log.d(TAG, "next tapped")Haptics.click()if (LocalPlayer.active.value) { LocalPlayer.next(); return }+ // Spotify is refusing licences: every skip asks for one more and makes the limit last+ // (a tester's log: 183 refusals in 8 min of fast skipping, the page then skipping on its+ // own through songs it could not play). Nothing is sent until the limit is over.+ if (MyspotiRuntime.host.licenseLimited()) {+ android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.spotify_limited, android.widget.Toast.LENGTH_SHORT).show()+ return+ }intendPlaying()- // The first tap skips at once. Taps that follow it within SKIP_BURST_MS become one- // jump to the song they add up to: a burst of "next" commands left the Web Player out- // of step (state conflicts, then a player stuck until reloaded).+ tapSeq+++ // The first tap skips at once. Taps that follow it within SKIP_BURST_MS, or within+ // MIN_SKIP_GAP_MS of the last skip sent, become one jump to the song they add up to: a+ // burst of "next" commands left the Web Player out of step (state conflicts, then a+ // player stuck until reloaded), and each song skipped through asks for a licence.val now = SystemClock.elapsedRealtime()- if (now - burstAt > SKIP_BURST_MS) {+ val sinceSent = now - skipSentAt+ if (now - burstAt > SKIP_BURST_MS && sinceSent >= MIN_SKIP_GAP_MS) {burstAt = nowburstUpcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()burstTaps = 1pendingSkips = 0+ skipSentAt = nowtransport(waitReady = !stateSeen) { api.player.next() }return}burstAt = now+ // A burst whose first tap was held (it came too soon after the last skip sent, e.g. a+ // previous): its songs are counted from the one playing now, none of its taps sent yet.+ if (burstTaps == 0 || burstUpcoming.isEmpty()) {+ burstUpcoming = apiQueue?.let { it.queued + it.nextUp }.orEmpty()+ burstTaps = 0+ }burstTaps++pendingSkips++main.removeCallbacks(sendSkips)- main.postDelayed(sendSkips, SKIP_BURST_MS)+ main.postDelayed(sendSkips, maxOf(SKIP_BURST_MS, MIN_SKIP_GAP_MS - sinceSent))}+ /** When the last skip command left (see [next]). */+ private var skipSentAt = 0L+/** When the last "next" tap came, the queue as it was at the first one, and the taps since. */private var burstAt = 0Lprivate var burstUpcoming: List<app.myspoti.api.NowPlaying> = emptyList()@@ -668,6 +761,7 @@ object SongPlayer {private val sendSkips = Runnable {if (pendingSkips <= 0) return@RunnablependingSkips = 0+ skipSentAt = SystemClock.elapsedRealtime()// The song [burstTaps] after the one playing at the first tap.val target = burstUpcoming.getOrNull(burstTaps - 1)transport(waitReady = !stateSeen) { if (target == null) api.player.next() else api.player.skipTo(target) }@@ -675,6 +769,7 @@ object SongPlayer {burstTarget = targetburstContext = _nowPlaying.value.contextUriburstSeq+++ verifyTap = tapSeqmain.removeCallbacks(verifyBurst)main.postDelayed(verifyBurst, BURST_VERIFY_MS)}@@ -690,18 +785,70 @@ object SongPlayer {private var burstContext = ""private var burstSeq = 0private var lastPageUri = ""++ /** Bumped by every user transport action (tap or pick); [verifyBurst] only runs if it did not move since it was scheduled. */+ private var tapSeq = 0+ private var verifyTap = 0private const val BURST_VERIFY_MS = 2_500Lprivate val verifyBurst = Runnable {val t = burstTarget ?: return@RunnableburstTarget = nullval seq = burstSeq- // A newer tap, pick or pause: the user moved on.- if (SystemClock.elapsedRealtime() - burstAt < BURST_VERIFY_MS || !playing) return@Runnable+ val tap = verifyTap+ // A newer tap, pick or pause: the user moved on (a reported log: a previous pressed+ // 1 s after the burst was undone by this check, which played the burst's song again).+ if (tap != tapSeq || SystemClock.elapsedRealtime() - burstAt < BURST_VERIFY_MS || !playing) return@Runnableif (lastPageUri == t.uri || burstContext.isBlank()) return@Runnable- Log.d(TAG, "skips landed on $lastPageUri, not ${t.name}: playing it")- transport { if (seq == burstSeq) api.player.play(burstContext, t.uri) }+ Log.d(TAG, "skips landed on $lastPageUri, not ${t.name}: playing it (${queueTag()})")+ // In the order it was played in (a sorted list, a smart shuffle), and a song the user+ // queued is not in the list: asking for it there would restart the list.+ if (t.provider == "queue") return@Runnable+ val order = playedOrder?.takeIf { it.first == burstContext }?.second+ transport { if (seq == burstSeq && tap == tapSeq) api.player.play(burstContext, t.uri, order = order) }+ }++ /**+ * The user does something else than "next" (a pick, a pause, a seek, a previous): whatever+ * the burst still had to send or check is dropped, or it would undo that action (reported:+ * a previous after two nexts was overridden by the burst's jump, then by its check).+ */+ private fun cancelBurst() {+ tapSeq+++ pendingSkips = 0+ burstTarget = null+ burstTaps = 0+ burstAt = 0L+ burstUpcoming = emptyList()+ main.removeCallbacks(sendSkips)+ main.removeCallbacks(verifyBurst)+ }++ /** "shuffle=…, next=[…]": the page's shuffle flag and the first upcoming songs, for the play logs. */+ private fun queueTag(): String {+ val up = apiQueue?.let { it.queued + it.nextUp }.orEmpty().take(5).joinToString { it.name.take(30) }+ return "shuffle=${api.player.state.value?.shuffle} next=[$up]"+ }++ fun previous() {+ Haptics.click()+ if (LocalPlayer.active.value) { LocalPlayer.previous(); return }+ intendPlaying()+ // A previous counts as -1 in the burst. Skips still waiting to be sent (nexts tapped+ // within SKIP_BURST_MS) just lose one: next, next, previous is one next, and nothing+ // is sent for the previous. Once the burst has left (or there is none), previous is a+ // plain one, and the burst is forgotten so it cannot send or verify anything later.+ if (pendingSkips > 0) {+ pendingSkips--+ burstTaps--+ tapSeq+++ burstAt = SystemClock.elapsedRealtime()+ if (pendingSkips == 0) main.removeCallbacks(sendSkips)+ return+ }+ cancelBurst()+ skipSentAt = SystemClock.elapsedRealtime()+ transport(waitReady = !stateSeen) { api.player.previous() }}- fun previous() { Haptics.click(); if (LocalPlayer.active.value) { LocalPlayer.previous(); return }; intendPlaying(); transport(waitReady = !stateSeen) { api.player.previous() } }/** Tracks shufflePlay plays without a context: the first one, plus up to 49 queued. */private const val SHUFFLE_QUEUE_MAX = 50@@ -723,9 +870,11 @@ object SongPlayer {if (songs.isEmpty()) returnLocalPlayer.stop()val ctx = contextRegistry[songs.first().url]+ cancelBurst()intendPlaying()transport {api.player.setShuffle(true)+ Log.d(TAG, "shuffle-playing ${ctx ?: "a shuffled list"}: ${queueTag()}")if (ctx == null) {// No registered context: play the list in a shuffled order (first// track now, the rest queued), not one random song alone. Capped at@@ -742,6 +891,34 @@ object SongPlayer {}}+ /** The list and the order of the last play that was not a smart shuffle's (null: the list's own). */+ @Volatile private var plainOrder: Pair<String, List<String>?>? = null+ /** The list a smart shuffle is playing as its own mixed order. */+ @Volatile private var smartPlayed: String? = null+ /** Smart shuffle ended on this list while paused: its order comes back at the next play. */+ @Volatile private var plainOrderDue: String? = null++ /** The list and order of the last play, kept for the replays that name a song only. */+ @Volatile private var playedOrder: Pair<String, List<String>?>? = null++ private fun endSmartShuffle(ctx: String) {+ if (smartPlayed != ctx) return+ smartPlayed = null+ if (_nowPlaying.value.contextUri != ctx) return+ if (playing) restorePlainOrder(ctx) else plainOrderDue = ctx+ }++ /** Plays the song now playing again in [ctx] as it was before the smart shuffle, where it is. */+ private fun restorePlainOrder(ctx: String): Boolean {+ plainOrderDue = null+ val uri = _nowPlaying.value.uri+ if (_nowPlaying.value.contextUri != ctx || uri.isBlank() || LocalPlayer.active.value) return false+ val song = if (uri.startsWith("spotify:episode:")) "episode:" + uri.substringAfterLast(':') else uri+ Log.d(TAG, "smart shuffle off: $ctx back in the list's order from ${_nowPlaying.value.uri}")+ playSong(song, contextUri = ctx, order = plainOrder?.takeIf { it.first == ctx }?.second, positionMs = getCurrentPosition())+ return true+ }+fun setShuffle(on: Boolean) {Haptics.toggle(on)if (LocalPlayer.active.value) { LocalPlayer.setShuffle(on); return }@@ -903,6 +1080,7 @@ object SongPlayer {fun seekTo(ms: Long) {if (LocalPlayer.active.value) { LocalPlayer.seekTo(ms); return }+ cancelBurst()positionMs = mspositionAt = SystemClock.elapsedRealtime()command { api.player.seek(ms) }@@ -956,9 +1134,12 @@ object SongPlayer {}}- /** Bumped at every like / unlike of a track: the Liked Songs page refreshes its top. */+ /** Bumped at every like / unlike of a track Spotify took: the Liked Songs page refreshes its top. */val likedChanges = kotlinx.coroutines.flow.MutableStateFlow(0)+ /** Every like / unlike of a track the moment it is tapped (and its undo): track id, liked. */+ val likedTaps = kotlinx.coroutines.flow.MutableSharedFlow<Pair<String, Boolean>>(extraBufferCapacity = 16)+/** Like / unlike a track by id. */fun setTrackSaved(trackId: String, on: Boolean) {if (trackId.isBlank()) return@@ -973,6 +1154,7 @@ object SongPlayer {intentUntil = SystemClock.elapsedRealtime() + 3000onLibraryItem(uri, on)val track = uri.startsWith(SPOTIFY_TRACK_PREFIX)+ if (track) likedTaps.tryEmit(trackIdOf(uri) to on)val write = libraryWrites.incrementAndGet()scope.launch {// One write at a time; a refused one is undone on screen if no newer tap replaced it.@@ -990,6 +1172,7 @@ object SongPlayer {if (write == libraryWrites.get()) {intentUntil = 0onLibraryItem(uri, !on)+ if (track) likedTaps.tryEmit(trackIdOf(uri) to !on)android.widget.Toast.makeText(Graph.app, app.myspoti.engine.R.string.library_change_failed, android.widget.Toast.LENGTH_SHORT).show()}}@@ -1183,8 +1366,31 @@ object SongPlayer {fun watchQueue(on: Boolean) {}fun requestQueue() {}+ /**+ * The queue row [item] stands for in Spotify's latest queue: by its row id, else by its song+ * (a row moved a moment ago got a new id, and the list on screen may still show the old one).+ */private fun apiItem(item: QueueItem): app.myspoti.api.NowPlaying? =- apiQueue?.let { q -> (q.queued + q.nextUp).firstOrNull { it.uri == item.uri && (item.uid.isBlank() || it.uid == item.uid) } }+ apiQueue?.let { q ->+ val all = q.queued + q.nextUp+ all.firstOrNull { it.uri == item.uri && (item.uid.isBlank() || it.uid == item.uid) } ?: all.firstOrNull { it.uri == item.uri }+ }++ /**+ * Queue edits, one at a time and each after Spotify has shown the one before. Sent together+ * they raced in the Web Player: "move up into the queue" (add + remove) lost its remove and+ * left the song twice, and that copy could then not be moved or taken out (reported).+ */+ private val queueLock = kotlinx.coroutines.sync.Mutex()+ private fun queueCommand(block: suspend () -> Unit) {+ scope.launch { queueLock.withLock { runCatching { block() }.onFailure { Log.w(TAG, "queue edit failed: ${it.message}") } } }+ }++ private const val QUEUE_ECHO_MS = 2_500L++ /** Waits (at most [QUEUE_ECHO_MS]) for Spotify's queue to show [done]; the queue then, or null. */+ private suspend fun awaitQueue(done: (app.myspoti.api.Queue) -> Boolean): app.myspoti.api.Queue? =+ kotlinx.coroutines.withTimeoutOrNull(QUEUE_ECHO_MS) { api.player.queue.first { it != null && done(it) } }/** "Play next": first in the queue, right after the current track. */fun playNext(trackId: String) {@@ -1201,6 +1407,7 @@ object SongPlayer {fun skipTo(item: QueueItem) {if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::skipTo); return }+ cancelBurst()val id = trackIdOf(item.uri)if (id.isNotBlank()) markPending(id)boundState?.updateSongState(item.song.coverUri, item.song.title, item.song.singer, true, item.song.id, 0, item.song.album)@@ -1224,26 +1431,49 @@ object SongPlayer {LocalPlayer.move(from, if (after) (if (from < t) t else t + 1) else (if (from < t) t - 1 else t))return}- val a = apiItem(item) ?: return- val b = apiItem(target) ?: return- command { api.player.moveInQueue(a, b, after) }+ // Read when the edit runs, after the ones before it: never a row id that has gone stale.+ queueCommand {+ val a = apiItem(item) ?: return@queueCommand+ val b = apiItem(target) ?: return@queueCommand+ val before = api.player.queue.value+ api.player.moveInQueue(a, b, after)+ awaitQueue { it !== before }+ }}/** Move a "next up" track into the queue, right after the current one. */- fun moveToQueueFront(item: QueueItem) {+ fun moveToQueueFront(item: QueueItem) = moveIntoQueue(item, null, after = false)++ /**+ * A "next up" track moved up into the queue, before / after [target] (a queued row; null: first).+ * As the official app: out of "next up" first, then queued — in that order and one after the+ * other (both at once left it in both places), then placed where it was dropped.+ */+ fun moveIntoQueue(item: QueueItem, target: QueueItem?, after: Boolean) {if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::moveNext); return }- val a = apiItem(item) ?: return- command {- api.player.addToQueue(listOf(a.uri))+ queueCommand {+ val a = apiItem(item) ?: return@queueCommand+ val first = apiQueue?.queued?.firstOrNull()api.player.removeFromQueue(listOf(a))+ awaitQueue { q -> q.nextUp.none { it.uid == a.uid } }+ api.player.addToQueue(listOf(a.uri))+ val added = awaitQueue { q -> q.queued.any { it.uri == a.uri } }?.queued?.lastOrNull { it.uri == a.uri } ?: return@queueCommand+ // Queued at the end: moved to the place it was dropped (the front when no target).+ val t = target?.let(::apiItem) ?: first?.takeIf { it.uid != added.uid } ?: return@queueCommand+ val before = api.player.queue.value+ api.player.moveInQueue(added, t, if (target == null) false else after)+ awaitQueue { it !== before }}}fun removeFromQueue(item: QueueItem) {if (item.provider == LOCAL) { item.uid.toIntOrNull()?.let(LocalPlayer::remove); return }_queue.value = _queue.value.let { q -> q.copy(queued = q.queued - item, nextUp = q.nextUp - item) }- val a = apiItem(item) ?: return- command { api.player.removeFromQueue(listOf(a)) }+ queueCommand {+ val a = apiItem(item) ?: return@queueCommand+ api.player.removeFromQueue(listOf(a))+ awaitQueue { q -> (q.queued + q.nextUp).none { it.uid == a.uid && it.uri == a.uri } }+ }}fun isPlaying(): Boolean = if (LocalPlayer.active.value) LocalPlayer.isPlaying() else playingdiff --git a/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.ktnew file mode 100644index 00000000..0d03badc--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/AddSongsScreen.kt@@ -0,0 +1,206 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+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.imePadding+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.CheckCircle+import androidx.compose.material.icons.filled.Close+import androidx.compose.material.icons.filled.Search+import androidx.compose.material.icons.outlined.AddCircleOutline+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.window.Dialog+import androidx.compose.ui.window.DialogProperties+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.data.api.Response+import com.music.spotui.data.entity.ContextPageModel+import com.music.spotui.data.entity.SongsModel+import com.music.spotui.di.Graph+import com.music.spotui.di.SongPlayer+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.withContext++private val Green = Color(0xFF1ED760)+private const val SUGGESTIONS = 20+private const val TYPE_PAUSE_MS = 300L++/**+ * "Add to this playlist", as in the official Android app: a Spotify search with a + on every+ * song, and Spotify's suggestions for the playlist while nothing is typed. Songs are added one+ * tap each without leaving the screen; [onClose] says whether any was added (the page reloads).+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+fun AddSongsScreen(page: ContextPageModel, onClose: (added: Boolean) -> Unit) {+ val context = LocalContext.current+ val keyboard = LocalSoftwareKeyboardController.current+ val playlistId = page.uri.substringAfterLast(':')+ val inList = remember(page.uri) { page.tracks.mapTo(HashSet()) { it.spotifyTrackId } }+ val added = remember { mutableStateListOf<String>() }+ var query by remember { mutableStateOf("") }+ var results by remember { mutableStateOf<List<SongsModel>?>(null) }+ var suggestions by remember { mutableStateOf<List<SongsModel>?>(null) }+ var suggestionsRound by remember { mutableStateOf(0) }+ val seen = remember { HashSet<String>() }+ val focus = remember { FocusRequester() }++ LaunchedEffect(suggestionsRound) {+ suggestions = null+ val skip = (inList + added + seen).map { "spotify:track:$it" }+ val got = withContext(Dispatchers.IO) {+ runCatching { MyspotiRuntime.api.playlists.recommended(page.uri, limit = SUGGESTIONS, skip = skip) }+ .getOrDefault(emptyList()).map(Graph.api::songOf)+ }.filter { it.spotifyTrackId !in inList }+ got.forEach { seen += it.spotifyTrackId }+ suggestions = got+ }+ LaunchedEffect(query) {+ val q = query.trim()+ if (q.isEmpty()) { results = null; return@LaunchedEffect }+ delay(TYPE_PAUSE_MS)+ val r = withContext(Dispatchers.IO) { Graph.api.searchTracks(q).first { it !is Response.Loading } }+ results = (r as? Response.Success)?.data.orEmpty()+ }+ LaunchedEffect(Unit) { runCatching { focus.requestFocus() } }++ val close = { onClose(added.isNotEmpty()) }+ Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {+ Column(Modifier.fillMaxSize().background(Color(0xFF121212)).statusBarsPadding().navigationBarsPadding().imePadding()) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 4.dp)) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.size(48.dp).clip(CircleShape).clickable(onClick = close)) {+ Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_songs_close), tint = Color.White)+ }+ Text(stringResource(R.string.add_songs_title), color = Color.White, fontSize = 17.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.weight(1f).padding(start = 4.dp), maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(horizontal = 16.dp).fillMaxWidth().height(44.dp)+ .clip(RoundedCornerShape(8.dp)).background(Color(0xFF2A2A2A)).padding(horizontal = 12.dp),+ ) {+ Icon(Icons.Default.Search, contentDescription = null, tint = Color(0xFFB3B3B3), modifier = Modifier.size(22.dp))+ Spacer(Modifier.width(10.dp))+ Box(Modifier.weight(1f)) {+ if (query.isEmpty()) Text(stringResource(R.string.add_songs_search_hint), color = Color(0xFFB3B3B3), fontSize = 15.sp)+ BasicTextField(+ value = query, onValueChange = { query = it }, singleLine = true,+ textStyle = TextStyle(color = Color.White, fontSize = 15.sp), cursorBrush = SolidColor(Green),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }),+ modifier = Modifier.fillMaxWidth().focusRequester(focus),+ )+ }+ if (query.isNotEmpty()) Icon(Icons.Default.Close, contentDescription = null, tint = Color.White,+ modifier = Modifier.size(20.dp).clickable { query = "" })+ }+ val searching = query.isNotBlank()+ val list = if (searching) results else suggestions+ LazyColumn(Modifier.weight(1f).padding(top = 8.dp)) {+ if (!searching) item(key = "suggestions-title") {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp, top = 8.dp)) {+ Text(stringResource(R.string.recommended_songs), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold, modifier = Modifier.weight(1f))+ TextButton(onClick = { suggestionsRound++ }) {+ Text(stringResource(R.string.recommended_songs_refresh), color = Color.White, fontWeight = FontWeight.Bold)+ }+ }+ }+ when {+ list == null -> item(key = "loading") { SkeletonList(count = 8) }+ list.isEmpty() && searching -> item(key = "none") {+ Text(stringResource(R.string.add_songs_nothing, query.trim()), color = Color(0xFFB3B3B3), fontSize = 14.sp,+ modifier = Modifier.padding(24.dp))+ }+ else -> items(list, key = { (if (searching) "r-" else "s-") + it.spotifyTrackId }) { song ->+ val there = song.spotifyTrackId in inList || song.spotifyTrackId in added+ AddSongRow(song, there, onPlay = { SongPlayer.playSong(song.url, context) }) {+ if (there) return@AddSongRow+ added += song.spotifyTrackId+ com.music.spotui.di.Haptics.confirm()+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, playlistId, song.spotifyTrackId) { ok ->+ if (!ok) android.os.Handler(android.os.Looper.getMainLooper()).post {+ added -= song.spotifyTrackId+ android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ }+ }+ }+ item { Spacer(Modifier.height(24.dp)) }+ }+ }+ }+}++@OptIn(ExperimentalGlideComposeApi::class)+@Composable+private fun AddSongRow(song: SongsModel, added: Boolean, onPlay: () -> Unit, onAdd: () -> Unit) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().clickable(onClick = onPlay).padding(start = 16.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),+ ) {+ GlideImage(model = song.coverUri, contentDescription = null, contentScale = ContentScale.Crop, transition = CrossFade,+ modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)))+ Column(Modifier.weight(1f).padding(start = 12.dp, end = 8.dp)) {+ Text(song.title, color = Color.White, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Row(verticalAlignment = Alignment.CenterVertically) {+ if (song.explicit) { com.music.spotui.ui.screens.ExplicitBadge(); Spacer(Modifier.width(6.dp)) }+ Text(song.singer, color = Color(0xFFB3B3B3), fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ Box(contentAlignment = Alignment.Center, modifier = Modifier.size(48.dp).clip(CircleShape).clickable(enabled = !added, onClick = onAdd)) {+ if (added) Icon(Icons.Default.CheckCircle, contentDescription = stringResource(R.string.add_songs_added), tint = Green, modifier = Modifier.size(26.dp))+ else Icon(Icons.Outlined.AddCircleOutline, contentDescription = stringResource(R.string.recommended_songs_add), tint = Color.White, modifier = Modifier.size(26.dp))+ }+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.ktindex b365b42a..3e4a7c25 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/AppComponents.kt@@ -118,6 +118,39 @@ fun Loader(kind: SkeletonKind = SkeletonKind.List) {enum class SkeletonKind { List, Home, Header }+/**+ * Rows of grey shapes for a list that is loading, inside a page already drawn (a search, a+ * profile's lists): the same static placeholder as [Loader], without taking the whole screen.+ * [round] draws circles (people) instead of covers.+ */+@Composable+fun SkeletonList(count: Int = 6, round: Boolean = false, modifier: Modifier = Modifier) {+ var visible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { delay(200); visible = true }+ Column(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp)) {+ if (!visible) return@Column+ if (round) repeat(count) {+ Row(Modifier.padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {+ Box(Modifier.size(48.dp).clip(androidx.compose.foundation.shape.CircleShape).background(Color(0xFF242424)))+ Box(Modifier.padding(start = 12.dp).width(150.dp).height(14.dp).clip(RoundedCornerShape(4.dp)).background(Color(0xFF2A2A2A)))+ }+ } else SkeletonRows(Color(0xFF242424), Color(0xFF2A2A2A), count)+ }+}++/** Lyrics loading: lines of grey bars of varied widths, in the lyrics' own colour. */+@Composable+fun SkeletonLyrics(color: Color, modifier: Modifier = Modifier) {+ var visible by remember { mutableStateOf(false) }+ LaunchedEffect(Unit) { delay(200); visible = true }+ Column(modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 16.dp)) {+ if (!visible) return@Column+ for (w in floatArrayOf(0.85f, 0.6f, 0.75f, 0.5f, 0.9f, 0.65f, 0.7f, 0.45f)) {+ Box(Modifier.padding(vertical = 9.dp).fillMaxWidth(w).height(22.dp).clip(RoundedCornerShape(6.dp)).background(color.copy(alpha = 0.18f)))+ }+ }+}+@Composableprivate fun SkeletonRows(tile: Color, line: Color, count: Int) {repeat(count) {@@ -184,6 +217,24 @@ fun MiniPlayer(navController: NavHostController) {CanvasPlayer.preload(context, url)}+ // The next song, made ready while this one plays, so a skip shows it whole at once: its big+ // cover (on storage, not in memory), its colour, and its Canvas (the address always, the clip+ // itself on storage over Wi-Fi only). After the current song's own loads.+ LaunchedEffect(np.next?.spotifyTrackId, energy.policy.allowCanvas, com.music.spotui.data.DataSaver.active) {+ val next = np.next ?: return@LaunchedEffect+ kotlinx.coroutines.delay(2_500)+ if (next.coverUri.isNotBlank()) {+ com.bumptech.glide.Glide.with(context).downloadOnly().load(next.coverUri).submit()+ Palette().extractFirstColorFromImageUrl(context, next.coverUri) { }+ Palette().extractSecondColorFromCoverUrl(context, next.coverUri) { }+ }+ if (next.spotifyTrackId.isBlank() || !energy.policy.allowCanvas || com.music.spotui.data.DataSaver.active) return@LaunchedEffect+ val url = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ runCatching { com.music.spotui.di.Graph.api.getCanvasUrl(next.spotifyTrackId) }.getOrNull()+ } ?: return@LaunchedEffect+ if (!com.music.spotui.data.DataSaver.metered) CanvasPlayer.warm(context, url)+ }+// The thin bar moves ~2 px/s: 4 ticks a second look identical to 20.// Covered by the full player: no ticks (they redrew the whole window under it).val frame = rememberFrameClock(songPlayingState && !com.music.spotui.ui.navigation.PlayerSheet.open.value, fps = 4)diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.ktindex 07749c08..435b0728 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/ArtistOptionsSheet.kt@@ -46,7 +46,7 @@ import kotlinx.coroutines.launch*/@OptIn(ExperimentalMaterial3Api::class)@Composable-fun ArtistOptionsSheet(artistId: String, artistName: String, onDismiss: () -> Unit) {+fun ArtistOptionsSheet(artistId: String, artistName: String, artistImage: String = "", onDismiss: () -> Unit) {val context = LocalContext.currentval sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)val uri = "spotify:artist:$artistId"@@ -67,11 +67,7 @@ fun ArtistOptionsSheet(artistId: String, artistName: String, onDismiss: () -> UnHorizontalDivider(color = Color(0xFF3E3E3E), thickness = 0.5.dp)Spacer(Modifier.height(8.dp))ArtistMenuRow(Icons.Default.Share, stringResource(R.string.share_link), enabled = artistId.isNotBlank()) {- val send = Intent(Intent.ACTION_SEND).apply {- type = "text/plain"- putExtra(Intent.EXTRA_TEXT, "https://open.spotify.com/artist/$artistId")- }- context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)))+ SpotifyCode.show(ShareTarget("spotify:artist:$artistId", artistName, coverUri = artistImage))onDismiss()}ArtistMenuRow(diff --git a/base/app/src/main/java/com/music/spotui/ui/components/BlendPanel.kt b/base/app/src/main/java/com/music/spotui/ui/components/BlendPanel.ktnew file mode 100644index 00000000..ddd77cae--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/BlendPanel.kt@@ -0,0 +1,210 @@+package com.music.spotui.ui.components++import android.content.Intent+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.expandVertically+import androidx.compose.animation.fadeIn+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+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.width+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Add+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+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 app.myspoti.api.BlendGroup+import app.myspoti.api.BlendStory+import app.myspoti.engine.R+import app.myspoti.host.android.MyspotiRuntime+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.withContext++/**+ * The Blend's own part of its page: one line (faces, match, invite), which opens on the+ * taste-match card and the members. Both come from Spotify's Blend service; the last few Blends opened are+ * kept so going back to one shows them at once (they are small, and few).+ */+@Composable+fun BlendPanel(uri: String) {+ var info by remember(uri) { mutableStateOf(BlendInfo.recent[uri]) }+ LaunchedEffect(uri) {+ val fresh = withContext(Dispatchers.IO) { BlendInfo.load(uri) } ?: return@LaunchedEffect+ info = fresh+ }+ var open by remember(uri) { mutableStateOf(false) }+ AnimatedVisibility(visible = info != null, enter = fadeIn() + expandVertically()) {+ val i = info ?: return@AnimatedVisibility+ Column(Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 8.dp)) {+ CompactLine(i) { open = !open }+ // The full card and the members, on a tap of the line.+ AnimatedVisibility(visible = open, enter = fadeIn() + expandVertically(), exit = androidx.compose.animation.fadeOut() + androidx.compose.animation.shrinkVertically()) {+ Column(Modifier.padding(top = 8.dp)) {+ i.story?.let { StoryCard(it) }+ i.group?.takeIf { it.members.isNotEmpty() }?.let { Members(it) }+ }+ }+ }+ }+}++/** One line: the members' faces, the match in Spotify's words, and "+" to invite more people. */+@Composable+private fun CompactLine(info: BlendInfo, onClick: () -> Unit) {+ val context = LocalContext.current+ val members = info.group?.members.orEmpty()+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 16.dp, vertical = 6.dp),+ ) {+ // Overlapping faces, as Spotify shows a Blend's members.+ Box(Modifier.width((28 + 18 * (members.size.coerceAtMost(4) - 1).coerceAtLeast(0)).dp).height(28.dp)) {+ members.take(4).forEachIndexed { n, m ->+ Box(Modifier.padding(start = (18 * n).dp).size(28.dp).clip(CircleShape).background(Color(0xFF121212)).padding(1.5.dp)) {+ ProfileAvatar(m.imageUrl, m.name, 25.dp)+ }+ }+ }+ Column(Modifier.weight(1f).padding(start = 10.dp, end = 8.dp)) {+ Text(info.story?.title ?: info.group?.title ?: stringResource(R.string.blend_title), color = Color.White, fontSize = 14.sp,+ fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (members.isNotEmpty()) Text(members.joinToString(", ") { it.name }, color = Color(0xFFB3B3B3), fontSize = 12.sp,+ maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ info.group?.link?.let { link ->+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.size(36.dp).clip(CircleShape).background(Color(0xFF2A2A2A)).clickable { BlendInfo.share(context, link) },+ ) { Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.blend_invite_more), tint = Color.White, modifier = Modifier.size(20.dp)) }+ }+ }+}++/** What a Blend's page shows besides its songs; the recent ones kept, at most [KEEP]. */+data class BlendInfo(val story: BlendStory?, val group: BlendGroup?) {+ companion object {+ private const val KEEP = 8+ val recent: MutableMap<String, BlendInfo> = java.util.Collections.synchronizedMap(+ object : LinkedHashMap<String, BlendInfo>(KEEP, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, BlendInfo>?) = size > KEEP+ })++ suspend fun load(uri: String): BlendInfo? = coroutineScope {+ val blends = MyspotiRuntime.api.blends+ val story = async { runCatching { blends.story(uri) }.getOrNull() }+ val group = async { runCatching { blends.group(uri) }.getOrNull() }+ BlendInfo(story.await(), group.await())+ .takeIf { it.story != null || it.group != null }+ ?.also { recent[uri] = it }+ }++ /** Shares [link], the Blend's invitation, through the system's share sheet. */+ fun share(context: android.content.Context, link: String) {+ val send = Intent(Intent.ACTION_SEND).setType("text/plain")+ .putExtra(Intent.EXTRA_TEXT, context.getString(R.string.blend_invite_message, link))+ context.startActivity(Intent.createChooser(send, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ }+ }+}++private fun color(hex: String?, fallback: Color): Color =+ hex?.let { runCatching { Color(android.graphics.Color.parseColor(it)) }.getOrNull() } ?: fallback++@OptIn(ExperimentalGlideComposeApi::class)+@Composable+private fun StoryCard(story: BlendStory) {+ val background = color(story.background, Color(0xFF2A2A2A))+ val title = color(story.titleColor, Color.White)+ val text = color(story.textColor, Color(0xFFB3B3B3))+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .padding(horizontal = 16.dp)+ .fillMaxWidth()+ .clip(RoundedCornerShape(16.dp))+ .background(background)+ .padding(16.dp),+ ) {+ Column(Modifier.weight(1f)) {+ Text(story.title, color = title, fontSize = 20.sp, fontWeight = FontWeight.Bold, lineHeight = 24.sp)+ story.subtitle?.let { Text(it, color = text, fontSize = 14.sp, modifier = Modifier.padding(top = 4.dp)) }+ story.detail?.let { Text(it, color = text, fontSize = 13.sp, fontWeight = FontWeight.Medium, modifier = Modifier.padding(top = 10.dp)) }+ }+ story.image?.let {+ Spacer(Modifier.width(12.dp))+ GlideImage(+ model = it, contentDescription = null, contentScale = ContentScale.Crop, transition = CrossFade,+ modifier = Modifier.size(72.dp).clip(CircleShape),+ )+ }+ }+}++@Composable+private fun Members(group: BlendGroup) {+ val context = LocalContext.current+ Text(+ group.title ?: stringResource(R.string.blend_members),+ color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 18.dp, bottom = 10.dp),+ )+ LazyRow(contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) {+ items(group.members, key = { it.username }) { m ->+ Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.width(72.dp)) {+ ProfileAvatar(m.imageUrl, m.name, 64.dp)+ Text(m.name, color = Color.White, fontSize = 12.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,+ textAlign = TextAlign.Center, modifier = Modifier.padding(top = 6.dp))+ }+ }+ group.link?.let { link ->+ item(key = "invite") {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.width(72.dp).clip(RoundedCornerShape(8.dp)).clickable { BlendInfo.share(context, link) },+ ) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.size(64.dp).clip(CircleShape).background(Color(0xFF2A2A2A))) {+ Icon(Icons.Filled.Add, contentDescription = null, tint = Color.White, modifier = Modifier.size(28.dp))+ }+ Text(group.inviteLabel ?: stringResource(R.string.blend_invite_more), color = Color(0xFFB3B3B3), fontSize = 12.sp,+ maxLines = 2, textAlign = TextAlign.Center, lineHeight = 14.sp, modifier = Modifier.padding(top = 6.dp))+ }+ }+ }+ }+ Spacer(Modifier.height(4.dp))+}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/CanvasPlayer.kt b/base/app/src/main/java/com/music/spotui/ui/components/CanvasPlayer.ktindex 9c761df7..c5079def 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/CanvasPlayer.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/CanvasPlayer.kt@@ -25,6 +25,21 @@ object CanvasPlayer {*/fun preload(context: android.content.Context, url: String) { get(context, url) }+ /**+ * Downloads the clip [url] to the media cache on storage, without a player and without+ * keeping anything in memory: the next song's Canvas, so it starts from storage when that+ * song comes (the player still loads it then, but from the phone, not the network).+ */+ suspend fun warm(context: android.content.Context, url: String) = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {+ runCatching {+ val source = androidx.media3.datasource.cache.CacheDataSource.Factory()+ .setCache(SongPlayer.mediaCache(context.applicationContext))+ .setUpstreamDataSourceFactory(androidx.media3.datasource.DefaultHttpDataSource.Factory())+ .createDataSource()+ androidx.media3.datasource.cache.CacheWriter(source, androidx.media3.datasource.DataSpec(android.net.Uri.parse(url)), null, null).cache()+ }+ }+fun get(context: android.content.Context, url: String): androidx.media3.exoplayer.ExoPlayer {val player = exo ?: run {val cached = androidx.media3.datasource.cache.CacheDataSource.Factory()diff --git a/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt b/base/app/src/main/java/com/music/spotui/ui/components/FindInList.ktindex 996bc226..9f4809ec 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/FindInList.kt@@ -27,18 +27,29 @@ import androidx.compose.ui.unit.spimport java.text.Normalizerimport java.util.Locale-private fun fold(s: String) = Normalizer.normalize(s, Normalizer.Form.NFD)- .replace(Regex("""\p{M}+"""), "").lowercase(Locale.ROOT)+private val MARKS = Regex("""\p{M}+""")+private val SPACES = Regex("""\s+""")++/**+ * Titles and names folded once (lower case, no accents) and kept: a playlist search folds each+ * row's fields on every key typed. The patterns were compiled again for every field of every row+ * and held the main thread over a second a key on a big playlist (reported: typing in the search+ * froze the player until the app crashed).+ */+private val folded = object : android.util.LruCache<String, String>(20_000) {+ override fun create(key: String): String = Normalizer.normalize(key, Normalizer.Form.NFD).replace(MARKS, "").lowercase(Locale.ROOT)+}++private fun fold(s: String): String = if (s.isEmpty()) s else folded.get(s)/*** "Find in…" match: every word of [query] appears in one of [fields], ignoring case and* accents ("beyonce hal" finds "Halo" by Beyoncé). A blank query matches everything.*/fun matchesFind(query: String, vararg fields: String): Boolean {- val words = fold(query).split(Regex("""\s+""")).filter { it.isNotEmpty() }+ val words = fold(query).split(SPACES).filter { it.isNotEmpty() }if (words.isEmpty()) return true- val text = fields.joinToString(" ") { fold(it) }- return words.all { it in text }+ return words.all { w -> fields.any { fold(it).contains(w) } }}/** The "Find in…" field at the top of a list of songs. */diff --git a/base/app/src/main/java/com/music/spotui/ui/components/MeaningSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/MeaningSheet.ktnew file mode 100644index 00000000..83ee4f5f--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/MeaningSheet.kt@@ -0,0 +1,167 @@+package com.music.spotui.ui.components++import android.content.Intent+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.verticalScroll+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxHeight+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import app.myspoti.engine.R+import com.music.spotui.data.api.GeniusMeaning+++/** The reader's choice between Genius's own words and their translation, for the whole session. */+private val showOriginal = mutableStateOf(false)++/** Genius's words as shown: each text in the reader's language as soon as its translation arrives. */+private class ShownMeaning(val meaning: GeniusMeaning.Meaning, val translating: Boolean, val canTranslate: Boolean)++@Composable+private fun rememberShown(original: GeniusMeaning.Meaning, texts: List<String>): ShownMeaning {+ val lang = readerLanguage()+ // The texts on screen are asked for first (the rest may already be on their way in the background).+ LaunchedEffect(original, texts) { texts.forEach { GeniusMeaning.requestTranslation(original, it, lang) } }+ val same = GeniusMeaning.isSameLanguage(original, lang)+ val show = !showOriginal.value && same != true+ fun t(text: String) = if (show) GeniusMeaning.translation(text, lang) ?: text else text+ val meaning = original.copy(about = original.about?.let(::t), notes = original.notes.map { it.copy(explanation = t(it.explanation)) })+ val translating = show && texts.any { GeniusMeaning.isTranslating(it, lang) }+ return ShownMeaning(meaning, translating, same == false)+}++@Composable+fun readerLanguage(): String {+ val context = LocalContext.current+ return remember { com.music.spotui.data.preferences.getLyricTranslateLang(context).ifBlank { java.util.Locale.getDefault().language.ifBlank { "en" } } }+}++@Composable+private fun TranslateChip(shown: ShownMeaning) {+ when {+ shown.translating -> Text(stringResource(R.string.lyrics_meaning_translating), color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp)+ // Spotify's small outlined pill.+ shown.canTranslate -> Text(+ stringResource(if (showOriginal.value) R.string.lyrics_meaning_translate else R.string.lyrics_meaning_original),+ color = Color.White, fontSize = 13.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.clip(RoundedCornerShape(50))+ .border(1.dp, Color.White.copy(alpha = 0.5f), RoundedCornerShape(50))+ .clickable { showOriginal.value = !showOriginal.value }.padding(horizontal = 14.dp, vertical = 7.dp),+ )+ }+}++@Composable+private fun GeniusSource(url: String) {+ val context = LocalContext.current+ Text(stringResource(R.string.lyrics_meaning_source_short), color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.clip(RoundedCornerShape(6.dp)).clickable(enabled = url.isNotBlank()) {+ runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, android.net.Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }+ }.padding(vertical = 6.dp))+}++/** The light bulb of the lyrics: what Genius says about the song as a whole. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun AboutSheet(original: GeniusMeaning.Meaning, background: Color, onDismiss: () -> Unit) {+ val shown = rememberShown(original, listOfNotNull(original.about))+ val m = shown.meaning+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),+ containerColor = cardColor(background),+ dragHandle = { androidx.compose.material3.BottomSheetDefaults.DragHandle(color = Color.White.copy(alpha = 0.4f)) },+ ) {+ Column(Modifier.fillMaxWidth().fillMaxHeight(0.8f).navigationBarsPadding().verticalScroll(rememberScrollState()).padding(24.dp, 4.dp, 24.dp, 24.dp)) {+ Text(stringResource(R.string.lyrics_meaning_about), color = Color.White, fontSize = 24.sp, fontWeight = FontWeight.Bold)+ Text("${m.title} · ${m.artist}", color = Color.White.copy(alpha = 0.7f), fontSize = 14.sp, fontWeight = FontWeight.Medium, modifier = Modifier.padding(top = 2.dp))+ Text(m.about.orEmpty(), color = Color.White.copy(alpha = 0.92f), fontSize = 16.sp, lineHeight = 23.sp,+ fontWeight = FontWeight.Medium, modifier = Modifier.padding(top = 16.dp))+ if (m.notes.isNotEmpty()) Text(stringResource(R.string.lyrics_meaning_hint), color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp,+ modifier = Modifier.padding(top = 18.dp))+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 20.dp)) {+ TranslateChip(shown)+ Spacer(Modifier.weight(1f))+ GeniusSource(m.url)+ }+ }+ }+}++/**+ * A line held in the lyrics: Genius's explanation of it, on the lyrics' own colour and in their+ * type (as Spotify's own cards on that screen), the lyrics still in view above it.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun NoteSheet(original: GeniusMeaning.Meaning, index: Int, background: Color, onDismiss: () -> Unit) {+ val shown = rememberShown(original, listOfNotNull(original.notes.getOrNull(index)?.explanation))+ val m = shown.meaning+ val note = m.notes.getOrNull(index) ?: return+ ModalBottomSheet(+ onDismissRequest = onDismiss,+ containerColor = cardColor(background),+ dragHandle = { androidx.compose.material3.BottomSheetDefaults.DragHandle(color = Color.White.copy(alpha = 0.4f)) },+ ) {+ Column(Modifier.fillMaxWidth().navigationBarsPadding().heightIn(max = 560.dp).verticalScroll(rememberScrollState()).padding(24.dp, 4.dp, 24.dp, 24.dp)) {+ Text(note.fragment, color = Color.White, fontSize = 22.sp, lineHeight = 28.sp, fontWeight = FontWeight.Bold)+ Text(note.explanation, color = Color.White.copy(alpha = 0.9f), fontSize = 16.sp, lineHeight = 23.sp,+ fontWeight = FontWeight.Medium, modifier = Modifier.padding(top = 16.dp))+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 20.dp)) {+ TranslateChip(shown)+ Spacer(Modifier.weight(1f))+ GeniusSource(m.url)+ }+ }+ }+}++/** The sheet's colour: the lyrics' own, darker, so the white text reads on any of them. */+private fun cardColor(background: Color) = androidx.compose.ui.graphics.lerp(background, Color.Black, 0.35f)++/** For each lyric line, the explanation that covers it (a Genius fragment can span several lines). */+fun notesByLine(meaning: GeniusMeaning.Meaning, lines: List<String>): Map<Int, Int> {+ val frags = meaning.notes.map { squash(it.fragment) }+ val out = HashMap<Int, Int>()+ lines.forEachIndexed { i, line ->+ val l = squash(line)+ if (l.length < 8) return@forEachIndexed+ // Several explanations on one line: the most liked.+ val n = frags.indices.filter { j -> frags[j].let { f -> f.contains(l) || (f.length >= 8 && l.contains(f)) } }+ .maxByOrNull { meaning.notes[it].votes } ?: return@forEachIndexed+ out[i] = n+ }+ return out+}++private fun squash(s: String) = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD)+ .replace(Regex("\\p{Mn}+"), "").lowercase().replace(Regex("[^\\p{L}\\p{N}]+"), "")diff --git a/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt b/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.ktindex 1e646086..c5c9ea6e 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/MusicVideo.kt@@ -26,6 +26,7 @@ import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Fullscreen+import androidx.compose.material.icons.filled.VolumeUpimport androidx.compose.material.icons.filled.FullscreenExitimport androidx.compose.material.icons.filled.MusicNoteimport androidx.compose.material.icons.filled.OndemandVideo@@ -107,9 +108,46 @@ private val OverMedia = Color.Black.copy(alpha = 0.6f)/** Spotify's "Passer à la vidéo" / "Passer à l'audio" pill. */@Composablefun VideoSwitchPill(on: Boolean, modifier: Modifier = Modifier) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = modifier) {+ SwitchPill(on)+ // With the video on: the clip's own sound instead of the song's (the song still plays, unheard).+ if (on) {+ val clip = MusicVideoController.clipSound.value+ val context = androidx.compose.ui.platform.LocalContext.current+ Spacer(Modifier.width(8.dp))+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .height(32.dp)+ .clip(RoundedCornerShape(50))+ .background(OverMedia)+ .clickable {+ MusicVideoController.setClipSound(!clip)+ // What changed, said once per tap: the label alone did not tell (reported).+ android.widget.Toast.makeText(context, if (clip) R.string.clip_sound_off_hint else R.string.clip_sound_on_hint, android.widget.Toast.LENGTH_LONG).show()+ }+ .padding(start = 10.dp, end = 12.dp),+ ) {+ Icon(+ Icons.Default.VolumeUp,+ contentDescription = null,+ tint = if (clip) com.music.spotui.ui.theme.AppAccent else Color.White,+ modifier = Modifier.size(16.dp),+ )+ Spacer(Modifier.width(6.dp))+ // The sound heard now: the song's, or the clip's own.+ Text(stringResource(if (clip) R.string.clip_sound_clip else R.string.clip_sound_song), color = if (clip) com.music.spotui.ui.theme.AppAccent else Color.White,+ fontSize = 13.sp, fontWeight = FontWeight.Bold, maxLines = 1)+ }+ }+ }+}++@Composable+private fun SwitchPill(on: Boolean) {Row(verticalAlignment = Alignment.CenterVertically,- modifier = modifier+ modifier = Modifier.height(32.dp).clip(RoundedCornerShape(50)).background(OverMedia)diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.ktindex c8b7d470..ad9ac4e0 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlayerSheets.kt@@ -51,6 +51,8 @@ import androidx.compose.material.icons.filled.Smartphoneimport androidx.compose.material.icons.filled.Speakerimport androidx.compose.material.icons.filled.Tvimport androidx.compose.material.icons.outlined.Timer+import androidx.compose.material.icons.outlined.AddCircleOutline+import androidx.compose.material.icons.outlined.AutoAwesomeimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.HorizontalDivider@@ -73,6 +75,7 @@ import androidx.compose.runtime.withFrameNanosimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawWithContentimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.layout.ContentScale@@ -100,12 +103,25 @@ fun activeDeviceLabel(): String {SongPlayer.activeDevice.value?.let { return it.name }val route = rememberAudioRoute()return when (route.kind) {+ // "This phone", in the player as in the official app. Spotify Connect still lists it under+ // the device's own name (the engine registers that name); only this label says "this phone".AudioRoute.Kind.SPEAKER -> stringResource(R.string.connect_phone_is_self)AudioRoute.Kind.BLUETOOTH -> route.name.ifBlank { stringResource(R.string.label_bluetooth) }AudioRoute.Kind.WIRED -> stringResource(R.string.headphones)}}+/** The icon of the output playing now, matching [activeDeviceLabel]: a phone when this phone plays. */+@Composable+fun activeDeviceIcon(): ImageVector {+ SongPlayer.activeDevice.value?.let { return deviceIcon(it.type) }+ return when (rememberAudioRoute().kind) {+ AudioRoute.Kind.SPEAKER -> Icons.Default.Smartphone+ AudioRoute.Kind.BLUETOOTH -> Icons.Default.Bluetooth+ AudioRoute.Kind.WIRED -> Icons.Default.Headphones+ }+}+private fun deviceIcon(type: String): ImageVector = when (type.uppercase()) {"SMARTPHONE", "TABLET" -> Icons.Default.Smartphone"SPEAKER", "AVR", "STB", "AUDIO_DONGLE" -> Icons.Default.Speaker@@ -441,7 +457,7 @@ fun QueueSheet(contextName: String, onDismiss: () -> Unit) {Text(contextName, color = Color.White, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 4.dp, bottom = 8.dp)) {- Icon(Icons.Default.Smartphone, contentDescription = null, tint = Green, modifier = Modifier.size(16.dp))+ Icon(activeDeviceIcon(), contentDescription = null, tint = Green, modifier = Modifier.size(16.dp))Spacer(Modifier.width(6.dp))Text(activeDeviceLabel(), color = Green, fontSize = 13.sp)}@@ -546,6 +562,23 @@ internal fun queueTopInViewport(return queueContentTop - (firstItemTop + firstVisibleScrollOffset)}+/** The y (in the queue block) of the gap [item] would drop into from [centerY]; mirrors the drop's own placement. */+private fun dropLineY(+ entries: List<QEntry>, item: SongPlayer.QueueItem, fromQueued: Boolean, centerY: Float,+ headerPx: Float, rowPx: Float, topOf: (Int) -> Float,+): Float? {+ val rowsOf = { queuedSection: Boolean -> entries.filterIsInstance<QEntry.Row>().filter { it.queued == queuedSection }.map { it.item } }+ fun rowTop(target: SongPlayer.QueueItem) = topOf(entries.indexOfFirst { it is QEntry.Row && it.item == target })+ val nextHeaderIndex = entries.indexOfFirst { it is QEntry.Header && !it.queuedSection }+ val nextHeaderMid = if (nextHeaderIndex >= 0) topOf(nextHeaderIndex) + headerPx / 2 else Float.MAX_VALUE+ val toQueue = centerY < nextHeaderMid+ val others = rowsOf(toQueue) - item+ if (others.isEmpty()) return if (toQueue && !fromQueued) 0f else null+ val slot = if (toQueue) ((centerY - headerPx) / rowPx).toInt().coerceIn(0, others.size)+ else ((centerY - (topOf(nextHeaderIndex) + headerPx)) / rowPx).toInt().coerceIn(0, others.size)+ return if (slot < others.size) rowTop(others[slot]) else rowTop(others.last()) + rowPx+}+private sealed class QEntry {data class Header(val queuedSection: Boolean) : QEntry()data class Row(val item: SongPlayer.QueueItem, val queued: Boolean) : QEntry()@@ -661,7 +694,8 @@ private fun QueueList(fun drop(item: SongPlayer.QueueItem, fromQueued: Boolean, centerY: Float) {val nextHeaderIndex = entries.indexOfFirst { it is QEntry.Header && !it.queuedSection }val nextHeaderMid = if (nextHeaderIndex >= 0) topOf(nextHeaderIndex) + headerPx / 2 else Float.MAX_VALUE- val toQueue = fromQueued || centerY < nextHeaderMid+ // Either way across the line: a song moved up into the queue can be taken back down.+ val toQueue = centerY < nextHeaderMidif (toQueue) {val others = queued - itemif (others.isEmpty()) {@@ -687,13 +721,29 @@ private fun QueueList(val slot = ((centerY - startY) / rowPx).toInt().coerceIn(0, others.size)val newNext = others.toMutableList().apply { add(slot, item) }if (newNext == nextUp) return+ if (fromQueued) queued = queued - itemnextUp = newNextif (slot < others.size) SongPlayer.reorder(item, others[slot], after = false)else SongPlayer.reorder(item, others[slot - 1], after = true)}}- Column {+ // Where the dragged song would land if let go: a thin accent bar between two rows, worked+ // out exactly as [drop] places it.+ val accent = com.music.spotui.ui.theme.AppAccent+ val dropBar = Modifier.drawWithContent {+ drawContent()+ val item = dragging ?: return@drawWithContent+ val from = entries.indexOfFirst { it is QEntry.Row && it.item == item }+ if (from < 0) return@drawWithContent+ val y = dropLineY(entries, item, (entries[from] as QEntry.Row).queued, topOf(from) + dragOffset + rowPx / 2, headerPx, rowPx, ::topOf)+ ?: return@drawWithContent+ val inset = 20.dp.toPx()+ val h = 1.5.dp.toPx()+ drawRoundRect(androidx.compose.ui.graphics.lerp(accent, Color.Black, 0.35f).copy(alpha = 0.8f), topLeft = androidx.compose.ui.geometry.Offset(inset, y - h / 2),+ size = androidx.compose.ui.geometry.Size(size.width - inset * 2, h), cornerRadius = androidx.compose.ui.geometry.CornerRadius(h / 2))+ }+ Column(dropBar) {entries.forEachIndexed { index, e ->when (e) {is QEntry.Header -> Row(@@ -859,6 +909,8 @@ private fun QueueSheetRow(trailing: @Composable () -> Unit,onClick: () -> Unit,) {+ val context = androidx.compose.ui.platform.LocalContext.current+ val rec = com.music.spotui.ui.screens.SmartShuffle.isRecommendation(song.spotifyTrackId)Row(verticalAlignment = Alignment.CenterVertically,modifier = Modifier@@ -886,10 +938,18 @@ private fun QueueSheetRow()}Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {+ // Mixed in by smart shuffle: marked, as in the official app, not taken for one of the playlist's songs.+ if (rec) { Icon(Icons.Outlined.AutoAwesome, contentDescription = stringResource(R.string.smart_shuffle_recommended), tint = Green, modifier = Modifier.size(14.dp)); Spacer(Modifier.width(4.dp)) }if (song.explicit) { ExplicitBadge(); Spacer(Modifier.width(6.dp)) }Text(song.singer, color = Color.White.copy(alpha = 0.7f), fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}}+ if (rec) Icon(+ Icons.Outlined.AddCircleOutline,+ contentDescription = stringResource(R.string.smart_shuffle_add),+ tint = Color.White,+ modifier = Modifier.padding(end = 12.dp).size(26.dp).clip(CircleShape).clickable { com.music.spotui.ui.screens.SmartShuffle.keep(context, song) },+ )trailing()}}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.ktindex dc4ad8b5..c1a8d228 100644--- a/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt+++ b/base/app/src/main/java/com/music/spotui/ui/components/PlaylistOptionsSheet.kt@@ -28,6 +28,13 @@ import androidx.compose.material.icons.outlined.Groupimport androidx.compose.material.icons.outlined.Lockimport androidx.compose.material.icons.outlined.Personimport androidx.compose.material.icons.outlined.Public+import androidx.compose.material.icons.outlined.Share+import androidx.compose.material.icons.outlined.AddCircleOutline+import androidx.compose.material.icons.outlined.GroupRemove+import androidx.compose.material.icons.outlined.PersonRemove+import androidx.compose.material.icons.outlined.PersonAdd+import androidx.compose.material.icons.outlined.QrCode2+import androidx.compose.material.icons.automirrored.outlined.Logoutimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.ExperimentalMaterial3Apiimport androidx.compose.material3.Icon@@ -45,6 +52,7 @@ import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.draw.alphaimport androidx.compose.ui.draw.clipimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.asImageBitmap@@ -66,22 +74,26 @@ import com.music.spotui.data.entity.ContextPageModelimport com.music.spotui.ui.theme.AppAccentimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.launch-import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContext/*** A playlist's ⋯ menu. On your own playlists: edit the name, description and cover, choose* who can see it (public, private, collaborative) and delete it. On someone else's: their- * profile. [onChanged] reloads the page after an edit; [onDeleted] leaves it.+ * profile. [onChanged] reloads the page after an edit; [onDeleted] leaves it. Changes show+ * at once and are written in the app's own scope, so closing the sheet does not cancel them.*/-@OptIn(ExperimentalMaterial3Api::class)+@OptIn(ExperimentalMaterial3Api::class, com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi::class)@Composablefun PlaylistOptionsSheet(page: ContextPageModel,onDismiss: () -> Unit,onChanged: () -> Unit,+ /** The name and description just saved, to show before Spotify has answered. */+ onEdited: (String, String) -> Unit,onDeleted: () -> Unit,onProfile: (String) -> Unit,+ /** "Add to this playlist" (search and suggestions), on your own playlists. */+ onAddSongs: (() -> Unit)? = null,) {val context = LocalContext.currentval scope = rememberCoroutineScope()@@ -98,6 +110,8 @@ fun PlaylistOptionsSheet(var published by remember { mutableStateOf<Boolean?>(null) }var editing by remember { mutableStateOf(false) }var deleting by remember { mutableStateOf(false) }+ var renamingBlend by remember { mutableStateOf(false) }+ var leavingBlend by remember { mutableStateOf(false) }LaunchedEffect(page.uri, mine) {if (mine) {access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()@@ -105,71 +119,99 @@ fun PlaylistOptionsSheet(}}- // Taps are sent one at a time, in order; a refused one puts back what Spotify really has.- val accessWrites = remember { kotlinx.coroutines.sync.Mutex() }+ // Taps are sent one at a time, in order (SpotifySync); a refused one puts back what Spotify really has.+ fun restore() = scope.launch {+ access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()+ published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()+ android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()+ }+fun setAccess(target: PlaylistAccess) {if (access == target) returnaccess = target// Made private, it leaves the profile too (as in the official apps).if (target == PlaylistAccess.PRIVATE) published = false- scope.launch {- accessWrites.withLock {- runCatching { MyspotiRuntime.api.playlists.setAccess(page.uri, target) }- .onSuccess { onChanged() }- .onFailure {- access = runCatching { MyspotiRuntime.api.playlists.access(page.uri) }.getOrNull()- published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()- android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()- }- }- }+ com.music.spotui.data.api.SpotifySync.setPlaylistAccess(page.uri, target) { ok -> if (!ok) restore() }}fun setPublished(on: Boolean) {if (published == on) returnpublished = on- scope.launch {- accessWrites.withLock {- runCatching { MyspotiRuntime.api.playlists.setPublished(page.uri, on) }- .onSuccess { onChanged() }- .onFailure {- published = runCatching { MyspotiRuntime.api.playlists.published(page.uri) }.getOrNull()- android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show()- }- }- }- }-- fun run(block: suspend () -> Unit, after: () -> Unit = onChanged) = scope.launch {- runCatching { block() }- .onSuccess { after() }- .onFailure { android.widget.Toast.makeText(context, R.string.playlist_change_refused, android.widget.Toast.LENGTH_SHORT).show() }+ com.music.spotui.data.api.SpotifySync.setPlaylistPublished(page.uri, on) { ok -> if (!ok) restore() }}ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Color(0xFF282828)) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {- Text(page.name, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1,- overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 12.dp))- if (mine) {+ // As the official app: the playlist itself on top (cover, name, owner), then one action a row.+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(20.dp, 0.dp, 20.dp, 12.dp)) {+ com.bumptech.glide.integration.compose.GlideImage(+ model = page.coverUri, contentDescription = null, contentScale = androidx.compose.ui.layout.ContentScale.Crop,+ modifier = Modifier.size(52.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(4.dp)),+ )+ Column(Modifier.weight(1f).padding(start = 12.dp)) {+ Text(page.name, color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)+ if (page.ownerName.isNotBlank()) Text(stringResource(R.string.playlist_by, page.ownerName), color = Color(0xFFB3B3B3), fontSize = 13.sp,+ maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ }+ androidx.compose.material3.HorizontalDivider(color = Color.White.copy(alpha = 0.08f))+ Spacer(Modifier.height(6.dp))+ val share = { SpotifyCode.show(ShareTarget(page.uri, page.name, page.ownerName, page.coverUri)); onDismiss() }+ if (page.isBlend) {+ // A Blend is Spotify's: renamed, shared and left through its own service.+ OptionRow(Icons.Outlined.Edit, stringResource(R.string.blend_rename)) { renamingBlend = true }+ OptionRow(Icons.Outlined.Share, stringResource(R.string.blend_invite_more)) {+ scope.launch {+ val link = BlendInfo.recent[page.uri]?.group?.link+ ?: runCatching { MyspotiRuntime.api.blends.group(page.uri).link }.getOrNull()+ if (link == null) android.widget.Toast.makeText(context, R.string.blend_failed, android.widget.Toast.LENGTH_SHORT).show()+ else { BlendInfo.share(context, link); onDismiss() }+ }+ }+ OptionRow(Icons.AutoMirrored.Outlined.Logout, stringResource(R.string.blend_leave)) { leavingBlend = true }+ } else if (mine) {+ onAddSongs?.let { add -> OptionRow(Icons.Outlined.AddCircleOutline, stringResource(R.string.add_songs_title)) { onDismiss(); add() } }OptionRow(Icons.Outlined.Edit, stringResource(R.string.playlist_edit_details)) { editing = true }- Text(stringResource(R.string.playlist_access_title), color = Color(0xFFB3B3B3), fontSize = 13.sp,- modifier = Modifier.padding(20.dp, 12.dp, 20.dp, 4.dp))- AccessRow(Icons.Outlined.Public, R.string.playlist_access_public, R.string.playlist_access_public_detail, access == PlaylistAccess.PUBLIC) {- setAccess(PlaylistAccess.PUBLIC)+ // Collaborative is not enough: only those who open its invitation link can add songs+ // (a plain link only shows it). Inviting makes it collaborative, as in the official app.+ OptionRow(Icons.Outlined.PersonAdd, stringResource(R.string.playlist_invite_collaborators)) {+ if (access != PlaylistAccess.COLLABORATIVE) setAccess(PlaylistAccess.COLLABORATIVE)+ scope.launch {+ val link = runCatching { MyspotiRuntime.api.playlists.collaboratorInvite(page.uri) }.getOrNull()+ if (link == null) { android.widget.Toast.makeText(context, R.string.playlist_invite_failed, android.widget.Toast.LENGTH_SHORT).show(); return@launch }+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).setType("text/plain")+ .putExtra(android.content.Intent.EXTRA_TEXT, context.getString(R.string.playlist_invite_message, page.name, link))+ context.startActivity(android.content.Intent.createChooser(send, null).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))+ onDismiss()+ }}- AccessRow(Icons.Outlined.Lock, R.string.playlist_access_private, R.string.playlist_access_private_detail, access == PlaylistAccess.PRIVATE) {- setAccess(PlaylistAccess.PRIVATE)+ OptionRow(Icons.Outlined.QrCode2, stringResource(R.string.context_menu_share), onClick = share)+ // Who sees it: one action naming what it does next (not three choices to read).+ val a = access+ fun change(target: PlaylistAccess, said: Int) {+ setAccess(target)+ android.widget.Toast.makeText(context, said, android.widget.Toast.LENGTH_SHORT).show()}- AccessRow(Icons.Outlined.Group, R.string.playlist_access_collaborative, R.string.playlist_access_collaborative_detail, access == PlaylistAccess.COLLABORATIVE) {- setAccess(PlaylistAccess.COLLABORATIVE)+ when (a) {+ null -> OptionRow(Icons.Outlined.Lock, stringResource(R.string.playlist_access_title), enabled = false) {}+ PlaylistAccess.PRIVATE -> OptionRow(Icons.Outlined.Public, stringResource(R.string.playlist_make_public)) { change(PlaylistAccess.PUBLIC, R.string.playlist_now_public) }+ PlaylistAccess.COLLABORATIVE -> OptionRow(Icons.Outlined.GroupRemove, stringResource(R.string.playlist_stop_collab)) { change(PlaylistAccess.PUBLIC, R.string.playlist_now_solo) }+ else -> OptionRow(Icons.Outlined.Lock, stringResource(R.string.playlist_make_private)) { change(PlaylistAccess.PRIVATE, R.string.playlist_now_private) }}// Only a playlist others may see can be listed on the profile.- if (access != null && access != PlaylistAccess.PRIVATE && published != null) {- ProfileRow(published == true) { setPublished(it) }+ if (a != null && a != PlaylistAccess.PRIVATE && published != null) {+ val on = published == true+ OptionRow(if (on) Icons.Outlined.PersonRemove else Icons.Outlined.Person,+ stringResource(if (on) R.string.playlist_remove_profile else R.string.playlist_add_profile)) {+ setPublished(!on)+ android.widget.Toast.makeText(context, if (on) R.string.playlist_now_off_profile else R.string.playlist_now_on_profile, android.widget.Toast.LENGTH_SHORT).show()+ }}- Spacer(Modifier.height(8.dp))OptionRow(Icons.Outlined.Delete, stringResource(R.string.local_delete_playlist)) { deleting = true }- } else if (page.ownerUri.startsWith("spotify:user:")) {+ } else {+ OptionRow(Icons.Outlined.QrCode2, stringResource(R.string.context_menu_share), onClick = share)+ }+ if (!mine && !page.isBlend && page.ownerUri.startsWith("spotify:user:")) {OptionRow(Icons.Outlined.Person, stringResource(R.string.go_to_profile)) {onDismiss(); onProfile(page.ownerUri.substringAfterLast(':'))}@@ -179,7 +221,11 @@ fun PlaylistOptionsSheet(if (editing) EditDetailsDialog(page, onDismiss = { editing = false }) { name, description, cover ->editing = false- run({+ // Name and description show at once, in the page and in the library; the cover needs the page again.+ if (name != page.name || description != page.description) onEdited(name, description)+ val renamed = if (name != page.name) com.music.spotui.data.api.LibraryEdits.Rename(page.uri, name) else null+ onDismiss()+ com.music.spotui.data.api.LibraryEdits.run(context, renamed, write = {if (name != page.name) MyspotiRuntime.api.playlists.rename(page.uri, name)if (description != page.description) MyspotiRuntime.api.playlists.setDescription(page.uri, description)when (cover) {@@ -187,12 +233,42 @@ fun PlaylistOptionsSheet(CoverChange.Remove -> MyspotiRuntime.api.playlists.setCover(page.uri, null)CoverChange.Keep -> {}}- }, {- android.widget.Toast.makeText(context, R.string.playlist_saved, android.widget.Toast.LENGTH_SHORT).show()- onDismiss(); onChanged()+ }, onDone = { ok ->+ if (ok) android.widget.Toast.makeText(context, R.string.playlist_saved, android.widget.Toast.LENGTH_SHORT).show()+ // Refused: the page goes back to what Spotify has; a new cover shows only once it is read again.+ if (!ok || cover != CoverChange.Keep) onChanged()})}+ if (renamingBlend) com.music.spotui.ui.screens.NameDialog(stringResource(R.string.blend_rename), page.name,+ stringResource(R.string.local_rename), onDismiss = { renamingBlend = false }) { name ->+ renamingBlend = false+ onDismiss()+ if (name == page.name) return@NameDialog+ onEdited(name, page.description)+ com.music.spotui.data.api.LibraryEdits.run(context, com.music.spotui.data.api.LibraryEdits.Rename(page.uri, name),+ write = { MyspotiRuntime.api.blends.rename(page.uri, name) },+ onDone = { ok -> if (!ok) onChanged() })+ }++ if (leavingBlend) AlertDialog(+ onDismissRequest = { leavingBlend = false },+ containerColor = Color(0xFF282828),+ title = { Text(stringResource(R.string.blend_leave), color = Color.White) },+ text = { Text(stringResource(R.string.blend_leave_confirm, page.name), color = Color(0xFFB3B3B3)) },+ confirmButton = {+ TextButton(onClick = {+ leavingBlend = false+ // The Blend leaves the library and the page closes now; a refusal brings it back.+ BlendInfo.recent.remove(page.uri)+ com.music.spotui.data.api.LibraryEdits.run(context, com.music.spotui.data.api.LibraryEdits.Remove(page.uri),+ write = { MyspotiRuntime.api.blends.leave(page.uri) })+ onDismiss(); onDeleted()+ }) { Text(stringResource(R.string.blend_leave_button), color = Color(0xFFF15E6C)) }+ },+ dismissButton = { TextButton(onClick = { leavingBlend = false }) { Text(stringResource(R.string.cancel), color = Color.White) } },+ )+if (deleting) AlertDialog(onDismissRequest = { deleting = false },containerColor = Color(0xFF282828),@@ -200,7 +276,10 @@ fun PlaylistOptionsSheet(confirmButton = {TextButton(onClick = {deleting = false- run({ MyspotiRuntime.api.playlists.delete(page.uri) }, { onDismiss(); onDeleted() })+ // The playlist leaves the library and the page closes now; a refusal brings it back.+ com.music.spotui.data.api.LibraryEdits.run(context, com.music.spotui.data.api.LibraryEdits.Remove(page.uri),+ write = { MyspotiRuntime.api.playlists.delete(page.uri) })+ onDismiss(); onDeleted()}) { Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C)) }},dismissButton = { TextButton(onClick = { deleting = false }) { Text(stringResource(R.string.cancel), color = Color.White) } },@@ -293,10 +372,11 @@ private fun coverJpeg(context: Context, uri: Uri): Pair<ByteArray, Bitmap> {}@Composable-private fun OptionRow(icon: ImageVector, label: String, onClick: () -> Unit) {+private fun OptionRow(icon: ImageVector, label: String, enabled: Boolean = true, onClick: () -> Unit) {Row(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 14.dp),+ modifier = Modifier.fillMaxWidth().clickable(enabled = enabled, onClick = onClick).padding(horizontal = 20.dp, vertical = 14.dp)+ .then(if (enabled) Modifier else Modifier.alpha(0.4f)),) {Icon(icon, null, tint = Color.White, modifier = Modifier.size(24.dp))Spacer(Modifier.width(16.dp))@@ -304,37 +384,3 @@ private fun OptionRow(icon: ImageVector, label: String, onClick: () -> Unit) {}}-@Composable-private fun ProfileRow(on: Boolean, onChange: (Boolean) -> Unit) {- Row(- verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().clickable { onChange(!on) }.padding(horizontal = 20.dp, vertical = 10.dp),- ) {- Icon(Icons.Outlined.Person, null, tint = Color.White, modifier = Modifier.size(24.dp))- Spacer(Modifier.width(16.dp))- Column(Modifier.weight(1f)) {- Text(stringResource(R.string.playlist_on_profile), color = Color.White, fontSize = 16.sp)- Text(stringResource(R.string.playlist_on_profile_detail), color = Color(0xFFB3B3B3), fontSize = 13.sp)- }- androidx.compose.material3.Switch(- checked = on, onCheckedChange = onChange,- colors = androidx.compose.material3.SwitchDefaults.colors(checkedTrackColor = AppAccent, checkedThumbColor = Color.Black),- )- }-}--@Composable-private fun AccessRow(icon: ImageVector, label: Int, detail: Int, selected: Boolean, onClick: () -> Unit) {- Row(- verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 20.dp, vertical = 10.dp),- ) {- Icon(icon, null, tint = if (selected) AppAccent else Color.White, modifier = Modifier.size(24.dp))- Spacer(Modifier.width(16.dp))- Column(Modifier.weight(1f)) {- Text(stringResource(label), color = if (selected) AppAccent else Color.White, fontSize = 16.sp)- Text(stringResource(detail), color = Color(0xFFB3B3B3), fontSize = 13.sp)- }- if (selected) Icon(Icons.Default.Check, null, tint = AppAccent, modifier = Modifier.size(20.dp))- }-}diff --git a/base/app/src/main/java/com/music/spotui/ui/components/ProfileAvatar.kt b/base/app/src/main/java/com/music/spotui/ui/components/ProfileAvatar.ktnew file mode 100644index 00000000..8ca0b9f1--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/ProfileAvatar.kt@@ -0,0 +1,52 @@+package com.music.spotui.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Person+import androidx.compose.material3.Icon+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.sp+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage++/** Background colours for a profile without a picture, picked from the name (stable per user). */+private val AVATAR_COLORS = listOf(+ 0xFF8D67AB, 0xFF1E3264, 0xFFE8115B, 0xFF148A08, 0xFFBA5D07, 0xFF477D95, 0xFFAF2896, 0xFF503750,+)++/**+ * A profile picture, round. A profile without one shows its name's first letter on a colour of its+ * own, as Spotify does; a profile without a name either, a person icon. Reported: an empty profile+ * picture showed nothing at all.+ */+@OptIn(ExperimentalGlideComposeApi::class)+@Composable+fun ProfileAvatar(url: String?, name: String?, size: Dp, modifier: Modifier = Modifier) {+ if (!url.isNullOrBlank()) {+ GlideImage(+ transition = CrossFade,+ model = url, contentDescription = null, contentScale = ContentScale.Crop,+ modifier = modifier.size(size).clip(CircleShape),+ )+ return+ }+ val label = name?.trim().orEmpty()+ val letter = label.firstOrNull()?.uppercaseChar()+ val color = Color(AVATAR_COLORS[(label.hashCode() and Int.MAX_VALUE) % AVATAR_COLORS.size])+ Box(modifier.size(size).clip(CircleShape).background(color), contentAlignment = Alignment.Center) {+ if (letter != null) Text(letter.toString(), color = Color.White, fontSize = (size.value * 0.42f).sp, fontWeight = FontWeight.Bold)+ else Icon(Icons.Filled.Person, contentDescription = null, tint = Color.White, modifier = Modifier.size(size * 0.55f))+ }+}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 11425180..0464c9f2 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@@ -304,10 +304,7 @@ fun SongOptionsSheet(MenuRow(Icons.Outlined.Speed, stringResource(R.string.playback_speed)) { showSpeed = true }}MenuRow(Icons.Outlined.Share, stringResource(R.string.context_menu_share), enabled = hasId) {- val send = Intent(Intent.ACTION_SEND)- .setType("text/plain")- .putExtra(Intent.EXTRA_TEXT, "https://open.spotify.com/track/${song.spotifyTrackId}")- context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ 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/components/SpotifyCodeSheet.kt b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.ktnew file mode 100644index 00000000..57112159--- /dev/null+++ b/base/app/src/main/java/com/music/spotui/ui/components/SpotifyCodeSheet.kt@@ -0,0 +1,207 @@+package com.music.spotui.ui.components++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.content.Intent+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.RectF+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.outlined.ContentCopy+import androidx.compose.material.icons.outlined.Image+import androidx.compose.material.icons.outlined.Share+import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.Icon+import androidx.compose.material3.ModalBottomSheet+import androidx.compose.material3.Text+import androidx.compose.material3.rememberModalBottomSheetState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.luminance+import androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+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.core.content.FileProvider+import app.myspoti.engine.R+import com.bumptech.glide.Glide+import com.bumptech.glide.integration.compose.CrossFade+import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi+import com.bumptech.glide.integration.compose.GlideImage+import com.music.spotui.di.Palette+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File++/** What a share sheet is about: a Spotify uri (track, album, playlist, artist, show, episode). */+data class ShareTarget(val uri: String, val title: String, val subtitle: String = "", val coverUri: String = "") {+ /** The open.spotify.com link of [uri]. */+ val link: String get() = uri.split(':').let { p -> if (p.size >= 3 && p[0] == "spotify") "https://open.spotify.com/${p[1]}/${p[2]}" else uri }+}++/**+ * Sharing, as in the official app: the Spotify Code first (the bars under the cover that+ * Spotify's camera scans), the link under it, then copy / share the link / share the code as+ * an image. Shown by the app's root (App.kt) so a menu can close itself right after asking.+ */+object SpotifyCode {+ val request = MutableStateFlow<ShareTarget?>(null)++ fun show(target: ShareTarget) { request.value = target }++ /**+ * Spotify's own image of the code of [uri]: its logo and bars, [bars] ("white" or "black") on+ * [background] (RRGGBB). The same service the Spotify apps and web codes use.+ */+ fun imageUrl(uri: String, background: Color, bars: String): String {+ val hex = String.format("%06X", background.toArgb() and 0xFFFFFF)+ return "https://scannables.scdn.co/uri/plain/png/$hex/$bars/640/$uri"+ }++ fun barsOn(background: Color) = if (background.luminance() > 0.45f) "black" else "white"++ /** The cover and its code on the cover's colour, as one picture (1080 wide), shared through the FileProvider. */+ suspend fun shareImage(context: Context, target: ShareTarget, background: Color, chooserTitle: String) {+ val file = withContext(Dispatchers.IO) {+ runCatching {+ val app = context.applicationContext+ val 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 w = 1080; val side = 840; val pad = 120+ val codeH = side * code.height / code.width.coerceAtLeast(1)+ val h = pad + (if (cover != null) side + 60 else 0) + codeH + pad+ val out = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ val c = Canvas(out)+ val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)+ c.drawColor(background.toArgb())+ var y = pad.toFloat()+ if (cover != null) {+ val src = if (cover.config == Bitmap.Config.HARDWARE) cover.copy(Bitmap.Config.ARGB_8888, false) else cover+ c.drawBitmap(src, null, RectF(((w - side) / 2).toFloat(), y, ((w + side) / 2).toFloat(), y + side), paint)+ y += side + 60+ }+ val codeSrc = if (code.config == Bitmap.Config.HARDWARE) code.copy(Bitmap.Config.ARGB_8888, false) else code+ c.drawBitmap(codeSrc, null, RectF(((w - side) / 2).toFloat(), y, ((w + side) / 2).toFloat(), y + codeH), paint)+ val dir = File(context.cacheDir, "shared").apply { mkdirs() }+ dir.listFiles()?.forEach { it.delete() }+ File(dir, "spotify_code.png").also { f -> f.outputStream().use { out.compress(Bitmap.CompressFormat.PNG, 100, it) } }+ }.getOrNull()+ } ?: return+ val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)+ val send = Intent(Intent.ACTION_SEND).setType("image/png")+ .putExtra(Intent.EXTRA_STREAM, uri)+ .putExtra(Intent.EXTRA_TEXT, target.link)+ .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ context.startActivity(Intent.createChooser(send, chooserTitle).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ }++ fun shareLink(context: Context, target: ShareTarget) {+ val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, target.link)+ context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))+ }+}++@OptIn(ExperimentalMaterial3Api::class, ExperimentalGlideComposeApi::class)+@Composable+fun SpotifyCodeSheet(target: ShareTarget, onDismiss: () -> Unit) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)+ var background by remember(target.coverUri) { mutableStateOf(Palette.cachedSecond(target.coverUri) ?: Color(0xFF535353)) }+ LaunchedEffect(target.coverUri) {+ if (target.coverUri.isNotBlank()) Palette().extractSecondColorFromCoverUrl(context, target.coverUri) { background = it }+ }+ val bars = SpotifyCode.barsOn(background)+ val text = if (bars == "black") Color.Black else Color.White+ ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState, containerColor = Color(0xFF121212)) {+ Column(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 24.dp), horizontalAlignment = Alignment.CenterHorizontally) {+ // The card: cover, name, and the code under them, all on the cover's colour.+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ 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,+ 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,+ textAlign = TextAlign.Center, modifier = Modifier.padding(top = 14.dp))+ if (target.subtitle.isNotBlank()) Text(target.subtitle, color = text.copy(alpha = 0.75f), fontSize = 14.sp, maxLines = 1,+ overflow = TextOverflow.Ellipsis, textAlign = TextAlign.Center)+ GlideImage(+ model = SpotifyCode.imageUrl(target.uri, background, bars),+ contentDescription = stringResource(R.string.spotify_code_description),+ contentScale = ContentScale.Fit, transition = CrossFade,+ modifier = Modifier.padding(top = 14.dp).fillMaxWidth().aspectRatio(4f),+ )+ }+ Text(stringResource(R.string.spotify_code_hint), color = Color(0xFFB3B3B3), fontSize = 13.sp, textAlign = TextAlign.Center,+ modifier = Modifier.padding(top = 12.dp))+ // The link itself, under the code.+ Text(target.link, color = Color.White.copy(alpha = 0.85f), fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,+ modifier = Modifier.padding(top = 14.dp).fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(Color(0xFF2A2A2A))+ .clickable { copy(context, target.link) }.padding(horizontal = 14.dp, vertical = 12.dp))+ Row(Modifier.fillMaxWidth().padding(top = 18.dp, bottom = 16.dp), horizontalArrangement = Arrangement.SpaceEvenly) {+ ShareAction(Icons.Outlined.ContentCopy, stringResource(R.string.copy_link)) { copy(context, target.link); onDismiss() }+ ShareAction(Icons.Outlined.Share, stringResource(R.string.share_link)) { SpotifyCode.shareLink(context, target); onDismiss() }+ val chooser = stringResource(R.string.action_share_label)+ ShareAction(Icons.Outlined.Image, stringResource(R.string.spotify_code_share_image)) {+ scope.launch { SpotifyCode.shareImage(context, target, background, chooser); onDismiss() }+ }+ }+ }+ }+}++private fun copy(context: Context, link: String) {+ (context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText("Spotify", link))+ // Android 13+ shows its own confirmation.+ if (android.os.Build.VERSION.SDK_INT < 33)+ android.widget.Toast.makeText(context, context.getString(R.string.link_copied), android.widget.Toast.LENGTH_SHORT).show()+}++@Composable+private fun ShareAction(icon: ImageVector, label: String, onClick: () -> Unit) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.width(96.dp).clip(RoundedCornerShape(8.dp)).clickable(onClick = onClick).padding(vertical = 6.dp)) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.size(52.dp).clip(CircleShape).background(Color(0xFF2A2A2A))) {+ Icon(icon, contentDescription = null, tint = Color.White, modifier = Modifier.size(24.dp))+ }+ Spacer(Modifier.height(6.dp))+ Text(label, color = Color.White, fontSize = 12.sp, textAlign = TextAlign.Center, maxLines = 2)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.ktindex 7d6e080e..e43e0a9e 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ArtistScreen.kt@@ -149,6 +149,7 @@ private fun ArtistOverviewContent(if (showArtistMenu) com.music.spotui.ui.components.ArtistOptionsSheet(artistId = overview.id,artistName = displayName,+ artistImage = overview.avatarImage.ifBlank { overview.headerImage },onDismiss = { showArtistMenu = false },)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.ktindex 103bd8ea..db40d02a 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ContextScreen.kt@@ -28,6 +28,9 @@ import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.foundation.lazy.itemsIndexedimport androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.material.icons.filled.Add+import androidx.compose.material.icons.outlined.Groupimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.automirrored.filled.ArrowBack@@ -46,6 +49,9 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.outlined.AddCircleOutline+import androidx.compose.ui.input.nestedscroll.nestedScrollimport androidx.compose.ui.draw.alphaimport androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.draw.clip@@ -160,17 +166,63 @@ class ContextViewModel(val contextSaved = mutableStateOf(false)/** The page is a playlist the user may change: only there can a track be removed. */val editableContext = mutableStateOf(false)+ /** Who can change this playlist: more than one when it is collaborative (their faces in the header). */+ val members = mutableStateOf<List<app.myspoti.api.PlaylistMember>>(emptyList())+ /** On a collaborative playlist: who added each row (by row id, then by song). */+ val adders = mutableStateOf<Map<String, app.myspoti.api.PlaylistMember>>(emptyMap())+ /** Someone else's collaborative playlist this account was never invited to: it can't add to it. */+ val collabLocked = mutableStateOf(false)private var key: String? = nullprivate var savedChecked = 0private var lastType = ""private var lastId = ""+ /** A pull-to-refresh is reading the page again. */+ val refreshing = mutableStateOf(false)++ /** "Recommended songs" under an own playlist; null until asked. */+ val recs = mutableStateOf<List<SongsModel>?>(null)+ /** Suggested already (shown, added or refreshed away): not suggested again on this page. */+ private val recsSeen = LinkedHashSet<String>()+ private var recsJob: kotlinx.coroutines.Job? = null++ /** Asks Spotify for songs that fit [p] (its name when it is empty), [refresh] for new ones. */+ fun loadRecs(p: ContextPageModel, refresh: Boolean = false) {+ if (recsJob?.isActive == true) return+ if (!refresh && recs.value != null) return+ recsJob = viewModelScope.launch(Dispatchers.IO) {+ val inList = p.tracks.mapTo(HashSet()) { it.spotifyTrackId }+ val skip = (inList + recsSeen).map { "spotify:track:$it" }+ val got = runCatching { MyspotiRuntime.api.playlists.recommended(p.uri, limit = RECS_COUNT, skip = skip) }+ .getOrDefault(emptyList()).map(api::songOf)+ .filter { it.spotifyTrackId !in inList && it.spotifyTrackId !in recsSeen }+ got.forEach { recsSeen += it.spotifyTrackId }+ recs.value = got+ }+ }++ /** [song] added to the playlist: it leaves the suggestions at once, and one more is asked for when few remain. */+ fun takeRec(p: ContextPageModel, song: SongsModel) {+ val left = recs.value.orEmpty().filter { it.spotifyTrackId != song.spotifyTrackId }+ recs.value = left+ if (left.size < 3) loadRecs(p, refresh = true)+ }++ fun refresh() {+ if (refreshing.value) return+ refreshing.value = true+ reload()+ }+/** After an edit (name, cover, description): the page from the server again. */fun reload() {val k = key ?: returnrecent.remove(k)key = null+ // The likes, the members and who added each song are read again with the new list (a+ // song just added showed no face on a collaborative playlist).+ savedChecked = 0load(lastType, lastId)}@@ -188,6 +240,10 @@ class ContextViewModel(runCatching { pending.await() }recent[key]?.let { _page.value = it }}+ // Fetched ahead (PagePrefetch) or opened before, on storage: shown whole at once.+ var fromDisk = false+ if (_page.value !is Response.Success && type == "playlist")+ com.music.spotui.data.api.ScreenCache.page(id).read()?.let { fromDisk = true; _page.value = Response.Success(it) }val flow = when (type) {"album" -> api.getAlbumPage(id)"liked" -> api.getLikedPage()@@ -196,11 +252,9 @@ class ContextViewModel(else -> api.getPlaylistPage(id)}// Liked Songs: a like or unlike anywhere puts the list right at once.- if (type == "liked") viewModelScope.launch(Dispatchers.IO) {- SongPlayer.likedChanges.drop(1).collectLatest {- kotlinx.coroutines.delay(1_500) // Spotify's library takes the change first- val songs = api.mergeLikedHead() ?: return@collectLatest- val current = (_page.value as? Response.Success)?.data ?: return@collectLatest+ if (type == "liked") {+ fun show(songs: List<SongsModel>) {+ val current = (_page.value as? Response.Success)?.data ?: returnval updated = Response.Success(current.copy(tracks = songs,metaLine = Graph.app.resources.getQuantityString(R.plurals.liked_songs_header_metadata_text, songs.size, songs.size),@@ -208,20 +262,44 @@ class ContextViewModel(_page.value = updatedrecent[key!!] = updated}+ // An unlike leaves the list on the tap, before Spotify has answered (reported: slow).+ viewModelScope.launch(Dispatchers.IO) {+ SongPlayer.likedTaps.collect { (id, liked) ->+ if (liked) return@collect+ val current = (_page.value as? Response.Success)?.data ?: return@collect+ if (current.tracks.any { it.spotifyTrackId == id }) show(current.tracks.filterNot { it.spotifyTrackId == id })+ }+ }+ // Once Spotify took it, the newest songs are read again: at once, then once more+ // in case the first read still had the old list.+ viewModelScope.launch(Dispatchers.IO) {+ SongPlayer.likedChanges.drop(1).collectLatest {+ api.mergeLikedHead()?.let(::show)+ kotlinx.coroutines.delay(2_500)+ api.mergeLikedHead()?.let(::show)+ }+ }}- flow.collect { r ->+ try { flow.collect { r ->if (r is Response.Loading && _page.value is Response.Success) return@collect+ // Offline or refused: the page already on screen stays rather than an error.+ if (r is Response.Error && fromDisk && _page.value is Response.Success) return@collect+ // A refresh keeps the full list on screen until the new one is complete: the first+ // page alone would cut a long playlist short and lose the place in it.+ if ((refreshing.value || fromDisk) && r is Response.Success && !r.data.complete &&+ (_page.value as? Response.Success)?.data?.let { it.uri == r.data.uri && it.tracks.size > r.data.tracks.size } == true) return@collect_page.value = rif (r is Response.Success) {recent[key!!] = rval p = r.data+ if (type == "playlist" && p.complete) com.music.spotui.data.api.PagePrefetch.refreshed(id, p)// Check saved state on the first page and again once complete.if ((savedChecked == 0 && p.tracks.isNotEmpty()) || (p.complete && savedChecked < 2)) {savedChecked = if (p.complete) 2 else 1refreshSaved(p)}}- }+ } } finally { refreshing.value = false }}}@@ -240,6 +318,27 @@ class ContextViewModel(if (p.type == "playlist") editableContext.value = withContext(Dispatchers.IO) {runCatching { EditablePlaylists.load().any { it.id == p.uri.substringAfterLast(':') } }.getOrDefault(false)}+ if (p.type == "playlist" && !p.isBlend) members.value = withContext(Dispatchers.IO) {+ runCatching { MyspotiRuntime.api.playlists.members(p.uri) }.getOrDefault(emptyList())+ }+ // Collaborative: each song shows who added it (the official app's small face on the row).+ val crew = members.value.associateBy { it.username }+ adders.value = if (crew.size < 2) emptyMap() else withContext(Dispatchers.IO) {+ runCatching {+ val out = HashMap<String, app.myspoti.api.PlaylistMember>()+ MyspotiRuntime.api.playlists.addedBy(p.uri).forEach { r ->+ val m = crew[r.username] ?: return@forEach+ if (r.rowUid.isNotBlank()) out["row:" + r.rowUid] = m+ out.putIfAbsent("song:" + r.trackUri.substringAfterLast(':'), m)+ }+ out+ }.getOrDefault(emptyMap())+ }+ // Collaborative yet not editable here: only an invitation link lets this account add songs.+ // Said on the page instead of leaving the user wondering where the + went.+ collabLocked.value = p.type == "playlist" && !p.isBlend && !editableContext.value && withContext(Dispatchers.IO) {+ runCatching { MyspotiRuntime.api.playlists.access(p.uri) == app.myspoti.api.PlaylistAccess.COLLABORATIVE }.getOrDefault(false)+ }}fun toggleContextSaved(p: ContextPageModel) {@@ -257,7 +356,20 @@ class ContextViewModel(fun dropTrack(song: SongsModel) {val k = key ?: returnval current = (_page.value as? Response.Success)?.data ?: return- val updated = Response.Success(current.copy(tracks = current.tracks.filterNot { it.id == song.id }))+ // The row, not the song: the same song twice in a playlist has the same id twice.+ val at = if (song.rowUid.isNotBlank()) current.tracks.indexOfFirst { it.rowUid == song.rowUid }+ else current.tracks.indexOfFirst { it.id == song.id }+ if (at < 0) return+ val updated = Response.Success(current.copy(tracks = current.tracks.toMutableList().apply { removeAt(at) }))+ _page.value = updated+ recent[k] = updated+ }++ /** A name or description just saved shows in the header at once; the page is read again behind it. */+ fun showDetails(name: String, description: String) {+ val k = key ?: return+ val current = (_page.value as? Response.Success)?.data ?: return+ val updated = Response.Success(current.copy(name = name, description = description))_page.value = updatedrecent[k] = updated}@@ -317,7 +429,7 @@ fun ContextScreen(navController: NavController, type: String, id: String) {}}-@OptIn(ExperimentalGlideComposeApi::class)+@OptIn(ExperimentalGlideComposeApi::class, androidx.compose.material3.ExperimentalMaterial3Api::class)@Composableprivate fun ContextContent(navController: NavController, vm: ContextViewModel, p: ContextPageModel) {val context = LocalContext.current@@ -343,6 +455,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pvar sort by remember(p.uri) { mutableStateOf(TrackOrder.load(ctx, p.uri)) }var askRemoveDownloads by remember { mutableStateOf(false) }var playlistMenu by remember { mutableStateOf(false) }+ var addingSongs by remember { mutableStateOf(false) }// A11: confirmations (and their Undo) float above the list, not inside a menu that closes.val snackbar = remember { androidx.compose.material3.SnackbarHostState() }val scope = androidx.compose.runtime.rememberCoroutineScope()@@ -352,7 +465,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pfun removeFromThisPlaylist(song: SongsModel) {val playlistId = p.uri.substringAfterLast(':')vm.dropTrack(song)- com.music.spotui.data.api.SpotifySync.removeTrackFromPlaylist(context, playlistId, song.spotifyTrackId) { ok ->+ com.music.spotui.data.api.SpotifySync.removeRowFromPlaylist(context, playlistId, song.spotifyTrackId, song.rowUid) { ok ->if (!ok) {vm.reload()android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()@@ -374,10 +487,13 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p}}+ if (addingSongs) com.music.spotui.ui.components.AddSongsScreen(p) { added -> addingSongs = false; if (added) vm.reload() }if (playlistMenu) com.music.spotui.ui.components.PlaylistOptionsSheet(page = p,+ onAddSongs = if (p.type == "playlist" && vm.editableContext.value && !p.isBlend) ({ addingSongs = true }) else null,onDismiss = { playlistMenu = false },onChanged = { vm.reload() },+ onEdited = { name, description -> vm.showDetails(name, description) },onDeleted = { navController.navigateUp() },onProfile = { navController.navigate(com.music.spotui.ui.navigation.profileRoute(it, p.ownerName)) },)@@ -423,27 +539,60 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pif (p.type == "liked" || p.type == "liked-artist") p.tracks.filter { SongPlayer.library["spotify:track:${it.spotifyTrackId}"] != false } else p.tracks}}- val rows by remember(p, find, sort) {+ // Unique and stable for a given list: a playlist can hold the same song twice (the id alone+ // is not unique) and the index changes at every sort (which would lose every item). Made with+ // the rows in one derived state: the list re-reads its rows outside composition (a like, a+ // search letter), and keys remembered apart from them could be one list behind (a crash).+ val shown by remember(p, find, sort) {derivedStateOf {val found = if (findable) all.filter { com.music.spotui.ui.components.matchesFind(find, it.title, it.singer, it.album) } else all- if (findable) sort.apply(found) else found- }- }- // Unique and stable for a given list: a playlist can hold the same song twice (the id alone- // is not unique) and the index changes at every sort (which would lose every item).- val keys = remember(rows) {- val seen = HashMap<String, Int>()- rows.map { s ->- val id = s.id.toString()- val n = (seen[id] ?: 0) + 1- seen[id] = n- if (n == 1) id else "$id#$n"+ val list = if (findable) sort.apply(found) else found+ val seen = HashMap<String, Int>()+ list to list.map { s ->+ val id = s.id.toString()+ val n = (seen[id] ?: 0) + 1+ seen[id] = n+ if (n == 1) id else "$id#$n"+ }}}+ val rows = shown.firstval listState = androidx.compose.foundation.lazy.rememberLazyListState()+ val pullState = androidx.compose.material3.pulltorefresh.rememberPullToRefreshState()+ val refreshing by vm.refreshing+ // The search field and the Blend line are folded away: the page opens on its songs. A pull+ // down at the top unfolds them in place (that pull does not refresh; the next one does), and+ // they fold again once the songs are scrolled past them, unless a search is typed.+ val hasExtras = (findable && all.isNotEmpty()) || p.isBlend+ var extrasShown by remember(p.uri) { mutableStateOf(false) }+ val revealPull = remember(p.uri) { ExtrasReveal() }+ revealPull.enabled = hasExtras && !extrasShown+ revealPull.onReveal = { extrasShown = true; com.music.spotui.di.Haptics.toggle(true) }+ // The search typed now, not the one when the page opened (always empty): read stale, the field+ // folded away under the user's fingers while typing, keyboard open (reported freezes and crashes).+ val findNow by androidx.compose.runtime.rememberUpdatedState(find)+ LaunchedEffect(p.uri, listState) {+ androidx.compose.runtime.snapshotFlow { listState.firstVisibleItemIndex }.collect { first ->+ if (first > 3 && findNow.isBlank()) extrasShown = false+ }+ }Box(Modifier.fillMaxSize()) {- LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {+ androidx.compose.material3.pulltorefresh.PullToRefreshBox(+ isRefreshing = refreshing,+ onRefresh = { vm.refresh() },+ state = pullState,+ modifier = Modifier.fillMaxSize(),+ // Below the status bar: the page's header runs under it.+ indicator = {+ androidx.compose.material3.pulltorefresh.PullToRefreshDefaults.Indicator(+ state = pullState, isRefreshing = refreshing,+ modifier = Modifier.align(Alignment.TopCenter).statusBarsPadding(),+ containerColor = Color(0xFF282828), color = SpotifyGreen,+ )+ },+ ) {+ LazyColumn(state = listState, modifier = Modifier.fillMaxSize().nestedScroll(revealPull)) {item {Column(modifier = Modifier@@ -483,7 +632,28 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pSpacer(Modifier.height(8.dp))Text(p.description, color = Color.White.copy(alpha = 0.7f), fontSize = 14.sp, maxLines = 3, overflow = TextOverflow.Ellipsis)}- if (p.ownerName.isNotBlank()) {+ val crew = vm.members.value+ if (crew.size > 1) {+ // Collaborative: everyone who adds to it, as the official app shows them.+ Spacer(Modifier.height(10.dp))+ var showMembers by remember { mutableStateOf(false) }+ if (showMembers) MembersSheet(crew, navController) { showMembers = false }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.pressable(0.96f) { showMembers = true }) {+ Box(Modifier.width((24 + 16 * (crew.size.coerceAtMost(4) - 1)).dp).height(24.dp)) {+ crew.take(4).forEachIndexed { n, m ->+ Box(Modifier.padding(start = (16 * n).dp).size(24.dp).clip(CircleShape).background(Color(0xFF121212)).padding(1.dp)) {+ com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 22.dp)+ }+ }+ }+ Spacer(Modifier.width(8.dp))+ Text(+ if (crew.size <= 2) crew.joinToString(", ") { it.name }+ else stringResource(R.string.playlist_members_more, crew.first().name, crew.size - 1),+ color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis,+ )+ }+ } else if (p.ownerName.isNotBlank()) {Spacer(Modifier.height(10.dp))Row(verticalAlignment = Alignment.CenterVertically,@@ -526,15 +696,17 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p.fillMaxWidth().padding(start = 16.dp, end = 16.dp, top = 12.dp, bottom = 8.dp)) {+ // Own playlist: "Add to this playlist" (search, suggestions), where the small cover was.+ if (p.type == "playlist" && vm.editableContext.value && !p.isBlend) {+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.size(36.dp).clip(CircleShape).background(Color.White.copy(alpha = 0.12f)).pressable(0.9f) { addingSongs = true },+ ) {+ Icon(Icons.Default.Add, contentDescription = stringResource(R.string.add_songs_title), tint = Color.White, modifier = Modifier.size(24.dp))+ }+ Spacer(Modifier.width(20.dp))+ }if (p.type != "liked") {- GlideImage(- transition = CrossFade,- model = p.coverUri,- contentDescription = "",- contentScale = ContentScale.Crop,- modifier = Modifier.size(width = 30.dp, height = 40.dp).clip(RoundedCornerShape(4.dp)),- )- Spacer(Modifier.width(24.dp))LikeButton(liked = SongPlayer.library[p.uri] ?: contextSaved, size = 28.dp) { vm.toggleContextSaved(p) }Spacer(Modifier.width(20.dp))}@@ -566,6 +738,11 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pIcon(Icons.Default.MoreVert, stringResource(R.string.content_description_context_menu), tint = Color.White.copy(alpha = 0.8f),modifier = Modifier.size(26.dp).pressable(0.9f) { playlistMenu = true })}+ // Sorting stays in reach in the header (the search field above the songs is folded).+ if (findable && all.isNotEmpty()) {+ Spacer(Modifier.width(16.dp))+ TrackSortButton(sort) { sort = it; TrackOrder.save(ctx, p.uri, it) }+ }Spacer(Modifier.weight(1f))val smart = SmartShuffle.on.value == p.uriBox {@@ -627,30 +804,52 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p}}// Liked Songs: a track unliked anywhere leaves the list right away.+ // A Blend: its taste-match card and its members, as on the official Blend page.+ if (vm.collabLocked.value && !vm.editableContext.value) item(key = "collab-locked") {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp).fillMaxWidth()+ .clip(RoundedCornerShape(10.dp)).background(Color.White.copy(alpha = 0.06f)).padding(12.dp),+ ) {+ Icon(Icons.Outlined.Group, contentDescription = null, tint = Color(0xFFB3B3B3), modifier = Modifier.size(20.dp))+ Text(stringResource(R.string.playlist_collab_locked, p.ownerName.ifBlank { stringResource(R.string.playlist_collab_owner) }),+ color = Color(0xFFB3B3B3), fontSize = 13.sp, modifier = Modifier.padding(start = 10.dp))+ }+ }+ if (p.isBlend) item(key = "blend") {+ androidx.compose.animation.AnimatedVisibility(extrasShown, enter = UnfoldIn, exit = FoldOut) {+ com.music.spotui.ui.components.BlendPanel(p.uri)+ }+ }if (findable && all.isNotEmpty()) item(key = "find") {- Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp)) {+ androidx.compose.animation.AnimatedVisibility(extrasShown || find.isNotBlank(), enter = UnfoldIn, exit = FoldOut) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 8.dp, bottom = 8.dp)) {com.music.spotui.ui.components.FindInListField(find, { find = it },stringResource(if (p.type == "liked") R.string.find_in_context_edit_text_liked_songs_hint else R.string.find_in_context_edit_text_playlist_hint),Modifier.weight(1f),)- TrackSortButton(sort) { sort = it; TrackOrder.save(ctx, p.uri, it) }+ }}}- if (rows.isEmpty() && find.isNotBlank()) item(key = "find-empty") {+ if (shown.first.isEmpty() && find.isNotBlank()) item(key = "find-empty") {com.music.spotui.ui.components.FindInListEmpty(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, find.trim()))}- itemsIndexed(rows, key = { i, _ -> keys[i] }) { _, song ->+ val (listed, keys) = shown+ itemsIndexed(listed, key = { i, _ -> keys[i] }) { _, song ->com.music.spotui.ui.components.SwipeToQueue(song) { TrackRow(song = song,showCover = p.type != "album",isCurrent = song.id == currentSongId,saved = SongPlayer.library["spotify:track:${song.spotifyTrackId}"] ?: ("spotify:track:${song.spotifyTrackId}" in saved),offline = com.music.spotui.data.offline.OfflineStore.statusOf(song.spotifyTrackId),+ addedBy = vm.adders.value.let { a -> a["row:" + song.rowUid] ?: a["song:" + song.spotifyTrackId] },onClick = { if (SmartShuffle.on.value == p.uri) vm.playSmart(p, song) else vm.play(p, song, sort) },onMore = { menuSong = song },) }}+ // "Recommended songs", as under an own playlist in the official apps (an empty one too).+ if (p.type == "playlist" && vm.editableContext.value && find.isBlank() && !p.isBlend) recommendedItems(vm, p, ctx, currentSongId)// Phone files added to this Spotify playlist on this phone (Spotify can't hold them).if (p.type == "playlist") {val playlistId = p.uri.substringAfterLast(":")@@ -667,6 +866,7 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pif (p.type == "album") item(key = "similar") { SimilarAlbums(navController, p.tracks.firstOrNull()?.spotifyTrackId.orEmpty(), p.uri) }item { Spacer(Modifier.height(com.music.spotui.ui.components.bottomBarsSpace())) }}+ }com.music.spotui.ui.components.FastScrollbar(listState, Modifier.align(Alignment.CenterEnd))// As in the official app: once the header has mostly scrolled away, a bar in the page's colour// fades in at the top with the back arrow and the name; the list no longer runs bare under the@@ -699,6 +899,38 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, pText(p.name, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis,textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = Modifier.weight(1f).padding(end = 56.dp))}+ // Opened from a collaborative-playlist invitation (…?pt=): the playlist is joined from here.+ val invite by com.music.spotui.data.api.InviteLinks.pending.collectAsState()+ var joining by remember { mutableStateOf(false) }+ val offered = invite?.takeIf { p.type == "playlist" && it.uri == p.uri && !vm.editableContext.value }+ if (offered != null) Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .padding(start = 16.dp, end = 16.dp, bottom = com.music.spotui.ui.components.bottomBarsSpace())+ .clip(RoundedCornerShape(12.dp))+ .background(Color(0xFF282828))+ .padding(start = 16.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),+ ) {+ Text(stringResource(R.string.playlist_invite_banner), color = Color.White, fontSize = 14.sp, modifier = Modifier.weight(1f).padding(end = 12.dp))+ androidx.compose.material3.Button(+ enabled = !joining,+ colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = SpotifyGreen, contentColor = Color.Black),+ onClick = {+ joining = true+ com.music.spotui.data.api.InviteLinks.join(context, offered, p) { ok ->+ joining = false+ if (ok) {+ vm.editableContext.value = true+ vm.contextSaved.value = true+ SongPlayer.library[p.uri] = true+ vm.reload()+ android.widget.Toast.makeText(context, context.getString(R.string.playlist_invite_joined), android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ },+ ) { Text(stringResource(R.string.playlist_invite_join), fontWeight = FontWeight.Bold) }+ }androidx.compose.material3.SnackbarHost(hostState = snackbar,modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = com.music.spotui.ui.components.bottomBarsSpace()),@@ -713,6 +945,118 @@ private fun ContextContent(navController: NavController, vm: ContextViewModel, p}}+private val UnfoldIn = androidx.compose.animation.expandVertically(androidx.compose.animation.core.tween(280, easing = androidx.compose.animation.core.FastOutSlowInEasing)) ++ androidx.compose.animation.fadeIn(androidx.compose.animation.core.tween(220, delayMillis = 60))+private val FoldOut = androidx.compose.animation.shrinkVertically(androidx.compose.animation.core.tween(220)) ++ androidx.compose.animation.fadeOut(androidx.compose.animation.core.tween(120))++/**+ * The pull that unfolds a page's folded parts (search, Blend line). It sits between the list and+ * the pull-to-refresh: a drag past the top goes here first, and the whole gesture is kept from+ * the refresh, so unfolding never also reloads the page.+ */+private class ExtrasReveal : androidx.compose.ui.input.nestedscroll.NestedScrollConnection {+ var enabled = false+ var onReveal: () -> Unit = {}+ /** This drag unfolded them: the rest of it is not a refresh pull. */+ private var swallowing = false++ override fun onPostScroll(consumed: androidx.compose.ui.geometry.Offset, available: androidx.compose.ui.geometry.Offset,+ source: androidx.compose.ui.input.nestedscroll.NestedScrollSource): androidx.compose.ui.geometry.Offset {+ if (source != androidx.compose.ui.input.nestedscroll.NestedScrollSource.UserInput || available.y <= 0f) return androidx.compose.ui.geometry.Offset.Zero+ if (enabled && !swallowing) { swallowing = true; onReveal() }+ return if (swallowing) available else androidx.compose.ui.geometry.Offset.Zero+ }++ override suspend fun onPreFling(available: androidx.compose.ui.unit.Velocity): androidx.compose.ui.unit.Velocity {+ if (!swallowing) return androidx.compose.ui.unit.Velocity.Zero+ swallowing = false+ return available+ }+}++private const val RECS_COUNT = 10++/** The suggestions under an own playlist: tap to listen, "+" to add, "Refresh" for others. */+private fun androidx.compose.foundation.lazy.LazyListScope.recommendedItems(vm: ContextViewModel, p: ContextPageModel, context: android.content.Context, currentSongId: Int) {+ item(key = "recs-title") {+ LaunchedEffect(p.uri) { vm.loadRecs(p) }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(16.dp, 28.dp, 8.dp, 4.dp)) {+ Column(Modifier.weight(1f)) {+ Text(stringResource(R.string.recommended_songs), color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold)+ Text(stringResource(if (p.tracks.isEmpty()) R.string.recommended_songs_from_name else R.string.recommended_songs_from_songs),+ color = Color(0xFFB3B3B3), fontSize = 13.sp)+ }+ androidx.compose.material3.TextButton(onClick = { vm.loadRecs(p, refresh = true) }) {+ Text(stringResource(R.string.recommended_songs_refresh), color = Color.White, fontWeight = FontWeight.Bold)+ }+ }+ }+ val recs = vm.recs.value+ if (recs == null) item(key = "recs-loading") { com.music.spotui.ui.components.SkeletonList(count = 3) }+ else items(recs, key = { "rec-" + it.spotifyTrackId }) { song ->+ RecommendedRow(+ song,+ isCurrent = song.id == currentSongId,+ onPlay = { SongPlayer.playSong(song.url, context) },+ onAdd = {+ vm.takeRec(p, song)+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, p.uri.substringAfterLast(':'), song.spotifyTrackId) { ok ->+ if (ok) vm.reload()+ else android.widget.Toast.makeText(context, context.getString(R.string.playlist_change_refused), android.widget.Toast.LENGTH_SHORT).show()+ }+ },+ modifier = Modifier.animateItem(),+ )+ }+}++@OptIn(ExperimentalGlideComposeApi::class)+@Composable+private fun RecommendedRow(song: SongsModel, isCurrent: Boolean, onPlay: () -> Unit, onAdd: () -> Unit, modifier: Modifier = Modifier) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = modifier.fillMaxWidth().clickable(onClick = onPlay).padding(start = 16.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),+ ) {+ GlideImage(model = song.coverUri, contentDescription = null, contentScale = androidx.compose.ui.layout.ContentScale.Crop,+ modifier = Modifier.size(48.dp).clip(RoundedCornerShape(4.dp)))+ Column(Modifier.weight(1f).padding(start = 12.dp, end = 8.dp)) {+ // The song playing is green, as in the playlist above.+ Text(song.title, color = if (isCurrent) SpotifyGreen else Color.White, fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(song.singer, color = Color(0xFFB3B3B3), fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ androidx.compose.material3.IconButton(onClick = onAdd) {+ Icon(androidx.compose.material.icons.Icons.Outlined.AddCircleOutline, contentDescription = stringResource(R.string.recommended_songs_add), tint = Color.White)+ }+ }+}++/** The people of a collaborative playlist: owner first, then collaborators; a tap opens a profile. */+@OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class)+@Composable+private fun MembersSheet(members: List<app.myspoti.api.PlaylistMember>, navController: NavController, onDismiss: () -> Unit) {+ androidx.compose.material3.ModalBottomSheet(onDismissRequest = onDismiss, containerColor = Color(0xFF282828)) {+ Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {+ Text(stringResource(R.string.playlist_members_title), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 12.dp))+ members.forEach { m ->+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.fillMaxWidth().clickable {+ onDismiss(); navController.navigate(com.music.spotui.ui.navigation.profileRoute(m.username, m.name))+ }.padding(horizontal = 20.dp, vertical = 10.dp),+ ) {+ com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 44.dp)+ Column(Modifier.weight(1f).padding(start = 14.dp)) {+ Text(m.name, color = Color.White, fontSize = 16.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(stringResource(if (m.isOwner) R.string.playlist_member_owner else R.string.playlist_member_collab), color = Color(0xFFB3B3B3), fontSize = 13.sp)+ }+ }+ }+ }+ }+}+/** How long a greyed track is given to start before the app says why it did not. */private const val UNAVAILABLE_CHECK_MS = 4_000L@@ -726,6 +1070,7 @@ private fun TrackRow(offline: com.music.spotui.data.offline.OfflineStatus?,onClick: () -> Unit,onMore: () -> Unit,+ addedBy: app.myspoti.api.PlaylistMember? = null,) {// A greyed row is still tried (see the click): the tap is followed by a check, not a refusal.val scope = androidx.compose.runtime.rememberCoroutineScope()@@ -786,6 +1131,11 @@ private fun TrackRow(Text(song.singer, color = Color.White.copy(alpha = 0.7f), fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}}+ // Collaborative playlist: who added this song.+ addedBy?.let { m ->+ com.music.spotui.ui.components.ProfileAvatar(m.imageUrl, m.name, 20.dp)+ Spacer(Modifier.width(14.dp))+ }if (saved) {Box(contentAlignment = Alignment.Center,@@ -828,6 +1178,37 @@ object SmartShuffle {/** The recommendations mixed into the playing list. */val recommended = androidx.compose.runtime.mutableStateOf<Set<String>>(emptySet())+ private val keepScope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)++ /** [trackId] was mixed in by smart shuffle: it is not in the playlist (yet). */+ fun isRecommendation(trackId: String): Boolean = on.value != null && trackId.isNotBlank() && trackId in recommended.value++ /**+ * The + of a recommendation, as in the official app: the song joins the playlist it was mixed+ * into (Liked Songs: it is liked), and is no longer marked as a recommendation.+ */+ fun keep(context: android.content.Context, song: SongsModel) {+ val list = on.value ?: return+ val id = song.spotifyTrackId+ recommended.value = recommended.value - id+ if (!list.startsWith("spotify:playlist:")) {+ if (SongPlayer.currentTrackId == id) SongPlayer.setLiked(true)+ else keepScope.launch { runCatching { MyspotiRuntime.api.library.add(listOf("spotify:track:$id")) } }+ android.widget.Toast.makeText(context, context.getString(R.string.snackbar_added_to_liked_songs), android.widget.Toast.LENGTH_SHORT).show()+ return+ }+ com.music.spotui.data.api.SpotifySync.addTrackToPlaylist(context, list.substringAfterLast(':'), id) { ok ->+ android.os.Handler(android.os.Looper.getMainLooper()).post {+ if (!ok) recommended.value = recommended.value + id+ val name = SongPlayer.knownContextName(list)+ android.widget.Toast.makeText(context,+ if (ok) context.getString(R.string.local_added_to, name.ifBlank { context.getString(R.string.smart_shuffle_title) })+ else context.getString(R.string.playlist_change_refused),+ android.widget.Toast.LENGTH_SHORT).show()+ }+ }+ }+/** Smart shuffle can play [contextUri]: a playlist or Liked Songs. */fun canPlay(contextUri: String): Boolean = contextUri.startsWith("spotify:playlist:") || contextUri.contains(":collection")@@ -945,11 +1326,10 @@ data class TrackOrder(val sort: TrackSort = TrackSort.CUSTOM, val reversed: Boolprivate fun TrackSortButton(sort: TrackOrder, onSort: (TrackOrder) -> Unit) {var open by remember { mutableStateOf(false) }Box {- androidx.compose.material3.IconButton(onClick = { open = true }) {- Icon(androidx.compose.material.icons.Icons.Default.SwapVert,- contentDescription = stringResource(R.string.filter_and_sort_sort_section_title),- tint = if (sort.isCustom) Color.White else SpotifyGreen)- }+ Icon(androidx.compose.material.icons.Icons.Default.SwapVert,+ contentDescription = stringResource(R.string.filter_and_sort_sort_section_title),+ tint = if (sort.isCustom) Color.White.copy(alpha = 0.8f) else SpotifyGreen,+ modifier = Modifier.size(26.dp).pressable(0.9f) { open = true })androidx.compose.material3.DropdownMenu(expanded = open, onDismissRequest = { open = false }, containerColor = Color(0xFF282828)) {Text(stringResource(R.string.filter_and_sort_sort_section_title), color = Color(0xFFB3B3B3), fontSize = 13.sp,modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.ktindex dcff5b9a..cd499ee0 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/DiscoverScreens.kt@@ -80,9 +80,7 @@ private fun ScreenHeader(title: String, navController: NavController) {}@Composable-private fun Loading() = Box(Modifier.fillMaxWidth().padding(40.dp), contentAlignment = Alignment.Center) {- CircularProgressIndicator(color = AppAccent)-}+private fun Loading() = com.music.spotui.ui.components.SkeletonList(count = 7)@Composableprivate fun SectionTitle(text: String) =diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.ktindex 97ceaf07..0f4ace7c 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/FollowListScreen.kt@@ -83,11 +83,7 @@ fun FollowListScreen(navController: NavController, userId: String, followers: Bo}}when {- list == null -> item {- Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {- CircularProgressIndicator(color = AppAccent)- }- }+ list == null -> item { com.music.spotui.ui.components.SkeletonList(count = 8, round = true) }list.isEmpty() -> item {Text(stringResource(R.string.profile_list_empty), color = Color(0xFFB3B3B3), fontSize = 15.sp,modifier = Modifier.padding(16.dp))diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.ktindex 349fc73c..f8bfbfe3 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/HomeScreen.kt@@ -451,11 +451,7 @@ private fun ProfileSheet(onOpen: (route: String) -> Unit = {}, onDismiss: () ->Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().clickable(enabled = myId != null) { myId?.let { onOpen(com.music.spotui.ui.navigation.profileRoute(it, name)) } }.padding(horizontal = 20.dp, vertical = 8.dp)) {- if (avatar != null) GlideImage(- transition = CrossFade,- model = avatar, contentDescription = null, contentScale = ContentScale.Crop,- modifier = Modifier.size(48.dp).clip(CircleShape),- )+ com.music.spotui.ui.components.ProfileAvatar(url = avatar, name = name, size = 48.dp)Text(name.ifBlank { stringResource(R.string.spotify_account) }, color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,modifier = Modifier.padding(start = 14.dp))if (com.music.spotui.data.api.SupportReminder.level != com.music.spotui.data.api.SupportReminder.Level.NONE)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.ktindex f166302e..acb9733a 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LibraryExtras.kt@@ -34,6 +34,9 @@ import androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.outlined.CreateNewFolderimport androidx.compose.material.icons.outlined.Deleteimport androidx.compose.material.icons.outlined.Edit+import androidx.compose.material.icons.outlined.Group+import androidx.compose.material.icons.outlined.Link+import androidx.compose.material.icons.outlined.Shareimport androidx.compose.material.icons.outlined.PhoneAndroidimport androidx.compose.material3.AlertDialogimport androidx.compose.material3.ExperimentalMaterial3Api@@ -45,6 +48,7 @@ import androidx.compose.material3.TextFieldimport androidx.compose.material3.TextFieldDefaultsimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsStateimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember@@ -71,6 +75,7 @@ import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApiimport com.bumptech.glide.integration.compose.CrossFadeimport com.bumptech.glide.integration.compose.GlideImageimport com.bumptech.glide.integration.compose.placeholder+import com.music.spotui.data.api.LibraryEditsimport com.music.spotui.data.api.LibraryFoldersimport com.music.spotui.data.api.Responseimport com.music.spotui.data.api.SpotifySync@@ -86,8 +91,11 @@ import com.music.spotui.ui.components.Loaderimport com.music.spotui.ui.components.SkeletonKindimport com.music.spotui.ui.components.pressableimport com.music.spotui.ui.navigation.localPlaylistRoute+import com.music.spotui.ui.navigation.playlistRoute+import com.music.spotui.ui.components.ProfileAvatarimport com.music.spotui.ui.theme.AppBackgroundimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.firstimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext@@ -146,17 +154,14 @@ fun LibraryCreateSheet(navController: NavController, onDismiss: () -> Unit, onLiwhen (asking) {"playlist" -> NameDialog(stringResource(R.string.create_playlist_content_description), context.getString(R.string.my_playlist),stringResource(R.string.create_playlist_create_button), onDismiss = onDismiss) { name ->- SpotifySync.createPlaylistWithTrack(context, name, "") { ok -> if (ok) onLibraryChanged() }+ // The row shows in the library at once; SpotifySync takes it back if Spotify refuses.+ SpotifySync.createPlaylistWithTrack(context, name, "")onDismiss()}"folder" -> NameDialog(stringResource(R.string.create_menu_item_folder_title), context.getString(R.string.create_folder_name_suggested_folder_name),stringResource(R.string.create_playlist_create_button), onDismiss = onDismiss) { name ->- scope.launch {- val uri = LibraryFolders.create(name)- if (uri != null) onLibraryChanged()- else Toast.makeText(context, context.getString(R.string.folder_create_failed), Toast.LENGTH_SHORT).show()- onDismiss()- }+ LibraryFolders.create(context, name)+ onDismiss()}"local" -> NameDialog(stringResource(R.string.local_playlist_new), context.getString(R.string.my_playlist),stringResource(R.string.create_playlist_create_button), onDismiss = onDismiss) { name ->@@ -164,9 +169,11 @@ fun LibraryCreateSheet(navController: NavController, onDismiss: () -> Unit, onLionDismiss()navController.navigate(localPlaylistRoute(p.id))}+ "blend" -> BlendSheet(navController, onDismiss)else -> ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {SheetRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.assisted_curation_search_playlist)) { asking = "playlist" }+ SheetRow(Icons.Outlined.Group, stringResource(R.string.blend_title), stringResource(R.string.blend_detail)) { asking = "blend" }SheetRow(Icons.Outlined.CreateNewFolder, stringResource(R.string.create_menu_item_folder_title)) { asking = "folder" }SheetRow(Icons.Outlined.PhoneAndroid, stringResource(R.string.local_playlist_new), stringResource(R.string.local_add_note)) { asking = "local" }}@@ -174,6 +181,152 @@ fun LibraryCreateSheet(navController: NavController, onDismiss: () -> Unit, onLi}}+/**+ * "Mix à plusieurs" (Spotify Blend): an invitation link to send, or one received to join with.+ * The Blend playlist only exists on Spotify once the friend has joined; then it is in the+ * library like any playlist.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+private fun BlendSheet(navController: NavController, onDismiss: () -> Unit) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val blends = app.myspoti.host.android.MyspotiRuntime.api.blends+ var joining by remember { mutableStateOf(false) }+ var busy by remember { mutableStateOf(false) }+ fun say(res: Int) = Toast.makeText(context, context.getString(res), Toast.LENGTH_SHORT).show()+ if (joining) NameDialog(stringResource(R.string.blend_join_title), "", stringResource(R.string.blend_join_button),+ onDismiss = { joining = false }) { link ->+ joining = false+ busy = true+ scope.launch {+ val opened = runCatching {+ val invitation = blends.invitation(link)+ when (invitation.state) {+ app.myspoti.api.BlendInvitationState.JOINABLE, app.myspoti.api.BlendInvitationState.UNKNOWN -> blends.join(link)+ app.myspoti.api.BlendInvitationState.JOINED -> invitation.playlist+ app.myspoti.api.BlendInvitationState.WAITING -> { say(R.string.blend_own_invite); null }+ app.myspoti.api.BlendInvitationState.FULL -> { say(R.string.blend_full); null }+ app.myspoti.api.BlendInvitationState.DELETED -> { say(R.string.blend_deleted); null }+ }+ }.onFailure {+ say(if (it is IllegalArgumentException) R.string.blend_bad_link else R.string.blend_failed)+ }.getOrNull()+ busy = false+ if (opened != null) { onDismiss(); navController.navigate(playlistRoute(opened.substringAfterLast(':'))) }+ }+ }+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {+ Text(stringResource(R.string.blend_title), color = Color.White, fontSize = 18.sp, fontWeight = FontWeight.Bold,+ modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 8.dp))+ if (busy) Text(stringResource(R.string.blend_working), color = Color(0xFFB3B3B3), fontSize = 14.sp, modifier = Modifier.padding(20.dp, 12.dp))+ else {+ SheetRow(Icons.Outlined.Share, stringResource(R.string.blend_invite)) {+ busy = true+ scope.launch {+ val link = runCatching { blends.invite().link }.getOrNull()+ busy = false+ if (link == null) return@launch say(R.string.blend_failed)+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).setType("text/plain")+ .putExtra(android.content.Intent.EXTRA_TEXT, context.getString(R.string.blend_invite_message, link))+ context.startActivity(android.content.Intent.createChooser(send, null).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))+ onDismiss()+ }+ }+ SheetRow(Icons.Outlined.Link, stringResource(R.string.blend_join)) { joining = true }+ }+ }+ }+}++/**+ * A Blend invitation link opened from outside (see InviteLinks.blend): who invites, and "Join".+ * Spotify's own words for the invitation's state are shown as they come (already translated).+ * An invitation already joined opens its playlist straight away; one of the account's own is+ * offered to be sent again.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun BlendInviteSheet(link: com.music.spotui.data.api.InviteLinks.BlendLink, navController: NavController, onDismiss: () -> Unit) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val api = app.myspoti.host.android.MyspotiRuntime.api+ var invitation by remember(link) { mutableStateOf<app.myspoti.api.BlendInvitation?>(null) }+ var failed by remember(link) { mutableStateOf(false) }+ var busy by remember(link) { mutableStateOf(false) }+ fun open(uri: String) { onDismiss(); navController.navigate(playlistRoute(uri.substringAfterLast(':'))) }+ LaunchedEffect(link) {+ api.ready.first { it }+ runCatching { api.blends.invitation(link.id) }+ .onSuccess { v ->+ if (v.state == app.myspoti.api.BlendInvitationState.JOINED && v.playlist != null) open(v.playlist!!)+ else invitation = v+ }+ .onFailure { failed = true }+ }+ ModalBottomSheet(onDismissRequest = onDismiss, containerColor = SheetColor) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth().navigationBarsPadding().padding(24.dp, 0.dp, 24.dp, 20.dp),+ ) {+ val v = invitation+ val inviter = v?.inviter+ val own = v?.state == app.myspoti.api.BlendInvitationState.WAITING+ val joinable = v?.state == app.myspoti.api.BlendInvitationState.JOINABLE || v?.state == app.myspoti.api.BlendInvitationState.UNKNOWN+ ProfileAvatar(inviter?.imageUrl, inviter?.name, 88.dp)+ Spacer(Modifier.height(16.dp))+ val title = when {+ failed -> stringResource(R.string.blend_failed)+ v == null -> stringResource(R.string.blend_title)+ joinable && inviter != null -> stringResource(R.string.blend_invited_by, inviter.name)+ else -> v.title ?: stringResource(R.string.blend_title)+ }+ Text(title, color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold, textAlign = androidx.compose.ui.text.style.TextAlign.Center)+ val detail = when {+ v == null && !failed -> stringResource(R.string.blend_working)+ v == null -> null+ joinable -> stringResource(R.string.blend_detail)+ else -> v.subtitle+ }+ if (detail != null) Text(detail, color = Color(0xFFB3B3B3), fontSize = 14.sp, textAlign = androidx.compose.ui.text.style.TextAlign.Center,+ modifier = Modifier.padding(top = 6.dp))+ Spacer(Modifier.height(24.dp))+ if (joinable) androidx.compose.material3.Button(+ enabled = !busy,+ onClick = {+ busy = true+ scope.launch {+ val uri = runCatching { api.blends.join(link.id) }.getOrNull()+ busy = false+ if (uri == null) Toast.makeText(context, context.getString(R.string.blend_failed), Toast.LENGTH_SHORT).show()+ else {+ com.music.spotui.data.api.Api.HomeCache.libraryRoot = null+ LibraryEdits.reloadSoon()+ open(uri)+ }+ }+ },+ colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = com.music.spotui.ui.theme.AppAccent, contentColor = Color.Black),+ modifier = Modifier.fillMaxWidth().height(48.dp),+ ) { Text(stringResource(if (busy) R.string.blend_working else R.string.blend_join_button), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ if (own) androidx.compose.material3.Button(+ onClick = {+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).setType("text/plain")+ .putExtra(android.content.Intent.EXTRA_TEXT, context.getString(R.string.blend_invite_message, "https://open.spotify.com/blend/taste-match/${link.id}"))+ context.startActivity(android.content.Intent.createChooser(send, null).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))+ onDismiss()+ },+ colors = androidx.compose.material3.ButtonDefaults.buttonColors(containerColor = Color.White, contentColor = Color.Black),+ modifier = Modifier.fillMaxWidth().height(48.dp),+ ) { Text(stringResource(R.string.blend_invite), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ TextButton(onClick = onDismiss, modifier = Modifier.padding(top = 4.dp)) {+ Text(stringResource(R.string.blend_later), color = Color.White)+ }+ }+ }+}+@Composableprivate fun PageHeader(title: String, subtitle: String?, navController: NavController, onMenu: (() -> Unit)?) {Row(@@ -200,19 +353,25 @@ private fun PageHeader(title: String, subtitle: String?, navController: NavContr@Composablefun FolderScreen(navController: NavController, uri: String, initialName: String) {val context = LocalContext.current- val scope = rememberCoroutineScope()var name by remember { mutableStateOf(initialName) }- var entries by remember { mutableStateOf<List<LibraryEntry>?>(null) }+ // The folder as Spotify gave it; [entries] is that with the changes Spotify has not caught up with.+ var server by remember { mutableStateOf<List<LibraryEntry>?>(null) }+ val edits by com.music.spotui.data.api.LibraryEdits.version.collectAsState()+ val entries = remember(server, edits) { server?.let { com.music.spotui.data.api.LibraryEdits.applyTo(uri, it) } }var menu by remember { mutableStateOf(false) }var renaming by remember { mutableStateOf(false) }var newPlaylist by remember { mutableStateOf(false) }var deletingFolder by remember { mutableStateOf(false) }var generation by remember { mutableStateOf(0) }+ var refreshing by remember { mutableStateOf(false) }LaunchedEffect(uri, generation) {withContext(Dispatchers.IO) {- Graph.repository.provideLibraryFolder(uri).collect { r -> if (r is Response.Success) entries = r.data else if (r is Response.Error && entries == null) entries = emptyList() }+ Graph.repository.provideLibraryFolder(uri).collect { r -> if (r is Response.Success) server = r.data else if (r is Response.Error && server == null) server = emptyList() }}+ refreshing = false}+ // A change just written: the folder is read again once Spotify's list has had time to catch up.+ LaunchedEffect(uri) { com.music.spotui.data.api.LibraryEdits.reloads.collect { generation++ } }if (menu) ModalBottomSheet(onDismissRequest = { menu = false }, containerColor = SheetColor) {Column(Modifier.navigationBarsPadding().padding(bottom = 12.dp)) {SheetRow(Icons.AutoMirrored.Filled.PlaylistAdd, stringResource(R.string.add_to_playlist_new_playlist_button_text)) { menu = false; newPlaylist = true }@@ -227,7 +386,9 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)confirmButton = {androidx.compose.material3.TextButton(onClick = {deletingFolder = false- scope.launch { if (LibraryFolders.delete(uri)) navController.navigateUp() }+ // The folder is gone from the library at once; a refusal brings it back.+ LibraryFolders.delete(context, uri)+ navController.navigateUp()}) { Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C)) }},dismissButton = { androidx.compose.material3.TextButton(onClick = { deletingFolder = false }) { Text(stringResource(R.string.cancel), color = Color.White) } },@@ -236,17 +397,14 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)if (newPlaylist) NameDialog(stringResource(R.string.create_playlist_content_description), context.getString(R.string.my_playlist),stringResource(R.string.create_playlist_create_button), onDismiss = { newPlaylist = false }) { playlistName ->newPlaylist = false- SpotifySync.createPlaylistWithTrack(context, playlistName, "", folderUri = uri) { ok ->- scope.launch {- if (ok) generation++- else Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()- }- }+ SpotifySync.createPlaylistWithTrack(context, playlistName, "", folderUri = uri)}if (renaming) NameDialog(stringResource(R.string.context_menu_rename_folder), name, stringResource(R.string.local_rename),onDismiss = { renaming = false }) { newName ->renaming = false- scope.launch { if (LibraryFolders.rename(uri, newName)) name = newName }+ val before = name+ name = newName+ LibraryFolders.rename(context, uri, newName) { ok -> if (!ok) name = before }}Column(Modifier.fillMaxSize().background(AppBackground)) {val n = entries?.size@@ -256,7 +414,11 @@ fun FolderScreen(navController: NavController, uri: String, initialName: String)else -> {com.music.spotui.data.local.LibraryOrder.versionval arranged = com.music.spotui.data.local.LibraryOrder.run { arrange(list, sort, custom(uri), 0) }- SumUpLibraryScreen(PaddingValues(0.dp), arranged, emptyList(), navController, reorderLevel = uri, onChanged = { generation++ })+ androidx.compose.material3.pulltorefresh.PullToRefreshBox(+ isRefreshing = refreshing, onRefresh = { refreshing = true; generation++ }, modifier = Modifier.fillMaxSize(),+ ) {+ SumUpLibraryScreen(PaddingValues(0.dp), arranged, emptyList(), navController, reorderLevel = uri, onChanged = { generation++ })+ }}}}@@ -419,19 +581,19 @@ private fun PickRow(name: String, detail: String, cover: String?, onClick: () ->/*** A library row's ⋯ menu: pin it at the top, move a playlist or folder into another folder- * (or back to the top level), delete a folder. [onChanged] reloads the list.+ * (or back to the top level), delete a folder. Each shows in the list at once ([LibraryEdits]),+ * which reads itself again when Spotify has had time to catch up; [onChanged] is kept for callers.*/@OptIn(ExperimentalMaterial3Api::class)@Composablefun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -> Unit) {val context = LocalContext.current- val scope = rememberCoroutineScope()var moving by remember { mutableStateOf(false) }var deleting by remember { mutableStateOf(false) }- fun act(block: suspend () -> Unit) = scope.launch {- val ok = runCatching { block() }.isSuccess- if (ok) { LibraryFolders.changed(); onChanged() }- else Toast.makeText(context, context.getString(R.string.playlist_change_refused), Toast.LENGTH_SHORT).show()+ // The change shows in the list at once and is written in the app's own scope (the sheet is+ // closed by then); a refusal puts the list back and says so.+ fun act(edit: LibraryEdits.Edit, block: suspend () -> Unit) {+ LibraryEdits.run(context, edit, write = { block(); LibraryFolders.changed() })onDismiss()}val api = app.myspoti.host.android.MyspotiRuntime.api@@ -441,7 +603,7 @@ fun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -modifier = Modifier.padding(20.dp, 0.dp, 20.dp, 8.dp))if (!moving) {SheetRow(Icons.Outlined.PushPin, stringResource(if (entry.pinned) R.string.library_unpin else R.string.library_pin)) {- act { if (entry.pinned) api.library.unpin(entry.uri) else api.library.pin(entry.uri) }+ act(LibraryEdits.Pin(entry.uri, !entry.pinned)) { if (entry.pinned) api.library.unpin(entry.uri) else api.library.pin(entry.uri) }}if (entry.isPlaylist || entry.isFolder) SheetRow(Icons.Outlined.DriveFileMove, stringResource(R.string.library_move_to_folder)) { moving = true }if (entry.isFolder) SheetRow(Icons.Outlined.Delete, stringResource(R.string.folder_delete)) { deleting = true }@@ -450,9 +612,9 @@ fun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -value = runCatching { api.library.items(folderUri = null, limit = 200).items.filter { it.kind == app.myspoti.api.MediaKind.FOLDER && it.uri != entry.uri } }.getOrDefault(emptyList())}- SheetRow(Icons.Outlined.Home, stringResource(R.string.library_top_level)) { act { api.library.moveToFolder(entry.uri, null) } }+ SheetRow(Icons.Outlined.Home, stringResource(R.string.library_top_level)) { act(LibraryEdits.Move(entry, null)) { api.library.moveToFolder(entry.uri, null) } }folders?.forEach { f ->- SheetRow(Icons.Outlined.Folder, f.name) { act { api.library.moveToFolder(entry.uri, f.uri) } }+ SheetRow(Icons.Outlined.Folder, f.name) { act(LibraryEdits.Move(entry, f.uri)) { api.library.moveToFolder(entry.uri, f.uri) } }}}}@@ -462,7 +624,7 @@ fun LibraryItemSheet(entry: LibraryEntry, onDismiss: () -> Unit, onChanged: () -containerColor = SheetColor,text = { Text(stringResource(R.string.folder_delete_confirm, entry.name), color = Color.White) },confirmButton = {- androidx.compose.material3.TextButton(onClick = { deleting = false; act { api.library.deleteFolder(entry.uri) } }) {+ androidx.compose.material3.TextButton(onClick = { deleting = false; act(LibraryEdits.Remove(entry.uri)) { api.library.deleteFolder(entry.uri) } }) {Text(stringResource(R.string.actions_picker_delete), color = Color(0xFFF15E6C))}},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 f5c89cb8..ff6b7172 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@@ -83,6 +83,7 @@ import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApiimport com.bumptech.glide.integration.compose.CrossFadeimport com.bumptech.glide.integration.compose.GlideImageimport com.music.spotui.data.api.Api+import com.music.spotui.data.api.LibraryEditsimport com.music.spotui.data.api.Responseimport com.music.spotui.data.entity.AccountModelimport app.myspoti.engine.R@@ -112,7 +113,7 @@ fun LibraryScreen(navController: NavController) {androidx.compose.runtime.LaunchedEffect((entries as? Response.Success)?.data?.take(8)?.map { it.spotifyId }) {val top = (entries as? Response.Success)?.data.orEmpty().take(8).mapNotNull { e ->when {- e.isFolder || e.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> null+ e.isFolder || LibraryEdits.isPending(e.spotifyId) || e.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> nulle.spotifyId in setOf(Api.HomeCache.LOCAL_FILES_ID, Api.HomeCache.DOWNLOADS_ID, Api.HomeCache.EPISODES_ID) -> nulle.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> "liked" to ""e.isPlaylist -> "playlist" to e.spotifyId@@ -273,10 +274,15 @@ fun LibraryScreen(navController: NavController) {}val followedArtists by libraryViewModel.followedArtists.collectAsState()+ val refreshing by libraryViewModel.refreshing.collectAsState()when (entries) {is Response.Loading -> LibrarySkeleton(PaddingValues(0.dp))// Offline / error: the pinned folders (Local Files, Downloaded) stay reachable.- else -> Box {+ else -> androidx.compose.material3.pulltorefresh.PullToRefreshBox(+ isRefreshing = refreshing,+ onRefresh = { libraryViewModel.refresh() },+ modifier = Modifier.fillMaxSize(),+ ) {val localName = stringResource(R.string.local_files_title)val downloadsName = stringResource(R.string.collection_downloaded)val localSubtitle = stringResource(R.string.assisted_curation_search_playlist) + " • " + stringResource(R.string.local_playlist_subtitle)@@ -492,7 +498,7 @@ fun SumUpLibraryScreen(Text(text = entry.subtitle, color = Color.Gray, fontSize = 12.sp, fontWeight = FontWeight.Medium, maxLines = 1, overflow = TextOverflow.Ellipsis)}}- if (entry.uri.isNotBlank()) Icon(Icons.Default.MoreVert, stringResource(R.string.content_description_context_menu),+ if (entry.uri.isNotBlank() && !LibraryEdits.isPending(entry.spotifyId)) Icon(Icons.Default.MoreVert, stringResource(R.string.content_description_context_menu),tint = Color(0xFFB3B3B3), modifier = Modifier.size(36.dp).clip(CircleShape).clickable { itemMenu = entry }.padding(6.dp))}}@@ -555,6 +561,7 @@ fun LibraryEntryCover(entry: LibraryEntry, modifier: Modifier) {const val LOCAL_PLAYLIST_PREFIX = "local-playlist:"private fun prefetchLibraryEntry(entry: LibraryEntry) = when {+ LibraryEdits.isPending(entry.spotifyId) -> Unitentry.isFolder || entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX) -> Unitentry.spotifyId == Api.HomeCache.LOCAL_FILES_ID || entry.spotifyId == Api.HomeCache.DOWNLOADS_ID || entry.spotifyId == Api.HomeCache.EPISODES_ID -> Unitentry.spotifyId == Api.HomeCache.LIKED_SONGS_ID -> ContextViewModel.prefetch("liked", "")@@ -563,6 +570,8 @@ private fun prefetchLibraryEntry(entry: LibraryEntry) = when {}private fun openLibraryEntry(entry: LibraryEntry, navController: NavController) {+ // A playlist or folder Spotify is still creating has no page yet.+ if (LibraryEdits.isPending(entry.spotifyId)) returnif (entry.isFolder) navController.navigate(folderRoute(entry.folderUri, entry.name))else if (entry.spotifyId.startsWith(LOCAL_PLAYLIST_PREFIX)) navController.navigate(localPlaylistRoute(entry.spotifyId.removePrefix(LOCAL_PLAYLIST_PREFIX)))else if (entry.spotifyId == Api.HomeCache.DOWNLOADS_ID) navController.navigate(Routes.Downloads.route)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.ktindex 0ee5fc47..3dd53068 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/LyricsScreen.kt@@ -7,6 +7,9 @@ import android.content.Contextimport android.content.Intentimport androidx.compose.animation.AnimatedVisibilityimport androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.EaseOut+import androidx.compose.animation.core.FastOutSlowInEasingimport androidx.compose.animation.core.tweenimport androidx.compose.animation.expandVerticallyimport androidx.compose.animation.fadeIn@@ -15,6 +18,7 @@ import androidx.compose.animation.shrinkVerticallyimport androidx.compose.foundation.Canvasimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.clickable+import androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.gestures.Orientationimport androidx.compose.foundation.gestures.detectTapGesturesimport androidx.compose.foundation.gestures.draggable@@ -47,6 +51,7 @@ import androidx.compose.material.icons.filled.Checkimport androidx.compose.material.icons.filled.KeyboardArrowDownimport androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.filled.OpenInFull+import androidx.compose.material.icons.outlined.Lightbulbimport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.DropdownMenuimport androidx.compose.material3.DropdownMenuItem@@ -64,6 +69,19 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.drawBehind+import com.music.spotui.data.entity.LyricWord+import androidx.compose.ui.draw.drawWithContent+import androidx.compose.ui.graphics.drawscope.clipPath+import androidx.compose.ui.graphics.Outline+import androidx.compose.ui.graphics.Shape+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.geometry.RoundRect+import androidx.compose.ui.layout.LayoutCoordinates+import androidx.compose.ui.layout.onGloballyPositioned+import androidx.compose.ui.unit.Density+import androidx.compose.ui.unit.LayoutDirectionimport androidx.compose.ui.geometry.CornerRadiusimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.geometry.Size@@ -108,7 +126,18 @@ import java.util.Localeprivate data class LyricsPalette(val background: Color, val text: Color, val highlight: Color)private fun paletteFor(lyrics: Lyrics?, accent: Color): LyricsPalette {- lyrics?.colors?.let { return LyricsPalette(Color(it.background), Color(it.text), Color(it.highlight)) }+ lyrics?.colors?.let { c ->+ // Spotify's colours for the song, with the sung white kept readable: on some songs the+ // background is light enough for white words to fade into it (reported on one song,+ // fine on another). The background is darkened only as much as that takes.+ val hi = Color(c.highlight)+ var bg = Color(c.background)+ var step = 0+ while (contrast(hi, bg) < MIN_CONTRAST && step < 8) { bg = lerp(bg, if (hi.luminance() > 0.5f) Color.Black else Color.White, 0.12f); step++ }+ // Upcoming lines (often black in Spotify's colours) stay readable on that background too.+ val text = Color(c.text).let { t -> if (contrast(t.copy(alpha = 1f), bg) < 1.8f) hi.copy(alpha = 0.55f) else t }+ return LyricsPalette(bg, text, hi)+ }// No Spotify colours (fallback source): the artwork colour, like Spotify's own fallback.val bg = lerp(accent, Color.Black, 0.15f)// B23: upcoming lines were black at 55 % — invisible on a dark (AMOLED) card. On a dark@@ -118,12 +147,22 @@ private fun paletteFor(lyrics: Lyrics?, accent: Color): LyricsPalette {return LyricsPalette(bg, text, Color.White)}+/** WCAG contrast ratio of two colours (1 = the same, 21 = black on white). */+private fun contrast(a: Color, b: Color): Float {+ val la = a.luminance(); val lb = b.luminance()+ return (maxOf(la, lb) + 0.05f) / (minOf(la, lb) + 0.05f)+}++/** What the sung (and karaoke) words need against the background to read at a glance. */+private const val MIN_CONTRAST = 3.2f+/** Playback position, re-read on every frame while playing (smooth word highlight). */@Composableprivate fun rememberPosition(running: Boolean): () -> Long {val frame = rememberFrameClock(running, fps = 30)return remember(frame) {- { frame.value; SongPlayer.getCurrentPosition().coerceAtLeast(0L) }+ // What is heard: Bluetooth plays it a little later than the player is.+ { frame.value; (SongPlayer.getCurrentPosition() - com.music.spotui.di.OutputLag.ms()).coerceAtLeast(0L) }}}@@ -140,6 +179,19 @@ private fun activeIndexFor(lyrics: Lyrics, positionMs: Long): Int {return found}+/**+ * How many characters of a word-timed line are lit at [p] (ms): each word lights up whole the+ * moment it is sung (asked for instead of a fill sliding through the words).+ */+private fun sungChars(words: List<LyricWord>, starts: List<Int>, p: Long): Float {+ var out = 0f+ for (i in words.indices) {+ if (p < words[i].startMs) break+ out = (starts[i] + words[i].text.length).toFloat()+ }+ return out+}+/** Seek to a tapped synced line and make sure we're playing. */private fun jumpTo(timeMs: Long) {com.music.spotui.di.Haptics.click()@@ -178,8 +230,12 @@ private fun AutoFollow(listState: LazyListState, activeIndex: Int, offsetPx: Intif (it is DragInteraction.Start || it is DragInteraction.Stop) userScrollAt = System.currentTimeMillis()}}+ // The first placement is instant: the screen opens (container transform) already on the+ // current line instead of scrolling there from the top while it grows.+ var placed by remember { mutableStateOf(false) }LaunchedEffect(activeIndex, enabled) {if (!enabled || activeIndex < 0) return@LaunchedEffect+ if (!placed) { placed = true; listState.scrollToItem(activeIndex, -offsetPx); return@LaunchedEffect }val wait = 3000 - (System.currentTimeMillis() - userScrollAt)if (wait > 0) delay(wait)listState.animateScrollToItem(activeIndex, -offsetPx)@@ -199,37 +255,80 @@ private fun LyricLineText(position: () -> Long,translation: String?,onTap: (() -> Unit)?,+ modifier: Modifier = Modifier,+ annotated: Boolean = false,+ onHold: (() -> Unit)? = null,) {val target = when (state) {1 -> palette.textelse -> palette.highlight}val color by animateColorAsState(target, tween(220), label = "lyricColor")- val modifier = Modifier+ val lineModifier = modifier.fillMaxWidth().then(- if (onTap != null) Modifier.clickable(+ if (onTap != null || onHold != null) Modifier.combinedClickable(interactionSource = remember { MutableInteractionSource() },indication = null,- ) { onTap() } else Modifier+ onLongClick = onHold,+ onClick = { onTap?.invoke() },+ ) else Modifier)- Column(modifier) {+ // Explained by Genius: a light dotted line under each row of the text.+ var layout by remember { mutableStateOf<androidx.compose.ui.text.TextLayoutResult?>(null) }+ val underline = if (!annotated) Modifier else Modifier.drawBehind {+ val t = layout ?: return@drawBehind+ val dot = 2.dp.toPx()+ val effect = androidx.compose.ui.graphics.PathEffect.dashPathEffect(floatArrayOf(0.01f, dot * 2.5f))+ for (r in 0 until t.lineCount) {+ val y = t.getLineBaseline(r) + 5.dp.toPx()+ drawLine(color.copy(alpha = color.alpha * 0.55f), androidx.compose.ui.geometry.Offset(t.getLineLeft(r), y),+ androidx.compose.ui.geometry.Offset(t.getLineRight(r), y), strokeWidth = dot, cap = androidx.compose.ui.graphics.StrokeCap.Round, pathEffect = effect)+ }+ }+ Column(lineModifier) {val words = line.wordsif (state == 0 && words != null) {- // Only this line follows the clock: count of words already sung.- val sung by remember(line) {- derivedStateOf { val p = position(); words.count { it.startMs <= p } }+ // Karaoke: each word goes straight from the upcoming colour to white as it is sung (drawn+ // on each frame, the line is not recomposed). Words in another colour were hard to tell apart.+ val shown = remember(line) { words.joinToString("") { it.text }.trimEnd() }+ val starts = remember(line) { var c = 0; words.map { w -> c.also { c += w.text.length } } }+ var fill by remember { mutableStateOf<androidx.compose.ui.text.TextLayoutResult?>(null) }+ Box {+ Text(+ text = shown,+ // The words to come keep the colour of the lines to come; sung, they turn white.+ color = palette.text,+ fontSize = fontSize,+ lineHeight = fontSize * 1.25f,+ fontWeight = FontWeight.Bold,+ onTextLayout = { layout = it },+ modifier = underline,+ )+ Text(+ text = shown,+ color = palette.highlight,+ fontSize = fontSize,+ lineHeight = fontSize * 1.25f,+ fontWeight = FontWeight.Bold,+ onTextLayout = { fill = it },+ modifier = Modifier.drawWithContent {+ val l = fill ?: return@drawWithContent+ val off = sungChars(words, starts, position()).coerceAtMost(shown.length.toFloat())+ if (off <= 0f) return@drawWithContent+ if (off >= shown.length) { drawContent(); return@drawWithContent }+ val whole = off.toInt()+ val row = l.getLineForOffset(whole)+ val x0 = l.getHorizontalPosition(whole, true)+ val x1 = if (l.getLineForOffset(whole + 1) == row) l.getHorizontalPosition(whole + 1, true) else l.getLineRight(row)+ val x = x0 + (x1 - x0) * (off - whole)+ val path = androidx.compose.ui.graphics.Path()+ for (r in 0 until row) path.addRect(androidx.compose.ui.geometry.Rect(0f, l.getLineTop(r), size.width, l.getLineBottom(r)))+ path.addRect(androidx.compose.ui.geometry.Rect(0f, l.getLineTop(row), x, l.getLineBottom(row)))+ clipPath(path) { [email protected]() }+ },+ )}- Text(- text = buildAnnotatedString {- words.forEachIndexed { i, w ->- withStyle(SpanStyle(color = if (i < sung) palette.highlight else palette.text)) { append(w.text) }- }- },- fontSize = fontSize,- lineHeight = fontSize * 1.25f,- fontWeight = FontWeight.Bold,- )} else {Text(text = line.text,@@ -237,6 +336,8 @@ private fun LyricLineText(fontSize = fontSize,lineHeight = fontSize * 1.25f,fontWeight = FontWeight.Bold,+ onTextLayout = { layout = it },+ modifier = underline,)}AnimatedVisibility(@@ -262,7 +363,18 @@ private fun lineState(lyrics: Lyrics, index: Int, active: Int): Int = when {else -> 1}-/** Full-screen lyrics (Spotify's "Lyrics" view). */+/**+ * Fade + small rise of one part of the screen while the container settles. [reveal] is the+ * open progress (0..1), read in the draw phase only: nothing recomposes per frame.+ */+private fun Modifier.revealIn(reveal: (() -> Float)?, start: Float, riseDp: Float, span: Float = 0.3f): Modifier =+ if (reveal == null) this else graphicsLayer {+ val a = ((reveal() - start) / span).coerceIn(0f, 1f)+ alpha = a+ translationY = (1f - a) * riseDp.dp.toPx()+ }++/** Full-screen lyrics (Spotify's "Lyrics" view). [reveal] drives the staggered entrance, null = all shown. */@Composablefun LyricsScreen(title: String,@@ -270,6 +382,7 @@ fun LyricsScreen(album: String,accentColor: Color,onClose: () -> Unit,+ reveal: (() -> Float)? = null,) {val context = LocalContext.currentval vm: LyricsViewModel = viewModel()@@ -281,11 +394,27 @@ fun LyricsScreen(val position = rememberPosition(playing)val targetLanguage = getLyricTranslateLang(context).ifBlank { Locale.getDefault().language.ifBlank { "en" } }var menu by remember { mutableStateOf(false) }+ // What the song means, from Genius: asked once the lyrics are there; the button shows only when it says something.+ // Looked up when the song started (App.kt): here at once, and still here on coming back.+ val lang = com.music.spotui.ui.components.readerLanguage()+ val trackId = SongPlayer.nowPlaying.value.uri.substringAfterLast(':')+ val meaning = com.music.spotui.data.api.GeniusMeaning.current.value?.takeIf { it.first == trackId }?.second+ var meaningOpen by remember { mutableStateOf(false) }+ var noteOpen by remember { mutableStateOf<Int?>(null) }+ val haptics = androidx.compose.ui.platform.LocalHapticFeedback.current+ val hintPrefs = remember { context.getSharedPreferences("lyrics", android.content.Context.MODE_PRIVATE) }+ var hintSeen by remember { mutableStateOf(hintPrefs.getBoolean("genius_hold_hint_seen", false)) }+ LaunchedEffect(trackId, title, artist) {+ // Opened before the look-up began (or it failed): asked now.+ if (meaning == null) com.music.spotui.data.api.GeniusMeaning.prefetch(trackId, title, artist, lang)+ }Column(modifier = Modifier.fillMaxSize()- .background(bg)+ // The background comes in over the first instants so the card's own lines+ // dissolve under it instead of vanishing on the first frame.+ .drawBehind { drawRect(bg, alpha = if (reveal == null) 1f else (reveal() / 0.08f).coerceIn(0f, 1f)) }.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null, onClick = {}).statusBarsPadding().navigationBarsPadding(),@@ -293,7 +422,7 @@ fun LyricsScreen(// ── Header: close, title / artist, more ──Row(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().height(64.dp).padding(horizontal = 4.dp),+ modifier = Modifier.fillMaxWidth().height(64.dp).padding(horizontal = 4.dp).revealIn(reveal, 0.3f, 8f),) {Box(contentAlignment = Alignment.Center,@@ -307,6 +436,17 @@ fun LyricsScreen(Text(title, color = palette.highlight, fontSize = 14.sp, fontWeight = FontWeight.Bold, maxLines = 1, overflow = TextOverflow.Ellipsis)Text(artist, color = palette.highlight.copy(alpha = 0.75f), fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis)}+ meaning?.takeIf { !it.about.isNullOrBlank() }?.let { m ->+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier.size(48.dp).clickable(+ interactionSource = remember { MutableInteractionSource() }, indication = null,+ ) { meaningOpen = true },+ ) {+ Icon(Icons.Outlined.Lightbulb, contentDescription = stringResource(R.string.lyrics_meaning_title), tint = palette.highlight)+ }+ if (meaningOpen) com.music.spotui.ui.components.AboutSheet(m, palette.background) { meaningOpen = false }+ }Box {Box(contentAlignment = Alignment.Center,@@ -329,8 +469,8 @@ fun LyricsScreen(when (state) {is LyricsViewModel.State.Loading ->- Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {- CircularProgressIndicator(color = palette.highlight)+ Box(Modifier.weight(1f).fillMaxWidth()) {+ com.music.spotui.ui.components.SkeletonLyrics(palette.highlight)}is LyricsViewModel.State.NotFound ->Box(Modifier.weight(1f).fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {@@ -338,10 +478,26 @@ fun LyricsScreen(}is LyricsViewModel.State.Loaded -> {val l = state.lyrics+ // Lines Genius explains: lightly underlined, held to read the explanation.+ val notes = remember(l, meaning) { meaning?.let { m -> com.music.spotui.ui.components.notesByLine(m, l.lines.map { it.text }) }.orEmpty() }+ val m = meaning+ noteOpen?.let { n -> if (m != null) com.music.spotui.ui.components.NoteSheet(m, n, palette.background) { noteOpen = null } }// Translation is requested by onTranslate; do not upload lyrics on screen entry.val active by remember(l) { derivedStateOf { activeIndexFor(l, position()) } }+ // Other lyrics for the same song (Spotify's lines, then the word-timed ones; or the+ // setting changed): the new ones fade in over the old, already on the line being+ // sung, instead of the list jumping.+ androidx.compose.animation.Crossfade(+ targetState = l, animationSpec = tween(450), label = "lyricsSwap",+ modifier = Modifier.weight(1f).fillMaxWidth(),+ ) { l ->+ val active by remember(l) { derivedStateOf { activeIndexFor(l, position()) } }+ val notes = remember(l, meaning) { meaning?.let { m -> com.music.spotui.ui.components.notesByLine(m, l.lines.map { it.text }) }.orEmpty() }val listState = rememberLazyListState()- BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) {+ // Lines near the current one rise in one after the other, the first just+ // above it; the rest of the screen's lines have no visible entrance.+ val staggerBase = remember(l) { (active - 4).coerceAtLeast(0) }+ BoxWithConstraints(Modifier.fillMaxSize()) {val offsetPx = with(LocalDensity.current) { (maxHeight * 0.28f).roundToPx() }AutoFollow(listState, active, offsetPx, enabled = l.synced)LazyColumn(@@ -350,6 +506,13 @@ fun LyricsScreen(contentPadding = PaddingValues(24.dp, 8.dp, 24.dp, 48.dp),verticalArrangement = Arrangement.spacedBy(14.dp),) {+ if (notes.isNotEmpty() && !hintSeen) item(key = "genius-hint") {+ Text(+ stringResource(R.string.lyrics_meaning_hint),+ color = palette.highlight.copy(alpha = 0.8f), fontSize = 13.sp,+ modifier = Modifier.padding(bottom = 8.dp),+ )+ }if (!l.synced) item {Text(stringResource(R.string.lyrics_fullscreen_unsynced),@@ -367,6 +530,13 @@ fun LyricsScreen(position = position,translation = if (state.showTranslation) state.translations?.getOrNull(i) else null,onTap = if (l.synced) ({ jumpTo(line.timeMs) }) else null,+ annotated = i in notes,+ onHold = notes[i]?.let { n -> {+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)+ noteOpen = n+ if (!hintSeen) { hintSeen = true; hintPrefs.edit().putBoolean("genius_hold_hint_seen", true).apply() }+ } },+ modifier = Modifier.revealIn(reveal, 0.35f + 0.045f * (i - staggerBase).coerceIn(0, 8), 22f),)}l.provider?.let { p ->@@ -381,6 +551,7 @@ fun LyricsScreen(}}}+ }val sameLanguage = state.sourceLanguage?.substringBefore('-')?.equals(targetLanguage.substringBefore('-'), ignoreCase = true) == trueLyricsControls(@@ -391,6 +562,7 @@ fun LyricsScreen(translating = state.translating && state.translationRequested,onTranslate = { vm.toggleTranslation(targetLanguage) },onShare = { shareLyrics(context, title, artist, l.lines.getOrNull(active)?.text) },+ modifier = Modifier.revealIn(reveal, 0.5f, 16f, span = 0.5f),)}}@@ -408,7 +580,26 @@ private fun LyricsMenu() {val context = LocalContext.currentvar extra by remember { mutableStateOf(isLyricsExtraSources(context)) }+ var words by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsWordSync(context)) }DropdownMenu(expanded = expanded, onDismissRequest = onDismiss) {+ // Word by word (karaoke) or line by line: the app then picks the source by itself.+ DropdownMenuItem(+ text = {+ Column {+ Text(stringResource(R.string.lyrics_word_sync_title))+ Text(stringResource(if (words) R.string.lyrics_word_sync_on else R.string.lyrics_word_sync_off), fontSize = 12.sp, color = Color.Gray)+ }+ },+ trailingIcon = { if (words) Icon(Icons.Default.Check, contentDescription = null) },+ onClick = {+ words = !words+ com.music.spotui.data.preferences.setLyricsWordSync(context, words)+ LyricsApi.wordSync = words+ LyricsApi.forgetAll()+ onDismiss()+ onReload()+ },+ )if (canTranslate) DropdownMenuItem(text = { Text(stringResource(if (translating) R.string.lyrics_fullscreen_translate_button_enabled_readout_value else R.string.lyrics_fullscreen_context_menu_main_page_translate_lyrics_action)) },onClick = { onDismiss(); onTranslate() },@@ -459,10 +650,11 @@ private fun LyricsControls(translating: Boolean,onTranslate: () -> Unit,onShare: () -> Unit,+ modifier: Modifier = Modifier,) {val durationMs = SongPlayer.getDuration().coerceAtLeast(0L)val playing = com.music.spotui.di.Graph.currentSongState.playingState.value- Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(bottom = 8.dp)) {+ Column(modifier.fillMaxWidth().padding(horizontal = 24.dp).padding(bottom = 8.dp)) {Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(bottom = 10.dp)) {LyricsChip(stringResource(R.string.lyrics_fullscreen_chip_label_share), R.drawable.ic_share, false, false, palette, onShare)if (showTranslate) LyricsChip(stringResource(R.string.lyrics_fullscreen_chip_label_translate), R.drawable.ic_translate_lyrics, translationActive, translating, palette, onTranslate)@@ -563,6 +755,8 @@ fun InlineLyrics(modifier = Modifier.fillMaxWidth().padding(16.dp, 8.dp, 16.dp, 40.dp)+ // The card's live bounds are read when the lyrics open / close (see LyricsOverlay).+ .onGloballyPositioned { LyricsCardAnchor.coords = it }.clip(RoundedCornerShape(12.dp)).background(palette.background).clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { onExpand() }@@ -627,3 +821,94 @@ private fun CardIconButton(palette: LyricsPalette, description: String, icon: @C.clickable(onClick = onClick),) { icon() }}++/** The inline card's layout node, so the full screen can grow out of it and fold back into it. */+private object LyricsCardAnchor { var coords: LayoutCoordinates? = null }++/** The visible part of the container: a rounded rectangle that moves from the card to the screen. */+private class LyricsWindow(private val rect: Rect, private val radius: Float) : Shape {+ override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density): Outline =+ Outline.Rounded(RoundRect(rect, CornerRadius(radius)))+}++private val CARD_CORNER = 12.dp++/**+ * Hosts [LyricsScreen] as a container transform: the screen is laid out once at full size and+ * revealed through a window that grows from the inline card's bounds (position, size, corner+ * radius, same colour) to the whole page, while its lines rise in staggered; closing plays+ * it backwards into the card. Only graphicsLayer / draw state moves per frame, no recomposition.+ * Without a visible card (swipe-up open, card scrolled away) it slides up as it always did.+ */+@Composable+fun LyricsOverlay(+ visible: Boolean,+ title: String,+ artist: String,+ album: String,+ accentColor: Color,+ onClose: () -> Unit,+) {+ val progress = remember { Animatable(0f) }+ var mounted by remember { mutableStateOf(false) }+ // Window the container starts from, in this host's pixels; null = slide-up fallback.+ var from by remember { mutableStateOf<Rect?>(null) }+ val host = remember { arrayOfNulls<LayoutCoordinates>(1) }++ fun cardRect(): Rect? {+ val h = host[0]?.takeIf { it.isAttached } ?: return null+ val card = LyricsCardAnchor.coords?.takeIf { it.isAttached } ?: return null+ val r = h.localBoundingBoxOf(card, clipBounds = false)+ val screen = Rect(0f, 0f, h.size.width.toFloat(), h.size.height.toFloat())+ val seen = r.intersect(screen)+ // Mostly off-screen card: growing out of it would look odd, slide up instead.+ return if (r.height > 0f && seen.height >= r.height * 0.4f && seen.width > 0f) r else null+ }++ LaunchedEffect(visible) {+ if (visible) {+ from = cardRect()+ mounted = true+ val spec = if (from != null) tween<Float>(560, easing = FastOutSlowInEasing) else tween(250, easing = EaseOut)+ progress.animateTo(1f, spec)+ } else if (mounted) {+ // Fold into the card where it is now; a slide-up opening slides back down.+ if (from != null) cardRect()?.let { from = it }+ val spec = if (from != null) tween<Float>(470, easing = FastOutSlowInEasing) else tween(200, easing = EaseOut)+ progress.animateTo(0f, spec)+ mounted = false+ }+ }++ Box(Modifier.fillMaxSize().onGloballyPositioned { host[0] = it }) {+ if (!mounted) return@Box+ val window = from+ val cornerPx = with(LocalDensity.current) { CARD_CORNER.toPx() }+ Box(+ Modifier.fillMaxSize().graphicsLayer {+ val p = progress.value+ if (window == null) {+ translationY = (1f - p) * size.height+ } else {+ shape = LyricsWindow(+ Rect(+ window.left * (1f - p), window.top * (1f - p),+ window.right + (size.width - window.right) * p, window.bottom + (size.height - window.bottom) * p,+ ),+ cornerPx * (1f - p),+ )+ clip = true+ }+ },+ ) {+ LyricsScreen(+ title = title,+ artist = artist,+ album = album,+ accentColor = accentColor,+ onClose = onClose,+ reveal = if (window == null) null else ({ progress.value }),+ )+ }+ }+}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 befcb561..6583591b 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@@ -25,6 +25,7 @@ import androidx.compose.animation.slideOutVerticallyimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.basicMarqueeimport androidx.compose.foundation.clickable+import androidx.compose.material.icons.outlined.AddCircleOutlineimport androidx.compose.foundation.interaction.MutableInteractionSourceimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.aspectRatio@@ -39,6 +40,8 @@ import androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.heightimport androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.asPaddingValues+import androidx.compose.foundation.layout.statusBarsimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.navigationBarsPaddingimport androidx.compose.foundation.layout.imePadding@@ -53,7 +56,6 @@ import androidx.compose.material.icons.filled.Favoriteimport androidx.compose.material.icons.filled.FavoriteBorderimport androidx.compose.material.icons.filled.KeyboardArrowDownimport androidx.compose.material.icons.filled.KeyboardArrowRight-import androidx.compose.material.icons.automirrored.filled.Listimport androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.filled.Notificationsimport androidx.compose.material.icons.filled.Person@@ -95,6 +97,7 @@ import androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.toArgbimport androidx.compose.ui.graphics.vector.ImageVector+import androidx.compose.ui.graphics.vector.pathimport androidx.compose.foundation.pager.HorizontalPagerimport androidx.compose.foundation.pager.rememberPagerStateimport androidx.compose.runtime.snapshotFlow@@ -220,6 +223,15 @@ fun PlayerScreen(navController: NavController) {}// Track changes cross-fade the background instead of snapping.val dominentColor by androidx.compose.animation.animateColorAsState(coverColor, androidx.compose.animation.core.tween(450), label = "cover")+ // The page's own gradient uses the mini player's colour (same cache entry, so no second+ // extraction when the mini player has already seen the cover); the muted colour above stays+ // for the lyrics and as a fallback for covers without a dark vibrant swatch.+ var tintColor by remember { mutableStateOf(Palette.cachedFirst(songCoverUri)) }+ LaunchedEffect(songCoverUri) {+ Palette.cachedFirst(songCoverUri)?.let { tintColor = it; return@LaunchedEffect }+ if (songCoverUri.isNotBlank()) Palette().extractFirstColorFromImageUrl(context, songCoverUri) { tintColor = it }+ }+ val backdropColor by androidx.compose.animation.animateColorAsState(tintColor ?: coverColor, androidx.compose.animation.core.tween(450), label = "backdrop")val shuffle = playerViewModel.shuffleState.valueval repeat = playerViewModel.repeatState.value@@ -247,10 +259,22 @@ fun PlayerScreen(navController: NavController) {LaunchedEffect(songId) {if (artworkPagerState.currentPage != 1) artworkPagerState.scrollToPage(1)}+ // Only a swipe changes track: the pager also lands on another page by itself when it is+ // laid out again at another size (the clip going full screen turns the phone landscape),+ // which skipped the song.+ var artworkSwiped by remember { mutableStateOf(false) }+ LaunchedEffect(artworkPagerState) {+ artworkPagerState.interactionSource.interactions.collect {+ if (it is androidx.compose.foundation.interaction.DragInteraction.Start) artworkSwiped = true+ }+ }LaunchedEffect(artworkPagerState) {snapshotFlow { artworkPagerState.settledPage }.distinctUntilChanged().collect { page ->+ if (page == 1) return@collect+ if (!artworkSwiped) { artworkPagerState.scrollToPage(1); return@collect }+ artworkSwiped = falsewhen (page) {2 -> SongPlayer.swipeNext()0 -> SongPlayer.previous()@@ -271,9 +295,10 @@ fun PlayerScreen(navController: NavController) {// Read from the cache in this very frame when already looked up (the view model's state// only follows one frame later): the screen then opens on the Canvas, not on the cover.val knownCanvas = remember(displayedTrackId) { com.music.spotui.di.Graph.api.knownCanvas(displayedTrackId)?.getOrNull() }+ val canvasAllowed = energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active &&+ !(com.music.spotui.data.DataSaver.metered && com.music.spotui.data.preferences.isCanvasWifiOnly(context))val canvasUrl = (if (canvas.trackId == displayedTrackId) canvas.url else knownCanvas).takeIf {- energy.policy.allowCanvas && !com.music.spotui.data.DataSaver.active &&- !(com.music.spotui.data.DataSaver.metered && com.music.spotui.data.preferences.isCanvasWifiOnly(context)) && displayedTrackId.isNotBlank()+ canvasAllowed && displayedTrackId.isNotBlank()}// The cover stays until the Canvas has drawn its first frame: hiding it earlier showed// the bare background for a moment (a flash) between the cover and the clip.@@ -282,15 +307,28 @@ fun PlayerScreen(navController: NavController) {// Cover to Canvas as one cross-fade: the clip (full screen) fades in while the cover fades// out and grows a little into it, instead of the background switching at once.val canvasOn = canvasUrl != null && canvasShown- // The immersive view is the Canvas's: a song without one leaves it.- LaunchedEffect(canvasOn) { if (!canvasOn) immersive = false }- // A clip already loaded shows at once; one still loading fades in over the cover.- val readyAtOnce = remember(canvasUrl) { canvasUrl != null && com.music.spotui.ui.components.CanvasPlayer.isReady(canvasUrl) }- val canvasProgress = remember { androidx.compose.animation.core.Animatable(if (readyAtOnce) 1f else 0f) }- LaunchedEffect(canvasOn, readyAtOnce) {+ // The immersive view is the Canvas's, but a skip must not collapse it while the next clip+ // loads: it is left only once the new song is known to have no Canvas (lookup done with no+ // url, or Canvases off). A lookup that never answers gives up after a few seconds.+ LaunchedEffect(immersive, canvasUrl, canvasAllowed, displayedTrackId) {+ if (!immersive || canvasUrl != null || displayedTrackId.isBlank()) return@LaunchedEffect+ kotlinx.coroutines.withTimeoutOrNull(8000) {+ while (canvasAllowed && com.music.spotui.di.Graph.api.knownCanvas(displayedTrackId) == null) kotlinx.coroutines.delay(250)+ }+ immersive = false+ }+ // Opening on a clip that is already showing starts at the end of the fade (the only+ // time it is not played); every later change animates, so a skip never cuts it short.+ val canvasProgress = remember { androidx.compose.animation.core.Animatable(if (canvasOn) 1f else 0f) }+ // Keyed on the target alone: a new song with the same target leaves the running fade+ // alone, and a real change continues from where it is, over the part still to travel.+ LaunchedEffect(canvasOn) {val target = if (canvasOn) 1f else 0f- if (canvasOn && readyAtOnce) canvasProgress.snapTo(target)- else canvasProgress.animateTo(target, androidx.compose.animation.core.tween(CANVAS_FADE_MS, easing = androidx.compose.animation.core.FastOutSlowInEasing))+ val left = kotlin.math.abs(target - canvasProgress.value)+ if (left > 0f) canvasProgress.animateTo(+ target,+ androidx.compose.animation.core.tween((CANVAS_FADE_MS * left).toInt(), easing = androidx.compose.animation.core.FastOutSlowInEasing),+ )}val canvasAlpha = canvasProgress.valueval coverAlpha = 1f - canvasProgress.value@@ -326,7 +364,7 @@ fun PlayerScreen(navController: NavController) {// Pulled down from the top, the player closes, like the back button (issue #4).val pullToClose = com.music.spotui.ui.components.rememberPullToDismiss { com.music.spotui.ui.navigation.PlayerSheet.close() }pullToClose.enabled = !showLyrics && !mv.fullscreen.value- Box(+ androidx.compose.foundation.layout.BoxWithConstraints(modifier = Modifier.graphicsLayer { translationY = pullToClose.offset }.fillMaxSize()@@ -334,15 +372,20 @@ fun PlayerScreen(navController: NavController) {// The tint follows the cover in BOTH modes: AMOLED used to be pure black, and the// colour was asked for anyway (that replaces the halo idea). The screen keeps its// gradient, the toggle still governs the rest of the app.+ // Official look: the cover's colour at the top, fading to near-black by the+ // bottom (still faintly tinted halfway), so white text stays readable.Brush.verticalGradient(- colors = listOf(- androidx.compose.ui.graphics.lerp(dominentColor, Color.Black, 0.35f),- Color(0xFF121212),- ),- startY = 0f+ 0f to backdropColor,+ 0.55f to androidx.compose.ui.graphics.lerp(backdropColor, PLAYER_BASE, 0.40f),+ 0.80f to androidx.compose.ui.graphics.lerp(backdropColor, PLAYER_BASE, 0.78f),+ 1f to PLAYER_BASE,))) {+ // The window's height (the inner constraints below shadow `maxHeight`) and the status+ // bar's, to size the page item itself: a LazyColumn item cannot ask for "parent minus x".+ val pageHeight = maxHeight+ val statusTop = androidx.compose.foundation.layout.WindowInsets.Companion.statusBars.asPaddingValues().calculateTopPadding()val pillAboveTitle = canvasUrl != null && !videoOnif (canvasUrl != null && !videoOn) {CanvasVideo(@@ -386,17 +429,18 @@ fun PlayerScreen(navController: NavController) {// Sized from the real space (foldables, tablets), not the screen: wide windows centre// the content in a capped column and the cover fits both the width and the height.androidx.compose.foundation.layout.BoxWithConstraints(- modifier = Modifier.fillParentMaxHeight().fillMaxWidth(),+ modifier = (if (immersive) Modifier.fillParentMaxHeight()+ // The page stops short of the screen's bottom so the lyrics card peeks in under+ // the buttons, as in the official app (scroll to open it).+ else Modifier.height(+ (pageHeight - statusTop - PLAYER_PEEK_DP.dp).coerceAtLeast(300.dp)+ )).fillMaxWidth(),contentAlignment = Alignment.TopCenter,) {val wide = maxWidth > 600.dp && maxWidth > maxHeightval contentWidth = if (wide) maxWidth.coerceAtMost(520.dp) else maxWidth- // Height budget from the screen, as before (the list item is shorter than the screen and- // gave a smaller cover); the width cap only matters on wide windows.- val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp// Immersive: the artwork takes the whole height instead of leaving room for controls.- val artSide = if (immersive) screenHeight- else minOf(contentWidth, screenHeight - PLAYER_CONTROLS_DP.dp).coerceAtLeast(160.dp)+ val screenHeight = androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dpColumn(modifier = Modifier.fillMaxHeight()@@ -412,7 +456,8 @@ fun PlayerScreen(navController: NavController) {np = np,fallbackName = playerViewModel.currentSongAlbum.value,)- Spacer(modifier = Modifier.height(28.dp))+ // Official: the cover starts closer to the header.+ Spacer(modifier = Modifier.height(14.dp))}// Media area: artwork (swipe to change track) or the music video, with// Spotify's "Passer à la vidéo" pill over it (black, like the official app).@@ -420,6 +465,20 @@ fun PlayerScreen(navController: NavController) {// screens): otherwise play / pause ends up under the lyrics card.// A clear upward drag on the artwork opens the lyrics (observed on the initial pass,// never consumed, so the pager and the pull-to-close keep working).+ // The media slot takes whatever height the controls below leave (they are measured+ // first, so they are never squeezed): the Connect row always stays above the lyrics+ // peek, with or without Canvas / clip pill, on short screens too. The art shrinks, the+ // controls do not; on tall screens the slot's spare height sits under the art.+ androidx.compose.foundation.layout.BoxWithConstraints(+ modifier = if (immersive) Modifier else Modifier.fillMaxWidth().weight(1f),+ contentAlignment = Alignment.TopCenter,+ ) {+ val artSide = if (immersive) screenHeight+ else minOf(contentWidth, maxHeight).coerceAtLeast(0.dp)+ // The cover: the width less its 24dp margins, or all the height when that is shorter.+ // The margins used to be taken off the height-bound side too, a cover 48dp smaller+ // than the room it had on most phones (reported: it looks small).+ val coverInset = ((artSide - minOf(contentWidth - 48.dp, maxHeight)) / 2).coerceAtLeast(0.dp)Box(modifier = Modifier.size(artSide).pointerInput(immersive, videoOn, canvasOn) {detectTapGestures(onTap = {// A tap on a Canvas hides the rest to show the whole clip. A plain cover has@@ -455,8 +514,19 @@ fun PlayerScreen(navController: NavController) {contentAlignment = Alignment.Center,modifier = Modifier.fillMaxSize(),) {- com.music.spotui.ui.components.VideoSurface(onTap = { mv.fullscreen.value = true })- } else HorizontalPager(+ // The full-screen button in the clip's corner: under it, it overlapped the pills.+ Box {+ com.music.spotui.ui.components.VideoSurface(onTap = { mv.fullscreen.value = true })+ if (!immersive) com.music.spotui.ui.components.VideoFullscreenButton(Modifier.align(Alignment.BottomEnd))+ }+ } else androidx.compose.runtime.key("artwork") {+ // Back on screen after the clip (or its full screen, laid out landscape): the pager+ // can come back on the page it had or a neighbour, which showed the next song's+ // cover (or the one before) over the song playing. It opens on the song playing.+ LaunchedEffect(songId) {+ if (artworkPagerState.currentPage != 1) { artworkSwiped = false; artworkPagerState.scrollToPage(1) }+ }+ HorizontalPager(state = artworkPagerState,// Immersive: the artwork fills the screen instead of sitting in a square.modifier = if (immersive) Modifier.fillMaxSize()@@ -472,7 +542,7 @@ fun PlayerScreen(navController: NavController) {transition = CrossFade,modifier = (if (immersive) Modifier.fillMaxSize()// Normal layout keeps the inset, rounded cover.- else Modifier.padding(horizontal = 24.dp).aspectRatio(1f).clip(RoundedCornerShape(8.dp)))+ else Modifier.padding(horizontal = coverInset).aspectRatio(1f).clip(RoundedCornerShape(8.dp))).graphicsLayer {alpha = coverAlphaval grow = 1f + (1f - coverAlpha) * 0.06f@@ -483,6 +553,7 @@ fun PlayerScreen(navController: NavController) {contentDescription = "")}}+ }// Over the artwork / video; with a Canvas the artwork is hidden, so the// pill sits above the title instead of floating mid-screen.if (!immersive && (videoReady || videoOn) && !pillAboveTitle) {@@ -491,18 +562,24 @@ fun PlayerScreen(navController: NavController) {modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 36.dp),)}- if (showVideo && !immersive) {- com.music.spotui.ui.components.VideoFullscreenButton(- modifier = Modifier.align(Alignment.BottomEnd).padding(end = 36.dp, bottom = 36.dp),- )}}- Spacer(modifier = Modifier.weight(1f))- if (!immersive && (videoReady || videoOn) && pillAboveTitle) {- com.music.spotui.ui.components.VideoSwitchPill(- on = videoOn,- modifier = Modifier.padding(bottom = 20.dp),+ // The slot (pill 32dp + 20dp gap) is reserved in every non-immersive layout, Canvas or+ // not, and before the clip is even known: the title, seek bar and buttons then sit at+ // the same height on every track, and a skip between the two kinds no longer moves+ // them. Only the Canvas layout draws the pill here, fading in inside the slot.+ if (!immersive) {+ val pillIn by androidx.compose.animation.core.animateFloatAsState(+ if (videoReady || videoOn) 1f else 0f, tween(250), label = "pillIn",)+ Box(modifier = Modifier.fillMaxWidth().height(52.dp), contentAlignment = Alignment.TopCenter) {+ if (pillAboveTitle && pillIn > 0f) com.music.spotui.ui.components.VideoSwitchPill(+ on = videoOn,+ modifier = Modifier+ .padding(bottom = 20.dp)+ .graphicsLayer { alpha = pillIn; val k = 0.85f + 0.15f * pillIn; scaleX = k; scaleY = k },+ )+ }}// Immersive mode keeps none of this: the compact strip at the bottom of@@ -548,7 +625,7 @@ fun PlayerScreen(navController: NavController) {modifier = Modifier.fillMaxWidth().padding(horizontal = 24.dp)- .padding(top = 14.dp),+ .padding(top = 11.dp),)Row(modifier = Modifier@@ -562,7 +639,8 @@ fun PlayerScreen(navController: NavController) {Text(text = playerViewModel.formatDuration(duration.coerceAtLeast(0)),color = Color.White.copy(alpha = 0.7f),- fontSize = 12.sp,+ fontSize = 13.sp,+ lineHeight = 14.sp,)}@@ -576,7 +654,8 @@ fun PlayerScreen(navController: NavController) {onDevices = { showDevices = true },onQueue = { showQueue = true },)- Spacer(modifier = Modifier.height(20.dp))+ // 8dp card margin + this = the official 37dp from the buttons' centre to the card.+ Spacer(modifier = Modifier.height(12.dp))}}}@@ -598,7 +677,7 @@ fun PlayerScreen(navController: NavController) {// app's collapsed layout. It swallows taps, so only the artwork leaves the mode.if (immersive) {ImmersiveStrip(- modifier = Modifier.align(Alignment.BottomCenter).navigationBarsPadding(),+ modifier = Modifier.align(Alignment.BottomCenter),coverUri = songCoverUri,title = songTitle,artists = songSinger,@@ -612,25 +691,15 @@ fun PlayerScreen(navController: NavController) {)}- AnimatedVisibility(+ // Container transform out of / back into the inline card (slide-up when it is not on screen).+ com.music.spotui.ui.screens.LyricsOverlay(visible = showLyrics,- enter = slideInVertically(- animationSpec = tween(durationMillis = 250, easing = EaseOut),- initialOffsetY = { it },- ),- exit = slideOutVertically(- animationSpec = tween(durationMillis = 200, easing = EaseOut),- targetOffsetY = { it },- ),- ) {- LyricsScreen(- title = songTitle,- artist = songSinger,- album = playerViewModel.currentSongAlbum.value,- accentColor = dominentColor,- onClose = { showLyrics = false }- )- }+ title = songTitle,+ artist = songSinger,+ album = playerViewModel.currentSongAlbum.value,+ accentColor = dominentColor,+ onClose = { showLyrics = false },+ )// Full-screen clip: the video over everything, turned sideways, with its own controls.if (videoOn && mv.fullscreen.value) VideoFullscreen()}@@ -662,6 +731,8 @@ private fun ImmersiveStrip(// Scrim only under the strip: the artwork above stays untouched.Brush.verticalGradient(listOf(Color.Transparent, Color.Black.copy(alpha = 0.72f))))+ // After the background, so the scrim runs down behind the navigation bar too.+ .navigationBarsPadding().padding(horizontal = 16.dp, vertical = 10.dp),) {Row(verticalAlignment = Alignment.CenterVertically) {@@ -794,7 +865,7 @@ fun PlayerTopBar(Row(verticalAlignment = Alignment.CenterVertically,horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()- .padding(horizontal = 20.dp, vertical = 12.dp)+ .padding(horizontal = 20.dp, vertical = 9.dp)) {Icon(modifier = Modifier.size(26.dp)@@ -804,7 +875,8 @@ fun PlayerTopBar() {com.music.spotui.ui.navigation.PlayerSheet.close()},- painter = painterResource(id = R.drawable.ic_down),+ // Official chevron: wide and thin (the old drawable was a short, heavy one).+ imageVector = PlayerIcons.chevronDown,tint = Color.White,contentDescription = stringResource(R.string.a11y_close_player))@@ -823,6 +895,7 @@ fun PlayerTopBar(text = line1,color = Color.White,fontSize = 12.sp,+ lineHeight = 15.sp,maxLines = 1,overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,)@@ -830,6 +903,7 @@ fun PlayerTopBar(text = line2,color = Color.White,fontSize = 14.sp,+ lineHeight = 18.sp,fontWeight = FontWeight.Bold,maxLines = 1,overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,@@ -897,7 +971,8 @@ fun LikeButton(liked: Boolean, size: androidx.compose.ui.unit.Dp = 28.dp, onClic) { onClick() }if (liked) {Box(contentAlignment = Alignment.Center, modifier = mod.clip(CircleShape).background(com.music.spotui.ui.theme.AppAccent)) {- Icon(Icons.Default.Check, contentDescription = stringResource(R.string.remove_from_liked), tint = Color.Black, modifier = Modifier.size(size * 0.65f))+ // The official check is bolder, with round ends.+ Icon(PlayerIcons.check, contentDescription = stringResource(R.string.remove_from_liked), tint = Color.Black, modifier = Modifier.size(size * 0.7f))}} else {Icon(painterResource(id = R.drawable.ic_add), contentDescription = stringResource(R.string.aligned_curation_context_menu_item_add_to_liked_songs), tint = Color.White, modifier = mod)@@ -948,13 +1023,14 @@ fun PlayerInfo(text = if (adPlaying) stringResource(R.string.ad_playing) else songTitle,color = Color.White,fontSize = 22.sp,+ lineHeight = 26.sp,fontWeight = FontWeight.Bold,maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,softWrap = false,)// The artist row belongs to the song: during an ad the previous one's artist is// what the state still holds, so it is not shown as if it were playing.- if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 2.dp)) {+ if (!adPlaying) Row(verticalAlignment = Alignment.CenterVertically) {if (explicit) {ExplicitBadge()Spacer(modifier = Modifier.width(6.dp))@@ -998,10 +1074,10 @@ private fun ElapsedLabel(playing: Boolean, override: Long?, format: (Long) -> St}// Seek while paused: pick the new position up as soon as it changes.LaunchedEffect(override) { if (override == null) now = mv.position() }- Text(text = format(override ?: now), color = Color.White.copy(alpha = 0.7f), fontSize = 12.sp)+ Text(text = format(override ?: now), color = Color.White.copy(alpha = 0.7f), fontSize = 13.sp, lineHeight = 14.sp)}-/** Thin Spotify-style seek bar: 3dp track, small white thumb, drag to scrub. */+/** Thin Spotify-style seek bar: 2dp track, small white thumb, drag to scrub. */@Composablefun SpotifySeekBar(fraction: () -> Float,@@ -1052,11 +1128,12 @@ fun SpotifySeekBar(}) {val y = size.height / 2- val track = 3.dp.toPx()+ // Official: a hairline track and a small knob (the old one was thicker and bigger).+ val track = 2.dp.toPx()val f = fraction().coerceIn(0f, 1f)drawLine(Color.White.copy(alpha = 0.3f), androidx.compose.ui.geometry.Offset(0f, y), androidx.compose.ui.geometry.Offset(size.width, y), track, androidx.compose.ui.graphics.StrokeCap.Round)drawLine(Color.White, androidx.compose.ui.geometry.Offset(0f, y), androidx.compose.ui.geometry.Offset(size.width * f, y), track, androidx.compose.ui.graphics.StrokeCap.Round)- drawCircle(Color.White, radius = 6.dp.toPx(), center = androidx.compose.ui.geometry.Offset(size.width * f, y))+ drawCircle(Color.White, radius = 5.dp.toPx(), center = androidx.compose.ui.geometry.Offset(size.width * f, y))}}@@ -1103,12 +1180,14 @@ fun PlayerFull(horizontalArrangement = Arrangement.SpaceBetween,modifier = Modifier.fillMaxWidth()- .padding(20.dp)+ // Official spacing: the icons' centres sit 36dp from the edges, the row 57dp under+ // the time labels and 74dp above the device row.+ .padding(start = 22.dp, end = 22.dp, top = 18.dp, bottom = 26.dp).height(64.dp)) {Icon(modifier = Modifier- .size(25.dp)+ .size(28.dp).drawWithContent {drawContent()if (shuffle || smartOn) drawCircle(com.music.spotui.ui.theme.AppAccent, radius = 2.dp.toPx(),@@ -1145,7 +1224,7 @@ fun PlayerFull(Icon(modifier = Modifier- .size(35.dp)+ .size(40.dp).pressable {// The queue itself is already in shuffled order when shuffle// is on (reordered once at toggle) — never re-shuffle per tap.@@ -1191,7 +1270,7 @@ fun PlayerFull(contentAlignment = Alignment.Center) {com.music.spotui.ui.components.PlayPauseIcon(- modifier = Modifier.size(30.dp),+ modifier = Modifier.size(36.dp),tint = Color.Black,playing = songPlayingState,contentDescription = stringResource(if (songPlayingState) R.string.notif_action_pause else R.string.notif_action_play))@@ -1199,7 +1278,7 @@ fun PlayerFull(Icon(modifier = Modifier- .size(35.dp)+ .size(40.dp).pressable {playerViewModel.playNextSongs(queueSongs, context)@@ -1210,7 +1289,7 @@ fun PlayerFull(contentDescription = stringResource(R.string.np_content_desc_next))Icon(modifier = Modifier- .size(20.dp)+ .size(28.dp).pressable {SongPlayer.cycleRepeat()@@ -1223,7 +1302,8 @@ fun PlayerFull(else{Color.White},- painter = painterResource(id = if (SongPlayer.repeatMode.value == 2) R.drawable.ic_repeat_one else R.drawable.ic_repeat_spotui),+ // The official loop with one arrow (drawn here: the old drawable was the two-arrow one).+ imageVector = if (SongPlayer.repeatMode.value == 2) PlayerIcons.repeatOne else PlayerIcons.repeat,contentDescription = when (SongPlayer.repeatMode.value) { 1 -> stringResource(R.string.repeat_on); 2 -> stringResource(R.string.repeat_one); else -> stringResource(R.string.repeat_off) })}}@@ -1242,7 +1322,7 @@ fun PlayerConnectRow(horizontalArrangement = Arrangement.SpaceBetween,modifier = Modifier.fillMaxWidth()- .padding(horizontal = 24.dp, vertical = 4.dp),+ .padding(horizontal = 20.dp, vertical = 4.dp),) {// Spotify Connect: current device, opens the device picker.Row(@@ -1253,19 +1333,20 @@ fun PlayerConnectRow() { onDevices() },) {Icon(- painter = painterResource(id = R.drawable.ic_devices),+ // What plays: a phone for this phone, a speaker, a computer… (as the label says).+ imageVector = com.music.spotui.ui.components.activeDeviceIcon(),tint = com.music.spotui.ui.theme.AppAccent,- modifier = Modifier.size(20.dp),+ modifier = Modifier.size(24.dp),contentDescription = stringResource(R.string.mr_user_route_category_name),)Text(text = com.music.spotui.ui.components.activeDeviceLabel(),color = com.music.spotui.ui.theme.AppAccent,- fontSize = 13.sp,+ fontSize = 12.sp,maxLines = 1,overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,modifier = Modifier- .padding(start = 8.dp)+ .padding(start = 6.dp).widthIn(max = 200.dp),)}@@ -1277,7 +1358,7 @@ fun PlayerConnectRow(painter = painterResource(id = R.drawable.ic_share),tint = Color.White,modifier = Modifier- .size(22.dp)+ .size(24.dp).clickable(interactionSource = remember { MutableInteractionSource() },indication = null,@@ -1293,13 +1374,10 @@ fun PlayerConnectRow(val parts = SongPlayer.nowPlaying.value.uri.split(':')val link = if (parts.size == 3 && parts[0] == "spotify") "https://open.spotify.com/${parts[1]}/${parts[2]}"else SongPlayer.currentTrackId.takeIf { it.isNotBlank() }?.let { "https://open.spotify.com/track/$it" }- if (link != null) {- val send = Intent(Intent.ACTION_SEND).apply {- type = "text/plain"- putExtra(Intent.EXTRA_TEXT, link)- }- context.startActivity(Intent.createChooser(send, context.getString(R.string.action_share_label)))- }+ if (link != null) com.music.spotui.ui.components.SpotifyCode.show(com.music.spotui.ui.components.ShareTarget(+ "spotify:" + link.removePrefix("https://open.spotify.com/").replace('/', ':'),+ title, artist, coverUri,+ ))},)androidx.compose.material3.DropdownMenuItem(@@ -1314,12 +1392,13 @@ fun PlayerConnectRow()}}- Spacer(modifier = Modifier.width(24.dp))+ Spacer(modifier = Modifier.width(28.dp))Icon(- imageVector = Icons.AutoMirrored.Filled.List,+ // Official queue glyph: a short line over stacked wide ones.+ imageVector = PlayerIcons.queue,tint = Color.White,modifier = Modifier- .size(26.dp)+ .size(24.dp).clickable(interactionSource = remember { MutableInteractionSource() },indication = null,@@ -1380,8 +1459,29 @@ fun AddButton(song: () -> SongsModel, liked: Boolean, size: androidx.compose.ui.savedIn?.let { s ->com.music.spotui.ui.components.SavedInSheet(song = s, context = context, onDismiss = { savedIn = null })}- LikeButton(liked = liked, size = size) {- if (liked) savedIn = song() else {+ // A song smart shuffle mixed in is not in the playlist: its + adds it there (Spotify's sparkle +).+ val current = song()+ // Saved somewhere, as in the official app: liked, or playing from one of the user's own+ // playlists (reported: songs of one's playlists showed a bare +, as if saved nowhere).+ val contextUri = SongPlayer.nowPlaying.value.contextUri+ val inOwnList by androidx.compose.runtime.produceState(false, contextUri) {+ value = contextUri.startsWith("spotify:playlist:") &&+ contextUri.substringAfterLast(':') in com.music.spotui.data.api.EditablePlaylists.ids()+ }+ // A queued song plays with the list still as its context: only the list's own rows count.+ val fromList = SongPlayer.nowPlaying.value.provider.let { it.isBlank() || it == "context" }+ val saved = liked || (inOwnList && fromList && !SmartShuffle.isRecommendation(current.spotifyTrackId))+ if (SmartShuffle.isRecommendation(current.spotifyTrackId)) {+ Icon(+ Icons.Outlined.AddCircleOutline,+ contentDescription = stringResource(R.string.smart_shuffle_add),+ tint = Color.White,+ modifier = Modifier.size(size).clip(CircleShape).clickable { SmartShuffle.keep(context, current) },+ )+ return+ }+ LikeButton(liked = saved, size = size) {+ if (saved) savedIn = song() else {onLike()android.widget.Toast.makeText(context, context.getString(R.string.snackbar_added_to_liked_songs), android.widget.Toast.LENGTH_SHORT).show()}@@ -1475,7 +1575,59 @@ private fun CanvasVideo(url: String, playing: Boolean, onFirstFrame: () -> Unit,}/** Cover to Canvas cross-fade. */-private const val CANVAS_FADE_MS = 550+private const val CANVAS_FADE_MS = 680++/** How much of the lyrics card shows under the buttons (its 8dp margin included). */+private const val PLAYER_PEEK_DP = 65+/** The gradient's bottom: near-black with a hint of blue, like the official page. */+private val PLAYER_BASE = Color(0xFF0F1114)-/** Height the player needs under the artwork: top bar, title, seek bar, controls, Connect row. */-private const val PLAYER_CONTROLS_DP = 450+/**+ * Glyphs drawn to look like the official player's (outlined, round-capped strokes). Material's+ * own repeat / queue / check differ in shape, and the app may not ship Spotify's artwork.+ */+private object PlayerIcons {+ private fun stroked(name: String, w: Float = 2f, build: androidx.compose.ui.graphics.vector.PathBuilder.() -> Unit): ImageVector =+ ImageVector.Builder(name, 24.dp, 24.dp, 24f, 24f).apply {+ path(+ stroke = androidx.compose.ui.graphics.SolidColor(Color.Black),+ strokeLineWidth = w,+ strokeLineCap = androidx.compose.ui.graphics.StrokeCap.Round,+ strokeLineJoin = androidx.compose.ui.graphics.StrokeJoin.Round,+ pathBuilder = build,+ )+ }.build()++ val chevronDown: ImageVector = stroked("chevronDown", 1.8f) {+ moveTo(4f, 8.5f); lineTo(12f, 16.5f); lineTo(20f, 8.5f)+ }+ val check: ImageVector = stroked("check", 3f) {+ moveTo(5f, 12.5f); lineTo(10f, 17.5f); lineTo(19f, 7f)+ }+ private fun androidx.compose.ui.graphics.vector.PathBuilder.loop() {+ // Rounded frame open at the lower left, where the arrow head sits.+ moveTo(3f, 12f); verticalLineTo(9f); arcTo(4f, 4f, 0f, false, true, 7f, 5f)+ horizontalLineTo(17f); arcTo(4f, 4f, 0f, false, true, 21f, 9f)+ verticalLineTo(12f); arcTo(4f, 4f, 0f, false, true, 17f, 16f)+ horizontalLineTo(8f)+ moveTo(11f, 12.5f); lineTo(7.5f, 16f); lineTo(11f, 19.5f)+ }+ val repeat: ImageVector = stroked("repeat") { loop() }+ val repeatOne: ImageVector = stroked("repeatOne") {+ loop()+ moveTo(10.5f, 8.8f); lineTo(12.5f, 7.8f); verticalLineTo(13f)+ }+ val device: ImageVector = stroked("device") {+ moveTo(6f, 5f); horizontalLineTo(18f); arcTo(1.5f, 1.5f, 0f, false, true, 19.5f, 6.5f)+ verticalLineTo(14f); arcTo(1.5f, 1.5f, 0f, false, true, 18f, 15.5f)+ horizontalLineTo(6f); arcTo(1.5f, 1.5f, 0f, false, true, 4.5f, 14f)+ verticalLineTo(6.5f); arcTo(1.5f, 1.5f, 0f, false, true, 6f, 5f)+ moveTo(3f, 19.5f); horizontalLineTo(21f)+ }+ val queue: ImageVector = stroked("queue", 1.8f) {+ moveTo(8.5f, 5f); horizontalLineTo(15.5f)+ moveTo(4.5f, 10f); horizontalLineTo(19.5f)+ moveTo(4.5f, 14.5f); horizontalLineTo(19.5f)+ moveTo(4.5f, 19f); horizontalLineTo(19.5f)+ }+}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.ktindex 917c58d0..da3cdd08 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/ProfileScreen.kt@@ -90,14 +90,9 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String}item {Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth().padding(16.dp)) {- GlideImage(- transition = CrossFade,- model = spotifyImageUrl(p?.images?.best(300)?.url),- contentDescription = null,- contentScale = ContentScale.Crop,- failure = placeholder(R.drawable.placeholder),- loading = placeholder(R.drawable.placeholder),- modifier = Modifier.size(150.dp).clip(CircleShape),+ com.music.spotui.ui.components.ProfileAvatar(+ url = spotifyImageUrl(p?.images?.best(300)?.url),+ name = p?.name ?: userName, size = 150.dp,)Spacer(Modifier.height(14.dp))com.music.spotui.ui.components.FitText(p?.name ?: userName, fontSize = 28.sp, minSize = 18.sp,@@ -142,11 +137,7 @@ fun ProfileScreen(navController: NavController, userId: String, userName: String}}when {- p == null && !failed -> item {- Box(Modifier.fillMaxWidth().padding(32.dp), contentAlignment = Alignment.Center) {- CircularProgressIndicator(color = AppAccent)- }- }+ p == null && !failed -> item { com.music.spotui.ui.components.SkeletonList(count = 5) }p == null -> item {com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.page_load_failed)) { attempt++ }}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.ktindex ab69383b..7cdb4951 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/RecentlyPlayedScreen.kt@@ -168,9 +168,7 @@ fun RecentlyPlayedScreen(navController: NavController) {stringResource(R.string.recently_played_failed, failure.orEmpty()),color = Subtle, fontSize = 14.sp, modifier = Modifier.padding(20.dp),)- entries == null -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- CircularProgressIndicator(color = com.music.spotui.ui.theme.AppAccent)- }+ entries == null -> com.music.spotui.ui.components.SkeletonList(count = 9)sections.isEmpty() -> Text(stringResource(R.string.recently_played_empty),color = Subtle, fontSize = 14.sp, modifier = Modifier.padding(20.dp),diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.ktindex 6c3b6ea4..6cc79bdb 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SearchScreen.kt@@ -401,7 +401,7 @@ sealed class SearchRow {private fun SearchStatus(query: String, loading: Boolean, failed: Boolean, onRetry: () -> Unit) {Column(Modifier.fillMaxWidth().padding(24.dp, 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {when {- loading -> androidx.compose.material3.CircularProgressIndicator(color = com.music.spotui.ui.theme.AppAccent)+ loading -> com.music.spotui.ui.components.SkeletonList(count = 7, modifier = Modifier.padding(top = 0.dp))failed -> com.music.spotui.ui.components.ErrorRetry(stringResource(R.string.search_failed), Modifier.padding(0.dp), onRetry)else -> Text(stringResource(R.string.assisted_curation_search_empty_view_no_result_title, query.trim()),color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.Bold,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 744d5704..c62fae57 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@@ -84,6 +84,26 @@ fun SettingsScreen(navController: NavController) {onChecked = { com.music.spotui.data.preferences.AutoplayPref.set(ctx, it) },)CrossfadeRow()+ var keepPlaying by remember { mutableStateOf(app.myspoti.host.android.PlaybackService.keepsPlayingOnClose(ctx)) }+ OptionRow(+ label = stringResource(R.string.settings_keep_playing_title),+ detail = stringResource(R.string.settings_keep_playing_detail),+ checked = keepPlaying,+ onChecked = { keepPlaying = it; app.myspoti.host.android.PlaybackService.setKeepsPlayingOnClose(ctx, it) },+ )+ // Lyrics: word by word (karaoke) first, or line by line with Spotify's first.+ var wordSync by remember { mutableStateOf(com.music.spotui.data.preferences.isLyricsWordSync(ctx)) }+ OptionRow(+ label = stringResource(R.string.lyrics_word_sync_title),+ detail = stringResource(if (wordSync) R.string.lyrics_word_sync_on else R.string.lyrics_word_sync_off),+ checked = wordSync,+ onChecked = {+ wordSync = it+ com.music.spotui.data.preferences.setLyricsWordSync(ctx, it)+ com.music.spotui.data.api.LyricsApi.wordSync = it+ com.music.spotui.data.api.LyricsApi.forgetAll()+ },+ )Divider()Section(R.string.settings_section_downloads)diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.ktindex b133bc8f..ad9aa6d9 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/SetupScreen.kt@@ -6,6 +6,25 @@ import android.content.pm.PackageManagerimport android.os.Buildimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.animateDpAsState+import androidx.compose.animation.core.spring+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.scaleOut+import androidx.compose.animation.slideInHorizontally+import androidx.compose.animation.slideOutHorizontally+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.width+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.graphicsLayer+import kotlinx.coroutines.delayimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Column@@ -66,57 +85,99 @@ private fun granted(context: Context, permission: String) =@Composablefun SetupScreen(onDone: () -> Unit, onSpotiflac: () -> Unit = {}) {val context = LocalContext.current- // Re-read when coming back from a system dialog or the settings.- var tick by remember { mutableIntStateOf(0) }- LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(800); tick++ } }- val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { tick++ }// First the sound quality, then the permissions (skipped when done before an update).var qualityStep by remember { mutableStateOf(!com.music.spotui.data.preferences.isQualityChosen(context)) }- if (qualityStep) {- QualityStep(onNext = {- com.music.spotui.data.preferences.setQualityChosen(context)- if (Setup.permissionsDone(context)) onDone() else qualityStep = false- })- return+ // Two steps to go through: dots say where the user is.+ val steps = remember { if (qualityStep && !Setup.permissionsDone(context)) 2 else 1 }+ Box(Modifier.fillMaxSize().background(AppBackground)) {+ Glow(Modifier.fillMaxSize(), alpha = 0.16f)+ Column(Modifier.fillMaxSize().statusBarsPadding().navigationBarsPadding()) {+ if (steps == 2) StepDots(current = if (qualityStep) 0 else 1, Modifier.padding(start = 20.dp, top = 16.dp))+ // One step slides away to the left as the next comes in from the right.+ AnimatedContent(+ targetState = qualityStep,+ transitionSpec = {+ (slideInHorizontally(tween(420, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(420))) togetherWith+ (slideOutHorizontally(tween(420, easing = FastOutSlowInEasing)) { -it / 3 } + fadeOut(tween(250)))+ },+ label = "setupStep",+ modifier = Modifier.weight(1f),+ ) { quality ->+ if (quality) QualityStep(onNext = {+ com.music.spotui.data.preferences.setQualityChosen(context)+ if (Setup.permissionsDone(context)) onDone() else qualityStep = false+ }) else PermissionsStep(onDone, onSpotiflac)+ }+ }}+}+/** Where the user is in the steps: the current one a longer green dash. */+@Composable+private fun StepDots(current: Int, modifier: Modifier = Modifier) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = modifier) {+ for (i in 0..1) {+ val w by animateDpAsState(if (i == current) 22.dp else 8.dp, tween(350), label = "dot")+ val c by animateColorAsState(if (i == current) Color(0xFF1DB954) else Color.White.copy(alpha = 0.25f), tween(350), label = "dotColor")+ Box(Modifier.height(6.dp).width(w).clip(RoundedCornerShape(50)).background(c))+ }+ }+}++/** Each part rising into place a beat after the one above it. */+@Composable+private fun Modifier.riseIn(index: Int): Modifier {+ val a = remember { Animatable(0f) }+ LaunchedEffect(Unit) { delay(80L + index * 70L); a.animateTo(1f, tween(450, easing = FastOutSlowInEasing)) }+ return graphicsLayer { alpha = a.value; translationY = (1f - a.value) * 18.dp.toPx() }+}++@Composable+private fun PermissionsStep(onDone: () -> Unit, onSpotiflac: () -> Unit) {+ val context = LocalContext.current+ // Re-read when coming back from a system dialog or the settings.+ var tick by remember { mutableIntStateOf(0) }+ LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(800); tick++ } }+ val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { tick++ }Column(- Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()- .verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 24.dp),+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(horizontal = 20.dp, vertical = 24.dp),verticalArrangement = Arrangement.spacedBy(12.dp),) {- Text(stringResource(R.string.setup_title), color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold)- Text(stringResource(R.string.setup_subtitle), color = Color(0xFFB3B3B3), fontSize = 14.sp)+ var row = 0+ Text(stringResource(R.string.setup_title), color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold, modifier = Modifier.riseIn(row++))+ Text(stringResource(R.string.setup_subtitle), color = Color(0xFFB3B3B3), fontSize = 14.sp, modifier = Modifier.riseIn(row++))Spacer(Modifier.height(8.dp))@Suppress("UNUSED_EXPRESSION") tickif (Build.VERSION.SDK_INT >= 33) SetupRow(stringResource(R.string.setup_notifications_title), stringResource(R.string.setup_notifications_detail),- granted(context, Manifest.permission.POST_NOTIFICATIONS),+ granted(context, Manifest.permission.POST_NOTIFICATIONS), Modifier.riseIn(row++),) { launcher.launch(Manifest.permission.POST_NOTIFICATIONS) }SetupRow(stringResource(R.string.setup_local_title), stringResource(R.string.setup_local_detail),- LocalMusic.hasPermission(context),+ LocalMusic.hasPermission(context), Modifier.riseIn(row++),) { launcher.launch(LocalMusic.permission) }if (Build.VERSION.SDK_INT >= 31) SetupRow(stringResource(R.string.setup_bluetooth_title), stringResource(R.string.setup_bluetooth_detail),- granted(context, Manifest.permission.BLUETOOTH_CONNECT),+ granted(context, Manifest.permission.BLUETOOTH_CONNECT), Modifier.riseIn(row++),) { launcher.launch(Manifest.permission.BLUETOOTH_CONNECT) }SetupRow(stringResource(R.string.setup_battery_title), stringResource(R.string.setup_battery_detail),- BatteryExemption.isExempt(context),+ BatteryExemption.isExempt(context), Modifier.riseIn(row++),) { BatteryExemption.request(context) }// Lossless downloads need SpotiFLAC's one-off verification (the quality toggle// lives in Settings); not verified yet, the lossless source stays OFF.if (com.music.spotui.data.preferences.getDownloadQuality(context) != com.music.spotui.data.preferences.DownloadQuality.OFF) SetupRow(stringResource(R.string.setup_spotiflac_title), stringResource(R.string.setup_spotiflac_detail),- com.music.spotui.data.preferences.hasSpotiflacSession(context),+ com.music.spotui.data.preferences.hasSpotiflacSession(context), Modifier.riseIn(row++),) { onSpotiflac() }Spacer(Modifier.height(12.dp))- Button(- onClick = { Setup.done(context); onDone() },- colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),- modifier = Modifier.fillMaxWidth().height(50.dp),- ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ Box(Modifier.riseIn(row)) {+ Button(+ onClick = { Setup.done(context); onDone() },+ colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),+ modifier = Modifier.fillMaxWidth().height(50.dp),+ ) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }+ }}}@@ -124,35 +185,41 @@ fun SetupScreen(onDone: () -> Unit, onSpotiflac: () -> Unit = {}) {@Composableprivate fun QualityStep(onNext: () -> Unit) {Column(- Modifier.fillMaxSize().background(AppBackground).statusBarsPadding().navigationBarsPadding()- .verticalScroll(rememberScrollState()).padding(vertical = 24.dp),+ Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(vertical = 24.dp),verticalArrangement = Arrangement.spacedBy(12.dp),) {Text(stringResource(R.string.setup_quality_title), color = Color.White, fontSize = 26.sp, fontWeight = FontWeight.Bold,- modifier = Modifier.padding(horizontal = 20.dp))+ modifier = Modifier.padding(horizontal = 20.dp).riseIn(0))Text(stringResource(R.string.setup_quality_subtitle), color = Color(0xFFB3B3B3), fontSize = 14.sp,- modifier = Modifier.padding(horizontal = 20.dp))- com.music.spotui.ui.components.StreamingQualityPicker(Modifier.padding(top = 8.dp))- com.music.spotui.ui.components.DownloadQualityPicker()+ modifier = Modifier.padding(horizontal = 20.dp).riseIn(1))+ Box(Modifier.riseIn(2)) { com.music.spotui.ui.components.StreamingQualityPicker(Modifier.padding(top = 8.dp)) }+ Box(Modifier.riseIn(3)) { com.music.spotui.ui.components.DownloadQualityPicker() }Button(onClick = onNext,colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF1DB954), contentColor = Color.Black),- modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).height(50.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp).height(50.dp).riseIn(4),) { Text(stringResource(R.string.setup_continue), fontWeight = FontWeight.Bold, fontSize = 16.sp) }}}@Composable-private fun SetupRow(title: String, detail: String, on: Boolean, onEnable: () -> Unit) {+private fun SetupRow(title: String, detail: String, on: Boolean, modifier: Modifier = Modifier, onEnable: () -> Unit) {Row(verticalAlignment = Alignment.CenterVertically,- modifier = Modifier.fillMaxWidth().background(Color(0xFF1E1E1E), RoundedCornerShape(12.dp)).padding(16.dp),+ modifier = modifier.fillMaxWidth().background(Color(0xFF1E1E1E), RoundedCornerShape(12.dp)).padding(16.dp),) {Column(Modifier.weight(1f)) {Text(title, color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)Text(detail, color = Color(0xFFB3B3B3), fontSize = 13.sp)}- if (on) Icon(Icons.Default.CheckCircle, contentDescription = null, tint = Color(0xFF1DB954), modifier = Modifier.padding(start = 12.dp).size(28.dp))- else TextButton(onClick = onEnable) { Text(stringResource(R.string.setup_enable), color = Color(0xFF1DB954), fontWeight = FontWeight.Bold) }+ // Allowed: the button gives way to a green check that pops in.+ AnimatedContent(+ targetState = on,+ transitionSpec = { (scaleIn(spring(dampingRatio = 0.5f)) + fadeIn()) togetherWith (scaleOut() + fadeOut()) },+ label = "allowed",+ ) { allowed ->+ if (allowed) Icon(Icons.Default.CheckCircle, contentDescription = null, tint = Color(0xFF1DB954), modifier = Modifier.padding(start = 12.dp).size(28.dp))+ else TextButton(onClick = onEnable) { Text(stringResource(R.string.setup_enable), color = Color(0xFF1DB954), fontWeight = FontWeight.Bold) }+ }}}diff --git a/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt b/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.ktindex 36cb134a..c82875f0 100644--- a/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt+++ b/base/app/src/main/java/com/music/spotui/ui/screens/WelcomeScreen.kt@@ -1,5 +1,19 @@package com.music.spotui.ui.screens+import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.core.Animatable+import androidx.compose.animation.core.FastOutSlowInEasing+import androidx.compose.animation.core.LinearEasing+import androidx.compose.animation.core.animateFloat+import androidx.compose.animation.core.infiniteRepeatable+import androidx.compose.animation.core.rememberInfiniteTransition+import androidx.compose.animation.core.tween+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.Canvasimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.Arrangement@@ -15,12 +29,18 @@ import androidx.compose.foundation.layout.systemBarsPaddingimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clipimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.Brushimport androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.font.FontWeight@@ -29,68 +49,126 @@ import androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport app.myspoti.engine.Rimport com.music.spotui.ui.components.pressable+import com.music.spotui.ui.theme.AppAccentimport com.music.spotui.ui.theme.AppBackgroundimport com.music.spotui.ui.theme.AppSans+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlin.math.PI+import kotlin.math.cos+import kotlin.math.sin/*** First screen of a signed-out app: what Myspoti is, then Spotify's own login page- * (shown by the engine once [onLogin] is tapped).+ * (shown by the engine once [onLogin] is tapped). The logo, the name, what the app adds and+ * the button rise into place one after the other, over a soft green light that drifts.*/@Composablefun WelcomeScreen(onLogin: () -> Unit) {- Box(- Modifier- .fillMaxSize()- .background(AppBackground)- .background(- Brush.radialGradient(- colors = listOf(Color(0x551ED760), Color.Transparent),- center = Offset(540f, 380f),- radius = 1100f,- ),- )- .systemBarsPadding()- .padding(horizontal = 28.dp, vertical = 24.dp),- ) {- Column(- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.Center,- modifier = Modifier.fillMaxWidth().align(Alignment.Center).padding(bottom = 120.dp),- ) {- Image(- painter = painterResource(R.drawable.ic_launcher_foreground),- contentDescription = null,- modifier = Modifier.size(132.dp).clip(RoundedCornerShape(36.dp)).background(Color(0xFF181818)),- )- Spacer(Modifier.height(28.dp))- Text("Myspoti", color = Color.White, fontFamily = AppSans, fontWeight = FontWeight.ExtraBold, fontSize = 40.sp)- Text(- stringResource(R.string.welcome_tagline),- color = Color.White.copy(alpha = 0.7f), fontFamily = AppSans, fontSize = 17.sp, lineHeight = 24.sp,- textAlign = TextAlign.Center, modifier = Modifier.padding(top = 12.dp),- )- }- Column(- horizontalAlignment = Alignment.CenterHorizontally,- modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter),- ) {- Box(- contentAlignment = Alignment.Center,- modifier = Modifier- .fillMaxWidth()- .height(54.dp)- .pressable(0.96f, onClick = onLogin)- .clip(RoundedCornerShape(50))- .background(com.music.spotui.ui.theme.AppAccent),+ // One entrance per part, a beat apart: logo, name, features, button.+ val parts = remember { List(4) { Animatable(0f) } }+ LaunchedEffect(Unit) {+ parts.forEachIndexed { i, a -> launch { delay(150L + i * 180L); a.animateTo(1f, tween(650, easing = FastOutSlowInEasing)) } }+ }+ fun Modifier.rise(i: Int) = graphicsLayer {+ val v = parts[i].value+ alpha = v+ translationY = (1f - v) * 24.dp.toPx()+ }+ Box(Modifier.fillMaxSize().background(AppBackground)) {+ Glow(Modifier.fillMaxSize())+ Box(Modifier.fillMaxSize().systemBarsPadding().padding(horizontal = 28.dp, vertical = 24.dp)) {+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ modifier = Modifier.fillMaxWidth().align(Alignment.Center).padding(bottom = 120.dp),+ ) {+ Image(+ painter = painterResource(R.drawable.ic_launcher_foreground),+ contentDescription = null,+ modifier = Modifier+ .size(120.dp)+ .graphicsLayer {+ val v = parts[0].value+ alpha = v+ val s = 0.85f + 0.15f * v+ scaleX = s; scaleY = s+ }+ .clip(RoundedCornerShape(32.dp))+ .background(Color(0xFF181818)),+ )+ Spacer(Modifier.height(28.dp))+ Text("Myspoti", color = Color.White, fontFamily = AppSans, fontWeight = FontWeight.ExtraBold, fontSize = 40.sp,+ modifier = Modifier.rise(1))+ Spacer(Modifier.height(12.dp))+ Box(Modifier.rise(2)) { Features() }+ }+ Column(+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth().align(Alignment.BottomCenter).rise(3),) {- Text(stringResource(R.string.welcome_login), color = Color.Black, fontFamily = AppSans,- fontWeight = FontWeight.Bold, fontSize = 17.sp)+ Box(+ contentAlignment = Alignment.Center,+ modifier = Modifier+ .fillMaxWidth()+ .height(54.dp)+ .pressable(0.96f, onClick = onLogin)+ .clip(RoundedCornerShape(50))+ .background(AppAccent),+ ) {+ Text(stringResource(R.string.welcome_login), color = Color.Black, fontFamily = AppSans,+ fontWeight = FontWeight.Bold, fontSize = 17.sp)+ }+ Text(+ stringResource(R.string.welcome_privacy),+ color = Color.White.copy(alpha = 0.5f), fontFamily = AppSans, fontSize = 13.sp, lineHeight = 18.sp,+ textAlign = TextAlign.Center, modifier = Modifier.padding(top = 14.dp),+ )}- Text(- stringResource(R.string.welcome_privacy),- color = Color.White.copy(alpha = 0.5f), fontFamily = AppSans, fontSize = 13.sp, lineHeight = 18.sp,- textAlign = TextAlign.Center, modifier = Modifier.padding(top = 14.dp),- )+ }+ }+}++/** A soft green light behind the logo, drifting slowly. */+@Composable+internal fun Glow(modifier: Modifier = Modifier, alpha: Float = 0.30f) {+ val t = rememberInfiniteTransition(label = "glow")+ val phase by t.animateFloat(0f, (2 * PI).toFloat(), infiniteRepeatable(tween(16_000, easing = LinearEasing)), label = "phase")+ Canvas(modifier) {+ val c = Offset(size.width * (0.5f + 0.12f * sin(phase)), size.height * (0.30f + 0.05f * cos(phase)))+ val r = size.width * 1.05f+ drawCircle(Brush.radialGradient(listOf(AppAccent.copy(alpha = alpha), Color.Transparent), c, r), r, c)+ }+}++/** "Your music," then what Myspoti adds to it, one feature after the other. */+@Composable+private fun Features() {+ val features = listOf(+ stringResource(R.string.welcome_rotate_ads),+ stringResource(R.string.welcome_rotate_lyrics),+ stringResource(R.string.welcome_rotate_clips),+ stringResource(R.string.welcome_rotate_lossless),+ stringResource(R.string.welcome_rotate_offline),+ )+ var index by remember { mutableIntStateOf(0) }+ LaunchedEffect(Unit) {+ delay(1_200)+ while (true) { delay(2_400); index = (index + 1) % features.size }+ }+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ Text(stringResource(R.string.welcome_lead), color = Color.White.copy(alpha = 0.7f), fontFamily = AppSans,+ fontSize = 17.sp, textAlign = TextAlign.Center)+ AnimatedContent(+ targetState = index,+ transitionSpec = {+ (slideInVertically(tween(400, easing = FastOutSlowInEasing)) { it / 2 } + fadeIn(tween(400))) togetherWith+ (slideOutVertically(tween(400, easing = FastOutSlowInEasing)) { -it / 2 } + fadeOut(tween(250)))+ },+ label = "feature",+ ) { i ->+ Text(features[i], color = Color.White, fontFamily = AppSans, fontWeight = FontWeight.Bold, fontSize = 19.sp,+ textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth().padding(top = 2.dp))}}}diff --git a/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt b/base/app/src/main/java/com/music/spotui/ui/theme/Theme.ktindex f2a4486b..efa11a7a 100644--- a/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt+++ b/base/app/src/main/java/com/music/spotui/ui/theme/Theme.kt@@ -79,6 +79,9 @@ fun SpotuiTheme(// B19: the navigation bar was left to the system — a white band under the always-dark// UI (reported in the modal sheets, where the bar was opaque) with dark icons on it.window.navigationBarColor = Color.Transparent.toArgb()+ // Without this Android lays its own translucent scrim on a transparent bar (API 29+),+ // which showed as a differently coloured strip under the full-screen Canvas.+ window.isNavigationBarContrastEnforced = falseWindowCompat.getInsetsController(window, view).isAppearanceLightNavigationBars = false}}diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.ktindex c66ba9fd..f5c7947e 100644--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LibraryViewModel.kt@@ -3,6 +3,7 @@ package com.music.spotui.ui.viewmodelimport com.music.spotui.di.Graphimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope+import com.music.spotui.data.api.LibraryEditsimport com.music.spotui.data.api.Responseimport com.music.spotui.data.entity.AccountModelimport com.music.spotui.data.entity.LibraryEntry@@ -14,6 +15,7 @@ import com.music.spotui.ui.repository.AppRepositoryimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.dropimport kotlinx.coroutines.launchclass LibraryViewModel constructor(@@ -31,10 +33,21 @@ class LibraryViewModel constructor(MutableStateFlow(emptyList())val followedArtists: StateFlow<List<com.music.spotui.data.entity.ArtistsModel>> = _followedArtists+ /** The list as Spotify gave it; [entries] is this with the changes not yet in Spotify's list on top. */+ @Volatile private var server: List<LibraryEntry>? = null++ private fun show() {+ val list = server ?: return+ _entries.value = Response.Success(LibraryEdits.applyTo(null, list))+ }+init {// Seed UI with the last-seen library immediately so it's visible offline.val cached = getCachedLibraryEntries(context)- if (cached.isNotEmpty()) _entries.value = Response.Success(cached)+ if (cached.isNotEmpty()) { server = cached; show() }+ // A delete, rename or new playlist is shown at once, and taken back if Spotify refuses.+ viewModelScope.launch { LibraryEdits.version.drop(1).collect { show() } }+ viewModelScope.launch { LibraryEdits.reloads.collect { load() } }val cachedArtists = getCachedFollowedArtists(context)if (cachedArtists.isNotEmpty()) _followedArtists.value = cachedArtists@@ -43,6 +56,20 @@ class LibraryViewModel constructor(loadFollowedArtists()}+ private val _refreshing = MutableStateFlow(false)+ /** A pull-to-refresh is reading the library again. */+ val refreshing: StateFlow<Boolean> = _refreshing++ fun refresh() {+ if (_refreshing.value) return+ _refreshing.value = true+ viewModelScope.launch {+ // Both flows end when Spotify has answered (or failed): that is when the spinner goes.+ kotlinx.coroutines.joinAll(load(), loadFollowedArtists())+ _refreshing.value = false+ }+ }+fun load() = viewModelScope.launch(Dispatchers.IO) {repository.provideLibrary().collect { response ->// Offline: keep the saved library instead of replacing it with a@@ -53,8 +80,11 @@ class LibraryViewModel constructor(_entries.value = Response.Success(emptyList())return@collect}- _entries.value = response- if (response is Response.Success) cacheLibraryEntries(context, response.data)+ if (response is Response.Success) {+ server = response.data+ show()+ cacheLibraryEntries(context, response.data)+ } else _entries.value = response}}diff --git a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.ktindex 6ec951c2..9be3855d 100644--- a/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt+++ b/base/app/src/main/java/com/music/spotui/ui/viewmodel/LyricsViewModel.kt@@ -40,13 +40,26 @@ class LyricsViewModel constructor() : ViewModel() {if (force) LyricsApi.forget(track)// Already resolved (prefetched while the track started): no loading flash.LyricsApi.cached(track)?.let { _state.value = loadedState(it); return }- _state.value = State.Loading+ // Read again (the setting changed): the lyrics shown stay until the new ones replace them.+ if (!(force && _state.value is State.Loaded)) _state.value = State.Loading+ // Spotify's own lines shown as soon as they are there; the word-timed ones replace them.+ val earlyJob = viewModelScope.launch {+ LyricsApi.early.collect { e ->+ if (e != null && e.first == key && loadedKey == key && _state.value is State.Loading) _state.value = loadedState(e.second)+ }+ }viewModelScope.launch(Dispatchers.IO) {val lyrics = LyricsApi.fetch(track)+ earlyJob.cancel()withContext(Dispatchers.Main) {// A skip during the fetch: don't show the previous song's lyrics.if (loadedKey != key) return@withContext- _state.value = if (lyrics == null || lyrics.isEmpty) State.NotFound else loadedState(lyrics)+ val shown = (_state.value as? State.Loaded)?.lyrics+ _state.value = when {+ lyrics == null || lyrics.isEmpty -> if (shown != null) _state.value else State.NotFound+ shown == lyrics -> _state.value+ else -> loadedState(lyrics)+ }}}}diff --git a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.ktindex 20d2f4fe..69bd2924 100644--- a/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt+++ b/base/app/src/main/java/com/music/spotui/video/MusicVideoController.kt@@ -18,6 +18,8 @@ import androidx.media3.exoplayer.dash.DashMediaSourceimport androidx.media3.exoplayer.dash.manifest.DashManifestParserimport androidx.media3.exoplayer.source.ProgressiveMediaSourceimport com.music.spotui.di.Graph+import app.myspoti.host.android.Logbook+import app.myspoti.host.android.MyspotiRuntimeimport com.music.spotui.di.SongPlayerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -108,14 +110,48 @@ object MusicVideoController {}private fun cacheFile(trackId: String) = File(cacheDir, "$trackId.json").also { it.parentFile?.mkdirs() }+ // The answers of the last songs only (a time map or "none", a few KB each): coming back to a+ // song shows its answer at once, with no disk and no job. No audio, no features, no decoder.+ private const val RECENT_MAX = 20+ private const val NONE_TTL_MS = 7 * 86_400_000L+ /** Bumped when the search finds clips it missed before (Spotify-confirmed label uploads, "$" names). */+ private const val NONE_RULES = 2+ private class Recent(val state: State, val at: Long)+ private val recent = object : LinkedHashMap<String, Recent>(32, 0.75f, true) {+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Recent>) = size > RECENT_MAX+ }+ // A failed look-up (network, decoding) waits 30 s before the next try, also after a skip and a return.+ private val failedUntil = HashMap<String, Long>()++ private fun recentAnswer(trackId: String): State? = synchronized(cacheLock) {+ val r = recent[trackId] ?: return@synchronized null+ if (r.state is State.Unavailable && System.currentTimeMillis() - r.at >= NONE_TTL_MS) { recent.remove(trackId); null } else r.state+ }++ private fun remember(trackId: String, s: State, at: Long = System.currentTimeMillis()) {+ if (s !is State.Ready && s !is State.Unavailable) return+ // The retained clip files belong to one running refinement, never to a remembered answer.+ synchronized(cacheLock) { recent[trackId] = Recent(if (s is State.Ready) s.copy(refinementToken = null) else s, at) }+ }++ private fun markFailed(trackId: String) {+ val now = SystemClock.elapsedRealtime()+ failedUntil.values.removeAll { it <= now }+ failedUntil[trackId] = now + 30_000+ }+private fun readCache(trackId: String): State? = synchronized(cacheLock) {+ recentAnswer(trackId)?.let { return@synchronized it }runCatching {val f = cacheFile(trackId)if (!f.exists()) return@runCatching nullval o = JSONObject(f.readText())+ // A file that is read stays among the recent ones when old entries are pruned.+ if (System.currentTimeMillis() - f.lastModified() > 86_400_000L) f.setLastModified(System.currentTimeMillis())if (o.optBoolean("none")) {- return@runCatching if (System.currentTimeMillis() - o.optLong("at") < 7 * 86_400_000L)- State.Unavailable else null+ // "No clip" found under older search rules is looked up again.+ return@runCatching if (o.optInt("rules") >= NONE_RULES && System.currentTimeMillis() - o.optLong("at") < NONE_TTL_MS)+ State.Unavailable.also { remember(trackId, it, o.optLong("at")) } else null}val score = o.getDouble("score")require(score.isFinite() && score >= MIN_SCORE)@@ -128,6 +164,7 @@ object MusicVideoController {require(segments.all { it.songStartMs >= 0 && it.songEndMs > it.songStartMs })require(segments.zipWithNext().all { (a, b) -> a.songEndMs <= b.songStartMs })State.Ready(trackId, o.getString("video"), AudioAlign.TimeMap(segments, score), mapComplete = o.optBoolean("complete"))+ .also { remember(trackId, it) }}.getOrElse {Log.w(TAG, "Ignoring invalid music video cache: ${it.javaClass.simpleName}")null@@ -144,7 +181,7 @@ object MusicVideoController {s.map.segments.forEach { put(JSONObject().put("from", it.songStartMs).put("to", it.songEndMs).put("offset", it.offsetMs)) }})}- else -> o.put("none", true).put("at", System.currentTimeMillis())+ else -> o.put("none", true).put("at", System.currentTimeMillis()).put("rules", NONE_RULES)}runCatching {val file = AtomicFile(cacheFile(trackId))@@ -157,17 +194,52 @@ object MusicVideoController {throw t}}+ remember(trackId, s)+ }+ }++ // Disk and cache folder stay small: old answers go, and clip files a killed run left behind.+ private const val KEEP_FILES = 300+ private const val KEEP_MS = 60 * 86_400_000L+ private const val TMP_MAX_AGE_MS = 3 * 3_600_000L++ private fun housekeeping() {+ val now = System.currentTimeMillis()+ app.cacheDir.listFiles { f ->+ f.isFile && (f.name.startsWith("mv_ref_") || f.name.startsWith("mv_cand_") || f.name.startsWith("mv_full_")) && now - f.lastModified() > TMP_MAX_AGE_MS+ }?.forEach { it.delete() }+ synchronized(cacheLock) {+ val kept = (cacheDir.listFiles() ?: return).filter { f ->+ val expired = !f.isFile || now - f.lastModified() > KEEP_MS || (f.name.endsWith(".json") && runCatching {+ JSONObject(f.readText()).let { it.optBoolean("none") && now - it.optLong("at") >= NONE_TTL_MS }+ }.getOrDefault(false))+ if (expired && f.isFile) f.delete()+ !expired+ }+ kept.sortedByDescending { it.lastModified() }.drop(KEEP_FILES).forEach { it.delete() }}}+ init {+ // Once per start, a little after it, so it never competes with the first screen.+ scope.launch(Dispatchers.IO) { delay(15_000); runCatching { housekeeping() } }+ }+// Background look-ups for tracks not on screen yet (the next one), one at a time.private val prefetching = java.util.Collections.synchronizedSet(HashSet<String>())private val prefetchJobs = java.util.concurrent.ConcurrentHashMap<String, Job>()-+ // The last prefetched track and when to look again: the caller repeats on every player+ // update, and without this each repeat would read and parse the disk cache again.+ @Volatile private var settledId = ""+ @Volatile private var settledUntil = 0L/** Resolve and cache a track's video in the background, without touching the UI state. */fun prefetch(trackId: String, title: String, artist: String, durationMs: Long) {- if (com.music.spotui.data.DataSaver.active || !appVisible || !EnergySettings.state.value.policy.allowBackgroundLookups || trackId.isBlank() || trackId == currentTrackId || !prefetching.add(trackId)) return+ if (com.music.spotui.data.DataSaver.active || !appVisible || !EnergySettings.state.value.policy.allowBackgroundLookups || trackId.isBlank() || trackId == currentTrackId) return+ if (trackId == settledId && SystemClock.elapsedRealtime() < settledUntil) return+ // Already answered (or failed a moment ago): nothing to look up, nothing to read.+ if (recentAnswer(trackId) != null || SystemClock.elapsedRealtime() < (failedUntil[trackId] ?: 0L)) return+ if (!prefetching.add(trackId)) returnval request = -prefetchSequence.incrementAndGet()val published = java.util.concurrent.atomic.AtomicBoolean(false)val job = scope.launch(start = kotlinx.coroutines.CoroutineStart.LAZY) {@@ -176,6 +248,10 @@ object MusicVideoController {val result = withContext(Dispatchers.IO) {readCache(trackId) ?: resolve(trackId, title, artist, durationMs, request).also { if (it != null) writeCache(trackId, it) }}+ // Only the answer on disk is kept: no audio, no features, no clip stream is held for a song not playing yet.+ settledId = trackId+ settledUntil = if (result != null) Long.MAX_VALUE else SystemClock.elapsedRealtime() + 30_000+ if (result == null) markFailed(trackId)if (trackId == currentTrackId && state.value is State.Searching) {if (result == null) nextPrepareAt = SystemClock.elapsedRealtime() + 30_000state.value = result ?: State.Idle@@ -185,6 +261,9 @@ object MusicVideoController {} catch (t: kotlinx.coroutines.CancellationException) {throw t} catch (t: Throwable) {+ settledId = trackId+ settledUntil = SystemClock.elapsedRealtime() + 30_000+ markFailed(trackId)if (trackId == currentTrackId && state.value is State.Searching) {nextPrepareAt = SystemClock.elapsedRealtime() + 30_000state.value = State.Idle@@ -224,6 +303,15 @@ object MusicVideoController {if (on.value) { on.value = false; fullscreen.value = false; syncJob?.cancel() }warmedFor = nullplayer?.let { it.stop(); it.clearMediaItems() }+ // Back on a song already answered: its stored answer is used at once, nothing is looked up again.+ recentAnswer(trackId)?.let { hit ->+ state.value = hit+ if (hit is State.Ready) { preloadStream(hit.videoUrl); resumeWanted() }+ return+ }+ // A look-up that failed less than 30 s ago waits, even when the song was left and came back.+ val retryAt = failedUntil[trackId] ?: 0L+ if (SystemClock.elapsedRealtime() < retryAt) { nextPrepareAt = retryAt; state.value = State.Idle; return }state.value = State.Searchingif (trackId in prefetching) returnprepareJob = scope.launch {@@ -233,14 +321,16 @@ object MusicVideoController {val cached = readCache(trackId)if (cached != null) cached else {val resolved = resolve(trackId, title, artist, durationMs, request)- currentCoroutineContext().ensureActive()+ // A finished look-up is stored even when the song was left meanwhile.if (resolved != null) writeCache(trackId, resolved)+ currentCoroutineContext().ensureActive()resolved}}if (generation.get() != request || currentTrackId != trackId) return@launchif (result == null) {nextPrepareAt = SystemClock.elapsedRealtime() + 30_000+ markFailed(trackId)state.value = State.Idlereturn@launch}@@ -252,6 +342,7 @@ object MusicVideoController {} catch (t: Throwable) {if (generation.get() == request) {nextPrepareAt = SystemClock.elapsedRealtime() + 30_000+ markFailed(trackId)state.value = State.Idle}Log.w(TAG, "Video preparation failed: ${t.javaClass.simpleName}")@@ -283,6 +374,13 @@ object MusicVideoController {val song = async(Dispatchers.IO) {runInterruptible { YouTubeSource.findSong(title, artist, durationMs) ?: YouTubeSource.findAudio(title, artist, durationMs) }}+ // Spotify has a clip of this song (its "switch to video"): a label's upload that+ // YouTube files as an ordinary video can be it (Bu$hi's "6 O'clock").+ val spotifyHasVideo = async(Dispatchers.IO) {+ kotlinx.coroutines.withTimeoutOrNull(4_000) {+ runCatching { MyspotiRuntime.api.catalog.track("spotify:track:$trackId").hasVideo }.getOrNull()+ } ?: false+ }val candidates = withContext(Dispatchers.IO) {YouTubeSource.videoCandidates(title, artist, durationMs)}.take(6)@@ -292,14 +390,17 @@ object MusicVideoController {downloadAudioFile(reference.url, refFile)runInterruptible { AudioAlign.features(AudioAlign.decode(refFile, 45)) }}+ val relaxed = spotifyHasVideo.await()+ if (relaxed) Log.i(TAG, "$title: Spotify has a clip of it, ordinary uploads checked too")val result = firstVerifiedClip(candidates,+ accepts = { it == "MUSIC_VIDEO_TYPE_OMV" || (relaxed && it == "MUSIC_VIDEO_TYPE_UGC") },classify = { c -> withContext(Dispatchers.IO) { runInterruptible { YouTubeSource.musicVideoType(c.url) } } },verify = { c ->val candFile = File(app.cacheDir, "mv_cand_${trackId}_${candidateFiles.size}_$token")candidateFiles.add(candFile)try {val info = withContext(Dispatchers.IO) { runInterruptible { YouTubeSource.info(c.url) } }- val trusted = YouTubeSource.isTrustedClip(info, artist)+ val trusted = YouTubeSource.isTrustedClip(info, artist, relaxed)if (!trusted) Log.i(TAG, "candidate ${info.name} (${info.uploaderName}, verified=${info.isUploaderVerified}): not the artist's clip")val still = if (trusted) withContext(Dispatchers.IO) { runInterruptible { YouTubeSource.isStatic(info) } } else falsewhen {@@ -454,7 +555,7 @@ object MusicVideoController {// and buffered as soon as the Now Playing screen shows (paused, at the mapped time),// so "Passer à la vidéo" only attaches the surface and plays.- private data class VideoSource(val url: String, val source: androidx.media3.exoplayer.source.MediaSource, val durationMs: Long, val at: Long, val maxHeight: Int)+ private data class VideoSource(val url: String, val source: androidx.media3.exoplayer.source.MediaSource, val durationMs: Long, val at: Long, val maxHeight: Int, val audio: androidx.media3.exoplayer.source.MediaSource? = null)private val sources = java.util.concurrent.ConcurrentHashMap<String, VideoSource>()private val resolving = java.util.Collections.synchronizedSet(HashSet<String>())@Volatile private var warmedFor: String? = null@@ -503,7 +604,7 @@ object MusicVideoController {val p = ensurePlayer()p.setMediaSource(vs.source)p.prepare()- p.seekTo(s.map.toVideo(SongPlayer.getCurrentPosition() + 400))+ p.seekTo(s.map.toVideo(SongPlayer.getCurrentPosition() + 400 - outputLagMs()))p.playWhenReady = falsewarmedFor = s.videoUrlvideoDurationMs = vs.durationMs@@ -601,13 +702,15 @@ object MusicVideoController {val vs = freshSource(s.videoUrl)if (vs == null) { preloadStream(s.videoUrl) { if (on.value && s.trackId == currentTrackId) start(s) }; return }val p = ensurePlayer()- if (warmedFor != s.videoUrl || p.playbackState == Player.STATE_IDLE) {- p.setMediaSource(vs.source)+ val withSound = clipSound.value && vs.audio != null+ val key = s.videoUrl + if (withSound) SOUND_KEY else ""+ if (warmedFor != key || p.playbackState == Player.STATE_IDLE) {+ p.setMediaSource(if (withSound) androidx.media3.exoplayer.source.MergingMediaSource(true, vs.source, vs.audio!!) else vs.source)p.prepare()- warmedFor = s.videoUrl+ warmedFor = key}videoDurationMs = vs.durationMs- p.seekTo(s.map.toVideo(SongPlayer.getCurrentPosition()))+ p.seekTo(s.map.toVideo((SongPlayer.getCurrentPosition() - outputLagMs()).coerceAtLeast(0)))p.playWhenReady = SongPlayer.isPlaying() && !SongPlayer.isBufferingp.addListener(object : Player.Listener {override fun onRenderedFirstFrame() {@@ -631,6 +734,20 @@ object MusicVideoController {}}+ private val hwDecoders = HashMap<String, Boolean>()++ /** Whether the phone has a hardware decoder for [mime] (software VP9 at 1080p drops frames). */+ private fun hardwareDecodes(mime: String): Boolean = synchronized(hwDecoders) {+ hwDecoders.getOrPut(mime) {+ if (android.os.Build.VERSION.SDK_INT < 29) return@getOrPut false+ runCatching {+ android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any { info ->+ !info.isEncoder && info.isHardwareAccelerated && info.supportedTypes.any { it.equals(mime, ignoreCase = true) }+ }+ }.getOrDefault(false)+ }+ }+private fun buildSource(url: String, fresh: Boolean = false): VideoSource {val t0 = SystemClock.elapsedRealtime()val info = YouTubeSource.info(url, fresh = fresh)@@ -641,13 +758,22 @@ object MusicVideoController {val lowestHeight = allStreams.minOfOrNull { it.height }allStreams.filter { it.height == lowestHeight }}- // H.264 remains preferred; the saver cap selects a smaller available stream.- val preferredHeight = minOf(720, maxHeight)- val avc = streams.filter { it.format == MediaFormat.MPEG_4 && it.codec?.startsWith("avc") == true }- val v = avc.filter { it.height <= preferredHeight }.maxByOrNull { it.height }- ?: avc.minByOrNull { it.height }- ?: streams.filter { it.height <= preferredHeight }.maxByOrNull { it.height }- ?: streams.minByOrNull { it.height }+ // The sharpest picture the network allows (reported: "rather mediocre" at 720p H.264):+ // 1080p on Wi-Fi, 720p on mobile data, the saver cap below both. At a height, VP9 when the+ // phone decodes it in hardware (sharper than H.264 at the same size), else H.264.+ val preferredHeight = minOf(if (com.music.spotui.data.DataSaver.metered) 720 else 1080, maxHeight)+ val fits = streams.filter { it.height <= preferredHeight }.ifEmpty { streams.filter { it.height == streams.minOf { s -> s.height } } }+ val vp9 = hardwareDecodes("video/x-vnd.on2.vp9")+ fun rank(st: org.schabi.newpipe.extractor.stream.VideoStream): Int {+ val c = st.codec.orEmpty()+ return when {+ c.startsWith("avc") && st.format == MediaFormat.MPEG_4 -> 1+ vp9 && (c == "vp9" || c.startsWith("vp09.00")) && st.format == MediaFormat.WEBM -> 2+ else -> 0+ }+ }+ val v = fits.filter { rank(it) > 0 }.maxWithOrNull(compareBy({ it.height }, { rank(it) }))+ ?: fits.maxByOrNull { it.height }?: error("no video stream")Log.i(TAG, "video ${v.height}p ${v.codec}")val headers = streamHeaders(v.content)@@ -664,7 +790,67 @@ object MusicVideoController {} else {ProgressiveMediaSource.Factory(http).createMediaSource(MediaItem.fromUri(v.content))}- return VideoSource(url, source, info.duration * 1000, SystemClock.elapsedRealtime(), maxHeight)+ // The clip's soundtrack, for "clip sound" only (nothing is fetched until it is played).+ val a = info.audioStreams.filter { it.format == MediaFormat.M4A }.ifEmpty { info.audioStreams }+ .let { list -> list.filter { it.averageBitrate in 1..160 }.maxByOrNull { it.averageBitrate } ?: list.minByOrNull { it.averageBitrate } }+ val audio = a?.let { st ->+ val h = streamHeaders(st.content)+ val ahttp = DefaultHttpDataSource.Factory()+ .apply { h["User-Agent"]?.let { setUserAgent(it) } }+ .setDefaultRequestProperties(h - "User-Agent")+ .setAllowCrossProtocolRedirects(true)+ runCatching {+ val ai = st.itagItem+ if (ai != null) {+ val mpd = YoutubeProgressiveDashManifestCreator.fromProgressiveStreamingUrl(st.content, ai, info.duration)+ DashMediaSource.Factory(ahttp).createMediaSource(DashManifestParser().parse(Uri.parse(st.content), mpd.byteInputStream()), MediaItem.fromUri(st.content))+ } else ProgressiveMediaSource.Factory(ahttp).createMediaSource(MediaItem.fromUri(st.content))+ }.getOrNull()+ }+ return VideoSource(url, source, info.duration * 1000, SystemClock.elapsedRealtime(), maxHeight, audio)+ }++ private const val SOUND_KEY = "#sound"+ private val prefs by lazy { app.getSharedPreferences("music_video", Context.MODE_PRIVATE) }++ /** The clip's own sound is heard instead of the song's (kept across songs and restarts). */+ val clipSound = mutableStateOf(false).also { st -> scope.launch { st.value = prefs.getBoolean("clip_sound", false) } }++ fun setClipSound(value: Boolean) {+ com.music.spotui.di.Haptics.click()+ clipSound.value = value+ prefs.edit().putBoolean("clip_sound", value).apply()+ if (!value) hush(false)+ // The clip is played again with (or without) its soundtrack, at the same place.+ (state.value as? State.Ready)?.let { if (on.value) start(it) }+ }++ /** The song is unheard on the phone: the clip's sound is what plays. */+ @Volatile private var hushed = false+ private var hushedFor = ""+ @Volatile private var hushWanted = false+ private val hushLock = kotlinx.coroutines.sync.Mutex()++ private fun hush(on: Boolean) {+ val track = SongPlayer.currentTrackId+ if (on == hushed && (!on || hushedFor == track)) return+ hushed = on+ hushedFor = if (on) track else ""+ player?.volume = if (on) 1f else 0f+ Logbook.log(if (on) "clip sound: the clip is heard, the song plays on unheard" else "clip sound: the song is heard")+ // Applied in order, the last wish wins (a quick on/off never leaves the song unheard).+ hushWanted = on+ scope.launch(Dispatchers.IO) { hushLock.withLock { MyspotiRuntime.spotify.player.setHushed(hushWanted) } }+ }++ /**+ * How late the sound is heard after the page plays it: Bluetooth delays it (reported: the clip+ * "out of sync from time to time" — with earbuds on). The picture follows what is heard.+ */+ private fun outputLagMs(): Long {+ // The clip's own sound: picture and sound leave the same player, already together.+ if (hushed) return 0L+ return com.music.spotui.di.OutputLag.ms()}/** Keeps the video on the song: small drifts by speed, big ones by seeking. */@@ -677,6 +863,12 @@ object MusicVideoController {val playing = SongPlayer.isPlaying()val shown = playing && !SongPlayer.isBuffering && appVisible && surfaces > 0 && SongPlayer.activeDevice.value == nullif (p.playWhenReady != shown) p.playWhenReady = shown+ // Clip sound: the song goes unheard only while the clip is really playing with its+ // sound; buffering, paused, an ad or anything else, the song is heard again at once.+ val sounding = shown && clipSound.value && warmedFor?.endsWith(SOUND_KEY) == true &&+ p.isPlaying && SongPlayer.currentTrackId == currentTrackId && !SongPlayer.adPlaying+ hush(sounding)+ p.volume = if (hushed) 1f else 0fif (!shown) {if (p.playbackParameters.speed != 1f) p.playbackParameters = PlaybackParameters(1f)delay(500)@@ -684,10 +876,19 @@ object MusicVideoController {}if (p.playbackState == Player.STATE_READY) {if (p.duration > 0) videoDurationMs = p.duration- val target = map.toVideo(SongPlayer.getCurrentPosition())+ val target = map.toVideo((SongPlayer.getCurrentPosition() - outputLagMs()).coerceAtLeast(0))val drift = p.currentPosition - targetwhen {- abs(drift) > 600 -> { p.seekTo(target); p.playbackParameters = PlaybackParameters(1f) }+ // A seek holds the picture until the frame is decoded (a visible freeze,+ // reported): seen only, a drift under 2.5 s is caught up by speed instead.+ (if (hushed) abs(drift) > 600 else abs(drift) > 2_500) -> {+ Logbook.log("clip: ${drift} ms off at ${SongPlayer.getCurrentPosition()} ms of the song, put back")+ p.seekTo(target); p.playbackParameters = PlaybackParameters(1f)+ }+ // Heard, the clip is corrected gently (a 10 % change is heard); seen only, firmly.+ hushed && abs(drift) > 120 -> p.playbackParameters = PlaybackParameters((1f - drift / 4000f).coerceIn(0.97f, 1.03f))+ hushed -> if (p.playbackParameters.speed != 1f && abs(drift) < 40) p.playbackParameters = PlaybackParameters(1f)+ playing && abs(drift) > 600 -> p.playbackParameters = PlaybackParameters((1f - drift / 2000f).coerceIn(0.6f, 1.5f))playing && abs(drift) > 40 -> p.playbackParameters = PlaybackParameters((1f - drift / 2000f).coerceIn(0.9f, 1.1f))p.playbackParameters.speed != 1f -> p.playbackParameters = PlaybackParameters(1f)}@@ -699,6 +900,7 @@ object MusicVideoController {private fun stop() {syncJob?.cancel()+ hush(false)player?.let { it.playWhenReady = false }refineJob?.cancel()// Keep the buffered source: switching back on is instant.@@ -743,7 +945,8 @@ object MusicVideoController {return}prepareJob?.cancel()- prefetchJobs.values.forEach { it.cancel() }+ // The look-up of the song about to start is not thrown away: prepare() adopts it when it finishes.+ prefetchJobs.forEach { (id, job) -> if (id != trackId || currentTrackId == trackId) job.cancel() }refineJob?.cancel()if (state.value is State.Searching) { state.value = State.Idle; nextPrepareAt = 0L }if (trackId.isNotBlank() && currentTrackId != trackId) {@@ -777,6 +980,9 @@ object MusicVideoController {on.value = falseprepareJob?.cancel()prefetchJobs.values.forEach { it.cancel() }+ settledId = ""+ synchronized(cacheLock) { recent.clear() }+ failedUntil.clear()stop()player?.stop()currentTrackId = ""@@ -787,6 +993,7 @@ object MusicVideoController {/** App in the background: the video pauses (nothing to show), video mode stays. */fun onBackground() {appVisible = false+ hush(false)prepareJob?.cancel()prefetchJobs.values.forEach { it.cancel() }refineJob?.cancel()diff --git a/base/app/src/main/java/com/music/spotui/video/OrderedClipResolver.kt b/base/app/src/main/java/com/music/spotui/video/OrderedClipResolver.ktindex 3ab570da..4e54be37 100644--- a/base/app/src/main/java/com/music/spotui/video/OrderedClipResolver.kt+++ b/base/app/src/main/java/com/music/spotui/video/OrderedClipResolver.kt@@ -9,6 +9,8 @@ internal data class ClipResolution<T>(val value: T?, val failed: Boolean)/** Rank is preserved; at most two classifications and one audio candidate at a time. */internal suspend fun <C, T> firstVerifiedClip(candidates: List<C>,+ /** The YouTube Music types worth a check: official music videos only, unless told otherwise. */+ accepts: (String) -> Boolean = { it == "MUSIC_VIDEO_TYPE_OMV" },classify: suspend (C) -> String?,verify: suspend (C) -> ClipVerification<T>,): ClipResolution<T> = coroutineScope {@@ -19,7 +21,7 @@ internal suspend fun <C, T> firstVerifiedClip(for ((index, candidate) in batch.withIndex()) {val type = types[index].await()if (type == null) { failed = true; continue }- if (type != "MUSIC_VIDEO_TYPE_OMV") continue+ if (!accepts(type)) continueverified++val result = verify(candidate)failed = failed || result.faileddiff --git a/base/app/src/main/java/com/music/spotui/video/YouTubeSource.kt b/base/app/src/main/java/com/music/spotui/video/YouTubeSource.ktindex 66f8af15..256dadec 100644--- a/base/app/src/main/java/com/music/spotui/video/YouTubeSource.kt+++ b/base/app/src/main/java/com/music/spotui/video/YouTubeSource.kt@@ -93,7 +93,8 @@ object YouTubeSource {data class Hit(val url: String, val name: String, val uploader: String, val durationSec: Long)- private fun folded(s: String) = java.text.Normalizer.normalize(s, java.text.Normalizer.Form.NFD)+ // "$" read as "s" in names: "Bu$hi" is the channel "BUSHI", "A$AP" is "ASAP".+ private fun folded(s: String) = java.text.Normalizer.normalize(s.replace('$', 's'), java.text.Normalizer.Form.NFD).replace(Regex("""\p{M}+"""), "").lowercase(Locale.ROOT)private fun norm(s: String) = folded(s)@@ -282,9 +283,12 @@ object YouTubeSource {* the artists' own (or their VEVO / Topic), or a verified channel (label, radio)* whose title says it is a clip.*/- fun isTrustedClip(info: StreamInfo, artist: String): Boolean {+ fun isTrustedClip(info: StreamInfo, artist: String, spotifyHasVideo: Boolean = false): Boolean {val name = info.name.orEmpty()if (excluded.containsMatchIn(name) || notAClip.containsMatchIn(name)) return false+ // Spotify itself has the clip: a label's channel (unverified, its upload filed as an+ // ordinary video) can be the one; the soundtrack check still decides.+ if (spotifyHasVideo) return trueval hit = Hit(info.url, name, info.uploaderName.orEmpty(), info.duration)val own = artist.split(",").map { it.trim() }.filter { it.isNotEmpty() }.any { sameArtist(hit, it) }return own || (info.isUploaderVerified && looksLikeClip(name))diff --git a/base/app/src/main/res/values-de/myspoti_strings.xml b/base/app/src/main/res/values-de/myspoti_strings.xmlindex e9d4c71f..d1300130 100644--- a/base/app/src/main/res/values-de/myspoti_strings.xml+++ b/base/app/src/main/res/values-de/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti-eigene Texte (Englisch als Standard, Deutsch). --><resources><string name="welcome_tagline">Deine Musik, mit synchronisierten Songtexten und offiziellen Musikvideos.</string>+ <string name="welcome_lead">Deine Musik,</string>+ <string name="welcome_rotate_ads">ohne Werbung.</string>+ <string name="welcome_rotate_lyrics">mit Lyrics Wort für Wort.</string>+ <string name="welcome_rotate_clips">mit den offiziellen Videos.</string>+ <string name="welcome_rotate_offline">sogar offline.</string>+ <string name="welcome_rotate_lossless">in verlustfreier Qualität.</string><string name="welcome_login">Mit Spotify anmelden</string><string name="welcome_privacy">Du meldest dich auf Spotifys eigener Seite an. Myspoti sieht dein Passwort nie.</string><string name="crash_heading">Myspoti ist abgestürzt</string>@@ -270,7 +276,7 @@<string name="playlist_access_private">Privat</string><string name="playlist_access_private_detail">Nur du kannst sie sehen</string><string name="playlist_access_collaborative">Gemeinsam</string>- <string name="playlist_access_collaborative_detail">Alle mit dem Link können Songs hinzufügen und entfernen</string>+ <string name="playlist_access_collaborative_detail">Nur eingeladene Personen können Songs hinzufügen und entfernen</string><string name="playlist_on_profile">Auf deinem Profil</string><string name="playlist_on_profile_detail">Auf deinem Profil für andere sichtbar</string><string name="choose_artist">Künstler auswählen</string>@@ -335,4 +341,165 @@<string name="download_on_mobile_data">Download über mobile Daten: Er verbraucht dein Datenvolumen</string><string name="restart_player_done">Player neu gestartet</string><string name="spotify_limited">Spotify begrenzt die Wiedergabe gerade. Versuche es in einer Minute erneut.</string>+ <string name="library_change_undone">Spotify hat die Änderung abgelehnt, deine Bibliothek ist wieder wie vorher</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">Eine Playlist aus deinem Geschmack und dem eines Freundes</string>+ <string name="blend_invite">Freund zu einem Blend einladen</string>+ <string name="blend_join">Mit Link beitreten</string>+ <string name="blend_join_title">Einladungslink einfügen</string>+ <string name="blend_join_button">Beitreten</string>+ <string name="blend_invite_message">Lass uns einen Blend auf Spotify machen: %1$s</string>+ <string name="blend_failed">Spotify-Blend nicht erreichbar, versuche es erneut</string>+ <string name="blend_bad_link">Das ist kein Blend-Einladungslink</string>+ <string name="blend_own_invite">Das ist deine eigene Einladung: schick sie an einen Freund</string>+ <string name="blend_full">Dieser Blend ist voll</string>+ <string name="blend_deleted">Dieser Blend wurde gelöscht</string>+ <string name="blend_working">Wird ausgeführt…</string>+ <string name="blend_invited_by">%1$s lädt dich zu einem Blend ein</string>+ <string name="blend_open">Blend öffnen</string>+ <string name="blend_later">Später</string>+ <string name="blend_members">Mitglieder</string>+ <string name="blend_invite_more">Weitere Personen einladen</string>+ <string name="blend_rename">Blend umbenennen</string>+ <string name="blend_leave">Blend verlassen</string>+ <string name="blend_leave_confirm">%1$s verlassen? Es verschwindet aus deiner Bibliothek, die anderen behalten es.</string>+ <string name="blend_leave_button">Verlassen</string>+ <string name="playlist_invite_banner">Du wurdest eingeladen, an dieser Playlist mitzuarbeiten</string>+ <string name="playlist_invite_join">Beitreten</string>+ <string name="playlist_invite_joined">Du bist jetzt Mitwirkender</string>+ <string name="podcast_download_protected">Diese Folge ist exklusiv bei Spotify: Sie lässt sich nur in der Spotify-App abspielen, nicht herunterladen.</string>+ <string name="podcast_download_unavailable">Diese Folge kann nicht heruntergeladen werden: Die Audiodatei des Verlags fehlt.</string>+ <string name="podcast_download_failed">Download fehlgeschlagen. Versuch es erneut.</string>+ <string name="ad_playing">Werbung</string>+ <string name="track_unavailable_region">In deiner Region nicht verfügbar</string>+ <string name="diagnostic_export_title">Diagnosebericht exportieren</string>+ <string name="diagnostic_export_detail">Teilt das aktuelle Protokoll der App und die Gerätedaten</string>+ <string name="diagnostic_export_failed">Der Diagnosebericht konnte nicht geschrieben werden</string>+ <string name="recently_played_title">Zuletzt gespielt</string>+ <string name="recently_played_empty">Was du mit diesem Konto abspielst, erscheint hier.</string>+ <string name="recently_played_failed">Die Liste der zuletzt gespielten Titel konnte nicht geladen werden (%1$s)</string>+ <string name="recents_title">Zuletzt</string>+ <string name="recents_detail">Was du auf allen Geräten gespielt hast</string>+ <string name="recents_filter_music">Musik</string>+ <string name="recents_filter_podcasts">Podcasts</string>+ <string name="recents_today">Heute</string>+ <string name="recents_yesterday">Gestern</string>+ <string name="recents_played_one">1 Titel gespielt</string>+ <string name="recents_played_many">%1$d Titel gespielt</string>+ <string name="recents_saved_one">1 Titel hinzugefügt</string>+ <string name="recents_saved_many">%1$d Titel hinzugefügt</string>+ <string name="recents_expand">Titel anzeigen</string>+ <string name="recents_collapse">Titel ausblenden</string>+ <string name="settings_auto_update_title">Beim Start nach Updates suchen</string>+ <string name="settings_auto_update_detail">Aus: Beim Start der App wird nicht gesucht. Die manuelle Suche unten funktioniert weiterhin.</string>+ <string name="settings_check_update_title">Jetzt nach Updates suchen</string>+ <string name="settings_check_update_detail">Sucht nach einer neueren Version und bietet die Installation an</string>+ <string name="settings_update_checking">Wird geprüft…</string>+ <string name="settings_update_check_latest">Myspoti ist auf dem neuesten Stand</string>+ <string name="downloads_stop_all_title">Alle Downloads stoppen</string>+ <string name="downloads_stop_all_detail">Bricht ab, was noch übrig ist; bereits heruntergeladene Songs bleiben erhalten</string>+ <string name="context_menu_remove_from_playlist">Aus dieser Playlist entfernen</string>+ <string name="context_menu_add_to_another_playlist">Zu einer anderen Playlist hinzufügen</string>+ <string name="add_to_playlist_search_hint">Playlist suchen</string>+ <string name="add_to_playlist_empty">Du hast keine Playlist, zu der du diesen Titel hinzufügen kannst</string>+ <string name="add_to_playlist_no_match">Keine Playlist passt zu \"%1$s\"</string>+ <string name="undo">Rückgängig</string>+ <string name="settings_crossfade_title">Crossfade (Titel werden ausgeblendet, überlappen sich nicht)</string>+ <string name="settings_crossfade_detail">Ein Titel blendet in seinen letzten Sekunden aus, der nächste blendet ein. Sie spielen nie gleichzeitig: ein Player, ein Audiostream.</string>+ <string name="settings_crossfade_off">Aus</string>+ <string name="settings_crossfade_seconds">%1$ds</string>+ <string name="show_follow">Folgen</string>+ <string name="show_following">Gefolgt</string>+ <string name="show_tab_episodes">Episoden</string>+ <string name="show_tab_chapters">Kapitel</string>+ <string name="show_tab_about">Info</string>+ <string name="show_sort_newest">Alle Episoden • Neueste</string>+ <string name="show_sort_oldest">Alle Episoden • Älteste</string>+ <string name="show_sort_chapters_newest">Alle Kapitel • Neueste</string>+ <string name="show_sort_chapters_oldest">Alle Kapitel • Älteste</string>+ <string name="show_empty">Hier gibt es noch nichts zum Abspielen</string>+ <string name="show_rating">%1$s (%2$s)</string>+ <string name="show_authors">Von %1$s</string>+ <string name="show_narrators">Gelesen von %1$s</string>+ <string name="show_followed">Du folgst diesem Podcast jetzt</string>+ <string name="show_unfollowed">Du folgst diesem Podcast nicht mehr</string>+ <string name="episode_duration_min">%1$d Min.</string>+ <string name="episode_remaining">noch %1$s</string>+ <string name="episode_mark_played">Als gehört markieren</string>+ <string name="episode_mark_unplayed">Als nicht gestartet markieren</string>+ <string name="episode_marked_played">Als gehört markiert</string>+ <string name="episode_marked_unplayed">Als nicht gestartet markiert</string>+ <string name="episode_play">Abspielen</string>+ <string name="episode_open">Episode öffnen</string>+ <string name="episode_add_queue">Zur Warteschlange hinzufügen</string>+ <string name="episode_show_more">mehr anzeigen</string>+ <string name="episode_show_less">weniger anzeigen</string>+ <string name="episode_download">Herunterladen</string>+ <string name="episode_downloading">Wird heruntergeladen…</string>+ <string name="episode_downloaded">Heruntergeladen</string>+ <string name="episode_download_remove">Download entfernen</string>+ <string name="episode_options">Episodenoptionen</string>+ <string name="episode_not_found">Episode nicht gefunden</string>+ <string name="show_not_found">Podcast nicht gefunden</string>+ <string name="podcast_playing_from">Wird aus dem Podcast abgespielt</string>+ <string name="player_speed_chip">%1$s×</string>+ <string name="player_back_15">15 Sekunden zurück</string>+ <string name="player_forward_15">15 Sekunden vor</string>+ <string name="player_show_remaining">Verbleibende Zeit anzeigen</string>+ <string name="player_show_elapsed">Vergangene Zeit anzeigen</string>+ <string name="player_sleep_timer">Schlaftimer</string>+ <string name="player_speed_a11y">Wiedergabegeschwindigkeit, %1$s×</string>+ <string name="settings_keep_playing_title">Nach dem Schließen weiterspielen</string>+ <string name="settings_keep_playing_detail">Aus: Myspoti in den letzten Apps schließen stoppt die Musik</string>+ <string name="recommended_songs_from_name">Basierend auf dem Namen dieser Playlist</string>+ <string name="recommended_songs_from_songs">Basierend auf dem Inhalt dieser Playlist</string>+ <string name="recommended_songs_refresh">Aktualisieren</string>+ <string name="recommended_songs_add">Zu dieser Playlist hinzufügen</string>+ <string name="smart_shuffle_recommended">Von Smart Shuffle empfohlen</string>+ <string name="smart_shuffle_add">Zu dieser Playlist hinzufügen</string>+ <string name="add_songs_title">Zu dieser Playlist hinzufügen</string>+ <string name="add_songs_close">Schließen</string>+ <string name="add_songs_search_hint">Nach Songs suchen</string>+ <string name="add_songs_nothing">Keine Songs für „%1$s“ gefunden</string>+ <string name="add_songs_added">Hinzugefügt</string>+ <string name="spotify_code_description">Spotify-Code</string>+ <string name="spotify_code_hint">Scanne ihn in Spotify (Suche, dann Kamera), um ihn zu öffnen.</string>+ <string name="spotify_code_share_image">Code teilen</string>+ <string name="copy_link">Link kopieren</string>+ <string name="link_copied">Link kopiert</string>+ <string name="lyrics_meaning_title">Bedeutung</string>+ <string name="lyrics_meaning_about">Info</string>+ <string name="lyrics_meaning_lines">Zeilen erklärt</string>+ <string name="lyrics_meaning_source">Von Genius · Song dort öffnen</string>+ <string name="lyrics_meaning_translating">Wird übersetzt …</string>+ <string name="lyrics_meaning_translate">Übersetzen</string>+ <string name="lyrics_meaning_original">Original anzeigen</string>+ <string name="lyrics_meaning_hint">Gepunktete Zeilen: halte eine gedrückt für die Erklärung von Genius.</string>+ <string name="clip_sound_song">Ton: Song</string>+ <string name="clip_sound_clip">Ton: Clip</string>+ <string name="clip_sound_on_hint">Du hörst jetzt den Ton des Clips. Der Song läuft stumm auf Spotify weiter und zählt weiterhin.</string>+ <string name="clip_sound_off_hint">Du hörst wieder den Spotify-Song.</string>+ <string name="lyrics_word_sync_title">Wort für Wort</string>+ <string name="lyrics_word_sync_on">Karaoke-Timing zuerst (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Zeile für Zeile, Spotify zuerst</string>+ <string name="playlist_invite_collaborators">Mitwirkende einladen</string>+ <string name="playlist_invite_message">Mach bei meiner Playlist „%1$s“ auf Spotify mit, du kannst Songs hinzufügen: %2$s</string>+ <string name="playlist_invite_failed">Einladungslink konnte nicht erstellt werden</string>+ <string name="playlist_by">Von %1$s</string>+ <string name="playlist_make_public">Öffentlich machen</string>+ <string name="playlist_make_private">Privat machen</string>+ <string name="playlist_stop_collab">Zusammenarbeit beenden</string>+ <string name="playlist_add_profile">Zum Profil hinzufügen</string>+ <string name="playlist_remove_profile">Vom Profil entfernen</string>+ <string name="playlist_now_public">Die Playlist ist öffentlich</string>+ <string name="playlist_now_private">Die Playlist ist privat</string>+ <string name="playlist_now_solo">Nur du kannst jetzt Songs hinzufügen</string>+ <string name="playlist_now_on_profile">Zu deinem Profil hinzugefügt</string>+ <string name="playlist_now_off_profile">Von deinem Profil entfernt</string>+ <string name="playlist_collab_locked">Gemeinsame Playlist: Um Songs hinzuzufügen, bitte %1$s um einen Einladungslink.</string>+ <string name="playlist_collab_owner">den Ersteller</string>+ <string name="playlist_members_title">Mitwirkende</string>+ <string name="playlist_member_owner">Ersteller</string>+ <string name="playlist_member_collab">Mitwirkende*r</string>+ <string name="playlist_members_more">%1$s und %2$d weitere</string></resources>diff --git a/base/app/src/main/res/values-el/myspoti_strings.xml b/base/app/src/main/res/values-el/myspoti_strings.xmlindex aee9b18d..59d2c137 100644--- a/base/app/src/main/res/values-el/myspoti_strings.xml+++ b/base/app/src/main/res/values-el/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti's own texts (English default, French, Italian, Greek). --><resources><string name="welcome_tagline">Η μουσική σου, με συγχρονισμένους στίχους και επίσημα μουσικά βίντεο.</string>+ <string name="welcome_lead">Η μουσική σου,</string>+ <string name="welcome_rotate_ads">χωρίς διαφημίσεις.</string>+ <string name="welcome_rotate_lyrics">με στίχους λέξη προς λέξη.</string>+ <string name="welcome_rotate_clips">με τα επίσημα βίντεο.</string>+ <string name="welcome_rotate_offline">ακόμα και εκτός σύνδεσης.</string>+ <string name="welcome_rotate_lossless">σε ποιότητα χωρίς απώλειες.</string><string name="welcome_login">Σύνδεση με Spotify</string><string name="welcome_privacy">Συνδέεσαι στη σελίδα του Spotify. Το Myspoti δεν βλέπει ποτέ τον κωδικό σου.</string><string name="crash_heading">Το Myspoti σταμάτησε να λειτουργεί</string>@@ -270,7 +276,7 @@<string name="playlist_access_private">Ιδιωτική</string><string name="playlist_access_private_detail">Μόνο εσύ μπορείς να τη δεις</string><string name="playlist_access_collaborative">Συνεργατική</string>- <string name="playlist_access_collaborative_detail">Όποιος έχει τον σύνδεσμο μπορεί να προσθέτει και να αφαιρεί τραγούδια</string>+ <string name="playlist_access_collaborative_detail">Μόνο όσοι προσκαλείς μπορούν να προσθέτουν και να αφαιρούν τραγούδια</string><string name="playlist_on_profile">Στο προφίλ σου</string><string name="playlist_on_profile_detail">Εμφανίζεται στο προφίλ σου για τους άλλους</string><string name="choose_artist">Επίλεξε καλλιτέχνη</string>@@ -335,4 +341,165 @@<string name="download_on_mobile_data">Λήψη με δεδομένα κινητής: χρησιμοποιεί το πακέτο δεδομένων σου</string><string name="restart_player_done">Η αναπαραγωγή ξεκίνησε ξανά</string><string name="spotify_limited">Το Spotify περιορίζει προσωρινά την αναπαραγωγή. Δοκιμάστε ξανά σε ένα λεπτό.</string>+ <string name="library_change_undone">Το Spotify απέρριψε την αλλαγή, η βιβλιοθήκη σας επανήλθε όπως ήταν</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">Μια playlist με τα γούστα σας και ενός φίλου</string>+ <string name="blend_invite">Πρόσκληση φίλου σε Blend</string>+ <string name="blend_join">Συμμετοχή με σύνδεσμο</string>+ <string name="blend_join_title">Επικολλήστε τον σύνδεσμο πρόσκλησης</string>+ <string name="blend_join_button">Συμμετοχή</string>+ <string name="blend_invite_message">Ας φτιάξουμε ένα Blend στο Spotify: %1$s</string>+ <string name="blend_failed">Δεν ήταν δυνατή η επικοινωνία με το Blend του Spotify, δοκιμάστε ξανά</string>+ <string name="blend_bad_link">Αυτός δεν είναι σύνδεσμος πρόσκλησης Blend</string>+ <string name="blend_own_invite">Αυτή είναι η δική σας πρόσκληση: στείλτε την σε έναν φίλο</string>+ <string name="blend_full">Αυτό το Blend είναι πλήρες</string>+ <string name="blend_deleted">Αυτό το Blend διαγράφηκε</string>+ <string name="blend_working">Σε εξέλιξη…</string>+ <string name="blend_invited_by">Ο/Η %1$s σε προσκαλεί σε ένα Blend</string>+ <string name="blend_open">Άνοιγμα του Blend</string>+ <string name="blend_later">Όχι τώρα</string>+ <string name="blend_members">Μέλη</string>+ <string name="blend_invite_more">Πρόσκληση περισσότερων ατόμων</string>+ <string name="blend_rename">Μετονομασία του Blend</string>+ <string name="blend_leave">Αποχώρηση από το Blend</string>+ <string name="blend_leave_confirm">Αποχώρηση από το %1$s; Φεύγει από τη βιβλιοθήκη σου, οι άλλοι το κρατούν.</string>+ <string name="blend_leave_button">Αποχώρηση</string>+ <string name="playlist_invite_banner">Έχετε προσκληθεί να συνεργαστείτε σε αυτήν τη λίστα αναπαραγωγής</string>+ <string name="playlist_invite_join">Συμμετοχή</string>+ <string name="playlist_invite_joined">Είστε πλέον συνεργάτης</string>+ <string name="podcast_download_protected">Αυτό το επεισόδιο είναι αποκλειστικό του Spotify: μπορεί να παιχτεί μόνο στην εφαρμογή Spotify, δεν μπορεί να γίνει λήψη του.</string>+ <string name="podcast_download_unavailable">Δεν είναι δυνατή η λήψη αυτού του επεισοδίου: λείπει το αρχείο ήχου του εκδότη.</string>+ <string name="podcast_download_failed">Η λήψη απέτυχε. Δοκίμασε ξανά.</string>+ <string name="ad_playing">Διαφήμιση</string>+ <string name="track_unavailable_region">Μη διαθέσιμο στην περιοχή σου</string>+ <string name="diagnostic_export_title">Εξαγωγή αναφοράς διαγνωστικών</string>+ <string name="diagnostic_export_detail">Μοιράζεται το πρόσφατο αρχείο καταγραφής της εφαρμογής και τα στοιχεία της συσκευής</string>+ <string name="diagnostic_export_failed">Δεν ήταν δυνατή η εγγραφή της αναφοράς διαγνωστικών</string>+ <string name="recently_played_title">Πρόσφατα αναπαραγωγής</string>+ <string name="recently_played_empty">Ό,τι παίζεις σε αυτόν τον λογαριασμό εμφανίζεται εδώ.</string>+ <string name="recently_played_failed">Δεν ήταν δυνατή η φόρτωση της λίστας πρόσφατων αναπαραγωγών (%1$s)</string>+ <string name="recents_title">Πρόσφατα</string>+ <string name="recents_detail">Όσα έπαιξες, σε όλες τις συσκευές</string>+ <string name="recents_filter_music">Μουσική</string>+ <string name="recents_filter_podcasts">Podcast</string>+ <string name="recents_today">Σήμερα</string>+ <string name="recents_yesterday">Χθες</string>+ <string name="recents_played_one">1 κομμάτι αναπαράχθηκε</string>+ <string name="recents_played_many">%1$d κομμάτια αναπαράχθηκαν</string>+ <string name="recents_saved_one">1 κομμάτι προστέθηκε</string>+ <string name="recents_saved_many">%1$d κομμάτια προστέθηκαν</string>+ <string name="recents_expand">Εμφάνιση των κομματιών</string>+ <string name="recents_collapse">Απόκρυψη των κομματιών</string>+ <string name="settings_auto_update_title">Έλεγχος για ενημερώσεις κατά την εκκίνηση</string>+ <string name="settings_auto_update_detail">Ανενεργό: δεν γίνεται έλεγχος όταν ανοίγει η εφαρμογή. Ο χειροκίνητος έλεγχος παρακάτω εξακολουθεί να λειτουργεί.</string>+ <string name="settings_check_update_title">Έλεγχος για ενημερώσεις τώρα</string>+ <string name="settings_check_update_detail">Αναζητά νεότερη έκδοση και προτείνει την εγκατάστασή της</string>+ <string name="settings_update_checking">Έλεγχος…</string>+ <string name="settings_update_check_latest">Το Myspoti είναι ενημερωμένο</string>+ <string name="downloads_stop_all_title">Διακοπή όλων των λήψεων</string>+ <string name="downloads_stop_all_detail">Ακυρώνει ό,τι απομένει· τα τραγούδια που έχουν ήδη ληφθεί διατηρούνται</string>+ <string name="context_menu_remove_from_playlist">Αφαίρεση από αυτή την playlist</string>+ <string name="context_menu_add_to_another_playlist">Προσθήκη σε άλλη playlist</string>+ <string name="add_to_playlist_search_hint">Αναζήτηση playlist</string>+ <string name="add_to_playlist_empty">Δεν έχεις playlist στην οποία να προσθέσεις αυτό το κομμάτι</string>+ <string name="add_to_playlist_no_match">Καμία playlist δεν ταιριάζει με το \"%1$s\"</string>+ <string name="undo">Αναίρεση</string>+ <string name="settings_crossfade_title">Crossfade (τα κομμάτια ξεθωριάζουν, δεν επικαλύπτονται)</string>+ <string name="settings_crossfade_detail">Ένα κομμάτι ξεθωριάζει τα τελευταία δευτερόλεπτά του και το επόμενο εμφανίζεται σταδιακά. Δεν παίζουν ποτέ ταυτόχρονα: ένας αναπαραγωγός, ένα ηχητικό ρεύμα.</string>+ <string name="settings_crossfade_off">Ανενεργό</string>+ <string name="settings_crossfade_seconds">%1$ds</string>+ <string name="show_follow">Ακολούθησε</string>+ <string name="show_following">Ακολουθείς</string>+ <string name="show_tab_episodes">Επεισόδια</string>+ <string name="show_tab_chapters">Κεφάλαια</string>+ <string name="show_tab_about">Πληροφορίες</string>+ <string name="show_sort_newest">Όλα τα επεισόδια • Νεότερα</string>+ <string name="show_sort_oldest">Όλα τα επεισόδια • Παλαιότερα</string>+ <string name="show_sort_chapters_newest">Όλα τα κεφάλαια • Νεότερα</string>+ <string name="show_sort_chapters_oldest">Όλα τα κεφάλαια • Παλαιότερα</string>+ <string name="show_empty">Δεν υπάρχει ακόμα τίποτα προς αναπαραγωγή εδώ</string>+ <string name="show_rating">%1$s (%2$s)</string>+ <string name="show_authors">Από %1$s</string>+ <string name="show_narrators">Αφήγηση: %1$s</string>+ <string name="show_followed">Ακολουθείς πλέον αυτό το podcast</string>+ <string name="show_unfollowed">Δεν ακολουθείς πλέον αυτό το podcast</string>+ <string name="episode_duration_min">%1$d λεπτ.</string>+ <string name="episode_remaining">Απομένουν %1$s</string>+ <string name="episode_mark_played">Σήμανση ως ακουσμένο</string>+ <string name="episode_mark_unplayed">Σήμανση ως μη ξεκινημένο</string>+ <string name="episode_marked_played">Σημάνθηκε ως ακουσμένο</string>+ <string name="episode_marked_unplayed">Σημάνθηκε ως μη ξεκινημένο</string>+ <string name="episode_play">Αναπαραγωγή</string>+ <string name="episode_open">Άνοιγμα επεισοδίου</string>+ <string name="episode_add_queue">Προσθήκη στην ουρά</string>+ <string name="episode_show_more">εμφάνιση περισσότερων</string>+ <string name="episode_show_less">εμφάνιση λιγότερων</string>+ <string name="episode_download">Λήψη</string>+ <string name="episode_downloading">Λήψη…</string>+ <string name="episode_downloaded">Ελήφθη</string>+ <string name="episode_download_remove">Κατάργηση λήψης</string>+ <string name="episode_options">Επιλογές επεισοδίου</string>+ <string name="episode_not_found">Το επεισόδιο δεν βρέθηκε</string>+ <string name="show_not_found">Το podcast δεν βρέθηκε</string>+ <string name="podcast_playing_from">Αναπαραγωγή από το podcast</string>+ <string name="player_speed_chip">%1$s×</string>+ <string name="player_back_15">Πίσω 15 δευτερόλεπτα</string>+ <string name="player_forward_15">Μπροστά 15 δευτερόλεπτα</string>+ <string name="player_show_remaining">Εμφάνιση του υπολειπόμενου χρόνου</string>+ <string name="player_show_elapsed">Εμφάνιση του χρόνου που πέρασε</string>+ <string name="player_sleep_timer">Χρονοδιακόπτης ύπνου</string>+ <string name="player_speed_a11y">Ταχύτητα αναπαραγωγής, %1$s×</string>+ <string name="settings_keep_playing_title">Συνέχιση αναπαραγωγής μετά το κλείσιμο</string>+ <string name="settings_keep_playing_detail">Απενεργοποιημένο: το κλείσιμο του Myspoti από τις πρόσφατες εφαρμογές σταματά τη μουσική</string>+ <string name="recommended_songs_from_name">Με βάση το όνομα αυτής της playlist</string>+ <string name="recommended_songs_from_songs">Με βάση το περιεχόμενο αυτής της playlist</string>+ <string name="recommended_songs_refresh">Ανανέωση</string>+ <string name="recommended_songs_add">Προσθήκη σε αυτή την playlist</string>+ <string name="smart_shuffle_recommended">Πρόταση της έξυπνης τυχαίας σειράς</string>+ <string name="smart_shuffle_add">Προσθήκη σε αυτή τη λίστα</string>+ <string name="add_songs_title">Προσθήκη σε αυτή τη λίστα</string>+ <string name="add_songs_close">Κλείσιμο</string>+ <string name="add_songs_search_hint">Αναζήτηση τραγουδιών</string>+ <string name="add_songs_nothing">Δεν βρέθηκαν τραγούδια για «%1$s»</string>+ <string name="add_songs_added">Προστέθηκε</string>+ <string name="spotify_code_description">Κωδικός Spotify</string>+ <string name="spotify_code_hint">Σάρωσέ τον στο Spotify (Αναζήτηση, μετά κάμερα) για να ανοίξει.</string>+ <string name="spotify_code_share_image">Κοινοποίηση κωδικού</string>+ <string name="copy_link">Αντιγραφή συνδέσμου</string>+ <string name="link_copied">Ο σύνδεσμος αντιγράφηκε</string>+ <string name="lyrics_meaning_title">Σημασία</string>+ <string name="lyrics_meaning_about">Σχετικά</string>+ <string name="lyrics_meaning_lines">Οι στίχοι εξηγημένοι</string>+ <string name="lyrics_meaning_source">Από το Genius · άνοιγμα του τραγουδιού εκεί</string>+ <string name="lyrics_meaning_translating">Μετάφραση…</string>+ <string name="lyrics_meaning_translate">Μετάφραση</string>+ <string name="lyrics_meaning_original">Δες το πρωτότυπο</string>+ <string name="lyrics_meaning_hint">Στίχοι με τελείες: κράτα πατημένο έναν για την εξήγηση του Genius.</string>+ <string name="clip_sound_song">Ήχος: τραγούδι</string>+ <string name="clip_sound_clip">Ήχος: βίντεο</string>+ <string name="clip_sound_on_hint">Τώρα ακούς τον ήχο του βίντεο. Το τραγούδι συνεχίζει σιωπηλά στο Spotify και μετράει κανονικά.</string>+ <string name="clip_sound_off_hint">Ακούς ξανά το τραγούδι του Spotify.</string>+ <string name="lyrics_word_sync_title">Λέξη προς λέξη</string>+ <string name="lyrics_word_sync_on">Συγχρονισμός καραόκε πρώτα (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Γραμμή προς γραμμή, πρώτα Spotify</string>+ <string name="playlist_invite_collaborators">Πρόσκληση συνεργατών</string>+ <string name="playlist_invite_message">Μπες στη λίστα μου «%1$s» στο Spotify, μπορείς να προσθέσεις τραγούδια: %2$s</string>+ <string name="playlist_invite_failed">Δεν ήταν δυνατή η δημιουργία συνδέσμου πρόσκλησης</string>+ <string name="playlist_by">Από %1$s</string>+ <string name="playlist_make_public">Δημόσια</string>+ <string name="playlist_make_private">Ιδιωτική</string>+ <string name="playlist_stop_collab">Τέλος συνεργασίας</string>+ <string name="playlist_add_profile">Προσθήκη στο προφίλ</string>+ <string name="playlist_remove_profile">Αφαίρεση από το προφίλ</string>+ <string name="playlist_now_public">Η λίστα είναι δημόσια</string>+ <string name="playlist_now_private">Η λίστα είναι ιδιωτική</string>+ <string name="playlist_now_solo">Μόνο εσύ μπορείς πλέον να προσθέτεις τραγούδια</string>+ <string name="playlist_now_on_profile">Προστέθηκε στο προφίλ σου</string>+ <string name="playlist_now_off_profile">Αφαιρέθηκε από το προφίλ σου</string>+ <string name="playlist_collab_locked">Συνεργατική λίστα: για να προσθέσεις τραγούδια, ζήτα από %1$s σύνδεσμο πρόσκλησης.</string>+ <string name="playlist_collab_owner">τον δημιουργό της</string>+ <string name="playlist_members_title">Συνεργάτες</string>+ <string name="playlist_member_owner">Δημιουργός</string>+ <string name="playlist_member_collab">Συνεργάτης</string>+ <string name="playlist_members_more">%1$s και %2$d ακόμα</string></resources>diff --git a/base/app/src/main/res/values-es/myspoti_strings.xml b/base/app/src/main/res/values-es/myspoti_strings.xmlindex b6a545ab..00b3ee28 100644--- a/base/app/src/main/res/values-es/myspoti_strings.xml+++ b/base/app/src/main/res/values-es/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti's own texts (English default, French, Italian). --><resources><string name="welcome_tagline">Tu música, con letras sincronizadas y vídeos musicales oficiales.</string>+ <string name="welcome_lead">Tu música,</string>+ <string name="welcome_rotate_ads">sin anuncios.</string>+ <string name="welcome_rotate_lyrics">con letras palabra por palabra.</string>+ <string name="welcome_rotate_clips">con los videoclips oficiales.</string>+ <string name="welcome_rotate_offline">incluso sin conexión.</string>+ <string name="welcome_rotate_lossless">en calidad sin pérdida.</string><string name="welcome_login">Inicia sesión con Spotify</string><string name="welcome_privacy">Inicias sesión en la página oficial de Spotify. Myspoti nunca ve tu contraseña.</string><string name="crash_heading">Myspoti se ha detenido</string>@@ -270,7 +276,7 @@<string name="playlist_access_private">Privada</string><string name="playlist_access_private_detail">Solo tú puedes verla</string><string name="playlist_access_collaborative">Colaborativa</string>- <string name="playlist_access_collaborative_detail">Cualquiera con el enlace puede añadir y quitar canciones</string>+ <string name="playlist_access_collaborative_detail">Solo las personas que invites pueden añadir y quitar canciones</string><string name="playlist_on_profile">En tu perfil</string><string name="playlist_on_profile_detail">Aparece en tu perfil para que otros la vean</string><string name="choose_artist">Elige un artista</string>@@ -335,4 +341,165 @@<string name="download_on_mobile_data">Descarga con datos móviles: usa tu tarifa de datos</string><string name="restart_player_done">Reproductor reiniciado</string><string name="spotify_limited">Spotify está limitando la reproducción por ahora. Inténtalo de nuevo en un minuto.</string>+ <string name="library_change_undone">Spotify rechazó el cambio, tu biblioteca vuelve a estar como antes</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">Una playlist con tus gustos y los de un amigo</string>+ <string name="blend_invite">Invitar a un amigo a un Blend</string>+ <string name="blend_join">Unirse con un enlace</string>+ <string name="blend_join_title">Pega el enlace de invitación</string>+ <string name="blend_join_button">Unirse</string>+ <string name="blend_invite_message">Hagamos un Blend en Spotify: %1$s</string>+ <string name="blend_failed">No se pudo contactar con el Blend de Spotify, inténtalo de nuevo</string>+ <string name="blend_bad_link">Ese no es un enlace de invitación a un Blend</string>+ <string name="blend_own_invite">Es tu propia invitación: envíasela a un amigo</string>+ <string name="blend_full">Este Blend está completo</string>+ <string name="blend_deleted">Este Blend se eliminó</string>+ <string name="blend_working">En curso…</string>+ <string name="blend_invited_by">%1$s te invita a un Blend</string>+ <string name="blend_open">Abrir el Blend</string>+ <string name="blend_later">Ahora no</string>+ <string name="blend_members">Miembros</string>+ <string name="blend_invite_more">Invitar a más personas</string>+ <string name="blend_rename">Cambiar el nombre del Blend</string>+ <string name="blend_leave">Salir del Blend</string>+ <string name="blend_leave_confirm">¿Salir de %1$s? Sale de tu biblioteca; los demás lo conservan.</string>+ <string name="blend_leave_button">Salir</string>+ <string name="playlist_invite_banner">Te han invitado a colaborar en esta lista</string>+ <string name="playlist_invite_join">Unirse</string>+ <string name="playlist_invite_joined">Ya eres colaborador</string>+ <string name="podcast_download_protected">Este episodio es exclusivo de Spotify: solo se puede reproducir en la app de Spotify, no descargar.</string>+ <string name="podcast_download_unavailable">No se puede descargar este episodio: falta el archivo de audio del editor.</string>+ <string name="podcast_download_failed">La descarga ha fallado. Inténtalo de nuevo.</string>+ <string name="ad_playing">Anuncio</string>+ <string name="track_unavailable_region">No disponible en tu región</string>+ <string name="diagnostic_export_title">Exportar un informe de diagnóstico</string>+ <string name="diagnostic_export_detail">Comparte el registro reciente de la app y los datos del dispositivo</string>+ <string name="diagnostic_export_failed">No se pudo guardar el informe de diagnóstico</string>+ <string name="recently_played_title">Reproducido recientemente</string>+ <string name="recently_played_empty">Lo que reproduzcas con esta cuenta aparecerá aquí.</string>+ <string name="recently_played_failed">No se pudo cargar la lista de reproducidos recientemente (%1$s)</string>+ <string name="recents_title">Recientes</string>+ <string name="recents_detail">Lo que has reproducido, en todos los dispositivos</string>+ <string name="recents_filter_music">Música</string>+ <string name="recents_filter_podcasts">Podcasts</string>+ <string name="recents_today">Hoy</string>+ <string name="recents_yesterday">Ayer</string>+ <string name="recents_played_one">1 canción reproducida</string>+ <string name="recents_played_many">%1$d canciones reproducidas</string>+ <string name="recents_saved_one">1 canción añadida</string>+ <string name="recents_saved_many">%1$d canciones añadidas</string>+ <string name="recents_expand">Mostrar las canciones</string>+ <string name="recents_collapse">Ocultar las canciones</string>+ <string name="settings_auto_update_title">Buscar actualizaciones al abrir</string>+ <string name="settings_auto_update_detail">Desactivado: no se busca al iniciar la app. La búsqueda manual de abajo sigue funcionando.</string>+ <string name="settings_check_update_title">Buscar actualizaciones ahora</string>+ <string name="settings_check_update_detail">Busca una versión más nueva y ofrece instalarla</string>+ <string name="settings_update_checking">Comprobando…</string>+ <string name="settings_update_check_latest">Myspoti está actualizado</string>+ <string name="downloads_stop_all_title">Detener todas las descargas</string>+ <string name="downloads_stop_all_detail">Cancela lo que queda; las canciones ya descargadas se conservan</string>+ <string name="context_menu_remove_from_playlist">Quitar de esta playlist</string>+ <string name="context_menu_add_to_another_playlist">Añadir a otra playlist</string>+ <string name="add_to_playlist_search_hint">Buscar una playlist</string>+ <string name="add_to_playlist_empty">No tienes ninguna playlist a la que añadir esta canción</string>+ <string name="add_to_playlist_no_match">Ninguna playlist coincide con \"%1$s\"</string>+ <string name="undo">Deshacer</string>+ <string name="settings_crossfade_title">Fundido cruzado (las pistas se desvanecen, no se superponen)</string>+ <string name="settings_crossfade_detail">Una pista se desvanece en sus últimos segundos y la siguiente entra poco a poco. Nunca suenan a la vez: un solo reproductor, un solo flujo de audio.</string>+ <string name="settings_crossfade_off">Desactivado</string>+ <string name="settings_crossfade_seconds">%1$ds</string>+ <string name="show_follow">Seguir</string>+ <string name="show_following">Siguiendo</string>+ <string name="show_tab_episodes">Episodios</string>+ <string name="show_tab_chapters">Capítulos</string>+ <string name="show_tab_about">Información</string>+ <string name="show_sort_newest">Todos los episodios • Más recientes</string>+ <string name="show_sort_oldest">Todos los episodios • Más antiguos</string>+ <string name="show_sort_chapters_newest">Todos los capítulos • Más recientes</string>+ <string name="show_sort_chapters_oldest">Todos los capítulos • Más antiguos</string>+ <string name="show_empty">Todavía no hay nada que reproducir aquí</string>+ <string name="show_rating">%1$s (%2$s)</string>+ <string name="show_authors">Por %1$s</string>+ <string name="show_narrators">Narrado por %1$s</string>+ <string name="show_followed">Ahora sigues este podcast</string>+ <string name="show_unfollowed">Has dejado de seguir este podcast</string>+ <string name="episode_duration_min">%1$d min</string>+ <string name="episode_remaining">Quedan %1$s</string>+ <string name="episode_mark_played">Marcar como reproducido</string>+ <string name="episode_mark_unplayed">Marcar como no iniciado</string>+ <string name="episode_marked_played">Marcado como reproducido</string>+ <string name="episode_marked_unplayed">Marcado como no iniciado</string>+ <string name="episode_play">Reproducir</string>+ <string name="episode_open">Abrir episodio</string>+ <string name="episode_add_queue">Añadir a la cola</string>+ <string name="episode_show_more">mostrar más</string>+ <string name="episode_show_less">mostrar menos</string>+ <string name="episode_download">Descargar</string>+ <string name="episode_downloading">Descargando…</string>+ <string name="episode_downloaded">Descargado</string>+ <string name="episode_download_remove">Quitar la descarga</string>+ <string name="episode_options">Opciones del episodio</string>+ <string name="episode_not_found">Episodio no encontrado</string>+ <string name="show_not_found">Podcast no encontrado</string>+ <string name="podcast_playing_from">Reproduciendo desde el podcast</string>+ <string name="player_speed_chip">%1$s×</string>+ <string name="player_back_15">Retroceder 15 segundos</string>+ <string name="player_forward_15">Avanzar 15 segundos</string>+ <string name="player_show_remaining">Mostrar el tiempo restante</string>+ <string name="player_show_elapsed">Mostrar el tiempo transcurrido</string>+ <string name="player_sleep_timer">Temporizador de apagado</string>+ <string name="player_speed_a11y">Velocidad de reproducción, %1$s×</string>+ <string name="settings_keep_playing_title">Seguir reproduciendo al cerrar la app</string>+ <string name="settings_keep_playing_detail">Desactivado: cerrar Myspoti desde las apps recientes detiene la música</string>+ <string name="recommended_songs_from_name">Según el nombre de esta playlist</string>+ <string name="recommended_songs_from_songs">Según el contenido de esta playlist</string>+ <string name="recommended_songs_refresh">Actualizar</string>+ <string name="recommended_songs_add">Añadir a esta playlist</string>+ <string name="smart_shuffle_recommended">Recomendada por el modo aleatorio inteligente</string>+ <string name="smart_shuffle_add">Añadir a esta playlist</string>+ <string name="add_songs_title">Añadir a esta playlist</string>+ <string name="add_songs_close">Cerrar</string>+ <string name="add_songs_search_hint">Buscar canciones</string>+ <string name="add_songs_nothing">No se encontraron canciones para «%1$s»</string>+ <string name="add_songs_added">Añadida</string>+ <string name="spotify_code_description">Código de Spotify</string>+ <string name="spotify_code_hint">Escanéalo en Spotify (Buscar y luego la cámara) para abrirlo.</string>+ <string name="spotify_code_share_image">Compartir el código</string>+ <string name="copy_link">Copiar enlace</string>+ <string name="link_copied">Enlace copiado</string>+ <string name="lyrics_meaning_title">Significado</string>+ <string name="lyrics_meaning_about">Acerca de</string>+ <string name="lyrics_meaning_lines">Versos explicados</string>+ <string name="lyrics_meaning_source">De Genius · abrir la canción allí</string>+ <string name="lyrics_meaning_translating">Traduciendo…</string>+ <string name="lyrics_meaning_translate">Traducir</string>+ <string name="lyrics_meaning_original">Ver original</string>+ <string name="lyrics_meaning_hint">Versos punteados: mantén uno pulsado para leer la explicación de Genius.</string>+ <string name="clip_sound_song">Sonido: canción</string>+ <string name="clip_sound_clip">Sonido: clip</string>+ <string name="clip_sound_on_hint">Ahora oyes el sonido del clip. La canción sigue sonando en silencio en Spotify y sigue contando.</string>+ <string name="clip_sound_off_hint">Vuelves a oír la canción de Spotify.</string>+ <string name="lyrics_word_sync_title">Palabra por palabra</string>+ <string name="lyrics_word_sync_on">Sincronía karaoke primero (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Línea por línea, Spotify primero</string>+ <string name="playlist_invite_collaborators">Invitar a colaboradores</string>+ <string name="playlist_invite_message">Únete a mi playlist «%1$s» en Spotify, podrás añadir canciones: %2$s</string>+ <string name="playlist_invite_failed">No se pudo crear el enlace de invitación</string>+ <string name="playlist_by">De %1$s</string>+ <string name="playlist_make_public">Hacer pública</string>+ <string name="playlist_make_private">Hacer privada</string>+ <string name="playlist_stop_collab">Dejar de colaborar</string>+ <string name="playlist_add_profile">Añadir al perfil</string>+ <string name="playlist_remove_profile">Quitar del perfil</string>+ <string name="playlist_now_public">La playlist es pública</string>+ <string name="playlist_now_private">La playlist es privada</string>+ <string name="playlist_now_solo">Ahora solo tú puedes añadir canciones</string>+ <string name="playlist_now_on_profile">Añadida a tu perfil</string>+ <string name="playlist_now_off_profile">Quitada de tu perfil</string>+ <string name="playlist_collab_locked">Playlist colaborativa: para añadir canciones, pide a %1$s un enlace de invitación.</string>+ <string name="playlist_collab_owner">su creador</string>+ <string name="playlist_members_title">Colaboradores</string>+ <string name="playlist_member_owner">Creador</string>+ <string name="playlist_member_collab">Colaborador</string>+ <string name="playlist_members_more">%1$s y %2$d más</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 eb88db20..b1dd693b 100644--- a/base/app/src/main/res/values-fr/myspoti_strings.xml+++ b/base/app/src/main/res/values-fr/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti's own texts (English default, French). --><resources><string name="welcome_tagline">Ta musique, avec les paroles synchronisées et les clips officiels.</string>+ <string name="welcome_lead">Ta musique,</string>+ <string name="welcome_rotate_ads">sans pubs.</string>+ <string name="welcome_rotate_lyrics">avec les paroles mot par mot.</string>+ <string name="welcome_rotate_clips">avec les clips officiels.</string>+ <string name="welcome_rotate_offline">même hors ligne.</string>+ <string name="welcome_rotate_lossless">en qualité sans perte.</string><string name="welcome_login">Se connecter avec Spotify</string><string name="welcome_privacy">Vous vous connectez sur la page officielle de Spotify. Myspoti ne voit jamais votre mot de passe.</string><string name="crash_heading">Myspoti s\'est arrêté</string>@@ -310,7 +316,7 @@<string name="playlist_access_private">Privée</string><string name="playlist_access_private_detail">Vous seul pouvez la voir</string><string name="playlist_access_collaborative">Collaborative</string>- <string name="playlist_access_collaborative_detail">Toute personne avec le lien peut ajouter et retirer des titres</string>+ <string name="playlist_access_collaborative_detail">Seules les personnes que vous invitez peuvent ajouter et retirer des titres</string><string name="playlist_on_profile">Sur votre profil</string><string name="playlist_on_profile_detail">Affichée sur votre profil, visible par les autres</string><string name="choose_artist">Choisir un artiste</string>@@ -422,4 +428,83 @@<string name="player_speed_a11y">Vitesse de lecture, %1$s×</string><string name="restart_player_done">Lecteur redémarré</string><string name="spotify_limited">Spotify limite la lecture pour le moment. Réessayez dans une minute.</string>+ <string name="library_change_undone">Spotify a refusé la modification, votre bibliothèque est revenue comme avant</string>+ <string name="blend_title">Mix à plusieurs</string>+ <string name="blend_detail">Une playlist mêlant vos goûts et ceux d\'un ami</string>+ <string name="blend_invite">Inviter un ami dans un mix</string>+ <string name="blend_join">Rejoindre avec un lien</string>+ <string name="blend_join_title">Collez le lien d\'invitation</string>+ <string name="blend_join_button">Rejoindre</string>+ <string name="blend_invite_message">On fait un Blend sur Spotify : %1$s</string>+ <string name="blend_failed">Impossible de joindre le Blend de Spotify, réessayez</string>+ <string name="blend_bad_link">Ce n\'est pas un lien d\'invitation à un Blend</string>+ <string name="blend_own_invite">C\'est votre propre invitation : envoyez-la à un ami</string>+ <string name="blend_full">Ce Blend est complet</string>+ <string name="blend_deleted">Ce Blend a été supprimé</string>+ <string name="blend_working">En cours…</string>+ <string name="blend_invited_by">%1$s t\'invite à un Blend</string>+ <string name="blend_open">Ouvrir le Blend</string>+ <string name="blend_later">Plus tard</string>+ <string name="blend_members">Membres</string>+ <string name="blend_invite_more">Inviter d\'autres personnes</string>+ <string name="blend_rename">Renommer le Blend</string>+ <string name="blend_leave">Quitter le Blend</string>+ <string name="blend_leave_confirm">Quitter %1$s ? Il quitte ta bibliothèque, les autres le gardent.</string>+ <string name="blend_leave_button">Quitter</string>+ <string name="playlist_invite_banner">Vous êtes invité à collaborer à cette playlist</string>+ <string name="playlist_invite_join">Rejoindre</string>+ <string name="playlist_invite_joined">Vous collaborez maintenant à cette playlist</string>+ <string name="settings_keep_playing_title">Continuer la lecture après fermeture</string>+ <string name="settings_keep_playing_detail">Désactivé : fermer Myspoti depuis les apps récentes arrête la musique</string>+ <string name="recommended_songs_from_name">Selon le nom de cette playlist</string>+ <string name="recommended_songs_from_songs">Selon le contenu de cette playlist</string>+ <string name="recommended_songs_refresh">Actualiser</string>+ <string name="recommended_songs_add">Ajouter à cette playlist</string>+ <string name="smart_shuffle_recommended">Recommandé par la lecture aléatoire intelligente</string>+ <string name="smart_shuffle_add">Ajouter à cette playlist</string>+ <string name="add_songs_title">Ajouter à cette playlist</string>+ <string name="add_songs_close">Fermer</string>+ <string name="add_songs_search_hint">Rechercher des titres</string>+ <string name="add_songs_nothing">Aucun titre trouvé pour « %1$s »</string>+ <string name="add_songs_added">Ajouté</string>+ <string name="spotify_code_description">Code Spotify</string>+ <string name="spotify_code_hint">Scanne-le dans Spotify (Rechercher, puis l’appareil photo) pour l’ouvrir.</string>+ <string name="spotify_code_share_image">Partager le code</string>+ <string name="copy_link">Copier le lien</string>+ <string name="link_copied">Lien copié</string>+ <string name="lyrics_meaning_title">Signification</string>+ <string name="lyrics_meaning_about">À propos</string>+ <string name="lyrics_meaning_lines">Les paroles expliquées</string>+ <string name="lyrics_meaning_source">Source : Genius · ouvrir le titre sur Genius</string>+ <string name="lyrics_meaning_translating">Traduction…</string>+ <string name="lyrics_meaning_translate">Traduire</string>+ <string name="lyrics_meaning_original">Voir l’original</string>+ <string name="lyrics_meaning_hint">Lignes en pointillé : maintiens-en une pour lire l’explication de Genius.</string>+ <string name="clip_sound_song">Son : morceau</string>+ <string name="clip_sound_clip">Son : clip</string>+ <string name="clip_sound_on_hint">Tu entends maintenant le son du clip. Le morceau continue en silencieux sur Spotify et compte toujours.</string>+ <string name="clip_sound_off_hint">Tu entends de nouveau le morceau Spotify.</string>+ <string name="lyrics_word_sync_title">Mot par mot</string>+ <string name="lyrics_word_sync_on">Synchro karaoké d’abord (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Ligne par ligne, Spotify d’abord</string>+ <string name="playlist_invite_collaborators">Inviter des collaborateurs</string>+ <string name="playlist_invite_message">Rejoins ma playlist « %1$s » sur Spotify, tu pourras y ajouter des titres : %2$s</string>+ <string name="playlist_invite_failed">Impossible de créer le lien d’invitation</string>+ <string name="playlist_by">De %1$s</string>+ <string name="playlist_make_public">Rendre publique</string>+ <string name="playlist_make_private">Rendre privée</string>+ <string name="playlist_stop_collab">Arrêter la collaboration</string>+ <string name="playlist_add_profile">Ajouter au profil</string>+ <string name="playlist_remove_profile">Retirer du profil</string>+ <string name="playlist_now_public">La playlist est publique</string>+ <string name="playlist_now_private">La playlist est privée</string>+ <string name="playlist_now_solo">Vous seul pouvez désormais ajouter des titres</string>+ <string name="playlist_now_on_profile">Ajoutée à votre profil</string>+ <string name="playlist_now_off_profile">Retirée de votre profil</string>+ <string name="playlist_collab_locked">Playlist collaborative : pour y ajouter des titres, demande un lien d’invitation à %1$s.</string>+ <string name="playlist_collab_owner">son créateur</string>+ <string name="playlist_members_title">Collaborateurs</string>+ <string name="playlist_member_owner">Créateur</string>+ <string name="playlist_member_collab">Collaborateur</string>+ <string name="playlist_members_more">%1$s et %2$d autres</string></resources>diff --git a/base/app/src/main/res/values-it/myspoti_strings.xml b/base/app/src/main/res/values-it/myspoti_strings.xmlindex 007c0466..b5774cdd 100644--- a/base/app/src/main/res/values-it/myspoti_strings.xml+++ b/base/app/src/main/res/values-it/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti's own texts, Italian. --><resources><string name="welcome_tagline">La tua musica, con testi sincronizzati e video musicali ufficiali.</string>+ <string name="welcome_lead">La tua musica,</string>+ <string name="welcome_rotate_ads">senza pubblicità.</string>+ <string name="welcome_rotate_lyrics">con i testi parola per parola.</string>+ <string name="welcome_rotate_clips">con i video ufficiali.</string>+ <string name="welcome_rotate_offline">anche offline.</string>+ <string name="welcome_rotate_lossless">in qualità lossless.</string><string name="welcome_login">Accedi con Spotify</string><string name="welcome_privacy">Accedi dalla pagina di Spotify. Myspoti non vede mai la tua password.</string><string name="crash_heading">Myspoti ha smesso di funzionare</string>@@ -270,7 +276,7 @@<string name="playlist_access_private">Privata</string><string name="playlist_access_private_detail">Solo tu puoi vederla</string><string name="playlist_access_collaborative">Collaborativa</string>- <string name="playlist_access_collaborative_detail">Chiunque abbia il link può aggiungere e rimuovere brani</string>+ <string name="playlist_access_collaborative_detail">Solo le persone che inviti possono aggiungere e rimuovere brani</string><string name="playlist_on_profile">Sul tuo profilo</string><string name="playlist_on_profile_detail">Mostrata sul tuo profilo, visibile agli altri</string><string name="choose_artist">Scegli un artista</string>@@ -333,4 +339,167 @@<string name="support_github_action">Sponsor su GitHub</string><string name="spotiflac_verify_again">La verifica SpotiFLAC è scaduta: ripetila nelle Impostazioni per scaricare in lossless</string><string name="download_on_mobile_data">Download con i dati mobili: usa il tuo piano dati</string>+ <string name="library_change_undone">Spotify ha rifiutato la modifica, la tua libreria è tornata com\'era</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">Una playlist con i tuoi gusti e quelli di un amico</string>+ <string name="blend_invite">Invita un amico a un Blend</string>+ <string name="blend_join">Unisciti con un link</string>+ <string name="blend_join_title">Incolla il link di invito</string>+ <string name="blend_join_button">Unisciti</string>+ <string name="blend_invite_message">Facciamo un Blend su Spotify: %1$s</string>+ <string name="blend_failed">Impossibile contattare il Blend di Spotify, riprova</string>+ <string name="blend_bad_link">Questo non è un link di invito a un Blend</string>+ <string name="blend_own_invite">È il tuo invito: invialo a un amico</string>+ <string name="blend_full">Questo Blend è al completo</string>+ <string name="blend_deleted">Questo Blend è stato eliminato</string>+ <string name="blend_working">In corso…</string>+ <string name="blend_invited_by">%1$s ti invita a un Blend</string>+ <string name="blend_open">Apri il Blend</string>+ <string name="blend_later">Non ora</string>+ <string name="blend_members">Membri</string>+ <string name="blend_invite_more">Invita altre persone</string>+ <string name="blend_rename">Rinomina il Blend</string>+ <string name="blend_leave">Esci dal Blend</string>+ <string name="blend_leave_confirm">Uscire da %1$s? Esce dalla tua libreria, gli altri lo tengono.</string>+ <string name="blend_leave_button">Esci</string>+ <string name="playlist_invite_banner">Sei stato invitato a collaborare a questa playlist</string>+ <string name="playlist_invite_join">Partecipa</string>+ <string name="playlist_invite_joined">Ora sei un collaboratore</string>+ <string name="podcast_download_protected">Questo episodio è esclusivo di Spotify: può essere riprodotto solo nell\'app Spotify, non scaricato.</string>+ <string name="podcast_download_unavailable">Impossibile scaricare questo episodio: manca il file audio dell\'editore.</string>+ <string name="podcast_download_failed">Download non riuscito. Riprova.</string>+ <string name="ad_playing">Pubblicità</string>+ <string name="track_unavailable_region">Non disponibile nella tua regione</string>+ <string name="diagnostic_export_title">Esporta un report diagnostico</string>+ <string name="diagnostic_export_detail">Condivide il registro recente dell\'app e i dati del dispositivo</string>+ <string name="diagnostic_export_failed">Impossibile scrivere il report diagnostico</string>+ <string name="recently_played_title">Riprodotti di recente</string>+ <string name="recently_played_empty">Quello che riproduci con questo account appare qui.</string>+ <string name="recently_played_failed">Impossibile caricare l\'elenco dei riprodotti di recente (%1$s)</string>+ <string name="recents_title">Recenti</string>+ <string name="recents_detail">Quello che hai riprodotto, su tutti i dispositivi</string>+ <string name="recents_filter_music">Musica</string>+ <string name="recents_filter_podcasts">Podcast</string>+ <string name="recents_today">Oggi</string>+ <string name="recents_yesterday">Ieri</string>+ <string name="recents_played_one">1 brano riprodotto</string>+ <string name="recents_played_many">%1$d brani riprodotti</string>+ <string name="recents_saved_one">1 brano aggiunto</string>+ <string name="recents_saved_many">%1$d brani aggiunti</string>+ <string name="recents_expand">Mostra i brani</string>+ <string name="recents_collapse">Nascondi i brani</string>+ <string name="settings_auto_update_title">Controlla gli aggiornamenti all\'avvio</string>+ <string name="settings_auto_update_detail">Disattivato: nessun controllo all\'avvio dell\'app. Il controllo manuale qui sotto funziona comunque.</string>+ <string name="settings_check_update_title">Controlla subito gli aggiornamenti</string>+ <string name="settings_check_update_detail">Cerca una versione più recente e propone di installarla</string>+ <string name="settings_update_checking">Controllo in corso…</string>+ <string name="settings_update_check_latest">Myspoti è aggiornato</string>+ <string name="downloads_stop_all_title">Interrompi tutti i download</string>+ <string name="downloads_stop_all_detail">Annulla quelli in corso; i brani già scaricati restano</string>+ <string name="context_menu_remove_from_playlist">Rimuovi da questa playlist</string>+ <string name="context_menu_add_to_another_playlist">Aggiungi a un\'altra playlist</string>+ <string name="add_to_playlist_search_hint">Cerca una playlist</string>+ <string name="add_to_playlist_empty">Non hai nessuna playlist a cui aggiungere questo brano</string>+ <string name="add_to_playlist_no_match">Nessuna playlist corrisponde a \"%1$s\"</string>+ <string name="undo">Annulla</string>+ <string name="settings_crossfade_title">Crossfade (i brani sfumano, non si sovrappongono)</string>+ <string name="settings_crossfade_detail">Un brano sfuma negli ultimi secondi e il successivo entra in dissolvenza. Non suonano mai insieme: un solo lettore, un solo flusso audio.</string>+ <string name="settings_crossfade_off">Disattivato</string>+ <string name="settings_crossfade_seconds">%1$ds</string>+ <string name="show_follow">Segui</string>+ <string name="show_following">Seguito</string>+ <string name="show_tab_episodes">Episodi</string>+ <string name="show_tab_chapters">Capitoli</string>+ <string name="show_tab_about">Info</string>+ <string name="show_sort_newest">Tutti gli episodi • Più recenti</string>+ <string name="show_sort_oldest">Tutti gli episodi • Meno recenti</string>+ <string name="show_sort_chapters_newest">Tutti i capitoli • Più recenti</string>+ <string name="show_sort_chapters_oldest">Tutti i capitoli • Meno recenti</string>+ <string name="show_empty">Non c\'è ancora nulla da riprodurre qui</string>+ <string name="show_rating">%1$s (%2$s)</string>+ <string name="show_authors">Di %1$s</string>+ <string name="show_narrators">Letto da %1$s</string>+ <string name="show_followed">Ora segui questo podcast</string>+ <string name="show_unfollowed">Non segui più questo podcast</string>+ <string name="episode_duration_min">%1$d min</string>+ <string name="episode_remaining">%1$s rimanenti</string>+ <string name="episode_mark_played">Segna come riprodotto</string>+ <string name="episode_mark_unplayed">Segna come non iniziato</string>+ <string name="episode_marked_played">Segnato come riprodotto</string>+ <string name="episode_marked_unplayed">Segnato come non iniziato</string>+ <string name="episode_play">Riproduci</string>+ <string name="episode_open">Apri episodio</string>+ <string name="episode_add_queue">Aggiungi alla coda</string>+ <string name="episode_show_more">mostra di più</string>+ <string name="episode_show_less">mostra meno</string>+ <string name="episode_download">Scarica</string>+ <string name="episode_downloading">Download in corso…</string>+ <string name="episode_downloaded">Scaricato</string>+ <string name="episode_download_remove">Rimuovi download</string>+ <string name="episode_options">Opzioni episodio</string>+ <string name="episode_not_found">Episodio non trovato</string>+ <string name="show_not_found">Podcast non trovato</string>+ <string name="podcast_playing_from">In riproduzione dal podcast</string>+ <string name="player_speed_chip">%1$s×</string>+ <string name="player_back_15">Indietro di 15 secondi</string>+ <string name="player_forward_15">Avanti di 15 secondi</string>+ <string name="player_show_remaining">Mostra il tempo rimanente</string>+ <string name="player_show_elapsed">Mostra il tempo trascorso</string>+ <string name="player_sleep_timer">Timer di spegnimento</string>+ <string name="player_speed_a11y">Velocità di riproduzione, %1$s×</string>+ <string name="restart_player_done">Player riavviato</string>+ <string name="spotify_limited">Spotify sta limitando la riproduzione per il momento. Riprova tra un minuto.</string>+ <string name="settings_keep_playing_title">Continua la riproduzione dopo la chiusura</string>+ <string name="settings_keep_playing_detail">Disattivato: chiudere Myspoti dalle app recenti ferma la musica</string>+ <string name="recommended_songs_from_name">In base al nome di questa playlist</string>+ <string name="recommended_songs_from_songs">In base al contenuto di questa playlist</string>+ <string name="recommended_songs_refresh">Aggiorna</string>+ <string name="recommended_songs_add">Aggiungi a questa playlist</string>+ <string name="smart_shuffle_recommended">Consigliato dalla riproduzione casuale intelligente</string>+ <string name="smart_shuffle_add">Aggiungi a questa playlist</string>+ <string name="add_songs_title">Aggiungi a questa playlist</string>+ <string name="add_songs_close">Chiudi</string>+ <string name="add_songs_search_hint">Cerca brani</string>+ <string name="add_songs_nothing">Nessun brano trovato per «%1$s»</string>+ <string name="add_songs_added">Aggiunto</string>+ <string name="spotify_code_description">Codice Spotify</string>+ <string name="spotify_code_hint">Scansionalo in Spotify (Cerca, poi la fotocamera) per aprirlo.</string>+ <string name="spotify_code_share_image">Condividi il codice</string>+ <string name="copy_link">Copia link</string>+ <string name="link_copied">Link copiato</string>+ <string name="lyrics_meaning_title">Significato</string>+ <string name="lyrics_meaning_about">Info</string>+ <string name="lyrics_meaning_lines">Versi spiegati</string>+ <string name="lyrics_meaning_source">Da Genius · apri il brano lì</string>+ <string name="lyrics_meaning_translating">Traduzione…</string>+ <string name="lyrics_meaning_translate">Traduci</string>+ <string name="lyrics_meaning_original">Vedi originale</string>+ <string name="lyrics_meaning_hint">Versi punteggiati: tieni premuto per leggere la spiegazione di Genius.</string>+ <string name="clip_sound_song">Audio: brano</string>+ <string name="clip_sound_clip">Audio: video</string>+ <string name="clip_sound_on_hint">Ora senti l’audio del video. Il brano continua in silenzio su Spotify e conta comunque.</string>+ <string name="clip_sound_off_hint">Senti di nuovo il brano di Spotify.</string>+ <string name="lyrics_word_sync_title">Parola per parola</string>+ <string name="lyrics_word_sync_on">Sincronia karaoke prima (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Riga per riga, prima Spotify</string>+ <string name="playlist_invite_collaborators">Invita collaboratori</string>+ <string name="playlist_invite_message">Unisciti alla mia playlist «%1$s» su Spotify, potrai aggiungere brani: %2$s</string>+ <string name="playlist_invite_failed">Impossibile creare il link di invito</string>+ <string name="playlist_by">Di %1$s</string>+ <string name="playlist_make_public">Rendi pubblica</string>+ <string name="playlist_make_private">Rendi privata</string>+ <string name="playlist_stop_collab">Interrompi collaborazione</string>+ <string name="playlist_add_profile">Aggiungi al profilo</string>+ <string name="playlist_remove_profile">Rimuovi dal profilo</string>+ <string name="playlist_now_public">La playlist è pubblica</string>+ <string name="playlist_now_private">La playlist è privata</string>+ <string name="playlist_now_solo">Ora solo tu puoi aggiungere brani</string>+ <string name="playlist_now_on_profile">Aggiunta al tuo profilo</string>+ <string name="playlist_now_off_profile">Rimossa dal tuo profilo</string>+ <string name="playlist_collab_locked">Playlist collaborativa: per aggiungere brani, chiedi a %1$s un link di invito.</string>+ <string name="playlist_collab_owner">chi l’ha creata</string>+ <string name="playlist_members_title">Collaboratori</string>+ <string name="playlist_member_owner">Creatore</string>+ <string name="playlist_member_collab">Collaboratore</string>+ <string name="playlist_members_more">%1$s e altri %2$d</string></resources>diff --git a/base/app/src/main/res/values-it/strings.xml b/base/app/src/main/res/values-it/strings.xmlindex 1faecf03..50717953 100644--- a/base/app/src/main/res/values-it/strings.xml+++ b/base/app/src/main/res/values-it/strings.xml@@ -32,4 +32,11 @@<string name="bridge_player_unlocked">Lettore sbloccato</string><string name="bridge_reloading">Ricaricamento…</string><string name="service_disabled_message">Il servizio non è attivo</string>+ <string name="account_page_title">Account Spotify</string>+ <string name="account_page_detail">Abbonamento, privacy e dispositivi, su spotify.com</string>+ <string name="energy_saver_title">Risparmio energetico</string>+ <string name="energy_saver_summary">Canvas disattivati, video e animazioni più leggeri</string>+ <string name="playback_seek_description">Posizione di riproduzione</string>+ <string name="video_fullscreen_enter">Schermo intero</string>+ <string name="video_fullscreen_exit">Esci dallo schermo intero</string></resources>diff --git a/base/app/src/main/res/values-pt/myspoti_strings.xml b/base/app/src/main/res/values-pt/myspoti_strings.xmlindex 08258e94..b0e6dd8d 100644--- a/base/app/src/main/res/values-pt/myspoti_strings.xml+++ b/base/app/src/main/res/values-pt/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Textos próprios do Myspoti (inglês por omissão, francês e português). --><resources><string name="welcome_tagline">A tua música, com letras sincronizadas e videoclipes oficiais.</string>+ <string name="welcome_lead">Sua música,</string>+ <string name="welcome_rotate_ads">sem anúncios.</string>+ <string name="welcome_rotate_lyrics">com letras palavra por palavra.</string>+ <string name="welcome_rotate_clips">com os clipes oficiais.</string>+ <string name="welcome_rotate_offline">até offline.</string>+ <string name="welcome_rotate_lossless">em qualidade sem perdas.</string><string name="welcome_login">Iniciar sessão com o Spotify</string><string name="welcome_privacy">Inicias sessão na página oficial do Spotify. O Myspoti nunca vê a tua palavra-passe.</string><string name="crash_heading">O Myspoti parou de funcionar</string>@@ -270,7 +276,7 @@<string name="playlist_access_private">Privada</string><string name="playlist_access_private_detail">Só tu a podes ver</string><string name="playlist_access_collaborative">Colaborativa</string>- <string name="playlist_access_collaborative_detail">Quem tiver a ligação pode adicionar e remover músicas</string>+ <string name="playlist_access_collaborative_detail">Só as pessoas que você convidar podem adicionar e remover músicas</string><string name="playlist_on_profile">No seu perfil</string><string name="playlist_on_profile_detail">Aparece no seu perfil para outras pessoas</string><string name="choose_artist">Escolha um artista</string>@@ -335,4 +341,165 @@<string name="download_on_mobile_data">Transferência com dados móveis: usa o teu tarifário</string><string name="restart_player_done">Player reiniciado</string><string name="spotify_limited">O Spotify está limitando a reprodução no momento. Tente de novo em um minuto.</string>+ <string name="library_change_undone">O Spotify recusou a alteração, a tua biblioteca voltou ao que era</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">Uma playlist com o teu gosto e o de um amigo</string>+ <string name="blend_invite">Convidar um amigo para um Blend</string>+ <string name="blend_join">Entrar com um link</string>+ <string name="blend_join_title">Cola o link do convite</string>+ <string name="blend_join_button">Entrar</string>+ <string name="blend_invite_message">Vamos fazer um Blend no Spotify: %1$s</string>+ <string name="blend_failed">Não foi possível contactar o Blend do Spotify, tenta de novo</string>+ <string name="blend_bad_link">Isto não é um link de convite para um Blend</string>+ <string name="blend_own_invite">É o teu próprio convite: envia-o a um amigo</string>+ <string name="blend_full">Este Blend está cheio</string>+ <string name="blend_deleted">Este Blend foi eliminado</string>+ <string name="blend_working">Em curso…</string>+ <string name="blend_invited_by">%1$s convida-te para um Blend</string>+ <string name="blend_open">Abrir o Blend</string>+ <string name="blend_later">Agora não</string>+ <string name="blend_members">Membros</string>+ <string name="blend_invite_more">Convidar mais pessoas</string>+ <string name="blend_rename">Mudar o nome do Blend</string>+ <string name="blend_leave">Sair do Blend</string>+ <string name="blend_leave_confirm">Sair de %1$s? Sai da tua biblioteca; os outros mantêm-no.</string>+ <string name="blend_leave_button">Sair</string>+ <string name="playlist_invite_banner">Foste convidado para colaborar nesta lista</string>+ <string name="playlist_invite_join">Entrar</string>+ <string name="playlist_invite_joined">Já és colaborador</string>+ <string name="podcast_download_protected">Este episódio é exclusivo do Spotify: só pode ser reproduzido na app do Spotify, não transferido.</string>+ <string name="podcast_download_unavailable">Não é possível transferir este episódio: falta o ficheiro de áudio do editor.</string>+ <string name="podcast_download_failed">A transferência falhou. Tenta outra vez.</string>+ <string name="ad_playing">Publicidade</string>+ <string name="track_unavailable_region">Não disponível na tua região</string>+ <string name="diagnostic_export_title">Exportar um relatório de diagnóstico</string>+ <string name="diagnostic_export_detail">Partilha o registo recente da app e os dados do dispositivo</string>+ <string name="diagnostic_export_failed">Não foi possível gravar o relatório de diagnóstico</string>+ <string name="recently_played_title">Reproduzidas recentemente</string>+ <string name="recently_played_empty">O que reproduzires nesta conta aparece aqui.</string>+ <string name="recently_played_failed">Não foi possível carregar a lista das reproduzidas recentemente (%1$s)</string>+ <string name="recents_title">Recentes</string>+ <string name="recents_detail">O que reproduziste, em todos os dispositivos</string>+ <string name="recents_filter_music">Música</string>+ <string name="recents_filter_podcasts">Podcasts</string>+ <string name="recents_today">Hoje</string>+ <string name="recents_yesterday">Ontem</string>+ <string name="recents_played_one">1 música reproduzida</string>+ <string name="recents_played_many">%1$d músicas reproduzidas</string>+ <string name="recents_saved_one">1 música adicionada</string>+ <string name="recents_saved_many">%1$d músicas adicionadas</string>+ <string name="recents_expand">Mostrar as músicas</string>+ <string name="recents_collapse">Ocultar as músicas</string>+ <string name="settings_auto_update_title">Procurar atualizações ao arrancar</string>+ <string name="settings_auto_update_detail">Desligado: não procura ao iniciar a app. A procura manual abaixo continua a funcionar.</string>+ <string name="settings_check_update_title">Procurar atualizações agora</string>+ <string name="settings_check_update_detail">Procura uma versão mais recente e oferece instalá-la</string>+ <string name="settings_update_checking">A verificar…</string>+ <string name="settings_update_check_latest">O Myspoti está atualizado</string>+ <string name="downloads_stop_all_title">Parar todas as transferências</string>+ <string name="downloads_stop_all_detail">Cancela o que falta; as músicas já transferidas são mantidas</string>+ <string name="context_menu_remove_from_playlist">Remover desta playlist</string>+ <string name="context_menu_add_to_another_playlist">Adicionar a outra playlist</string>+ <string name="add_to_playlist_search_hint">Procurar uma playlist</string>+ <string name="add_to_playlist_empty">Não tens nenhuma playlist à qual adicionar esta música</string>+ <string name="add_to_playlist_no_match">Nenhuma playlist corresponde a \"%1$s\"</string>+ <string name="undo">Anular</string>+ <string name="settings_crossfade_title">Crossfade (as faixas desvanecem, não se sobrepõem)</string>+ <string name="settings_crossfade_detail">Uma faixa desvanece nos últimos segundos e a seguinte entra gradualmente. Nunca tocam ao mesmo tempo: um só leitor, um só fluxo de áudio.</string>+ <string name="settings_crossfade_off">Desligado</string>+ <string name="settings_crossfade_seconds">%1$ds</string>+ <string name="show_follow">Seguir</string>+ <string name="show_following">A seguir</string>+ <string name="show_tab_episodes">Episódios</string>+ <string name="show_tab_chapters">Capítulos</string>+ <string name="show_tab_about">Sobre</string>+ <string name="show_sort_newest">Todos os episódios • Mais recentes</string>+ <string name="show_sort_oldest">Todos os episódios • Mais antigos</string>+ <string name="show_sort_chapters_newest">Todos os capítulos • Mais recentes</string>+ <string name="show_sort_chapters_oldest">Todos os capítulos • Mais antigos</string>+ <string name="show_empty">Ainda não há nada para reproduzir aqui</string>+ <string name="show_rating">%1$s (%2$s)</string>+ <string name="show_authors">Por %1$s</string>+ <string name="show_narrators">Narrado por %1$s</string>+ <string name="show_followed">Agora segues este podcast</string>+ <string name="show_unfollowed">Deixaste de seguir este podcast</string>+ <string name="episode_duration_min">%1$d min</string>+ <string name="episode_remaining">Faltam %1$s</string>+ <string name="episode_mark_played">Marcar como reproduzido</string>+ <string name="episode_mark_unplayed">Marcar como não iniciado</string>+ <string name="episode_marked_played">Marcado como reproduzido</string>+ <string name="episode_marked_unplayed">Marcado como não iniciado</string>+ <string name="episode_play">Reproduzir</string>+ <string name="episode_open">Abrir episódio</string>+ <string name="episode_add_queue">Adicionar à fila</string>+ <string name="episode_show_more">mostrar mais</string>+ <string name="episode_show_less">mostrar menos</string>+ <string name="episode_download">Transferir</string>+ <string name="episode_downloading">A transferir…</string>+ <string name="episode_downloaded">Transferido</string>+ <string name="episode_download_remove">Remover a transferência</string>+ <string name="episode_options">Opções do episódio</string>+ <string name="episode_not_found">Episódio não encontrado</string>+ <string name="show_not_found">Podcast não encontrado</string>+ <string name="podcast_playing_from">A reproduzir a partir do podcast</string>+ <string name="player_speed_chip">%1$s×</string>+ <string name="player_back_15">Recuar 15 segundos</string>+ <string name="player_forward_15">Avançar 15 segundos</string>+ <string name="player_show_remaining">Mostrar o tempo restante</string>+ <string name="player_show_elapsed">Mostrar o tempo decorrido</string>+ <string name="player_sleep_timer">Temporizador de suspensão</string>+ <string name="player_speed_a11y">Velocidade de reprodução, %1$s×</string>+ <string name="settings_keep_playing_title">Continuar a reproduzir ao fechar a app</string>+ <string name="settings_keep_playing_detail">Desativado: fechar o Myspoti nas apps recentes para a música</string>+ <string name="recommended_songs_from_name">Com base no nome desta playlist</string>+ <string name="recommended_songs_from_songs">Com base no conteúdo desta playlist</string>+ <string name="recommended_songs_refresh">Atualizar</string>+ <string name="recommended_songs_add">Adicionar a esta playlist</string>+ <string name="smart_shuffle_recommended">Recomendada pelo modo aleatório inteligente</string>+ <string name="smart_shuffle_add">Adicionar a esta playlist</string>+ <string name="add_songs_title">Adicionar a esta playlist</string>+ <string name="add_songs_close">Fechar</string>+ <string name="add_songs_search_hint">Buscar músicas</string>+ <string name="add_songs_nothing">Nenhuma música encontrada para “%1$s”</string>+ <string name="add_songs_added">Adicionada</string>+ <string name="spotify_code_description">Código do Spotify</string>+ <string name="spotify_code_hint">Escaneie no Spotify (Buscar e depois a câmera) para abrir.</string>+ <string name="spotify_code_share_image">Compartilhar o código</string>+ <string name="copy_link">Copiar link</string>+ <string name="link_copied">Link copiado</string>+ <string name="lyrics_meaning_title">Significado</string>+ <string name="lyrics_meaning_about">Sobre</string>+ <string name="lyrics_meaning_lines">Versos explicados</string>+ <string name="lyrics_meaning_source">Do Genius · abrir a música lá</string>+ <string name="lyrics_meaning_translating">Traduzindo…</string>+ <string name="lyrics_meaning_translate">Traduzir</string>+ <string name="lyrics_meaning_original">Ver original</string>+ <string name="lyrics_meaning_hint">Versos pontilhados: segure um para ler a explicação do Genius.</string>+ <string name="clip_sound_song">Som: música</string>+ <string name="clip_sound_clip">Som: clipe</string>+ <string name="clip_sound_on_hint">Agora você ouve o som do clipe. A música continua em silêncio no Spotify e ainda conta.</string>+ <string name="clip_sound_off_hint">Você ouve a música do Spotify de novo.</string>+ <string name="lyrics_word_sync_title">Palavra por palavra</string>+ <string name="lyrics_word_sync_on">Sincronia karaokê primeiro (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Linha por linha, Spotify primeiro</string>+ <string name="playlist_invite_collaborators">Convidar colaboradores</string>+ <string name="playlist_invite_message">Entre na minha playlist “%1$s” no Spotify, você poderá adicionar músicas: %2$s</string>+ <string name="playlist_invite_failed">Não foi possível criar o link de convite</string>+ <string name="playlist_by">De %1$s</string>+ <string name="playlist_make_public">Tornar pública</string>+ <string name="playlist_make_private">Tornar privada</string>+ <string name="playlist_stop_collab">Parar de colaborar</string>+ <string name="playlist_add_profile">Adicionar ao perfil</string>+ <string name="playlist_remove_profile">Remover do perfil</string>+ <string name="playlist_now_public">A playlist é pública</string>+ <string name="playlist_now_private">A playlist é privada</string>+ <string name="playlist_now_solo">Agora só você pode adicionar músicas</string>+ <string name="playlist_now_on_profile">Adicionada ao seu perfil</string>+ <string name="playlist_now_off_profile">Removida do seu perfil</string>+ <string name="playlist_collab_locked">Playlist colaborativa: para adicionar músicas, peça a %1$s um link de convite.</string>+ <string name="playlist_collab_owner">quem a criou</string>+ <string name="playlist_members_title">Colaboradores</string>+ <string name="playlist_member_owner">Criador</string>+ <string name="playlist_member_collab">Colaborador</string>+ <string name="playlist_members_more">%1$s e mais %2$d</string></resources>diff --git a/base/app/src/main/res/values/myspoti_strings.xml b/base/app/src/main/res/values/myspoti_strings.xmlindex 3c175684..4967b10a 100644--- a/base/app/src/main/res/values/myspoti_strings.xml+++ b/base/app/src/main/res/values/myspoti_strings.xml@@ -2,6 +2,12 @@<!-- Myspoti's own texts (English default, French, Italian). --><resources><string name="welcome_tagline">Your music, with synced lyrics and official music videos.</string>+ <string name="welcome_lead">Your music,</string>+ <string name="welcome_rotate_ads">without ads.</string>+ <string name="welcome_rotate_lyrics">with word-by-word lyrics.</string>+ <string name="welcome_rotate_clips">with the official videos.</string>+ <string name="welcome_rotate_offline">even offline.</string>+ <string name="welcome_rotate_lossless">in lossless quality.</string><string name="welcome_login">Log in with Spotify</string><string name="welcome_privacy">You sign in on Spotify\'s own page. Myspoti never sees your password.</string><string name="crash_heading">Myspoti stopped working</string>@@ -310,7 +316,7 @@<string name="playlist_access_private">Private</string><string name="playlist_access_private_detail">Only you can see it</string><string name="playlist_access_collaborative">Collaborative</string>- <string name="playlist_access_collaborative_detail">Anyone with the link can add and remove songs</string>+ <string name="playlist_access_collaborative_detail">Only the people you invite can add and remove songs</string><string name="playlist_on_profile">On your profile</string><string name="playlist_on_profile_detail">Listed on your profile for others to see</string><string name="choose_artist">Choose an artist</string>@@ -422,4 +428,84 @@<string name="player_speed_a11y">Playback speed, %1$s×</string><string name="restart_player_done">Player restarted</string><string name="spotify_limited">Spotify is limiting playback for a moment. Try again in a minute.</string>+ <string name="library_change_undone">Spotify refused the change, your library is back as it was</string>+ <string name="blend_title">Blend</string>+ <string name="blend_detail">A playlist mixed from your taste and a friend\'s</string>+ <string name="blend_invite">Invite a friend to a Blend</string>+ <string name="blend_join">Join with a link</string>+ <string name="blend_join_title">Paste the invitation link</string>+ <string name="blend_join_button">Join</string>+ <string name="blend_invite_message">Let\'s make a Blend on Spotify: %1$s</string>+ <string name="blend_failed">Couldn\'t reach Spotify\'s Blend, try again</string>+ <string name="blend_bad_link">That is not a Blend invitation link</string>+ <string name="blend_own_invite">This is your own invitation: send it to a friend</string>+ <string name="blend_full">This Blend is full</string>+ <string name="blend_deleted">This Blend was deleted</string>+ <string name="blend_working">Working…</string>+ <string name="blend_invited_by">%1$s invites you to a Blend</string>+ <string name="blend_open">Open the Blend</string>+ <string name="blend_later">Not now</string>+ <string name="blend_members">Members</string>+ <string name="blend_invite_more">Invite more people</string>+ <string name="blend_rename">Rename Blend</string>+ <string name="blend_leave">Leave Blend</string>+ <string name="blend_leave_confirm">Leave %1$s? It leaves your library; the others keep it.</string>+ <string name="blend_leave_button">Leave</string>+ <string name="playlist_invite_banner">You are invited to collaborate on this playlist</string>+ <string name="playlist_invite_join">Join</string>+ <string name="playlist_invite_joined">You are now a collaborator</string>+ <string name="settings_keep_playing_title">Keep playing after closing the app</string>+ <string name="settings_keep_playing_detail">When off, closing Myspoti from the recent apps stops the music</string>+ <string name="recommended_songs_from_name">Based on this playlist\'s name</string>+ <string name="recommended_songs_from_songs">Based on what\'s in this playlist</string>+ <string name="recommended_songs_refresh">Refresh</string>+ <string name="recommended_songs_add">Add to this playlist</string>+ <string name="smart_shuffle_recommended">Recommended by smart shuffle</string>+ <string name="smart_shuffle_add">Add to this playlist</string>+ <string name="add_songs_title">Add to this playlist</string>+ <string name="add_songs_close">Close</string>+ <string name="add_songs_search_hint">Search for songs</string>+ <string name="add_songs_nothing">No songs found for “%1$s”</string>+ <string name="add_songs_added">Added</string>+ <string name="spotify_code_description">Spotify Code</string>+ <string name="spotify_code_hint">Scan it in Spotify (Search, then the camera) to open it.</string>+ <string name="spotify_code_share_image">Share the code</string>+ <string name="copy_link">Copy link</string>+ <string name="link_copied">Link copied</string>+ <string name="lyrics_meaning_title">Meaning</string>+ <string name="lyrics_meaning_about">About</string>+ <string name="lyrics_meaning_lines">Lines explained</string>+ <string name="lyrics_meaning_source">From Genius · open the song there</string>+ <string name="lyrics_meaning_translating">Translating…</string>+ <string name="lyrics_meaning_translate">Translate</string>+ <string name="lyrics_meaning_original">See original</string>+ <string name="lyrics_meaning_hint">Dotted lines: hold one to read what Genius says about it.</string>+ <string name="clip_sound_song">Sound: song</string>+ <string name="clip_sound_clip">Sound: clip</string>+ <string name="clip_sound_on_hint">You now hear the clip’s own sound. The song keeps playing silently on Spotify, so it still counts.</string>+ <string name="clip_sound_off_hint">You now hear the Spotify song again.</string>+ <string name="lyrics_meaning_source_short" translatable="false">Genius ↗</string>+ <string name="lyrics_word_sync_title">Word by word</string>+ <string name="lyrics_word_sync_on">Karaoke timing first (LyricsPlus, lrc.red, Kugou)</string>+ <string name="lyrics_word_sync_off">Line by line, Spotify first</string>+ <string name="playlist_invite_collaborators">Invite collaborators</string>+ <string name="playlist_invite_message">Join my playlist “%1$s” on Spotify, you can add songs to it: %2$s</string>+ <string name="playlist_invite_failed">Couldn’t make the invitation link</string>+ <string name="playlist_by">By %1$s</string>+ <string name="playlist_make_public">Make public</string>+ <string name="playlist_make_private">Make private</string>+ <string name="playlist_stop_collab">Stop collaborating</string>+ <string name="playlist_add_profile">Add to profile</string>+ <string name="playlist_remove_profile">Remove from profile</string>+ <string name="playlist_now_public">The playlist is public</string>+ <string name="playlist_now_private">The playlist is private</string>+ <string name="playlist_now_solo">Only you can add songs now</string>+ <string name="playlist_now_on_profile">Added to your profile</string>+ <string name="playlist_now_off_profile">Removed from your profile</string>+ <string name="playlist_collab_locked">Collaborative playlist: to add songs, ask %1$s for an invitation link.</string>+ <string name="playlist_collab_owner">its owner</string>+ <string name="playlist_members_title">Collaborators</string>+ <string name="playlist_member_owner">Creator</string>+ <string name="playlist_member_collab">Collaborator</string>+ <string name="playlist_members_more">%1$s and %2$d others</string></resources>diff --git a/base/app/src/test/java/com/music/spotui/video/OrderedClipResolverTest.kt b/base/app/src/test/java/com/music/spotui/video/OrderedClipResolverTest.ktindex 02eb18d6..71ecabda 100644--- a/base/app/src/test/java/com/music/spotui/video/OrderedClipResolverTest.kt+++ b/base/app/src/test/java/com/music/spotui/video/OrderedClipResolverTest.kt@@ -24,31 +24,31 @@ class OrderedClipResolverTest {}@Test fun audioMismatchFallsBackInRankOrder() = runBlocking {val tried = mutableListOf<Int>()- val result = firstVerifiedClip(listOf(1, 2, 3), { "MUSIC_VIDEO_TYPE_OMV" }) {+ val result = firstVerifiedClip(listOf(1, 2, 3), classify = { "MUSIC_VIDEO_TYPE_OMV" }) {tried += it; ClipVerification(if (it == 2) "matched" else null)}assertEquals("matched", result.value); assertEquals(listOf(1, 2), tried)}@Test fun identityWorkIsBoundedWhenEveryOfficialCandidateMismatches() = runBlocking {var downloaded = 0- val result = firstVerifiedClip((0..9).toList(), { "MUSIC_VIDEO_TYPE_OMV" }) {+ val result = firstVerifiedClip((0..9).toList(), classify = { "MUSIC_VIDEO_TYPE_OMV" }) {downloaded++; ClipVerification<String>()}assertNull(result.value); assertEquals(3, downloaded)}@Test fun classificationNeverAcceptsUnofficialUploads() = runBlocking {var downloaded = 0- val result = firstVerifiedClip(listOf(0, 1), { "MUSIC_VIDEO_TYPE_UGC" }) {+ val result = firstVerifiedClip(listOf(0, 1), classify = { "MUSIC_VIDEO_TYPE_UGC" }) {downloaded++; ClipVerification("bad")}assertNull(result.value); assertFalse(result.failed); assertEquals(0, downloaded)}@Test fun unknownClassificationMustNotBeCachedAsUnavailable() = runBlocking {- val result = firstVerifiedClip(listOf(0, 1), { if (it == 0) null else "MUSIC_VIDEO_TYPE_ATV" }) { ClipVerification("unused") }+ val result = firstVerifiedClip(listOf(0, 1), classify = { if (it == 0) null else "MUSIC_VIDEO_TYPE_ATV" }) { ClipVerification("unused") }assertNull(result.value); assertTrue(result.failed)}@Test fun failedDownloadAllowsAnotherOfficialCandidate() = runBlocking {- val result = firstVerifiedClip(listOf(0, 1), { "MUSIC_VIDEO_TYPE_OMV" }) {+ val result = firstVerifiedClip(listOf(0, 1), classify = { "MUSIC_VIDEO_TYPE_OMV" }) {if (it == 0) ClipVerification(failed = true) else ClipVerification("next")}assertEquals("next", result.value)diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.ktindex bc23935d..94050941 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/ControlRelay.kt@@ -32,6 +32,8 @@ import java.util.concurrent.TimeUnit* client token, connection id), then hands the response back to the page.*/internal class ControlRelay(private val view: WebView, private val fingerprint: Fingerprint) {+ /** The page's player registered its playback device (it started, and takes commands). */+ @Volatile var onDeviceRegistered: (() -> Unit)? = nullprivate val main = Handler(Looper.getMainLooper())/**@@ -180,6 +182,7 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:val net = android.os.SystemClock.uptimeMillis() - askedLogbook.log("relay $method ${shortPath(url)} -> ${it.code} in $net ms")if (it.code >= 400) Logbook.log("relay error body: ${text.take(400)}")+ if (it.code in 200..299 && method == "POST" && url.substringBefore('?').endsWith("/track-playback/v1/devices")) onDeviceRegistered?.invoke()// B3 (402 on some free accounts): what a tester's report must carry to tell the// causes apart — the refusal's own headers, and what the refused command asked// (the license the page put in it, a picked song or not). No ids, no cookies.@@ -193,7 +196,18 @@ internal class ControlRelay(private val view: WebView, private val fingerprint:?.let { m -> Logbook.log("registration: effective_license=${m.groupValues[1]}") }if (debuggable && registration) Logbook.log("registration answered: ${text.take(500)}")if (debuggable && AD_MARK.containsMatchIn(text)) keepAdSample(method, url, body, text)- reply(id, it.code, out.toString(), text)+ // An ad in the queue Spotify sends: the song before it goes on to the next song+ // instead, before the page sees the queue (see AdBlock.withoutAds).+ val given = if (url.contains("/track-playback/")) app.myspoti.spotify.bridge.AdBlock.withoutAds(text) else null+ given?.second?.forEach { note -> Logbook.log("ad left out: $note") }+ val sent = given?.first ?: text+ // Both ways on from this song lead to the ad: the player plays the next song+ // just before this one ends (AdBlock.adAhead).+ if (url.contains("/track-playback/")) app.myspoti.spotify.bridge.AdBlock.adAhead(sent)?.let { a ->+ if (app.myspoti.spotify.bridge.AdBlock.ahead.value != a) Logbook.log("ad ahead: ${a.nextUri} is played before the end")+ app.myspoti.spotify.bridge.AdBlock.ahead.value = a+ }+ reply(id, it.code, out.toString(), sent)}}})diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/LastExit.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/LastExit.ktnew file mode 100644index 00000000..79c4567a--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/LastExit.kt@@ -0,0 +1,83 @@+package app.myspoti.host.android++import android.app.ActivityManager+import android.app.ApplicationExitInfo+import android.content.Context+import android.os.Build+import java.io.File++/**+ * How the app last ended, put back in the diagnostic report of the next run: the report lives in+ * memory and died with the process, so a crash or a freeze ("app isn't responding") left nothing+ * to read (reported: crashes while typing in a playlist's search, with an empty report after).+ *+ * - A Kotlin/Java crash: its stack, written to storage by the default handler before Android ends+ * the app, read and deleted at the next start.+ * - A freeze Android ended (ANR) or a native crash: Android's own record of the exit (API 30+),+ * with the main thread's stack for an ANR.+ *+ * Release builds rename the app's classes: the build's mapping file reads them back.+ */+object LastExit {+ private const val FILE = "last_crash.txt"+ private const val PREFS = "last_exit"+ private const val SEEN = "seen_at"++ /** Called first thing at start: records crashes from now on, reports the last exit. */+ fun install(context: Context) {+ val app = context.applicationContext+ val previous = Thread.getDefaultUncaughtExceptionHandler()+ Thread.setDefaultUncaughtExceptionHandler { thread, error ->+ runCatching {+ val text = buildString {+ append("crash on ").append(thread.name).append(": ").append(error.toString()).append('\n')+ error.stackTrace.take(40).forEach { append(" at ").append(it.toString()).append('\n') }+ generateSequence(error.cause) { it.cause }.take(3).forEach { c ->+ append("caused by ").append(c.toString()).append('\n')+ c.stackTrace.take(15).forEach { append(" at ").append(it.toString()).append('\n') }+ }+ }+ File(app.filesDir, FILE).writeText(text)+ }+ previous?.uncaughtException(thread, error)+ }+ runCatching { reportCrashFile(app) }+ runCatching { reportExitInfo(app) }+ }++ private fun reportCrashFile(context: Context) {+ val f = File(context.filesDir, FILE)+ if (!f.exists()) return+ Logbook.log("previous run crashed:")+ f.readLines().take(60).forEach { Logbook.log(" $it") }+ f.delete()+ }++ private fun reportExitInfo(context: Context) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return+ val am = context.getSystemService(ActivityManager::class.java) ?: return+ val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+ val seen = prefs.getLong(SEEN, 0L)+ val exits = am.getHistoricalProcessExitReasons(context.packageName, 0, 5).filter { it.timestamp > seen }+ exits.maxOfOrNull { it.timestamp }?.let { prefs.edit().putLong(SEEN, it).apply() }+ for (e in exits.sortedBy { it.timestamp }) {+ val reason = when (e.reason) {+ ApplicationExitInfo.REASON_ANR -> "not responding (ANR)"+ ApplicationExitInfo.REASON_CRASH -> "crash"+ ApplicationExitInfo.REASON_CRASH_NATIVE -> "native crash"+ ApplicationExitInfo.REASON_LOW_MEMORY -> "low memory"+ ApplicationExitInfo.REASON_USER_REQUESTED, ApplicationExitInfo.REASON_USER_STOPPED -> continue+ ApplicationExitInfo.REASON_EXIT_SELF, ApplicationExitInfo.REASON_SIGNALED -> continue+ else -> "reason ${e.reason}"+ }+ val at = java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.US).format(java.util.Date(e.timestamp))+ Logbook.log("previous exit at $at: $reason${e.description?.let { " ($it)" } ?: ""}")+ // An ANR's trace: the main thread's stack is what was holding it.+ if (e.reason == ApplicationExitInfo.REASON_ANR) runCatching {+ val trace = e.traceInputStream?.bufferedReader()?.use { it.readText() } ?: return@runCatching+ val main = trace.substringAfter("\"main\"", "").lineSequence().take(30).toList()+ main.forEach { Logbook.log(" $it") }+ }+ }+ }+}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MainThreadWatch.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MainThreadWatch.ktnew file mode 100644index 00000000..65c24246--- /dev/null+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MainThreadWatch.kt@@ -0,0 +1,85 @@+package app.myspoti.host.android++import android.os.Handler+import android.os.HandlerThread+import android.os.Looper+import android.os.SystemClock++/**+ * Says in the diagnostic report what held the main thread when the app froze for a moment+ * (reported: "micro hangs" on opening the app or switching tasks, with nothing in the log to+ * say why). A background thread asks the main thread for a sign of life every [PING_MS]; when+ * none comes for [STALL_MS], the main thread's stack is read a few times until it answers, and+ * the frames seen most are logged with the length of the stall.+ *+ * Runs only while the app is on screen (and [TAIL_MS] after, for the stall of leaving it).+ */+object MainThreadWatch {+ private const val PING_MS = 100L+ private const val STALL_MS = 150L+ private const val TAIL_MS = 3_000L+ private const val FRAMES = 6++ private val main = Handler(Looper.getMainLooper())+ private val thread by lazy { HandlerThread("main-watch").also { it.start() } }+ private val watch by lazy { Handler(thread.looper) }++ @Volatile private var askedAt = 0L+ @Volatile private var answered = true+ @Volatile private var answeredAt = 0L+ @Volatile private var runUntil = 0L+ @Volatile private var running = false+ private var stalled = false+ private val seen = HashMap<String, Int>()++ private val pong = Runnable { answeredAt = SystemClock.uptimeMillis(); answered = true }++ private val tick: Runnable = object : Runnable {+ override fun run() {+ val now = SystemClock.uptimeMillis()+ if (!answered) {+ // No answer yet: past STALL_MS, the main thread is read until it answers.+ if (now - askedAt >= STALL_MS) { stalled = true; sample() }+ watch.postDelayed(this, 50L)+ return+ }+ if (stalled) report(answeredAt - askedAt)+ if (now > runUntil) { running = false; return }+ askedAt = now; answered = false+ main.post(pong)+ watch.postDelayed(this, PING_MS)+ }+ }++ /** The app came on screen: watched until [stop] and a little after. */+ fun start() {+ runUntil = Long.MAX_VALUE+ if (running) return+ running = true+ answered = true+ watch.post(tick)+ }++ /** The app left the screen: still watched for [TAIL_MS]. */+ fun stop() { runUntil = SystemClock.uptimeMillis() + TAIL_MS }++ private fun sample() {+ val stack = Looper.getMainLooper().thread.stackTrace+ // What the thread is in (often the framework: a lock, a file, the WebView), then the app's+ // own frames that led there. Release builds rename the app's classes: the build's mapping+ // file reads them back.+ val inner = stack.take(3)+ val own = stack.drop(3).filterNot { f -> FRAMEWORK.any { f.className.startsWith(it) } }.take(FRAMES)+ val key = (inner + own).joinToString(" < ") { "${it.className}.${it.methodName}:${it.lineNumber}" }+ seen[key] = (seen[key] ?: 0) + 1+ }++ private val FRAMEWORK = listOf("android.", "androidx.", "java.", "javax.", "kotlin.", "kotlinx.", "com.android.", "dalvik.", "libcore.", "sun.", "org.chromium.", "com.google.")++ private fun report(ms: Long) {+ val top = seen.maxByOrNull { it.value }?.key+ stalled = false+ seen.clear()+ if (top != null) Logbook.log("main thread held $ms ms: $top")+ }+}diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.ktindex ca8af779..ca72aa4a 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/MyspotiRuntime.kt@@ -85,8 +85,8 @@ object MyspotiRuntime {// report needs the session itself — a token that is anonymous means no account.val session = when {host.loginRequired.value -> "login-page"- runCatching { isSignedIn() }.getOrDefault(false) -> "signed-in"- else -> "anonymous"+ // The token in hand: a fresh one every 10 s held every request behind the page's answer.+ else -> when (spotify.signedInHint()) { true -> "signed-in"; false -> "anonymous"; null -> "unknown" }}val line = "status ready=${spotify.ready.value} session=$session " +"track=${s?.item?.name} paused=${s?.isPaused} buffering=${s?.isBuffering} url=${host.url.value.take(60)}"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 20b9f380..dac2d663 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@@ -146,10 +146,28 @@ class PlaybackService : MediaBrowserServiceCompat() {super.onDestroy()}+ /**+ * The app closed from the recent apps. The music stops with it (asked by users: it went on+ * playing with nothing on screen), unless the setting keeps it playing ([keepsPlayingOnClose]);+ * a Spotify Connect device that plays is left playing. The pause fades out, then the+ * notification goes with the service.+ */override fun onTaskRemoved(rootIntent: Intent?) {+ if (current?.playing == true && !playingRemote && !keepsPlayingOnClose(this)) {+ controls?.pause()+ handler.postDelayed({+ ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)+ foreground = false+ stopSelf()+ }, CLOSE_STOP_MS)+ return+ }if (current?.playing != true) stopSelf()}+ /** A Spotify Connect device plays (the session's volume is that device's). */+ private var playingRemote = false+private val callback = object : MediaSessionCompat.Callback() {override fun onPlay() { controls?.play() }override fun onPause() { controls?.pause() }@@ -351,6 +369,7 @@ class PlaybackService : MediaBrowserServiceCompat() {/** Playback on a Connect device: the volume keys drive that device instead of the phone. */private fun setRemote(remote: Boolean, volume: Int) {+ playingRemote = remoteif (!remote) {session.setPlaybackToLocal(android.media.AudioManager.STREAM_MUSIC)return@@ -428,6 +447,18 @@ class PlaybackService : MediaBrowserServiceCompat() {}companion object {+ /** Time left to the pause's fade-out before the notification goes. */+ private const val CLOSE_STOP_MS = 800L+ private const val CLOSE_PREFS = "playback_service"+ private const val KEEP_PLAYING_KEY = "keep_playing_on_close"++ /** The music goes on when the app is closed from the recent apps (off: it stops). */+ fun keepsPlayingOnClose(context: Context): Boolean =+ context.getSharedPreferences(CLOSE_PREFS, Context.MODE_PRIVATE).getBoolean(KEEP_PLAYING_KEY, false)++ fun setKeepsPlayingOnClose(context: Context, on: Boolean) =+ context.getSharedPreferences(CLOSE_PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEEP_PLAYING_KEY, on).apply()+const val ROOT_ID = "root"/** Root for callers that may control playback but not browse (see onGetRoot). */private const val EMPTY_ROOT_ID = "empty"diff --git a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.ktindex ecd182c4..b35802aa 100644--- a/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt+++ b/base/host-android/src/main/kotlin/app/myspoti/host/android/WebPlayerHost.kt@@ -156,7 +156,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {// The page plays the audio: its renderer keeps its priority when the screen is off.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, false)// Playback control requests leave from the app, without the WebView's X-Requested-With.- relay = ControlRelay(this, fingerprint).also { it.install() }+ relay = ControlRelay(this, fingerprint).also {+ it.onDeviceRegistered = { drmAsked = true; main.removeCallbacks(drmWatch) }+ it.install()+ }val webView = thisCookieManager.getInstance().apply {setAcceptCookie(true)@@ -173,6 +176,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {override fun onPermissionRequest(request: PermissionRequest) {Logbook.log("permission request: ${request.resources.joinToString()}")+ if (PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID in request.resources) { drmAsked = true; main.removeCallbacks(drmWatch) }val allowed = request.resources.filter { it == PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID }if (allowed.isNotEmpty()) request.grant(allowed.toTypedArray()) else request.deny()}@@ -215,7 +219,8 @@ class WebPlayerHost(private val context: Context) : BridgeHost {pageStarts++_url.value = url_loginRequired.value = isLoginPage(url)- if (url.startsWith(PLAYER_URL)) { onPageStarting?.invoke(); relay.injectNow() }+ if (url.startsWith(PLAYER_URL)) { drmAsked = false; onPageStarting?.invoke(); relay.injectNow() }+ if (PLAYER_ROOT.matches(url) && url != roots.getString(ROOT_KEY, null)) roots.edit().putString(ROOT_KEY, url).apply()}override fun onReceivedError(view: WebView, request: WebResourceRequest, error: android.webkit.WebResourceError) {@@ -240,7 +245,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {if (url.startsWith(PLAYER_URL) && !mainFrameFailed) { pageFailures = 0; main.removeCallbacks(retryPlayerPage) }_url.value = url_loginRequired.value = isLoginPage(url)- if (url.startsWith(PLAYER_URL)) onPageLoaded?.invoke()+ if (url.startsWith(PLAYER_URL)) {+ onPageLoaded?.invoke()+ if (!drmAsked) { main.removeCallbacks(drmWatch); main.postDelayed(drmWatch, DRM_WATCH_MS) }+ }}override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {@@ -258,7 +266,10 @@ class WebPlayerHost(private val context: Context) : BridgeHost {* kills the whole process if one is still used after this returns false: the page is* rebuilt on a new WebView, and true says "handled, do not kill the app".*/- override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {+ override fun onRenderProcessGone(gone: WebView, detail: RenderProcessGoneDetail): Boolean {+ // Killed (memory pressure) or crashed: both end here. A late callback from a view+ // that was already replaced must not tear down the healthy new one.+ if (gone !== [email protected]) return trueLogbook.log("renderer gone (crashed=${detail.didCrash()}): rebuilding the page")rebuild()return true@@ -277,10 +288,12 @@ class WebPlayerHost(private val context: Context) : BridgeHost {* the new one takes its place in the same container, and the page loads again. Without this* the app kept a dead page — a blank screen with the sound gone — until it was restarted.*/- private fun rebuild() = main.post {+ private fun rebuild(): Boolean = main.post {+ main.removeCallbacks(drmWatch)val wasLoaded = loadAskedval box = containerbox?.let { runCatching { it.removeView(view) } }+ (view as? AwakeWebView)?.releaseFromWindow()runCatching { view.stopLoading() }runCatching { view.destroy() }view = createView()@@ -290,7 +303,9 @@ class WebPlayerHost(private val context: Context) : BridgeHost {// just after, once, so a rebuilt page is loaded exactly once.loadAsked = falsebox?.let { attach(it, lastVisible) }- if (wasLoaded) load() else view.loadUrl("about:blank")+ // The new view's first navigation can be lost while the browser side still settles after+ // the kill (seen: no page start for 4 s): the watchdog looks again after 1.5 s, not 4 s.+ if (wasLoaded) load(firstWatchMs = REBUILD_WATCH_MS) else view.loadUrl("about:blank")}private fun isLoginPage(url: String?) =@@ -298,11 +313,13 @@ class WebPlayerHost(private val context: Context) : BridgeHost {// "Continue with Google / Facebook / Apple": still mid sign-in on their pages.url.contains("accounts.google.com") || url.contains("facebook.com") || url.contains("appleid.apple.com"))- fun load() = main.post {+ fun load() = load(firstWatchMs = LOAD_WATCH_MS)++ private fun load(firstWatchMs: Long) = main.post {pageStarts = 0loadAsked = true- view.loadUrl(PLAYER_URL)- watchLoad(PLAYER_URL, attempt = 1)+ view.loadUrl(playerRoot())+ watchLoad(playerRoot(), attempt = 1, firstWatchMs)}/** Page starts since the last [load]; the load watchdog looks at it. */@@ -318,18 +335,67 @@ class WebPlayerHost(private val context: Context) : BridgeHost {* navigation of a WebView made in Application.onCreate: no page start, ever. When* nothing started after a while, the page is asked for again (a few times, further apart).*/- private fun watchLoad(url: String, attempt: Int) {+ private fun watchLoad(url: String, attempt: Int, firstWatchMs: Long = LOAD_WATCH_MS) {main.postDelayed({if (pageStarts > 0 || !loadAsked || attempt > LOAD_RETRIES) return@postDelayedLogbook.log("page never started: loading again (attempt $attempt)")if (attempt > 1) view.stopLoading()view.loadUrl(url)watchLoad(url, attempt + 1)- }, LOAD_WATCH_MS * attempt)+ }, if (attempt == 1) firstWatchMs else LOAD_WATCH_MS * attempt)}+ private val roots by lazy { context.getSharedPreferences("web_player", Context.MODE_PRIVATE) }++ /**+ * Where Spotify sends "/" for this account's language (`…/intl-fr/`), loaded directly: the+ * redirect cost a whole navigation, about 0.5 s, on every start and reload (measured on the+ * test phone). Learnt from the last load; a language where "/" is final keeps [PLAYER_URL].+ */+ private fun playerRoot(): String = roots.getString(ROOT_KEY, null)?.takeIf { PLAYER_ROOT.matches(it) } ?: PLAYER_URL+/** The player's own URL, not the page's current one: the bridge parks the page on an empty route. */- fun reload() = main.post { view.loadUrl(PLAYER_URL) }+ fun reload() = main.post {+ // A page whose player never started is not helped by loading it again in the same renderer.+ if (pageStarts > 0 && !drmAsked && _url.value.startsWith(PLAYER_URL) && newViewAllowed()) {+ Logbook.log("reload: the player never started on this page (no DRM request): new WebView instead")+ rebuild()+ } else view.loadUrl(playerRoot())+ }++ /**+ * The page's player started since the page last started: it asked for DRM (Widevine), as it+ * does on every load, or its playback device was registered. A page that never asks never registers its device, and every command+ * then fails with "No such device" (seen on a Xiaomi just after signing in: six minutes and+ * five reloads, until the renderer was replaced, after which it asked at once).+ */+ @Volatile private var drmAsked = false++ /** Times the page was put on a new WebView because its player never started (at most 2 in 10 min). */+ private val drmRebuilds = ArrayDeque<Long>()++ private fun newViewAllowed(): Boolean {+ val now = android.os.SystemClock.elapsedRealtime()+ while (drmRebuilds.isNotEmpty() && now - drmRebuilds.first() > DRM_REBUILD_WINDOW_MS) drmRebuilds.removeFirst()+ if (drmRebuilds.size >= DRM_REBUILDS_MAX) return false+ drmRebuilds.addLast(now)+ return true+ }++ private val drmWatch: Runnable = Runnable {+ if (drmAsked || !loadAsked || !_url.value.startsWith(PLAYER_URL) || isLoginPage(_url.value)) return@Runnable+ if (!newViewAllowed()) { Logbook.log("player never started on this page (no DRM request); new WebViews used up for now"); return@Runnable }+ Logbook.log("player never started on this page (no DRM request ${DRM_WATCH_MS / 1000} s after load): new WebView")+ rebuild()+ }++ /**+ * Hides the page without hiding it from Chromium (it keeps running as on screen): after the+ * sign-in, while the session is being confirmed, the app's own waiting screen shows instead of+ * Spotify's desktop player (reported: it flashed before the first screen). [attach] and+ * [openLogin] show it again.+ */+ fun veil(on: Boolean) = main.post { view.alpha = if (on) 0f else 1f }/** A player page that did not load (Spotify answering 504 to a reload, the network down at that@@ -343,7 +409,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {if (!loadAsked || _loginRequired.value) return@RunnableLogbook.log("player page: load again (attempt ${pageFailures + 1})")view.stopLoading()- view.loadUrl(PLAYER_URL)+ view.loadUrl(playerRoot())}private val loadTimeout = Runnable {if (!loadAsked || _loginRequired.value) return@Runnable@@ -360,7 +426,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {main.postDelayed(retryPlayerPage, wait)}- fun openLogin() = main.post { view.loadUrl(LOGIN_URL) }+ fun openLogin() = main.post { view.alpha = 1f; view.loadUrl(LOGIN_URL) }/** Signs out of Spotify in this WebView, then shows the login page. */fun logout() = main.post {@@ -403,6 +469,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {(view.parent as? ViewGroup)?.removeView(view)val size = if (visible) ViewGroup.LayoutParams.MATCH_PARENT else 1container.addView(view, ViewGroup.LayoutParams(size, size))+ keepClearOfSystemBars(visible)view.alpha = 1fview.visibility = if (visible) View.VISIBLE else View.INVISIBLEview.importantForAccessibility = if (visible) View.IMPORTANT_FOR_ACCESSIBILITY_AUTO else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS@@ -413,7 +480,33 @@ class WebPlayerHost(private val context: Context) : BridgeHost {if (visible) view.requestFocus()view.requestLayout()// Now in a window: a first navigation that never started gets another go.- if (loadAsked && _url.value.isEmpty() && pageStarts == 0) view.loadUrl(PLAYER_URL)+ if (loadAsked && _url.value.isEmpty() && pageStarts == 0) view.loadUrl(playerRoot())+ }++ /**+ * The app draws edge to edge: the login page shown full screen went under the status bar+ * (reported: Spotify's logo under the clock) and its form under the keyboard. Shown, the page+ * keeps clear of the system bars, the cutout and the keyboard; hidden, it takes no room.+ */+ private fun keepClearOfSystemBars(visible: Boolean) {+ val v = view+ androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(v) { _, insets ->+ val lp = v.layoutParams as? ViewGroup.MarginLayoutParams+ if (lp != null) {+ val bars = if (lastVisible) insets.getInsets(+ androidx.core.view.WindowInsetsCompat.Type.systemBars() or+ androidx.core.view.WindowInsetsCompat.Type.displayCutout() or+ androidx.core.view.WindowInsetsCompat.Type.ime()+ ) else androidx.core.graphics.Insets.NONE+ if (lp.topMargin != bars.top || lp.bottomMargin != bars.bottom || lp.leftMargin != bars.left || lp.rightMargin != bars.right) {+ lp.setMargins(bars.left, bars.top, bars.right, bars.bottom)+ v.layoutParams = lp+ }+ }+ insets+ }+ if (visible) androidx.core.view.ViewCompat.requestApplyInsets(v)+ else (v.layoutParams as? ViewGroup.MarginLayoutParams)?.let { it.setMargins(0, 0, 0, 0); v.layoutParams = it }}fun detach() = main.post { (view.parent as? ViewGroup)?.removeView(view) }@@ -425,8 +518,13 @@ class WebPlayerHost(private val context: Context) : BridgeHost {/** Logcat tag of the engine: `adb logcat -s Myspoti`. */const val LOG = "Myspoti"const val PLAYER_URL = "https://open.spotify.com/"+ private val PLAYER_ROOT = Regex("""https://open\.spotify\.com/intl-[a-z]{2,3}(?:-[a-zA-Z]{2,4})?/""")+ private const val ROOT_KEY = "player_root"private const val PLAYER_HOST = "open.spotify.com"private const val PAGE_LOAD_TIMEOUT_MS = 25_000L+ private const val DRM_WATCH_MS = 10_000L+ private const val DRM_REBUILDS_MAX = 2+ private const val DRM_REBUILD_WINDOW_MS = 600_000Lprivate const val LIMIT_COUNT = 6private const val LIMIT_WINDOW_MS = 10_000Lprivate const val LIMIT_HOLD_MS = 60_000L@@ -434,6 +532,7 @@ class WebPlayerHost(private val context: Context) : BridgeHost {private const val LIMIT_FORGET_MS = 1_800_000Lprivate val RETRY_PAGE_MS = longArrayOf(2_000, 5_000, 15_000, 30_000, 60_000)private const val LOAD_WATCH_MS = 4_000L+ private const val REBUILD_WATCH_MS = 1_500Lprivate const val LOAD_RETRIES = 4const val LOGIN_URL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"}@@ -456,4 +555,31 @@ private class AwakeWebView(context: Context) : WebView(context) {override fun getVisibility(): Int = View.VISIBLEoverride fun getWindowVisibility(): Int = View.VISIBLEoverride fun onWindowVisibilityChanged(visibility: Int) = super.onWindowVisibilityChanged(View.VISIBLE)++ /**+ * Closing the app (swiped from recents, back) destroys the activity and its window, and the+ * view leaves the window with it. Chromium then marks the page's view and window hidden and+ * tears down its compositor: the music stopped for a moment until the player's repair+ * restarted it (reported on build 2022), while the foreground service was still there. The+ * departure is kept from Chromium, as the visibility above is: the page keeps playing as in+ * a window that is on screen, and Chromium is told for real when the view is attached+ * again (the new window needs a fresh attach) or destroyed.+ */+ private var detachHeld = false++ override fun onDetachedFromWindow() {+ detachHeld = true+ }++ override fun onAttachedToWindow() {+ releaseFromWindow()+ super.onAttachedToWindow()+ }++ /** Tells Chromium about a detach that was held back; no-op when none is pending. */+ fun releaseFromWindow() {+ if (!detachHeld) return+ detachHeld = false+ super.onDetachedFromWindow()+ }}diff --git a/docs/api/ADS.md b/docs/api/ADS.mdindex 4d41fa36..072dbb4b 100644--- a/docs/api/ADS.md+++ b/docs/api/ADS.md@@ -87,3 +87,57 @@ Engine rules:- Whether blocked ads come back sooner (rhythm after a failed ad), over a 1-hour session.- Video ads and podcast ad slots, which may use other hosts.++## Measured again (2026-10-20): a refused ad no longer moves on++Setup: free account, desktop Chrome, the app's current bridge, about two hours of listening.++- The page's ad-manager latch (`ads.off`) does not stop audio ads: one ad after ~17 min with the latch+ on, one after ~19 min without it. The server queues them whatever the page's managers say.+- With the ad MP3 refused (aborted, or answered `403` as on Android), the ad now stays current for+ good: buffering at 0:00, 20 min in one run. `inStreamApi.skipToNext()`, `player.next` and+ `player.play` on the next song are all refused (`ad_disallow`). The 2026-10-16 behaviour (error,+ next song within a second) is gone.+- A page reload leaves it: the new page registers a new device, which the ad does not follow, and+ playing the context again starts a song within a second. This is the app's last resort.+- The "Test ad" (`spotify:ad:test`) seen in device logs was `tools/playback_test.py`'s own fake.++## Where the ad sits in the state machine++The ad arrives in a `PUT track-playback/v1/devices/{device}/state` reply when the song before it+starts (about 3 min ahead). The song's state has these transitions:++| transition | first try | after an ad was left out |+|---|---|---|+| `advance` (natural end) | the ad state | the ad state |+| `skip_next` | the next song | the ad state |+| `show_next` (shown as next) | the next song | the next song |++The ad state itself has no transitions and `ad_disallow` restrictions.++## What the engine does now++Three steps, measured on desktop (free account, 20/10, ~1 h 30 of listening, 5 ad tries):++1. `AdBlock.withoutAds` rewrites every reply that leads to an ad before the page sees it: the+ `advance` of a song that leads to an ad goes where its `skip_next` goes. The next song started+ 60 ms after the end of the song, and every state the page reported was answered `200`.+ `show_next` is not a usable target: it points at a display-only state, and a page sent there+ had every report refused (`502 unknown_state_ref`) and stopped playing.+2. When `skip_next` leads to the ad as well (Spotify's next try, after an ad was left out once),+ `AdBlock.adAhead` names the song the page shows as next, and the player plays it 1 s before+ the song ends (`player.play` in the same context). A new play puts the due ad first, but an ad+ at the start of a play, its audio refused, moves on by itself: the next song came within about a+ second (three tries, at the end and in the middle of a song), every report was `200`, the songs+ after it went on with no ad, and songs the user had queued stayed queued. A "next" while an ad+ is due is sent the same way, since Spotify points the skip at the ad too and a page that steps+ onto an ad stays on it. The UI shows an ad only after 2 s, so this one never shows.+ Seen on a tester's phone: while Spotify refuses licences (429, after fast skipping), the song+ after the ad cannot start and the ad stays until the limit is over.+3. The ad audio host stays refused, and the reload stays as the last resort for an ad that is+ already the current state.++On Android the replies pass through `ControlRelay`, which applies steps 1 and 2. The desktop CDP+host does not rewrite replies yet.++Over the measured session: no ad heard or shown, no reload.diff --git a/docs/api/LIBRARY.md b/docs/api/LIBRARY.mdindex a5dde3e5..bfa8facc 100644--- a/docs/api/LIBRARY.md+++ b/docs/api/LIBRARY.md@@ -466,10 +466,47 @@ Rootlist and liked-songs-artist pushes carried only fields 1, 2 and 9. Simplestrule: on any playlist push, re-fetch that playlist (or the rootlist / `libraryV3`) unlessthe revision equals the one already held.+## Blend ("Mix à plusieurs")++The Web Player has Blend routes (`/blend/invitation`, `/blend/taste-match/{id}`), all on one+spclient service, `https://spclient.wg.spotify.com/blend-invitation` (no GraphQL operation,+no page service). Checked live on the free test account (token and client-token as for any+spclient call):++| Call | Answer |+|---|---|+| `POST /v1/generate` (empty body) | `201 {"invite":"https://open.spotify.com/blend/taste-match/{id}?si=…&fallback=getapp&blendDecoration=…"}` |+| `GET /v3/view-invitation/{id}` | `200 {page_type, members, recipient{name,username,image_url,hash}, playlist_uri, title, subtitle, members_title, button_text, footnote}` |+| `PUT /v2/join/{id}` (empty body) | `200 {"playlist_uri":"spotify:playlist:37i9dQZF1E…"}` |++`page_type`: `PENDING_INVITATION` (own invitation, nobody joined), `READY_TO_JOIN_EMPTY_BLEND` /+`READY_TO_JOIN_ALREADY_CREATED_BLEND` (someone else's, open), `MAX_MEMBERS`, `ALREADY_JOINED`+(then `playlist_uri` is set), `DELETED`. The Blend playlist only exists once a second account+has joined: joining one's own invitation returned a `playlist_uri` that `fetchPlaylist` answers+"not found" and that sits in the rootlist as a `placeholder` item (removed again with+`RootlistAPI.remove`). An invitation cannot be revoked. A real Blend is an ordinary playlist+(`format: "blend"` in `fetchPlaylist`), opened, played and listed like any other. A link+`open.spotify.com/blend/taste-match/{id}` opened in the app shows the invitation (view, then join).++The Blend page itself (members, taste match, rename, leave) uses calls the Web Player has no+screen for; they are the ones Spotify's mobile apps make for that page. The two reads were+checked live on a real two-member Blend (21/10), and rename; leave was not sent yet:++| Call | Answer |+|---|---|+| `GET /v3/get-invitation/{playlistId}` | `200 {title, button_text, invitation_link, members[{name, image_url, hash, username}]}` (`image_url` may be `""`) |+| `GET /v3/data-stories/{playlistId}` | `200 {intro_story{title1{text,text_color}, subtitle1, background_color, audio_uri}, stories[{story_type, title, subtitle, body, image, background_color, button{navigation_uri}}]}` |+| `PUT blend-writer/v1/rename/{playlistId}` `{"name":…}` | `200`, empty body (checked with the Blend's own name) |+| `PUT /v1/leave` `{"playlist_uri":"spotify:playlist:…"}` | not sent yet |++`blend-writer` is a sibling of `blend-invitation` on the same host. The texts (titles, button+words, story lines) come translated in the account's language.+## Gaps (not captured)-- Remove tracks from a playlist (expected `playlist/v2/playlist/{id}/changes` with a `REM`- op, or a GraphQL `removeFromPlaylist`; unknown).+- Remove tracks from a playlist: GraphQL `removeFromPlaylist {playlistUri, uids}` removes+ exactly the rows named by `uid` (checked live: the same song twice has two uids, removing+ one leaves the other). Never address a row by its track uri.- Reorder tracks (`MOV`, or `addToPlaylist`/move with `fromUid`; unknown).- Delete a playlist (for an own playlist the Web Player probably only does the rootlist`REM`; not confirmed).diff --git a/docs/screenshots/album.jpg b/docs/screenshots/album.jpgindex 4727bb35..9429b9a7 100644Binary files a/docs/screenshots/album.jpg and b/docs/screenshots/album.jpg differdiff --git a/docs/screenshots/artist.jpg b/docs/screenshots/artist.jpgindex bbcb0ef3..4159636c 100644Binary files a/docs/screenshots/artist.jpg and b/docs/screenshots/artist.jpg differdiff --git a/docs/screenshots/banner.jpg b/docs/screenshots/banner.jpgindex 44d0ab82..5abeb70c 100644Binary files a/docs/screenshots/banner.jpg and b/docs/screenshots/banner.jpg differdiff --git a/docs/screenshots/home.jpg b/docs/screenshots/home.jpgindex 3421ce0c..48140e8c 100644Binary files a/docs/screenshots/home.jpg and b/docs/screenshots/home.jpg differdiff --git a/docs/screenshots/player.jpg b/docs/screenshots/player.jpgindex 825eaa55..37a4391e 100644Binary files a/docs/screenshots/player.jpg and b/docs/screenshots/player.jpg differ