Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.
Kotlin alternativeandroidandroid-applicationclientglassmorphisminnertubelibrespotliquid-glassspotifyspotify-connectspotifyapiyoutube-musicyoutube-playerytdlnis
Making a playlist is a sheet of its own, and editing one uses it too
Leloniod4feef0ef54a
diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.ktindex 0deadbf..a161db5 100644--- a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt@@ -87,6 +87,14 @@ data class HomeFeed(* throwing: no screen should have to know which backend is active to stay* usable.*/+/** A playlist as its edit sheet shows it. */+data class PlaylistDetails(+ val name: String,+ val description: String,+ val public: Boolean,+ val artworkUrl: String?,+)+interface MusicBackend {val id: BackendId@@ -174,9 +182,30 @@ interface MusicBackend {val canEditPlaylists: Boolean get() = false/** Creates an empty playlist and returns it, ready to be opened. */- suspend fun createPlaylist(name: String): CatalogPlaylist =+ /**+ * Makes a playlist. The description and the visibility are taken where+ * the source keeps them; see [describesPlaylists].+ */+ suspend fun createPlaylist(+ name: String,+ description: String = "",+ public: Boolean = false,+ ): CatalogPlaylist = throw UnsupportedOperationException()++ /** Whether a new playlist can be given a description, a visibility and a cover. */+ val describesPlaylists: Boolean get() = false++ /** Sets a playlist's cover from a JPEG; see [describesPlaylists]. */+ suspend fun setPlaylistCover(uri: String, jpeg: ByteArray): Unit =throw UnsupportedOperationException()+ /** What the edit sheet starts from; null where the source only names a playlist. */+ suspend fun playlistDetails(uri: String): PlaylistDetails? = null++ /** Changes what [describesPlaylists] covers, or only the name elsewhere. */+ suspend fun updatePlaylist(uri: String, name: String, description: String, public: Boolean) =+ renamePlaylist(uri, name)+suspend fun renamePlaylist(uri: String, name: String): Unit =throw UnsupportedOperationException()diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.ktindex 4aefeda..10ff4b9 100644--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt@@ -1,5 +1,6 @@package dev.lelonio.square.backend+import okhttp3.RequestBody.Companion.toRequestBodyimport androidx.media3.common.Playerimport androidx.media3.common.util.UnstableApiimport dev.lelonio.square.SquareApplication@@ -271,11 +272,18 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {override val canEditPlaylists: Booleanget() = container.spotifySignedIn && container.webApi.isReady- override suspend fun createPlaylist(name: String): CatalogPlaylist {+ override val describesPlaylists: Boolean get() = true++ override suspend fun createPlaylist(name: String, description: String, public: Boolean): CatalogPlaylist {// The account's own id: Spotify creates a playlist under a user rather// than under "me", even though the token already says who that is.val userId = container.api.me().id- val created = container.api.createPlaylist(userId, PlaylistDetailsDto(name))+ val created = container.api.createPlaylist(+ userId,+ // Sent even when empty: left out, Spotify stored the word "null"+ // as the description, and every client showed it.+ PlaylistDetailsDto(name, isPublic = public, description = description.trim()),+ )return CatalogPlaylist(uri = created.uri,name = created.name,@@ -283,6 +291,39 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {)}+ override suspend fun setPlaylistCover(uri: String, jpeg: ByteArray) {+ val body = android.util.Base64.encodeToString(jpeg, android.util.Base64.NO_WRAP)+ container.api.uploadPlaylistCover(+ uri.substringAfterLast(':'),+ body.toRequestBody(null),+ )+ }++ override suspend fun playlistDetails(uri: String): PlaylistDetails {+ val dto = container.api.playlist(uri.substringAfterLast(':'), fields = "id,uri,name,description,public,images")+ return PlaylistDetails(+ name = dto.name,+ // Spotify hands descriptions back HTML-escaped: an apostrophe+ // arrives as '.+ description = androidx.core.text.HtmlCompat+ .fromHtml(dto.description.orEmpty(), androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY)+ .toString()+ // What a playlist made without one was given; saving the sheet+ // as it opens clears it.+ .takeUnless { it == "null" }+ .orEmpty(),+ public = dto.public ?: false,+ artworkUrl = dto.images.firstOrNull()?.url,+ )+ }++ override suspend fun updatePlaylist(uri: String, name: String, description: String, public: Boolean) {+ container.api.updatePlaylistDetails(+ uri.substringAfterLast(':'),+ PlaylistDetailsDto(name, isPublic = public, description = description.trim()),+ )+ }+override suspend fun renamePlaylist(uri: String, name: String) {container.api.updatePlaylistDetails(uri.substringAfterLast(':'), PlaylistDetailsDto(name))}diff --git a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.ktindex 3dfd3bc..f3c8ffc 100644--- a/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt+++ b/app/src/main/java/dev/lelonio/square/backend/youtube/YouTubeBackend.kt@@ -654,7 +654,7 @@ class YouTubeBackend(private val account: YouTubeAccount) : MusicBackend {override val canEditPlaylists: Booleanget() = account.isSignedIn- override suspend fun createPlaylist(name: String): CatalogPlaylist =+ override suspend fun createPlaylist(name: String, description: String, public: Boolean): CatalogPlaylist =withContext(Dispatchers.IO) {// Blocking upstream, deliberately not wrapped in runCatching there:// a failure has to reach the caller, which is a screen waiting todiff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.ktindex 734201a..840c60a 100644--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt@@ -136,6 +136,11 @@ data class CatalogPlaylist(* portrait among square covers is how a shelf says "these are people".*/val isArtist: Boolean = false,+ /**+ * Whether it is the account's own, where the account's index says: what+ * decides if it can be edited. Null when nobody said.+ */+ val mine: Boolean? = null,)/** One credited artist: what to write, and where it leads. */@@ -246,6 +251,11 @@ object Catalog {const val DJ_URI = "spotify:playlist:37i9dQZF1EYkqdzj48dyYq"/** The account's own playlists. */+ /** Whether a playlist is the account's own, from the playlist service; see catalog.rs. */+ suspend fun playlistMine(uri: String): Boolean? = withContext(Dispatchers.IO) {+ runCatching { json.decodeFromString<Boolean?>(NativeBridge.playlistMine(uri)) }.getOrNull()+ }+suspend fun playlists(): List<CatalogPlaylist> = withContext(Dispatchers.IO) {json.decodeFromString<List<CatalogPlaylist>>(NativeBridge.rootlist()).filterNot { it.uri == DJ_URI }diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.ktindex 4be7260..513b03a 100644--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt@@ -266,6 +266,18 @@ interface SpotifyApi {@Body request: PlaylistDetailsDto,): PlaylistDto+ /**+ * Replaces a playlist's cover with a JPEG, sent as base64 text of at most+ * 256 KB. Needs `ugc-image-upload`, which an application connected before+ * Square asked for it does not have: that answers 401 or 403.+ */+ @PUT("v1/playlists/{id}/images")+ @retrofit2.http.Headers("Content-Type: image/jpeg")+ suspend fun uploadPlaylistCover(+ @Path("id") playlistId: String,+ @Body jpegBase64: okhttp3.RequestBody,+ )+/** Renames one; the same endpoint changes description and visibility. */@PUT("v1/playlists/{id}")suspend fun updatePlaylistDetails(@@ -420,7 +432,14 @@ data class AddTracksRequestDto(val uris: List<String>)@Serializabledata class PlaylistDetailsDto(val name: String,- @SerialName("public") val isPublic: Boolean = false,+ /**+ * Null to leave it as it is. Not a plain false: a value equal to its+ * default is not written out, and Spotify reads a missing `public` on a+ * new playlist as true, so "private" used to make a public one.+ */+ @SerialName("public") val isPublic: Boolean? = null,+ /** Null to leave it as it is; empty to clear it. */+ val description: String? = null,)@Serializable@@ -593,6 +612,8 @@ data class PlaylistDto(val name: String,val description: String? = null,val images: List<ImageDto> = emptyList(),+ /** Asked for only where it matters; see MusicBackend.playlistDetails. */+ val public: Boolean? = null,val tracks: PlaylistTracksRefDto? = null,/*** Who made it. The one field that tells "This Is Fabri Fibra", whichdiff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.ktindex e905d4b..c4597c6 100644--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt@@ -466,6 +466,8 @@ object NativeBridge {* A playlist's title, for one arriving by link rather than from the account.*/fun playlistName(uri: String): String = nativePlaylistName(uri)+ /** Whether a playlist is the account's own: JSON true, false or null. */+ fun playlistMine(uri: String): String = nativePlaylistMine(uri)/** What the people this account follows are listening to. */fun friendActivity(): String = nativeFriendActivity()@@ -473,6 +475,7 @@ object NativeBridge {private external fun nativeFriendActivity(): Stringprivate external fun nativePlaylistCover(uri: String): Stringprivate external fun nativePlaylistName(uri: String): String+ private external fun nativePlaylistMine(uri: String): Stringprivate external fun nativeInitContext(context: android.content.Context)private external fun nativeSetAudioOutput(output: Any)private external fun nativeStart(diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.ktindex b752458..2bd55af 100644--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt@@ -1701,6 +1701,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {// 403 and the heart never fills."user-library-read","user-library-modify",+ // A new playlist's cover.+ "ugc-image-upload",),)}@@ -2355,7 +2357,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {*/private fun loadMissingCovers() = viewModelScope.launch {val ready = _state.value as? UiState.Ready ?: return@launch- val missing = ready.playlists.filter { it.artworkUrl == null }+ // A content:// address is a picker's grant from an earlier run, long+ // since unreadable; see fetchUploadedCover.+ val missing = ready.playlists.filter { it.artworkUrl == null || it.artworkUrl.startsWith("content://") }if (missing.isEmpty()) return@launchmissing.forEach { playlist ->@@ -2383,6 +2387,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {if (!container.webApi.isReady) return@launchrunCatching { container.api.me() }.onSuccess { profile ->+ // First, and whatever the screen is doing: it used to be set+ // only once the library was on screen, so a profile that+ // answered sooner left it unset for the whole run, every+ // playlist's "mine" unknown, and what hangs on it hidden.+ meId = profile.idval ready = _state.value as? UiState.Ready ?: return@onSuccess_state.value = ready.copy(displayName = profile.displayName?.takeIf(String::isNotBlank)@@ -2552,14 +2561,28 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {private suspend fun detailsOf(uri: String): PlaylistDetails? {if (!container.webApi.isReady || !uri.startsWith("spotify:playlist:")) return null- val dto = runCatching { container.api.playlist(uri.substringAfterLast(':')) }+ // The owner asked for by name: the default fields leave it out, and+ // without it no playlist was ever known to be the account's own.+ val dto = runCatching {+ container.api.playlist(+ uri.substringAfterLast(':'),+ fields = "id,uri,name,images,description,owner(id,display_name)",+ )+ }.onFailure { android.util.Log.w(TAG, "no details for $uri: ${describe(it)}") }- .getOrNull() ?: return null+ .getOrNull()+ // Spotify's own lists answer 404 to an application in development+ // mode. Whose it is still matters — it is what hides "Edit" — and+ // the playlist service says.+ ?: return PlaylistDetails(description = null, mine = Catalog.playlistMine(uri), owner = null)val owner = dto.owner?.id+ // Asked for here if the profile has not been read yet, rather than+ // left unknown for the page.+ val me = meId ?: runCatching { container.api.me().id }.getOrNull()?.also { meId = it }// Null rather than false when either side is missing: "not yours" hides// the actions, and hiding them because a request came back thin is// worse than the button that was there before.- val mine = if (owner == null || meId == null) null else owner == meId+ val mine = if (owner == null || me == null) null else owner == meval text = dto.description?.replace(Regex("<[^>]*>"), "")?.replace("&", "&")@@ -2567,7 +2590,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {?.replace("'", "'")?.replace("'", "'")?.trim()- ?.takeIf { it.isNotEmpty() }+ // The word a playlist made without a description was given.+ ?.takeIf { it.isNotEmpty() && it != "null" }return PlaylistDetails(description = text,mine = mine,@@ -4219,15 +4243,296 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {* list a playlist it has just created, and a new playlist that does not* appear reads as the button having failed.*/- fun createPlaylist(name: String) = viewModelScope.launch {- runCatching { container.activeBackend.createPlaylist(name.trim()) }- .onSuccess { created ->- val ready = _state.value as? UiState.Ready ?: return@onSuccess- _state.value = ready.copy(playlists = listOf(created) + ready.playlists)+ /** The new-playlist sheet: whether it is waiting, and what went wrong. */+ data class CreatePlaylistState(val busy: Boolean = false, val error: String? = null)++ private val _creatingPlaylist = MutableStateFlow(CreatePlaylistState())+ val creatingPlaylist: StateFlow<CreatePlaylistState> = _creatingPlaylist.asStateFlow()++ fun resetCreatePlaylist() {+ _creatingPlaylist.value = CreatePlaylistState()+ }++ /** Whether the active source takes a description, a visibility and a cover. */+ val describesPlaylists: Boolean get() = container.activeBackend.describesPlaylists++ /**+ * Makes a playlist, puts it at the top of the library and hands it to+ * [onCreated], which opens it.+ *+ * The sheet stays up until the service answers: a playlist that might or+ * might not exist is worse than a moment's wait, and a refusal is said on+ * the sheet rather than in the log. The cover goes up after, and a cover+ * that fails does not take the playlist with it: it is said in a toast,+ * with what to do when the reason is a missing permission.+ */+ fun createPlaylist(+ name: String,+ description: String,+ public: Boolean,+ cover: android.net.Uri?,+ onCreated: (CatalogPlaylist) -> Unit,+ ) {+ if (_creatingPlaylist.value.busy) return+ _creatingPlaylist.value = CreatePlaylistState(busy = true)+ viewModelScope.launch {+ val backend = container.activeBackend+ runCatching { backend.createPlaylist(name.trim(), description, public) }+ .onSuccess { created ->+ (_state.value as? UiState.Ready)?.let { ready ->+ _state.value = ready.copy(playlists = listOf(created) + ready.playlists)+ }+ if (cover != null && backend.describesPlaylists) {+ runCatching {+ val jpeg = withContext(Dispatchers.Default) { coverJpeg(cover) }+ backend.setPlaylistCover(created.uri, jpeg)+ }.onSuccess {+ fetchUploadedCover(created.uri)+ }.onFailure {+ android.util.Log.e(TAG, "playlist cover failed: ${chain(it)}", it)+ val permission = describe(it).let { why -> "401" in why || "403" in why }+ android.widget.Toast.makeText(+ getApplication(),+ string(if (permission) R.string.cover_needs_permission else R.string.cover_failed),+ android.widget.Toast.LENGTH_LONG,+ ).show()+ }+ }+ _creatingPlaylist.value = CreatePlaylistState()+ onCreated(created)+ }+ .onFailure {+ android.util.Log.e(TAG, "create playlist failed: ${chain(it)}", it)+ _creatingPlaylist.value = CreatePlaylistState(error = string(R.string.create_playlist_failed))+ }+ }+ }++ /** Songs offered under one of the account's own playlists. */+ data class SuggestionsState(+ val playlistUri: String? = null,+ val tracks: List<CatalogTrack> = emptyList(),+ val loading: Boolean = false,+ )++ private val _suggestions = MutableStateFlow(SuggestionsState())+ val suggestions: StateFlow<SuggestionsState> = _suggestions.asStateFlow()+ private var suggestionsJob: Job? = null++ /**+ * Songs to add to a playlist of the account's own, as Spotify offers+ * under one.+ *+ * Drawn from the stations of a couple of its songs, picked at random so+ * that asking again brings different ones, or of liked songs while the+ * playlist is still empty. Nothing already in it is offered.+ */+ fun loadSuggestions(playlistUri: String, refresh: Boolean = false) {+ if (!playlistUri.startsWith("spotify:playlist:")) return+ val current = _suggestions.value+ if (!refresh && current.playlistUri == playlistUri && (current.loading || current.tracks.isNotEmpty())) return+ suggestionsJob?.cancel()+ _suggestions.value = SuggestionsState(playlistUri, loading = true)+ suggestionsJob = viewModelScope.launch {+ val present = _playlist.value.takeIf { it.uri == playlistUri }?.tracks.orEmpty()+ val presentUris = present.mapTo(mutableSetOf()) { it.uri }+ val seeds = present.map { it.uri }.filter { it.startsWith("spotify:track:") }+ .ifEmpty { container.likedStore.likedTracks.value.toList() }+ .shuffled()+ .take(SUGGESTION_SEEDS)+ val uris = seeds.flatMap { seed ->+ runCatching { Catalog.contextTrackUris("spotify:station:track:${seed.substringAfterLast(':')}") }+ .getOrDefault(emptyList())+ }+ .filter { it.startsWith("spotify:track:") && it !in presentUris && it !in seeds }+ .distinct()+ .shuffled()+ .take(SUGGESTION_COUNT)+ val tracks = runCatching { Catalog.tracks(uris) }+ .onFailure { android.util.Log.w(TAG, "suggestions unavailable: ${describe(it)}") }+ .getOrDefault(emptyList())+ if (_suggestions.value.playlistUri == playlistUri) {+ _suggestions.value = SuggestionsState(playlistUri, tracks)}- .onFailure { android.util.Log.e(TAG, "create playlist failed: ${chain(it)}", it) }+ }}+ /**+ * One of [suggestions], into the playlist on screen. At once on screen,+ * and back among the suggestions if Spotify refuses it.+ */+ fun addSuggestion(track: CatalogTrack) {+ val uri = _playlist.value.uri?.takeIf { it.startsWith("spotify:playlist:") } ?: return+ _suggestions.value = _suggestions.value.copy(tracks = _suggestions.value.tracks.filterNot { it.uri == track.uri })+ _playlist.value = _playlist.value.copy(tracks = _playlist.value.tracks + track)+ invalidateContext(uri)+ viewModelScope.launch {+ runCatching { container.api.addToPlaylist(uri.substringAfterLast(':'), AddTracksRequestDto(listOf(track.uri))) }+ .onFailure {+ android.util.Log.e(TAG, "add suggestion failed: ${chain(it)}", it)+ if (_playlist.value.uri == uri) {+ _playlist.value = _playlist.value.copy(tracks = _playlist.value.tracks.filterNot { it.uri == track.uri })+ }+ if (_suggestions.value.playlistUri == uri) {+ _suggestions.value = _suggestions.value.copy(tracks = listOf(track) + _suggestions.value.tracks)+ }+ }+ }+ }++ private val SUGGESTION_SEEDS = 2+ private val SUGGESTION_COUNT = 10++ /** The edit sheet of an existing playlist: what it shows and how it is going. */+ data class EditPlaylistState(+ val playlist: CatalogPlaylist,+ val details: dev.lelonio.square.backend.PlaylistDetails? = null,+ val loading: Boolean = false,+ val busy: Boolean = false,+ val error: String? = null,+ )++ private val _editingPlaylist = MutableStateFlow<EditPlaylistState?>(null)+ val editingPlaylist: StateFlow<EditPlaylistState?> = _editingPlaylist.asStateFlow()++ /** Opens the edit sheet, reading what the playlist has now where the source keeps it. */+ fun openEditPlaylist(playlist: CatalogPlaylist) {+ val backend = container.activeBackend+ val plain = dev.lelonio.square.backend.PlaylistDetails(playlist.name, "", false, playlist.artworkUrl)+ if (!backend.describesPlaylists) {+ _editingPlaylist.value = EditPlaylistState(playlist, details = plain)+ return+ }+ _editingPlaylist.value = EditPlaylistState(playlist, loading = true)+ viewModelScope.launch {+ val details = runCatching { backend.playlistDetails(playlist.uri) }+ .onFailure { android.util.Log.w(TAG, "playlist details unavailable: ${describe(it)}") }+ .getOrNull() ?: plain+ _editingPlaylist.value = _editingPlaylist.value+ ?.takeIf { it.playlist.uri == playlist.uri }+ ?.copy(details = details, loading = false)+ }+ }++ fun closeEditPlaylist() {+ _editingPlaylist.value = null+ }++ /**+ * Saves the edit sheet. The sheet waits for the service, as the new one+ * does, and the cover follows as it does there: a cover that fails leaves+ * the rest saved.+ */+ fun savePlaylist(name: String, description: String, public: Boolean, cover: android.net.Uri?) {+ val editing = _editingPlaylist.value ?: return+ if (editing.busy) return+ val uri = editing.playlist.uri+ val trimmed = name.trim()+ _editingPlaylist.value = editing.copy(busy = true, error = null)+ viewModelScope.launch {+ val backend = container.activeBackend+ runCatching { backend.updatePlaylist(uri, trimmed, description, public) }+ .onSuccess {+ (_state.value as? UiState.Ready)?.let { ready ->+ _state.value = ready.copy(+ playlists = ready.playlists.map { if (it.uri == uri) it.copy(name = trimmed) else it },+ )+ }+ if (_playlist.value.uri == uri) {+ _playlist.value = _playlist.value.copy(name = trimmed, description = description.trim())+ }+ invalidateContext(uri)+ if (cover != null && backend.describesPlaylists) {+ runCatching {+ val jpeg = withContext(Dispatchers.Default) { coverJpeg(cover) }+ backend.setPlaylistCover(uri, jpeg)+ }.onSuccess {+ coverCache.remove(uri)+ fetchUploadedCover(uri)+ }.onFailure {+ android.util.Log.e(TAG, "playlist cover failed: ${chain(it)}", it)+ val permission = describe(it).let { why -> "401" in why || "403" in why }+ android.widget.Toast.makeText(+ getApplication(),+ string(if (permission) R.string.cover_needs_permission else R.string.cover_failed),+ android.widget.Toast.LENGTH_LONG,+ ).show()+ }+ }+ _editingPlaylist.value = null+ }+ .onFailure {+ android.util.Log.e(TAG, "edit playlist failed: ${chain(it)}", it)+ _editingPlaylist.value = _editingPlaylist.value?.copy(+ busy = false,+ error = string(R.string.save_playlist_failed),+ )+ }+ }+ }++ /**+ * The cover Spotify made of an upload, put on the library's tile.+ *+ * The picker's own address for the picture is no use for this: it is+ * readable only while the grant lasts, and a tile holding it stayed blank+ * once it lapsed — and was never looked up again, since it was not empty.+ * Spotify takes an upload and makes its sizes afterwards, so the cover is+ * asked for a few times before giving up.+ */+ private fun fetchUploadedCover(uri: String) = viewModelScope.launch {+ // A playlist that had a cover goes on answering with it until the new+ // one is ready.+ val previous = (_state.value as? UiState.Ready)?.playlists?.firstOrNull { it.uri == uri }?.artworkUrl+ repeat(COVER_POLLS) {+ delay(COVER_POLL_MS)+ val url = Catalog.playlistCover(uri)?.takeIf { it.isNotEmpty() && it != previous } ?: return@repeat+ coverCache[uri] = url+ (_state.value as? UiState.Ready)?.let { ready ->+ _state.value = ready.copy(+ playlists = ready.playlists.map { if (it.uri == uri) it.copy(artworkUrl = url) else it },+ )+ }+ if (_playlist.value.uri == uri) _playlist.value = _playlist.value.copy(artworkUrl = url)+ return@launch+ }+ }++ private val COVER_POLLS = 6+ private val COVER_POLL_MS = 1_500L++ /**+ * The picture as Spotify takes a cover: square, cut from the middle, at+ * most 640 pixels a side, and a JPEG whose base64 fits in 256 KB.+ */+ private fun coverJpeg(uri: android.net.Uri): ByteArray {+ val resolver = getApplication<android.app.Application>().contentResolver+ val source = resolver.openInputStream(uri)?.use { android.graphics.BitmapFactory.decodeStream(it) }+ ?: error("cannot read $uri")+ val side = minOf(source.width, source.height)+ val square = android.graphics.Bitmap.createBitmap(+ source, (source.width - side) / 2, (source.height - side) / 2, side, side,+ )+ val scaled = if (side > COVER_SIDE) {+ android.graphics.Bitmap.createScaledBitmap(square, COVER_SIDE, COVER_SIDE, true)+ } else {+ square+ }+ var quality = 90+ while (true) {+ val bytes = java.io.ByteArrayOutputStream().use { out ->+ scaled.compress(android.graphics.Bitmap.CompressFormat.JPEG, quality, out)+ out.toByteArray()+ }+ // Base64 is four characters for every three bytes.+ if (bytes.size * 4 / 3 <= COVER_MAX_BASE64 || quality <= 30) return bytes+ quality -= 10+ }+ }++ private val COVER_SIDE = 640+ private val COVER_MAX_BASE64 = 256 * 1024+fun renamePlaylist(uri: String, name: String) = viewModelScope.launch {val trimmed = name.trim()if (trimmed.isEmpty()) return@launchdiff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.ktindex 6c1e8f7..5a1b9c2 100644--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt@@ -1742,7 +1742,12 @@ fun SquareApp(pinned = pinnedPlaylists,canEdit = viewModel.canEditPlaylists,onCreatePlaylist = { naming = NamingRequest(null) },- onPlaylistMenu = { playlistMenu = it },+ onPlaylistMenu = {+ // Whose it is, from the library's own index;+ // unknown is still offered, as before.+ playlistMenuMine = it.mine != false+ playlistMenu = it+ },artists = followedArtists,albums = savedAlbums,onRetryOnline = viewModel::retryOnline,@@ -1858,7 +1863,18 @@ fun SquareApp(// callbacks: those are not composables.val source = page.sourceLabel()SquareTheme(seed = detailAccent) {+ val suggested by viewModel.suggestions.collectAsStateWithLifecycle()+ // Asked for once the page knows it is the+ // account's own and every song is in.+ LaunchedEffect(page.uri, page.mine, page.loadingMore) {+ val uri = page.uri+ if (uri != null && page.mine == true && !page.loadingMore) viewModel.loadSuggestions(uri)+ }PlaylistScreen(+ suggestions = suggested.tracks.takeIf { suggested.playlistUri == page.uri }.orEmpty(),+ suggestionsLoading = suggested.loading && suggested.playlistUri == page.uri,+ onAddSuggestion = viewModel::addSuggestion,+ onRefreshSuggestions = { page.uri?.let { viewModel.loadSuggestions(it, refresh = true) } },state = page,offline = offlineNow,// Read per row rather than handed over as a@@ -3152,10 +3168,10 @@ fun SquareApp(val editable = !shownPlaylist.uri.endsWith(":collection") &&playlistMenuMineif (editable) TrackSheetAction(- stringResource(R.string.rename),+ stringResource(R.string.edit_playlist),PhosphorIcons.Regular.PencilSimple,) {- naming = NamingRequest(shownPlaylist)+ viewModel.openEditPlaylist(shownPlaylist)playlistMenu = null}// The whole playlist in one link. yt-dlp and the apps@@ -3278,22 +3294,51 @@ fun SquareApp()}- naming?.let { request ->+ val editing by viewModel.editingPlaylist.collectAsStateWithLifecycle()+ editing?.let { edit ->+ dev.lelonio.square.ui.components.CreatePlaylistDialog(+ title = stringResource(R.string.edit_playlist),+ confirmLabel = stringResource(R.string.save),+ describes = viewModel.describesPlaylists,+ busy = edit.busy,+ error = edit.error,+ initial = edit.details,+ loading = edit.loading,+ onCreate = { name, description, public, cover ->+ viewModel.savePlaylist(name, description, public, cover)+ },+ onDismiss = viewModel::closeEditPlaylist,+ )+ }++ naming?.takeIf { it.playlist == null }?.let {+ val creating by viewModel.creatingPlaylist.collectAsStateWithLifecycle()+ dev.lelonio.square.ui.components.CreatePlaylistDialog(+ title = stringResource(R.string.new_playlist),+ confirmLabel = stringResource(R.string.create),+ describes = viewModel.describesPlaylists,+ busy = creating.busy,+ error = creating.error,+ onCreate = { name, description, public, cover ->+ viewModel.createPlaylist(name, description, public, cover) { created ->+ naming = null+ navController.openPlaylist(viewModel, created)+ }+ },+ onDismiss = {+ viewModel.resetCreatePlaylist()+ naming = null+ },+ )+ }++ naming?.playlist?.let { playlist ->dev.lelonio.square.ui.components.NameDialog(- title = stringResource(- if (request.playlist == null) R.string.new_playlist else R.string.rename,- ),- initial = request.playlist?.name.orEmpty(),- confirmLabel = stringResource(- if (request.playlist == null) R.string.create else R.string.save,- ),+ title = stringResource(R.string.rename),+ initial = playlist.name,+ confirmLabel = stringResource(R.string.save),onConfirm = { name ->- val playlist = request.playlist- if (playlist == null) {- viewModel.createPlaylist(name)- } else {- viewModel.renamePlaylist(playlist.uri, name)- }+ viewModel.renamePlaylist(playlist.uri, name)naming = null},onDismiss = { naming = null },diff --git a/app/src/main/java/dev/lelonio/square/ui/components/CreatePlaylistDialog.kt b/app/src/main/java/dev/lelonio/square/ui/components/CreatePlaylistDialog.ktnew file mode 100644index 0000000..96ad7ef--- /dev/null+++ b/app/src/main/java/dev/lelonio/square/ui/components/CreatePlaylistDialog.kt@@ -0,0 +1,332 @@+package dev.lelonio.square.ui.components++import android.net.Uri+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.PickVisualMediaRequest+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.animateDpAsState+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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.offset+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.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+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.saveable.rememberSaveable+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.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.compose.ui.window.Dialog+import coil.compose.AsyncImage+import com.adamglin.PhosphorIcons+import com.adamglin.phosphoricons.Regular+import com.adamglin.phosphoricons.regular.ImageSquare+import dev.lelonio.square.R+import dev.lelonio.square.ui.theme.Ink+import dev.lelonio.square.ui.theme.InkDim++/**+ * A playlist's name, and where the source keeps them, a description, whether+ * others can find it, and a cover: for a new one, and for changing one.+ *+ * The same skin as [NameDialog], which renames one, so making a playlist and+ * renaming it look like the same kind of thing. It stays up while the service+ * answers and says so when it refuses; on success the caller opens the+ * playlist, which is the next thing anyone does with a new one.+ */+@Composable+fun CreatePlaylistDialog(+ title: String,+ confirmLabel: String,+ /** Description, visibility and cover; see MusicBackend.describesPlaylists. */+ describes: Boolean,+ busy: Boolean,+ error: String?,+ onCreate: (name: String, description: String, public: Boolean, cover: Uri?) -> Unit,+ onDismiss: () -> Unit,+ /** What an existing playlist has now; null for a new one. */+ initial: dev.lelonio.square.backend.PlaylistDetails? = null,+ /** Waiting for [initial]: the fields are not shown half-filled. */+ loading: Boolean = false,+) {+ var name by rememberSaveable(initial) { mutableStateOf(initial?.name.orEmpty()) }+ var description by rememberSaveable(initial) { mutableStateOf(initial?.description.orEmpty()) }+ var public by rememberSaveable(initial) { mutableStateOf(initial?.public ?: false) }+ var cover by rememberSaveable { mutableStateOf<Uri?>(null) }+ val focus = remember { FocusRequester() }+ // The system's photo picker: no permission to ask for, and only the one+ // picture it hands back is ever readable.+ val pick = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { picked ->+ if (picked != null) cover = picked+ }+ val shape = RoundedCornerShape(24.dp)+ val create = { if (name.isNotBlank() && !busy) onCreate(name, description, public, cover) }++ Dialog(onDismissRequest = { if (!busy) onDismiss() }) {+ Column(+ Modifier+ .fillMaxWidth()+ .menuSkin(shape)+ .padding(22.dp),+ ) {+ Text(title, style = MaterialTheme.typography.titleMedium, color = Ink)++ if (loading) {+ Box(Modifier.fillMaxWidth().padding(vertical = 36.dp), contentAlignment = Alignment.Center) {+ CircularProgressIndicator(strokeWidth = 2.dp, color = Ink, modifier = Modifier.size(22.dp))+ }+ return@Column+ }++ Row(+ Modifier.padding(top = 18.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (describes) {+ Box(+ Modifier+ .size(COVER)+ .clip(RoundedCornerShape(14.dp))+ .background(FieldFill)+ .clickable(enabled = !busy) {+ pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ },+ contentAlignment = Alignment.Center,+ ) {+ val shown: Any? = cover ?: initial?.artworkUrl+ if (shown != null) {+ AsyncImage(+ model = shown,+ contentDescription = stringResource(R.string.change_cover),+ contentScale = ContentScale.Crop,+ modifier = Modifier.fillMaxSize(),+ )+ } else {+ Icon(+ PhosphorIcons.Regular.ImageSquare,+ contentDescription = stringResource(R.string.choose_cover),+ tint = InkDim,+ modifier = Modifier.size(28.dp),+ )+ }+ }+ }+ Column(+ Modifier+ .weight(1f)+ .padding(start = if (describes) 14.dp else 0.dp),+ ) {+ Field(+ value = name,+ onValueChange = { name = it },+ hint = stringResource(R.string.playlist_name),+ singleLine = true,+ imeAction = if (describes) ImeAction.Next else ImeAction.Done,+ onDone = create,+ modifier = Modifier.focusRequester(focus),+ )+ if (describes) {+ Text(+ stringResource(+ if (cover == null && initial?.artworkUrl == null) R.string.choose_cover else R.string.change_cover,+ ),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ modifier = Modifier+ .padding(top = 8.dp)+ .clip(RoundedCornerShape(50))+ .clickable(enabled = !busy) {+ pick.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ }+ .padding(horizontal = 4.dp, vertical = 2.dp),+ )+ }+ }+ }++ if (describes) {+ Field(+ value = description,+ onValueChange = { description = it },+ hint = stringResource(R.string.playlist_description),+ singleLine = false,+ imeAction = ImeAction.Default,+ onDone = {},+ modifier = Modifier+ .padding(top = 12.dp)+ .heightIn(min = 72.dp),+ )++ Row(+ Modifier+ .padding(top = 14.dp)+ .fillMaxWidth()+ .clip(RoundedCornerShape(14.dp))+ .clickable(enabled = !busy) { public = !public }+ .padding(vertical = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(stringResource(R.string.public_playlist), style = MaterialTheme.typography.bodyLarge, color = Ink)+ Text(+ stringResource(if (public) R.string.public_playlist_on else R.string.public_playlist_off),+ style = MaterialTheme.typography.bodySmall,+ color = InkDim,+ )+ }+ Switch(on = public)+ }+ }++ if (error != null) {+ Text(+ error,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ modifier = Modifier.padding(top = 12.dp),+ )+ }++ Row(+ Modifier+ .padding(top = 18.dp)+ .fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Action(stringResource(R.string.cancel), if (busy) InkDim.copy(alpha = 0.5f) else InkDim) {+ if (!busy) onDismiss()+ }+ if (busy) {+ CircularProgressIndicator(+ strokeWidth = 2.dp,+ color = Ink,+ modifier = Modifier+ .padding(horizontal = 26.dp)+ .size(18.dp),+ )+ } else {+ // Nothing to create while the name is empty: neither+ // service takes a playlist called nothing.+ Action(confirmLabel, if (name.isBlank()) InkDim else Ink, create)+ }+ }+ }+ }++ // The keyboard up at once for a new playlist: the name is what that sheet+ // is for. Not for an existing one, where the cover or the description is+ // as likely the reason it was opened.+ LaunchedEffect(loading) { if (!loading && initial == null) runCatching { focus.requestFocus() } }+}++@Composable+private fun Field(+ value: String,+ onValueChange: (String) -> Unit,+ hint: String,+ singleLine: Boolean,+ imeAction: ImeAction,+ onDone: () -> Unit,+ modifier: Modifier = Modifier,+) {+ Box(+ modifier+ .fillMaxWidth()+ .clip(RoundedCornerShape(14.dp))+ .background(FieldFill)+ .padding(horizontal = 14.dp, vertical = 12.dp),+ ) {+ if (value.isEmpty()) {+ Text(hint, style = MaterialTheme.typography.bodyLarge, color = InkDim)+ }+ BasicTextField(+ value = value,+ onValueChange = onValueChange,+ singleLine = singleLine,+ maxLines = if (singleLine) 1 else 4,+ textStyle = MaterialTheme.typography.bodyLarge.copy(color = Ink),+ cursorBrush = SolidColor(Ink),+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.Sentences,+ imeAction = imeAction,+ ),+ keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onDone() }),+ modifier = Modifier.fillMaxWidth(),+ )+ }+}++/** A plain switch in the dialog's ink: lit when on, a hairline track when off. */+@Composable+private fun Switch(on: Boolean) {+ val track by animateColorAsState(if (on) Ink else FieldFill, label = "switch track")+ val knobColor by animateColorAsState(if (on) Ink.copy(alpha = 0f) else InkDim, label = "switch knob")+ val offset by animateDpAsState(if (on) TRACK_W - KNOB - 4.dp else 4.dp, label = "switch offset")+ Box(+ Modifier+ .width(TRACK_W)+ .height(KNOB + 8.dp)+ .clip(CircleShape)+ .background(track),+ contentAlignment = Alignment.CenterStart,+ ) {+ Box(+ Modifier+ .offset(x = offset)+ .size(KNOB)+ .clip(CircleShape)+ .background(if (on) MaterialTheme.colorScheme.surface else knobColor),+ )+ }+}++@Composable+private fun Action(label: String, color: Color, onClick: () -> Unit) {+ Text(+ label,+ style = MaterialTheme.typography.bodyLarge,+ color = color,+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .clickable(onClick = onClick)+ .padding(horizontal = 16.dp, vertical = 8.dp),+ )+}++private val COVER: Dp = 84.dp+private val TRACK_W: Dp = 46.dp+private val KNOB: Dp = 20.dp+private val FieldFill = Color.White.copy(alpha = 0.08f)diff --git a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.ktindex bc7f77b..a5d6ba1 100644--- a/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/library/PlaylistScreen.kt@@ -14,6 +14,7 @@ import dev.lelonio.square.ui.player.GlassFilmimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.aspectRatioimport androidx.compose.foundation.border+import androidx.compose.foundation.clickableimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Column@@ -243,6 +244,11 @@ fun PlaylistScreen(onMenu: () -> Unit = {},/** Keeps the page in the library, or lets it go. */onToggleSaved: () -> Unit = {},+ /** Songs offered for one of the account's own playlists; see MainViewModel.loadSuggestions. */+ suggestions: List<CatalogTrack> = emptyList(),+ suggestionsLoading: Boolean = false,+ onAddSuggestion: (CatalogTrack) -> Unit = {},+ onRefreshSuggestions: () -> Unit = {},/** The remembered track order, and where a change to it is stored. */storedSort: String? = null,onSortChange: (String) -> Unit = {},@@ -966,6 +972,101 @@ fun PlaylistScreen(}}+ // What could go in next, under a playlist of the account's own, as+ // Spotify offers it: after the songs, once they are all in.+ if (state.mine == true && query.isBlank() && !state.loadingMore &&+ (suggestions.isNotEmpty() || suggestionsLoading)+ ) {+ item(contentType = "suggestionsHeader") {+ Row(+ Modifier+ .fillMaxWidth()+ .padding(start = 24.dp, end = 12.dp, top = 28.dp, bottom = 4.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Column(Modifier.weight(1f)) {+ Text(+ stringResource(R.string.suggested_songs),+ style = MaterialTheme.typography.titleLarge,+ fontWeight = FontWeight.Bold,+ color = MaterialTheme.colorScheme.onSurface,+ )+ Text(+ stringResource(R.string.suggested_songs_note),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (suggestionsLoading) {+ CircularProgressIndicator(+ strokeWidth = 2.dp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier+ .padding(end = 12.dp)+ .size(18.dp),+ )+ } else {+ Text(+ stringResource(R.string.refresh_suggestions),+ style = MaterialTheme.typography.bodyMedium,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.onSurface,+ modifier = Modifier+ .clip(RoundedCornerShape(50))+ .clickable(onClick = onRefreshSuggestions)+ .padding(horizontal = 12.dp, vertical = 8.dp),+ )+ }+ }+ }+ items(suggestions, key = { "suggested:" + it.uri }, contentType = { "suggestion" }) { track ->+ Row(+ Modifier+ .fillMaxWidth()+ .clickable { onAddSuggestion(track) }+ .padding(start = 24.dp, end = 12.dp, top = 6.dp, bottom = 6.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Artwork(+ url = track.artworkUrl,+ title = track.name,+ modifier = Modifier.size(46.dp),+ corner = 8.dp,+ decodeSize = 46.dp,+ )+ Column(+ Modifier+ .weight(1f)+ .padding(start = 14.dp),+ ) {+ Text(+ track.name,+ style = MaterialTheme.typography.titleMedium,+ fontWeight = FontWeight.SemiBold,+ color = MaterialTheme.colorScheme.onSurface,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ track.artist,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ )+ }+ IconButton(onClick = { onAddSuggestion(track) }) {+ Icon(+ PhosphorIcons.Bold.Plus,+ contentDescription = stringResource(R.string.add_to_this_playlist),+ tint = MaterialTheme.colorScheme.onSurface,+ modifier = Modifier.size(20.dp),+ )+ }+ }+ }+ }+// Lists like this one, once every song is in: under a list still// filling in, the row would land between its songs.if (!isArtist && state.relatedPlaylists.isNotEmpty() && query.isBlank() &&diff --git a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.ktindex f8f69a9..26091ab 100644--- a/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt+++ b/app/src/main/java/dev/lelonio/square/ui/settings/SettingsScreen.kt@@ -1929,6 +1929,7 @@ private val SCOPES = listOf("playlist-modify-private" to R.string.scope_private_playlists,"playlist-modify-public" to R.string.scope_public_playlists,"user-library-modify" to R.string.scope_library,+ "ugc-image-upload" to R.string.scope_cover,)private val LICENCES = listOf(diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex 00b49b4..5e9603a 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -481,4 +481,20 @@<string name="added_to_queue">Zur Warteschlange hinzugefügt: %s</string><string name="videos">Videos</string><string name="web_playback_on">Spotify verweigert diesem Konto die Schlüssel für die Songs: Sie werden wie im Webplayer abgespielt. Spotify Connect und Downloads sind so nicht verfügbar.</string>+ <string name="playlist_description">Beschreibung (optional)</string>+ <string name="choose_cover">Cover wählen</string>+ <string name="change_cover">Cover ändern</string>+ <string name="public_playlist">Öffentlich</string>+ <string name="public_playlist_on">Jeder kann sie in deinem Profil finden</string>+ <string name="public_playlist_off">Nur du kannst sie sehen</string>+ <string name="create_playlist_failed">Die Playlist konnte nicht erstellt werden. Prüfe deine Verbindung und versuche es erneut.</string>+ <string name="cover_failed">Die Playlist wurde erstellt, aber ihr Cover konnte nicht gespeichert werden.</string>+ <string name="cover_needs_permission">Die Playlist wurde ohne Cover erstellt: Verbinde deine Spotify-App in den Einstellungen erneut, um Cover zu erlauben.</string>+ <string name="scope_cover">Playlist-Cover festlegen</string>+ <string name="edit_playlist">Bearbeiten</string>+ <string name="save_playlist_failed">Die Änderungen konnten nicht gespeichert werden. Prüfe deine Verbindung und versuche es erneut.</string>+ <string name="suggested_songs">Empfohlene Songs</string>+ <string name="suggested_songs_note">Basierend auf dem, was in dieser Playlist ist</string>+ <string name="refresh_suggestions">Aktualisieren</string>+ <string name="add_to_this_playlist">Zu dieser Playlist hinzufügen</string></resources>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex 40c8bab..4b661cf 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -487,4 +487,20 @@<string name="added_to_queue">Añadido a la cola: %s</string><string name="videos">Vídeos</string><string name="web_playback_on">Spotify niega a esta cuenta las claves de las canciones: se reproducen como en el reproductor web. Spotify Connect y las descargas no están disponibles así.</string>+ <string name="playlist_description">Descripción (opcional)</string>+ <string name="choose_cover">Elegir portada</string>+ <string name="change_cover">Cambiar portada</string>+ <string name="public_playlist">Pública</string>+ <string name="public_playlist_on">Cualquiera puede encontrarla en tu perfil</string>+ <string name="public_playlist_off">Solo tú puedes verla</string>+ <string name="create_playlist_failed">No se pudo crear la playlist. Comprueba la conexión e inténtalo de nuevo.</string>+ <string name="cover_failed">La playlist se creó, pero no se pudo guardar su portada.</string>+ <string name="cover_needs_permission">La playlist se creó sin portada: vuelve a conectar tu app de Spotify en Ajustes para permitir portadas.</string>+ <string name="scope_cover">Poner portadas a las playlists</string>+ <string name="edit_playlist">Editar</string>+ <string name="save_playlist_failed">No se pudieron guardar los cambios. Comprueba la conexión e inténtalo de nuevo.</string>+ <string name="suggested_songs">Canciones recomendadas</string>+ <string name="suggested_songs_note">Según lo que hay en esta playlist</string>+ <string name="refresh_suggestions">Actualizar</string>+ <string name="add_to_this_playlist">Añadir a esta playlist</string></resources>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 4e99014..45a183b 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -481,4 +481,20 @@<string name="added_to_queue">Ajouté à la file d\'attente : %s</string><string name="videos">Vidéos</string><string name="web_playback_on">Spotify refuse à ce compte les clés des titres : ils sont lus comme dans le lecteur web. Spotify Connect et les téléchargements ne sont pas disponibles ainsi.</string>+ <string name="playlist_description">Description (facultative)</string>+ <string name="choose_cover">Choisir une pochette</string>+ <string name="change_cover">Changer la pochette</string>+ <string name="public_playlist">Publique</string>+ <string name="public_playlist_on">Tout le monde peut la trouver sur ton profil</string>+ <string name="public_playlist_off">Toi seul peux la voir</string>+ <string name="create_playlist_failed">La playlist n\'a pas pu être créée. Vérifie ta connexion et réessaie.</string>+ <string name="cover_failed">La playlist a été créée, mais sa pochette n\'a pas pu être enregistrée.</string>+ <string name="cover_needs_permission">La playlist a été créée sans pochette : reconnecte ton app Spotify dans les Réglages pour autoriser les pochettes.</string>+ <string name="scope_cover">Définir les pochettes des playlists</string>+ <string name="edit_playlist">Modifier</string>+ <string name="save_playlist_failed">Les modifications n\'ont pas pu être enregistrées. Vérifie ta connexion et réessaie.</string>+ <string name="suggested_songs">Titres recommandés</string>+ <string name="suggested_songs_note">D\'après ce que contient cette playlist</string>+ <string name="refresh_suggestions">Actualiser</string>+ <string name="add_to_this_playlist">Ajouter à cette playlist</string></resources>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex 3d0ec55..2b702b2 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -496,4 +496,20 @@<string name="added_to_queue">कतार में जोड़ा गया: %s</string><string name="videos">वीडियो</string><string name="web_playback_on">Spotify इस खाते को गानों की कुंजियाँ नहीं दे रहा: उन्हें वेब प्लेयर की तरह चलाया जा रहा है। इस तरह Spotify Connect और डाउनलोड उपलब्ध नहीं हैं।</string>+ <string name="playlist_description">विवरण (वैकल्पिक)</string>+ <string name="choose_cover">कवर चुनें</string>+ <string name="change_cover">कवर बदलें</string>+ <string name="public_playlist">सार्वजनिक</string>+ <string name="public_playlist_on">कोई भी इसे आपकी प्रोफ़ाइल पर देख सकता है</string>+ <string name="public_playlist_off">केवल आप इसे देख सकते हैं</string>+ <string name="create_playlist_failed">प्लेलिस्ट नहीं बन सकी। कनेक्शन जाँचें और फिर से कोशिश करें।</string>+ <string name="cover_failed">प्लेलिस्ट बन गई, लेकिन उसका कवर सहेजा नहीं जा सका।</string>+ <string name="cover_needs_permission">प्लेलिस्ट बिना कवर के बनी: कवर की अनुमति देने के लिए सेटिंग्स में अपना Spotify ऐप फिर से जोड़ें।</string>+ <string name="scope_cover">प्लेलिस्ट कवर सेट करना</string>+ <string name="edit_playlist">संपादित करें</string>+ <string name="save_playlist_failed">बदलाव सहेजे नहीं जा सके। कनेक्शन जाँचें और फिर से कोशिश करें।</string>+ <string name="suggested_songs">सुझाए गए गाने</string>+ <string name="suggested_songs_note">इस प्लेलिस्ट में मौजूद गानों के आधार पर</string>+ <string name="refresh_suggestions">रीफ़्रेश करें</string>+ <string name="add_to_this_playlist">इस प्लेलिस्ट में जोड़ें</string></resources>diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex c6f3c21..290cd28 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -516,4 +516,20 @@<string name="web_sdk_limits">Con questo player non sono disponibili dissolvenza incrociata, effetti audio, karaoke, scelta della qualità e download.</string><string name="web_sdk_settings_open">Configura player web</string><string name="web_sdk_authorized">Account Spotify autorizzato</string>+ <string name="playlist_description">Descrizione (facoltativa)</string>+ <string name="choose_cover">Scegli una copertina</string>+ <string name="change_cover">Cambia copertina</string>+ <string name="public_playlist">Pubblica</string>+ <string name="public_playlist_on">Chiunque può trovarla sul tuo profilo</string>+ <string name="public_playlist_off">Puoi vederla solo tu</string>+ <string name="create_playlist_failed">Non è stato possibile creare la playlist. Controlla la connessione e riprova.</string>+ <string name="cover_failed">La playlist è stata creata, ma non è stato possibile salvare la copertina.</string>+ <string name="cover_needs_permission">La playlist è stata creata senza copertina: collega di nuovo la tua app Spotify nelle Impostazioni per consentire le copertine.</string>+ <string name="scope_cover">Impostare le copertine delle playlist</string>+ <string name="edit_playlist">Modifica</string>+ <string name="save_playlist_failed">Non è stato possibile salvare le modifiche. Controlla la connessione e riprova.</string>+ <string name="suggested_songs">Brani consigliati</string>+ <string name="suggested_songs_note">In base a quello che c\'è in questa playlist</string>+ <string name="refresh_suggestions">Aggiorna</string>+ <string name="add_to_this_playlist">Aggiungi a questa playlist</string></resources>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex d9c4f3d..e6e0c82 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -481,4 +481,20 @@<string name="added_to_queue">Adicionado à fila: %s</string><string name="videos">Vídeos</string><string name="web_playback_on">O Spotify recusa a esta conta as chaves das músicas: elas tocam como no reprodutor web. Spotify Connect e downloads não estão disponíveis assim.</string>+ <string name="playlist_description">Descrição (opcional)</string>+ <string name="choose_cover">Escolher capa</string>+ <string name="change_cover">Mudar capa</string>+ <string name="public_playlist">Pública</string>+ <string name="public_playlist_on">Qualquer pessoa pode encontrá-la no seu perfil</string>+ <string name="public_playlist_off">Só você pode vê-la</string>+ <string name="create_playlist_failed">Não foi possível criar a playlist. Verifique a conexão e tente novamente.</string>+ <string name="cover_failed">A playlist foi criada, mas não foi possível salvar a capa.</string>+ <string name="cover_needs_permission">A playlist foi criada sem capa: conecte seu app do Spotify novamente nas Configurações para permitir capas.</string>+ <string name="scope_cover">Definir capas de playlists</string>+ <string name="edit_playlist">Editar</string>+ <string name="save_playlist_failed">Não foi possível salvar as alterações. Verifique a conexão e tente novamente.</string>+ <string name="suggested_songs">Músicas recomendadas</string>+ <string name="suggested_songs_note">Com base no que há nesta playlist</string>+ <string name="refresh_suggestions">Atualizar</string>+ <string name="add_to_this_playlist">Adicionar a esta playlist</string></resources>diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xmlindex 8424baf..5c5e999 100644--- a/app/src/main/res/values-ru/strings.xml+++ b/app/src/main/res/values-ru/strings.xml@@ -508,4 +508,20 @@<string name="added_to_queue">Добавлено в очередь: %s</string><string name="videos">Видео</string><string name="web_playback_on">Spotify не выдаёт этому аккаунту ключи для треков: они воспроизводятся как в веб-плеере. Spotify Connect и загрузки так недоступны.</string>+ <string name="playlist_description">Описание (необязательно)</string>+ <string name="choose_cover">Выбрать обложку</string>+ <string name="change_cover">Сменить обложку</string>+ <string name="public_playlist">Публичный</string>+ <string name="public_playlist_on">Любой может найти его в вашем профиле</string>+ <string name="public_playlist_off">Видите только вы</string>+ <string name="create_playlist_failed">Не удалось создать плейлист. Проверьте подключение и попробуйте ещё раз.</string>+ <string name="cover_failed">Плейлист создан, но обложку сохранить не удалось.</string>+ <string name="cover_needs_permission">Плейлист создан без обложки: снова подключите своё приложение Spotify в настройках, чтобы разрешить обложки.</string>+ <string name="scope_cover">Устанавливать обложки плейлистов</string>+ <string name="edit_playlist">Изменить</string>+ <string name="save_playlist_failed">Не удалось сохранить изменения. Проверьте подключение и попробуйте ещё раз.</string>+ <string name="suggested_songs">Рекомендуемые треки</string>+ <string name="suggested_songs_note">На основе того, что есть в этом плейлисте</string>+ <string name="refresh_suggestions">Обновить</string>+ <string name="add_to_this_playlist">Добавить в этот плейлист</string></resources>diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xmlindex 9684b59..0765299 100644--- a/app/src/main/res/values-tr/strings.xml+++ b/app/src/main/res/values-tr/strings.xml@@ -494,4 +494,20 @@<string name="added_to_queue">Sıraya eklendi: %s</string><string name="videos">Videolar</string><string name="web_playback_on">Spotify bu hesaba şarkı anahtarlarını vermiyor: şarkılar web oynatıcıdaki gibi çalınıyor. Bu şekilde Spotify Connect ve indirmeler kullanılamaz.</string>+ <string name="playlist_description">Açıklama (isteğe bağlı)</string>+ <string name="choose_cover">Kapak seç</string>+ <string name="change_cover">Kapağı değiştir</string>+ <string name="public_playlist">Herkese açık</string>+ <string name="public_playlist_on">Herkes profilinde bulabilir</string>+ <string name="public_playlist_off">Yalnızca sen görebilirsin</string>+ <string name="create_playlist_failed">Çalma listesi oluşturulamadı. Bağlantını kontrol edip tekrar dene.</string>+ <string name="cover_failed">Çalma listesi oluşturuldu ama kapağı kaydedilemedi.</string>+ <string name="cover_needs_permission">Çalma listesi kapaksız oluşturuldu: kapaklara izin vermek için Ayarlar’da Spotify uygulamanı yeniden bağla.</string>+ <string name="scope_cover">Çalma listesi kapaklarını ayarlama</string>+ <string name="edit_playlist">Düzenle</string>+ <string name="save_playlist_failed">Değişiklikler kaydedilemedi. Bağlantını kontrol edip tekrar dene.</string>+ <string name="suggested_songs">Önerilen şarkılar</string>+ <string name="suggested_songs_note">Bu çalma listesindekilere göre</string>+ <string name="refresh_suggestions">Yenile</string>+ <string name="add_to_this_playlist">Bu çalma listesine ekle</string></resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex f781fcd..2a8a785 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -543,4 +543,20 @@<string name="web_sdk_limits">With this player, crossfade, audio effects, karaoke, sound quality and downloads are not available.</string><string name="web_sdk_settings_open">Configure web player</string><string name="web_sdk_authorized">Spotify account authorized</string>+ <string name="playlist_description">Description (optional)</string>+ <string name="choose_cover">Choose a cover</string>+ <string name="change_cover">Change cover</string>+ <string name="public_playlist">Public</string>+ <string name="public_playlist_on">Anyone can find it on your profile</string>+ <string name="public_playlist_off">Only you can see it</string>+ <string name="create_playlist_failed">The playlist could not be created. Check your connection and try again.</string>+ <string name="cover_failed">The playlist was created, but its cover could not be saved.</string>+ <string name="cover_needs_permission">The playlist was created without its cover: connect your Spotify app again in Settings to allow covers.</string>+ <string name="scope_cover">Set playlist covers</string>+ <string name="edit_playlist">Edit</string>+ <string name="save_playlist_failed">The changes could not be saved. Check your connection and try again.</string>+ <string name="suggested_songs">Recommended songs</string>+ <string name="suggested_songs_note">Based on what is in this playlist</string>+ <string name="refresh_suggestions">Refresh</string>+ <string name="add_to_this_playlist">Add to this playlist</string></resources>diff --git a/native/src/catalog.rs b/native/src/catalog.rsindex 865fc21..3380d79 100644--- a/native/src/catalog.rs+++ b/native/src/catalog.rs@@ -49,6 +49,7 @@ pub fn rootlist() -> EngineResult<String> {let list = SelectedListContent::parse_from_bytes(&bytes).map_err(|e| format!("rootlist was not a SelectedListContent: {e}"))?;+ let me = session.username();let contents = list.contents;let playlists: Vec<Value> = contents.items@@ -62,7 +63,14 @@ pub fn rootlist() -> EngineResult<String> {.filter(|name| !name.is_empty()).unwrap_or("Senza nome");let artwork = meta.and_then(|meta| image_url(meta.attributes.picture()));- json!({ "uri": item.uri(), "name": name, "artworkUrl": artwork })+ // Whose it is, from the index itself: the Web API answers 404+ // for Spotify's own lists to an application in development+ // mode, which left saved editorial playlists looking editable.+ let mine = meta+ .map(|meta| meta.owner_username())+ .filter(|owner| !owner.is_empty())+ .map(|owner| owner == me);+ json!({ "uri": item.uri(), "name": name, "artworkUrl": artwork, "mine": mine })}).collect();@@ -919,3 +927,29 @@ pub fn remove_from_playlist(playlist_uri: &str, item_uri: &str) -> EngineResult<Ok(())})}++/// Whether a playlist is the account's own, from the playlist service, or+/// `null` when it does not say. For the lists the Web API will not describe.+pub fn playlist_mine(uri: &str) -> EngineResult<String> {+ let parsed = SpotifyUri::from_uri(uri).map_err(|e| format!("bad uri: {e}"))?;+ let SpotifyUri::Playlist { id, .. } = parsed else {+ return Ok("null".into());+ };++ let session = with_session(|s| s.clone())?;+ block_on(async move {+ let bytes = session+ .spclient()+ .get_playlist(&id)+ .await+ .map_err(|e| format!("playlist read failed: {e}"))?;+ let list = SelectedListContent::parse_from_bytes(&bytes)+ .map_err(|e| format!("playlist was not a SelectedListContent: {e}"))?;+ let owner = list.owner_username();+ Ok(if owner.is_empty() {+ "null".into()+ } else {+ json!(owner == session.username()).to_string()+ })+ })+}diff --git a/native/src/ffi.rs b/native/src/ffi.rsindex ea23745..4250aca 100644--- a/native/src/ffi.rs+++ b/native/src/ffi.rs@@ -443,6 +443,22 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeRemguard(&mut env, "RemoveFromPlaylist", || catalog::remove_from_playlist(&playlist, &item));}+#[no_mangle]+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaylistMine(+ mut env: JNIEnv,+ _class: JClass,+ uri: JString,+) -> jstring {+ let uri = match read_string(&mut env, &uri) {+ Ok(value) => value,+ Err(message) => {+ let _ = env.throw_new(EXCEPTION, message);+ return JObject::null().into_raw() as jstring;+ }+ };+ guard_string(&mut env, "PlaylistMine", || catalog::playlist_mine(&uri))+}+#[no_mangle]pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaylistCover(mut env: JNIEnv,