Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Open what people send you, and see what they play

Lelonioa7839fb815cd
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 1703a5b..13f6180 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -17,6 +17,17 @@
-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
+ <!--
+ Reading the audio already on the phone. Square hands downloading to
+ another app, so what comes back is an ordinary file in the media store
+ rather than anything this app placed. Audio only: the newer permission
+ exists so a music player does not have to ask to see photographs.
+ -->
+ <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
+ <uses-permission
+ android:name="android.permission.READ_EXTERNAL_STORAGE"
+ android:maxSdkVersion="32" />
+
<!--
Package visibility, required from Android 11 to see any of this. Without
it a downloader is invisible to resolve and to setPackage alike, so the
@@ -51,6 +62,38 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
+
+ <!--
+ Spotify's own scheme. Nothing verifies these, so a phone with both
+ apps installed simply asks which one, and a phone with only Square
+ opens Square.
+ -->
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="spotify" />
+ </intent-filter>
+
+ <!--
+ The links people actually send each other.
+
+ `autoVerify` asks Android to check for a statement file on the
+ host, and open.spotify.com will never carry one naming this app, so
+ the check fails and the link is not handled automatically. That is
+ the platform working as designed: since Android 12 a web link
+ belongs to whoever the domain vouches for, and everyone else has to
+ be chosen by hand, once, under "Open by default" — which the
+ settings screen links to.
+ -->
+ <intent-filter android:autoVerify="true">
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="https" android:host="open.spotify.com" />
+ <data android:scheme="http" android:host="open.spotify.com" />
+ <data android:scheme="https" android:host="link.tospotify.com" />
+ </intent-filter>
</activity>
<service
diff --git a/app/src/main/java/dev/lelonio/square/data/Catalog.kt b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
index afb3809..847677f 100644
--- a/app/src/main/java/dev/lelonio/square/data/Catalog.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Catalog.kt
@@ -196,6 +196,13 @@ object Catalog {
runCatching { json.decodeFromString<String?>(NativeBridge.playlistCover(uri)) }.getOrNull()
}
+ /** The title of a playlist the account does not follow; see the native side. */
+ suspend fun playlistName(uri: String): String? = withContext(Dispatchers.IO) {
+ runCatching { json.decodeFromString<String?>(NativeBridge.playlistName(uri)) }
+ .onFailure { android.util.Log.w("SquareCatalog", "no name for $uri: $it") }
+ .getOrNull()
+ }
+
/**
* Tracks of the account's first playlist.
*
diff --git a/app/src/main/java/dev/lelonio/square/data/FriendActivity.kt b/app/src/main/java/dev/lelonio/square/data/FriendActivity.kt
new file mode 100644
index 0000000..9d97543
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/FriendActivity.kt
@@ -0,0 +1,99 @@
+package dev.lelonio.square.data
+
+import dev.lelonio.square.nativecore.NativeBridge
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+
+/**
+ * What one person the account follows was last heard playing.
+ *
+ * Flat, like everything else that reaches the UI: the endpoint's own shape is
+ * four levels of nesting and none of it belongs above this file.
+ */
+data class FriendListen(
+ val userUri: String,
+ val userName: String,
+ val avatarUrl: String?,
+ val trackUri: String,
+ val trackName: String,
+ val artist: String,
+ val artworkUrl: String?,
+ /** The playlist, album or artist page they were playing it from. */
+ val contextName: String,
+ /** When they were last heard from, in milliseconds since the epoch. */
+ val at: Long,
+)
+
+/**
+ * Spotify's "Friend Activity", read through the access point.
+ *
+ * The same list the desktop client shows down its right-hand side, and one of
+ * the few things in this app that has no Web API equivalent at all: there is no
+ * public endpoint for it, and the private one behind the desktop client answers
+ * the session this app already holds.
+ */
+object FriendActivity {
+
+ private val json = Json { ignoreUnknownKeys = true }
+
+ /**
+ * The list, most recently heard first.
+ *
+ * Empty is an ordinary answer: an account can follow nobody, and everybody
+ * it follows can have their listening set to private.
+ */
+ suspend fun friends(): List<FriendListen> = withContext(Dispatchers.IO) {
+ val raw = NativeBridge.friendActivity()
+ json.decodeFromString<BuddyList>(raw).friends
+ .mapNotNull { friend ->
+ val user = friend.user ?: return@mapNotNull null
+ val track = friend.track ?: return@mapNotNull null
+ FriendListen(
+ userUri = user.uri.orEmpty(),
+ userName = user.name.orEmpty(),
+ avatarUrl = user.imageUrl?.takeIf { it.isNotEmpty() },
+ trackUri = track.uri.orEmpty(),
+ trackName = track.name.orEmpty(),
+ artist = track.artist?.name.orEmpty(),
+ artworkUrl = track.imageUrl?.takeIf { it.isNotEmpty() },
+ contextName = track.context?.name.orEmpty(),
+ at = friend.timestamp,
+ )
+ }
+ .filter { it.trackUri.startsWith("spotify:track:") }
+ .sortedByDescending { it.at }
+ }
+
+ @Serializable
+ private data class BuddyList(val friends: List<Friend> = emptyList())
+
+ @Serializable
+ private data class Friend(
+ val timestamp: Long = 0,
+ val user: User? = null,
+ val track: PlayedTrack? = null,
+ )
+
+ @Serializable
+ private data class User(
+ val uri: String? = null,
+ val name: String? = null,
+ @SerialName("imageUrl") val imageUrl: String? = null,
+ )
+
+ @Serializable
+ private data class PlayedTrack(
+ val uri: String? = null,
+ val name: String? = null,
+ @SerialName("imageUrl") val imageUrl: String? = null,
+ val artist: Named? = null,
+ val album: Named? = null,
+ val context: Named? = null,
+ )
+
+ @Serializable
+ private data class Named(val uri: String? = null, val name: String? = null)
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
index a251334..2eb0d3e 100644
--- a/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyApi.kt
@@ -248,6 +248,45 @@ interface SpotifyApi {
@DELETE("v1/playlists/{id}/followers")
suspend fun unfollowPlaylist(@Path("id") playlistId: String)
+ /**
+ * Following an artist, exactly as the green button does.
+ *
+ * Needs `user-follow-modify`, and its sibling below needs
+ * `user-follow-read`. An account connected before those existed keeps
+ * working everywhere else and is told to reconnect only here, where the
+ * permission is actually missing.
+ */
+ @PUT("v1/me/following")
+ suspend fun followArtists(
+ @Query("type") type: String = "artist",
+ @Query("ids") ids: String,
+ )
+
+ @DELETE("v1/me/following")
+ suspend fun unfollowArtists(
+ @Query("type") type: String = "artist",
+ @Query("ids") ids: String,
+ )
+
+ @GET("v1/me/following/contains")
+ suspend fun isFollowing(
+ @Query("type") type: String = "artist",
+ @Query("ids") ids: String,
+ ): List<Boolean>
+
+ /**
+ * The artists the account follows.
+ *
+ * Cursor-paged rather than offset-paged, alone among the endpoints this app
+ * reads: the answer carries the id to continue after.
+ */
+ @GET("v1/me/following")
+ suspend fun followedArtists(
+ @Query("type") type: String = "artist",
+ @Query("limit") limit: Int = 50,
+ @Query("after") after: String? = null,
+ ): FollowedArtistsDto
+
@GET("v1/search")
suspend fun search(
@Query("q") query: String,
@@ -329,14 +368,41 @@ data class ArtistDto(
val uri: String? = null,
val name: String,
val images: List<ImageDto> = emptyList(),
+ /** How many accounts follow them; the number under the name. */
+ val followers: FollowersDto? = null,
+ /** Spotify's own labels for them, lowercase and often several. */
+ val genres: List<String> = emptyList(),
+)
+
+@Serializable
+data class FollowersDto(val total: Int = 0)
+
+/** The cursor-paged shape `me/following` answers with, and nothing else does. */
+@Serializable
+data class FollowedArtistsDto(val artists: ArtistCursorPageDto = ArtistCursorPageDto())
+
+@Serializable
+data class ArtistCursorPageDto(
+ val items: List<ArtistDto> = emptyList(),
+ val total: Int = 0,
+ val cursors: CursorsDto? = null,
)
+@Serializable
+data class CursorsDto(val after: String? = null)
+
@Serializable
data class AlbumDto(
val id: String? = null,
val uri: String? = null,
val name: String,
val images: List<ImageDto> = emptyList(),
+ /**
+ * Which shelf it belongs on for the artist it was asked about: `album`,
+ * `single`, `compilation` or `appears_on`. Only `artists/{id}/albums`
+ * fills it, which is the one place it is needed.
+ */
+ @SerialName("album_group") val albumGroup: String? = null,
/** ISO date, and not always a full one — Spotify returns bare years too. */
@SerialName("release_date") val releaseDate: String? = null,
@SerialName("total_tracks") val totalTracks: Int = 0,
@@ -394,6 +460,17 @@ data class PlaylistDto(
val description: String? = null,
val images: List<ImageDto> = emptyList(),
val tracks: PlaylistTracksRefDto? = null,
+ /**
+ * Who made it. The one field that tells "This Is Fabri Fibra", which
+ * Spotify itself built, from a playlist a stranger named the same thing.
+ */
+ val owner: OwnerDto? = null,
+)
+
+@Serializable
+data class OwnerDto(
+ val id: String? = null,
+ @SerialName("display_name") val displayName: String? = null,
)
@Serializable
diff --git a/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt b/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt
new file mode 100644
index 0000000..7fa6942
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/SpotifyLink.kt
@@ -0,0 +1,52 @@
+package dev.lelonio.square.data
+
+import android.net.Uri
+
+/**
+ * Turns a link somebody shared into the URI the app works in.
+ *
+ * Spotify hands out the same thing in three shapes: its own `spotify:` scheme,
+ * the web address of the page, and the web address with a language in front of
+ * it. All three name the same track, and the app only ever speaks the first.
+ */
+object SpotifyLink {
+
+ /**
+ * The `spotify:` URI a link points at, or null if it points at nothing this
+ * app can open.
+ *
+ * Deliberately strict about the kinds it accepts. A share sheet will hand
+ * over a search page, a concert listing or somebody's profile just as
+ * readily as a track, and an app that answered those with a blank page
+ * would be worse at handling links than the browser it took them from.
+ */
+ fun parse(uri: Uri?): String? {
+ val raw = uri?.toString().orEmpty()
+ if (raw.isEmpty()) return null
+
+ if (uri?.scheme.equals("spotify", ignoreCase = true)) {
+ // Already in hand. Query strings ride along on shared links —
+ // `?si=` is on every one of them — and mean nothing here.
+ return raw.substringBefore('?').takeIf { it.isKind() }
+ }
+
+ val host = uri?.host?.lowercase()
+ if (host != "open.spotify.com" && host != "link.tospotify.com") return null
+
+ // "intl-it" and friends sit in front of the path on a shared link, and
+ // a user's own playlist link still carries the old `/user/<id>` prefix.
+ val parts = uri.pathSegments
+ .filter { it.isNotEmpty() && !it.startsWith("intl-") }
+ val kind = parts.getOrNull(parts.size - 2) ?: return null
+ val id = parts.lastOrNull()?.substringBefore('?') ?: return null
+ if (id.isEmpty()) return null
+
+ return "spotify:$kind:$id".takeIf { it.isKind() }
+ }
+
+ /** Whether this is one of the pages the app has somewhere to put. */
+ private fun String.isKind(): Boolean =
+ KINDS.any { startsWith("spotify:$it:") }
+
+ private val KINDS = listOf("track", "album", "playlist", "artist")
+}
diff --git a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
index 8057817..9163df3 100644
--- a/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
+++ b/app/src/main/java/dev/lelonio/square/nativecore/NativeBridge.kt
@@ -337,7 +337,17 @@ object NativeBridge {
*/
fun playlistCover(uri: String): String = nativePlaylistCover(uri)
+ /**
+ * A playlist's title, for one arriving by link rather than from the account.
+ */
+ fun playlistName(uri: String): String = nativePlaylistName(uri)
+
+ /** What the people this account follows are listening to. */
+ fun friendActivity(): String = nativeFriendActivity()
+
+ private external fun nativeFriendActivity(): String
private external fun nativePlaylistCover(uri: String): String
+ private external fun nativePlaylistName(uri: String): String
private 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/MainActivity.kt b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
index 165df56..2029b4b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainActivity.kt
@@ -49,6 +49,15 @@ class MainActivity : ComponentActivity() {
*/
private var openPlayer by mutableStateOf(0)
+ /**
+ * A Spotify link the app was opened with.
+ *
+ * Carries a number for the same reason [openPlayer] does: the same link
+ * twice is two requests, and a plain string would look unchanged the second
+ * time.
+ */
+ private var link by mutableStateOf<LinkRequest?>(null)
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Transparent bars; SquareTheme sets the icon colour, because it is the
@@ -66,6 +75,7 @@ class MainActivity : ComponentActivity() {
if (intent?.opensPlayer() == true) {
openPlayer++
}
+ intent?.let(::takeLink)
setContent {
SquareApp(
@@ -73,6 +83,7 @@ class MainActivity : ComponentActivity() {
onPlay = ::play,
onEnqueue = ::enqueue,
openPlayer = openPlayer,
+ link = link,
)
}
}
@@ -116,6 +127,19 @@ class MainActivity : ComponentActivity() {
if (intent.opensPlayer()) {
openPlayer++
}
+ takeLink(intent)
+ }
+
+ /**
+ * The whole of link handling on this side: recognise it, and pass it on.
+ *
+ * A `singleTask` activity gets the second link through `onNewIntent` rather
+ * than a new instance, so both ways in lead here.
+ */
+ private fun takeLink(intent: android.content.Intent) {
+ if (intent.action != android.content.Intent.ACTION_VIEW) return
+ val uri = dev.lelonio.square.data.SpotifyLink.parse(intent.data) ?: return
+ link = LinkRequest(uri, (link?.n ?: 0) + 1)
}
private fun android.content.Intent.opensPlayer(): Boolean =
@@ -245,6 +269,9 @@ class MainActivity : ComponentActivity() {
.build()
}
+/** A `spotify:` URI the app was opened with, and which opening it was. */
+data class LinkRequest(val uri: String, val n: Int)
+
/** Key for the context URI carried in a media item's metadata extras. */
const val EXTRA_CONTEXT_URI = "dev.lelonio.square.CONTEXT_URI"
diff --git a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
index 4102e37..e672ce3 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -109,6 +109,23 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val kind: DetailKind = DetailKind.PLAYLIST,
/** Populated for artists only. */
val albums: List<SearchItem> = emptyList(),
+ /** Their singles and EPs, kept apart from the albums above. */
+ val singles: List<SearchItem> = emptyList(),
+ /** Records that are somebody else's, with them on it. */
+ val appearsOn: List<SearchItem> = emptyList(),
+ /** The playlists Spotify built around them, "This Is" first. */
+ val artistPlaylists: List<SearchItem> = emptyList(),
+ /** How many accounts follow them, and what Spotify files them under. */
+ val followers: Int = 0,
+ val genres: List<String> = emptyList(),
+ /**
+ * Whether this account follows them.
+ *
+ * Null while unknown, which is not the same as false: a button drawn as
+ * "follow" before the answer arrives is a button that lies for a second
+ * and then corrects itself in front of the reader.
+ */
+ val following: Boolean? = null,
)
private val container get() = getApplication<SquareApplication>()
@@ -828,6 +845,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// caller's, so both are asked for.
"playlist-modify-private",
"playlist-modify-public",
+ // Following artists, and the list of the ones followed.
+ "user-follow-read",
+ "user-follow-modify",
),
)
}
@@ -878,6 +898,37 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* Filtered rather than kept apart so that switching back finds the history
* still there.
*/
+ private val _friends =
+ MutableStateFlow<List<dev.lelonio.square.data.FriendListen>>(emptyList())
+
+ /**
+ * What the people this account follows are playing.
+ *
+ * Kept rather than fetched per screen: it is one request, it changes on its
+ * own schedule and not on the app's, and the header shows a corner of it
+ * whether or not anybody has opened the list.
+ */
+ val friends: StateFlow<List<dev.lelonio.square.data.FriendListen>> = _friends.asStateFlow()
+
+ /**
+ * Reads the list again.
+ *
+ * Silent on failure by design. This is a private endpoint with no promises
+ * attached, an account may follow nobody, and everybody it follows may be
+ * listening privately: all three are the same empty list, and none of them
+ * is worth an error on the home page.
+ */
+ fun loadFriends() = viewModelScope.launch {
+ if (container.activeBackend.id != BackendId.SPOTIFY) {
+ _friends.value = emptyList()
+ return@launch
+ }
+ if (!awaitEngine()) return@launch
+ runCatching { dev.lelonio.square.data.FriendActivity.friends() }
+ .onSuccess { _friends.value = it }
+ .onFailure { android.util.Log.w(TAG, "friend activity unavailable: ${describe(it)}") }
+ }
+
val recent: StateFlow<List<CatalogTrack>> =
combine(container.recentStore.tracks, container.preferences.backend) { tracks, _ ->
tracks.filter { container.activeBackend.owns(it.uri) }
@@ -1015,6 +1066,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
loadMissingCovers()
// Spotify's own shelves, once there is a session to ask with.
loadHomeShelves()
+ loadFriends()
+ loadFollowedArtists()
}
.onFailure {
android.util.Log.e(TAG, "library load failed: ${chain(it)}", it)
@@ -1128,6 +1181,88 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* access-point round trips, and returning to a playlist from the player is
* the common case.
*/
+ /**
+ * Opens a page the app was handed from outside, by URI alone.
+ *
+ * A link carries no name and no picture, and a page whose title is blank
+ * until its tracks land looks broken rather than busy. The name is asked for
+ * first when there is an application to ask with, and the page is opened
+ * either way: a list of tracks under no title is still the playlist somebody
+ * sent.
+ */
+ fun openLink(uri: String) = viewModelScope.launch {
+ // A Spotify link is a Spotify page. Arriving on the other backend, it
+ // would resolve against a catalogue that has never heard of it.
+ if (container.activeBackend.id != BackendId.SPOTIFY) {
+ container.preferences.setBackend(BackendId.SPOTIFY)
+ }
+ // No name and no picture: the page asks for both itself, and shows the
+ // list without waiting for either.
+ openContext(uri, "")
+ }
+
+ /**
+ * Publishes a detail page without taking back what arrived while it was
+ * being built.
+ *
+ * The page is assembled from a snapshot taken when it opened, and the title
+ * and the picture of a page opened by URI alone are not in that snapshot:
+ * they are asked for separately and land whenever the network answers. Every
+ * later write is built from the same snapshot, so a name that arrived in
+ * between was on screen until the next one, which is a title appearing for
+ * half a second and vanishing. Neither field is ever cleared here: an empty
+ * name and a missing picture mean "not known yet", never "gone".
+ */
+ private fun publishPlaylist(state: PlaylistState) {
+ val current = _playlist.value
+ _playlist.value = if (current.uri != state.uri) {
+ state
+ } else {
+ state.copy(
+ name = state.name.ifEmpty { current.name },
+ artworkUrl = state.artworkUrl ?: current.artworkUrl,
+ )
+ }
+ }
+
+ /** A link's own title, from whichever side of Spotify will say. */
+ private suspend fun nameOf(uri: String): String? {
+ val kind = kindOf(uri)
+ val id = uri.substringAfterLast(':')
+
+ if (container.webApi.isReady) {
+ runCatching {
+ when (kind) {
+ DetailKind.ARTIST -> container.api.artist(id).name
+ DetailKind.ALBUM -> container.api.album(id).name
+ DetailKind.PLAYLIST -> container.api.playlist(id).name
+ }
+ }
+ .onFailure { android.util.Log.w(TAG, "no name for $uri: ${describe(it)}") }
+ .getOrNull()
+ ?.let { return it }
+ }
+
+ // The Web API answers 404 for everything Spotify generates itself — the
+ // daily mixes, the editorial lists, the one somebody is most likely to
+ // send — and those are exactly the playlists the access point can name.
+ if (kind == DetailKind.PLAYLIST && awaitEngine()) {
+ return Catalog.playlistName(uri)
+ }
+ return null
+ }
+
+ /**
+ * One track, resolved from its URI, for a link that names a song rather
+ * than a page.
+ */
+ suspend fun resolveTrack(uri: String): CatalogTrack? {
+ if (!awaitEngine()) return null
+ return runCatching { Catalog.tracks(listOf(uri)).firstOrNull() }
+ .onFailure { android.util.Log.e(TAG, "link track failed: ${chain(it)}", it) }
+ .getOrNull()
+ }
+
fun openContext(uri: String, name: String, artworkUrl: String? = null) =
openPlaylist(CatalogPlaylist(uri = uri, name = name, artworkUrl = artworkUrl))
@@ -1258,15 +1393,29 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
)
val remembered = contextCache[playlist.uri]
- _playlist.value = base.copy(
+ publishPlaylist(base.copy(
tracks = remembered?.tracks.orEmpty(),
loading = remembered == null,
- )
+ ))
playlistJob = viewModelScope.launch {
// Opened by URI alone, from a tap on the player's text: there was no
// row to take the picture from. Asked for alongside the track list
// rather than before it, since the list is what the page is for.
+ // Opened by URI alone from outside the app: a link carries no title
+ // either. Written through `base` like the picture below, and for the
+ // same reason: every state published here is built from it, so a
+ // name patched onto the state instead would be taken back off the
+ // screen by the next write, which is a title that appears for half a
+ // second and vanishes.
+ if (base.name.isEmpty()) launch {
+ val name = nameOf(playlist.uri) ?: return@launch
+ base = base.copy(name = name)
+ if (_playlist.value.uri == playlist.uri) {
+ _playlist.value = _playlist.value.copy(name = name)
+ }
+ }
+
if (base.artworkUrl == null) launch {
val art = artworkFor(playlist.uri, kind) ?: return@launch
base = base.copy(artworkUrl = art)
@@ -1281,7 +1430,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val entry = remembered ?: container.contextCache.read(playlist.uri)?.also {
contextCache[playlist.uri] = it
rememberMembership(playlist.uri, it.tracks)
- _playlist.value = base.copy(tracks = it.tracks, loading = false)
+ publishPlaylist(base.copy(tracks = it.tracks, loading = false))
}
val cached = entry?.tracks.orEmpty()
@@ -1292,14 +1441,25 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
// around the Web API's paging and the access point's
// per-track lookups, neither of which exists here.
val tracks = container.activeBackend.tracksOf(playlist.uri)
- _playlist.value = base.copy(tracks = tracks, loading = false)
+ publishPlaylist(base.copy(tracks = tracks, loading = false))
} else if (kind == DetailKind.ARTIST) {
- val (tracks, albums) = loadArtist(playlist.uri)
- _playlist.value = base.copy(tracks = tracks, albums = albums)
+ val page = loadArtist(playlist.uri)
+ publishPlaylist(
+ base.copy(
+ tracks = page.tracks,
+ albums = page.albums,
+ singles = page.singles,
+ appearsOn = page.appearsOn,
+ artistPlaylists = page.playlists,
+ followers = page.followers,
+ genres = page.genres,
+ following = _playlist.value.following,
+ ),
+ )
} else if (cached.isNotEmpty() && isUnchanged(playlist.uri, entry?.snapshotId)) {
// Nothing to do: one small request said the copy on screen
// is the current one.
- _playlist.value = base.copy(tracks = cached, loadingMore = false)
+ publishPlaylist(base.copy(tracks = cached, loadingMore = false))
} else {
loadContextInto(base, playlist.uri, showProgress = cached.isEmpty())
}
@@ -1308,8 +1468,9 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
android.util.Log.e(TAG, "detail load failed: ${chain(it)}", it)
// Only when there is nothing to show. A refresh that fails
// over a list already on screen should leave the list.
- _playlist.value =
- if (cached.isEmpty()) base.copy(error = describe(it)) else base.copy(tracks = cached)
+ publishPlaylist(
+ if (cached.isEmpty()) base.copy(error = describe(it)) else base.copy(tracks = cached),
+ )
}
}
}
@@ -1341,6 +1502,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
if (fetched != null) return fetched
}
+ // The access point carries the art for the lists Spotify generates,
+ // which is where the Web API answers 404.
+ if (kind == DetailKind.PLAYLIST) return Catalog.playlistCover(uri)
+
// An album's cover is on every one of its tracks, which is the way in
// when the user has not registered an application of their own.
if (kind != DetailKind.ALBUM) return null
@@ -1494,7 +1659,7 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val tracks = viaWebApi ?: accessPointTracks(base, uri, showProgress)
- _playlist.value = base.copy(tracks = tracks, loadingMore = false)
+ publishPlaylist(base.copy(tracks = tracks, loadingMore = false))
// Stamped with the version it was read from, so the next open can ask
// one question instead of reading it all again. Without a stamp the
@@ -1537,10 +1702,10 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
}
offset += page.items.size
if (showProgress) {
- _playlist.value = base.copy(
+ publishPlaylist(base.copy(
tracks = loaded.toList(),
loadingMore = offset < page.total,
- )
+ ))
}
if (page.items.isEmpty() || offset >= page.total) return loaded
}
@@ -1559,14 +1724,14 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
batches.forEachIndexed { index, batch ->
loaded += Catalog.tracks(batch)
if (showProgress) {
- _playlist.value = base.copy(
+ publishPlaylist(base.copy(
tracks = loaded.toList(),
// Counted in batches, not in tracks: a delisted track
// resolves to nothing, so the list is legitimately shorter
// than the URIs asked for and comparing the two totals left
// "more coming" on forever.
loadingMore = index < batches.lastIndex,
- )
+ ))
}
}
return loaded
@@ -1580,21 +1745,183 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
* screen which cannot work until the user has registered their own
* application, hence the explicit message rather than a raw 401.
*/
- private suspend fun loadArtist(uri: String): Pair<List<CatalogTrack>, List<SearchItem>> {
+ /** Everything an artist page shows, gathered in one go. */
+ private data class ArtistPage(
+ val tracks: List<CatalogTrack>,
+ val albums: List<SearchItem>,
+ val singles: List<SearchItem>,
+ val appearsOn: List<SearchItem>,
+ val playlists: List<SearchItem>,
+ val followers: Int,
+ val genres: List<String>,
+ )
+
+ private suspend fun loadArtist(uri: String): ArtistPage {
if (!container.webApi.isReady) {
error(string(R.string.artist_needs_app))
}
val id = uri.substringAfterLast(':')
val tracks = container.api.artistTopTracks(id).tracks.map { it.toCatalogTrack() }
- val albums = container.api.artistAlbums(id).items.mapNotNull { album ->
- SearchItem(
- uri = album.uri ?: return@mapNotNull null,
- title = album.name,
- subtitle = album.releaseDate?.take(4).orEmpty(),
- artworkUrl = album.images.firstOrNull()?.url,
- )
+
+ // One request for every kind of record rather than three. Spotify says
+ // which shelf each one belongs on, and asking per shelf would spend the
+ // account's quota three times for the same answer.
+ val releases = container.api.artistAlbums(
+ id,
+ groups = "album,single,compilation,appears_on",
+ limit = 50,
+ ).items
+
+ fun shelf(vararg groups: String): List<SearchItem> = releases
+ .filter { it.albumGroup in groups }
+ .mapNotNull { album ->
+ SearchItem(
+ uri = album.uri ?: return@mapNotNull null,
+ title = album.name,
+ subtitle = album.releaseDate?.take(4).orEmpty(),
+ artworkUrl = album.images.firstOrNull()?.url,
+ )
+ }
+ // The same record is often listed several times, once per market.
+ .distinctBy { it.title.lowercase() }
+ .sortedByDescending { it.subtitle }
+
+ // Not fatal, either of them. The page is worth showing without the
+ // number under the name, and an account whose application predates the
+ // follow permissions still gets everything else.
+ val artist = runCatching { container.api.artist(id) }.getOrNull()
+ val following = runCatching { container.api.isFollowing(ids = id).firstOrNull() }
+ .onFailure { android.util.Log.w(TAG, "cannot tell if followed: ${describe(it)}") }
+ .getOrNull()
+
+ if (following != null) {
+ _playlist.value = _playlist.value.let {
+ if (it.uri == uri) it.copy(following = following) else it
+ }
+ }
+
+ return ArtistPage(
+ playlists = artistPlaylists(artist?.name.orEmpty()),
+ tracks = tracks,
+ albums = shelf("album", "compilation"),
+ singles = shelf("single"),
+ appearsOn = shelf("appears_on"),
+ followers = artist?.followers?.total ?: 0,
+ genres = artist?.genres.orEmpty(),
+ )
+ }
+
+ /**
+ * The playlists Spotify built around one artist.
+ *
+ * There is no endpoint for this. The desktop client reads it from the
+ * gateway that answers the personalised pages, addressed by a hash of a
+ * query this app does not have, so the way in is the search: "This Is" and
+ * the rest are ordinary public playlists, and what makes them Spotify's own
+ * rather than a stranger's copy is the owner.
+ *
+ * Named after the artist too, because searching a name returns everything
+ * anybody ever titled after them.
+ */
+ private suspend fun artistPlaylists(name: String): List<SearchItem> {
+ if (name.isEmpty()) return emptyList()
+ val needle = name.lowercase()
+ return runCatching {
+ container.api.search(
+ query = "\"This Is $name\"",
+ type = "playlist",
+ limit = 20,
+ ).playlists?.items.orEmpty()
+ .filterNotNull()
+ .filter { it.owner?.id == "spotify" && it.name.lowercase().contains(needle) }
+ .map { playlist ->
+ SearchItem(
+ uri = playlist.uri,
+ title = playlist.name,
+ subtitle = playlist.description.orEmpty(),
+ artworkUrl = playlist.images.firstOrNull()?.url,
+ )
+ }
+ // "This Is" first when it is there: it is the one everybody
+ // means by "the artist's playlist".
+ .sortedBy { if (it.title.lowercase().startsWith("this is")) 0 else 1 }
+ .take(10)
}
- return tracks to albums
+ .onFailure { android.util.Log.w(TAG, "no playlists for $name: ${describe(it)}") }
+ .getOrDefault(emptyList())
+ }
+
+ /**
+ * Follows or unfollows the artist whose page is open.
+ *
+ * The button moves first and is put back if Spotify refuses: this is one
+ * request over a network, and a control that waits for a round trip before
+ * acknowledging a tap feels broken even when it works.
+ */
+ fun toggleFollowArtist() = viewModelScope.launch {
+ val page = _playlist.value
+ val uri = page.uri ?: return@launch
+ if (page.kind != DetailKind.ARTIST) return@launch
+ val was = page.following ?: false
+ val id = uri.substringAfterLast(':')
+
+ _playlist.value = _playlist.value.copy(following = !was)
+ runCatching {
+ if (was) container.api.unfollowArtists(ids = id) else container.api.followArtists(ids = id)
+ }
+ .onSuccess { loadFollowedArtists() }
+ .onFailure {
+ android.util.Log.e(TAG, "follow failed: ${chain(it)}", it)
+ if (_playlist.value.uri == uri) {
+ _playlist.value = _playlist.value.copy(following = was)
+ }
+ // Almost always the same cause: an application connected before
+ // this feature existed, whose token carries no permission to
+ // follow anybody. Saying so is more use than the error itself.
+ _webApi.value = _webApi.value.copy(expired = true)
+ }
+ }
+
+ private val _followedArtists = MutableStateFlow<List<SearchItem>>(emptyList())
+
+ /** The artists this account follows, for the library. */
+ val followedArtists: StateFlow<List<SearchItem>> = _followedArtists.asStateFlow()
+
+ fun loadFollowedArtists() = viewModelScope.launch {
+ if (!container.webApi.isReady || container.activeBackend.id != BackendId.SPOTIFY) {
+ _followedArtists.value = emptyList()
+ return@launch
+ }
+ runCatching {
+ val gathered = mutableListOf<SearchItem>()
+ var after: String? = null
+ // Cursor-paged, and an account can follow hundreds: walk it to the
+ // end rather than showing the first page and calling it the list.
+ while (true) {
+ val page = container.api.followedArtists(after = after).artists
+ gathered += page.items.mapNotNull { artist ->
+ SearchItem(
+ uri = artist.uri ?: return@mapNotNull null,
+ title = artist.name,
+ subtitle = "",
+ artworkUrl = artist.images.firstOrNull()?.url,
+ )
+ }
+ after = page.cursors?.after?.takeIf { page.items.isNotEmpty() } ?: break
+ }
+ gathered.sortedBy { it.title.lowercase() }
+ }
+ .onSuccess { _followedArtists.value = it }
+ .onFailure {
+ android.util.Log.w(TAG, "followed artists unavailable: ${describe(it)}")
+ // 403 here has one cause: an application connected before the
+ // follow permissions were asked for. The token is valid and
+ // will never be allowed to read this, so the way out is the
+ // same one an expired session takes — sign in again, once.
+ if (describe(it).contains("403")) {
+ _webApi.value = _webApi.value.copy(expired = true)
+ }
+ }
}
private fun kindOf(uri: String): DetailKind = when {
diff --git a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
index 366001b..3615d8d 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -43,6 +43,8 @@ import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
+import dev.lelonio.square.ui.components.FriendsPanel
+import dev.lelonio.square.ui.components.SharedTrackCard
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
@@ -198,6 +200,8 @@ fun SquareApp(
* already open is still a request.
*/
openPlayer: Int = 0,
+ /** A Spotify link the app was opened with; see [LinkRequest]. */
+ link: LinkRequest? = null,
viewModel: MainViewModel = viewModel(),
) {
val state by viewModel.state.collectAsStateWithLifecycle()
@@ -304,6 +308,8 @@ fun SquareApp(
val playlistOrder by viewModel.playlistOrder.collectAsStateWithLifecycle()
val pinnedPlaylists by viewModel.pinnedPlaylists.collectAsStateWithLifecycle()
val likedTracks by viewModel.likedTracks.collectAsStateWithLifecycle()
+ val friends by viewModel.friends.collectAsStateWithLifecycle()
+ val followedArtists by viewModel.followedArtists.collectAsStateWithLifecycle()
val devices by viewModel.devices.collectAsStateWithLifecycle()
val addToPlaylist by viewModel.addToPlaylist.collectAsStateWithLifecycle()
val trackSort by viewModel.trackSort.collectAsStateWithLifecycle()
@@ -320,6 +326,10 @@ fun SquareApp(
var trackMenu by remember { mutableStateOf<TrackMenuRequest?>(null) }
// The playlist a long press opened the actions for.
var playlistMenu by remember { mutableStateOf<CatalogPlaylist?>(null) }
+ // A song somebody sent, waiting to be looked at; see SharedTrackCard.
+ var sharedTrack by remember { mutableStateOf<CatalogTrack?>(null) }
+ // Whether the friend list is open; the faces in the header open it.
+ var friendsOpen by remember { mutableStateOf(false) }
// Open when a name is being asked for; the playlist is null when the name is
// for one that does not exist yet.
var naming by remember { mutableStateOf<NamingRequest?>(null) }
@@ -534,6 +544,26 @@ fun SquareApp(
val currentEntry by navController.currentBackStackEntryAsState()
val route = currentEntry?.destination?.route
+ // A link from outside.
+ //
+ // A song is offered rather than started. Whoever sent it may
+ // have meant "listen to this now" or "keep this", and a link
+ // that begins playing over whatever was already on takes the
+ // choice away: the card shows what the link is, and both
+ // answers are one tap.
+ //
+ // Everything else is a page, and the page opens in front of
+ // whatever was on screen.
+ LaunchedEffect(link) {
+ val uri = link?.uri ?: return@LaunchedEffect
+ if (uri.startsWith("spotify:track:")) {
+ sharedTrack = viewModel.resolveTrack(uri)
+ } else {
+ viewModel.openLink(uri)
+ navController.navigate(Routes.PLAYLIST)
+ }
+ }
+
// Back to the home page when the source changes: an open
// playlist, a search or a detail page all belong to the
// catalogue that was just swapped out.
@@ -607,7 +637,8 @@ fun SquareApp(
// it refracts was not being recorded while it was the only
// thing open, so the glass had nothing behind it and the sheet
// came up as a transparent panel with no depth at all.
- val sheetsOpen = trackMenu != null || addToPlaylist.open || playlistMenu != null
+ val sheetsOpen = trackMenu != null || addToPlaylist.open || playlistMenu != null ||
+ sharedTrack != null || friendsOpen
// Kept on a little past the close, or the layer would stop
// being recorded while the sheet is still fading out over it
// and the panel would go black on the way down.
@@ -681,6 +712,14 @@ fun SquareApp(
onPlay(tracks, index, null, false, trendingLabel, 0L)
},
onOpenSettings = { navController.navigate(Routes.SETTINGS) },
+ friends = friends,
+ onOpenFriends = {
+ friendsOpen = true
+ // Read again as it opens: what somebody is
+ // playing is only worth showing if it is
+ // what they are playing now.
+ viewModel.loadFriends()
+ },
)
}
@@ -726,6 +765,15 @@ fun SquareApp(
canEdit = viewModel.canEditPlaylists,
onCreatePlaylist = { naming = NamingRequest(null) },
onPlaylistMenu = { playlistMenu = it },
+ artists = followedArtists,
+ onOpenArtist = { artist ->
+ viewModel.openContext(
+ artist.uri,
+ artist.title,
+ artist.artworkUrl,
+ )
+ navController.navigate(Routes.PLAYLIST)
+ },
backdrop = artBackdrop,
)
}
@@ -819,6 +867,7 @@ fun SquareApp(
item.artworkUrl,
)
},
+ onToggleFollow = viewModel::toggleFollowArtist,
)
}
}
@@ -838,6 +887,18 @@ fun SquareApp(
.padding(top = statusBar + 8.dp),
)
+ // Out here for the same reason as the bars below: it refracts
+ // `pageBackdrop`, so it cannot be drawn inside it.
+ SessionExpiredNotice(
+ visible = webApi.expired && !webApi.connecting,
+ backdrop = pageBackdrop,
+ onReconnect = viewModel::connectWebApi,
+ onDismiss = viewModel::dismissWebApiExpiry,
+ modifier = Modifier
+ .align(Alignment.TopCenter)
+ .padding(top = statusBar + 8.dp),
+ )
+
// Outside the recorded layer, and that is structural rather than
// stylistic: these refract `pageBackdrop`, and a pane drawn
// inside the layer it samples recurses on the render thread
@@ -1211,6 +1272,45 @@ fun SquareApp(
}
}
+ FriendsPanel(
+ visible = friendsOpen,
+ friends = friends,
+ backdrop = overlayBackdrop,
+ onOpenTrack = { friend ->
+ friendsOpen = false
+ sharedTrack = dev.lelonio.square.data.CatalogTrack(
+ uri = friend.trackUri,
+ name = friend.trackName,
+ artist = friend.artist,
+ artworkUrl = friend.artworkUrl,
+ )
+ },
+ onDismiss = { friendsOpen = false },
+ )
+
+ // A song that arrived by link. Held one beat past the dismissal
+ // for the same reason the track sheet is: the card is still on
+ // its way out, and reading the track off the state that closed
+ // it would empty the cover and the title as it goes.
+ var lastShared by remember { mutableStateOf<CatalogTrack?>(null) }
+ LaunchedEffect(sharedTrack) { sharedTrack?.let { lastShared = it } }
+ SharedTrackCard(
+ visible = sharedTrack != null,
+ track = sharedTrack ?: lastShared,
+ backdrop = overlayBackdrop,
+ onPlay = {
+ val track = sharedTrack ?: return@SharedTrackCard
+ sharedTrack = null
+ onPlay(listOf(track), 0, null, false, "", 0L)
+ },
+ onAddToPlaylist = {
+ val track = sharedTrack ?: return@SharedTrackCard
+ sharedTrack = null
+ viewModel.openAddToPlaylist(track.uri, track.name)
+ },
+ onDismiss = { sharedTrack = null },
+ )
+
// Over everything, including the player: the same sheet is
// opened from a track row in the library and from the plus in
// the player, and it is one sheet with one state.
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/FriendsPanel.kt b/app/src/main/java/dev/lelonio/square/ui/components/FriendsPanel.kt
new file mode 100644
index 0000000..85d7e9c
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/FriendsPanel.kt
@@ -0,0 +1,228 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.animation.AnimatedVisibility
+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.foundation.clickable
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+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.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+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.material3.MaterialTheme
+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.graphics.RectangleShape
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.kyant.backdrop.Backdrop
+import com.kyant.backdrop.drawBackdrop
+import com.kyant.backdrop.effects.blur
+import dev.lelonio.square.R
+import dev.lelonio.square.data.FriendListen
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.player.GlassSurface
+import dev.lelonio.square.ui.theme.softShadow
+
+/**
+ * Who the account follows, and what they were last heard playing.
+ *
+ * Spotify's own friend activity, which the desktop client keeps down its side
+ * and the phone app does not have at all. A panel rather than a page: it is
+ * something to glance at on the way to something else, and a tab of its own
+ * would make a whole destination out of a list that is often three lines long.
+ *
+ * Every row is a way in. Somebody's song is a song, so tapping one offers it
+ * exactly as a link to it would.
+ */
+@Composable
+fun BoxScope.FriendsPanel(
+ visible: Boolean,
+ friends: List<FriendListen>,
+ backdrop: Backdrop,
+ onOpenTrack: (FriendListen) -> Unit,
+ onDismiss: () -> Unit,
+) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(180)),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .drawBackdrop(
+ backdrop = backdrop,
+ shape = { RectangleShape },
+ effects = { blur(28f.dp.toPx()) },
+ onDrawSurface = { drawRect(Color.Black.copy(alpha = 0.46f)) },
+ )
+ .clickable(interactionSource = null, indication = null, onClick = onDismiss),
+ )
+ }
+
+ AnimatedVisibility(
+ visible = visible,
+ enter = scaleIn(tween(240), initialScale = 0.9f) + fadeIn(tween(160)),
+ exit = scaleOut(tween(160), targetScale = 0.94f) + fadeOut(tween(140)),
+ modifier = Modifier.align(Alignment.Center),
+ ) {
+ val shape = RoundedCornerShape(32.dp)
+ GlassSurface(
+ backdrop = backdrop,
+ shape = shape,
+ surfaceColor = Color.White.copy(alpha = 0.08f),
+ blurRadius = 46.dp,
+ modifier = Modifier
+ .padding(horizontal = 22.dp)
+ .fillMaxWidth()
+ .clip(shape)
+ .softShadow(shape, elevation = 26.dp, spot = 0.35f)
+ .clickable(interactionSource = null, indication = null) {},
+ ) {
+ Column(Modifier.padding(vertical = 22.dp)) {
+ Text(
+ stringResource(R.string.friends_listening),
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 22.dp),
+ )
+
+ if (friends.isEmpty()) {
+ // Says why it is empty, because there are three reasons and
+ // none of them is a failure the listener could act on.
+ Text(
+ stringResource(R.string.friends_none),
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.6f),
+ modifier = Modifier.padding(horizontal = 22.dp, vertical = 14.dp),
+ )
+ return@Column
+ }
+
+ LazyColumn(
+ Modifier
+ .padding(top = 6.dp)
+ // Bounded, so a well-connected account gets a list that
+ // scrolls rather than a panel taller than the screen.
+ .heightIn(max = 420.dp),
+ ) {
+ items(friends, key = { it.userUri + it.trackUri }) { friend ->
+ FriendRow(friend) { onOpenTrack(friend) }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun FriendRow(friend: FriendListen, onClick: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .pressable(onClick = onClick, shape = RoundedCornerShape(18.dp), pressedScale = 0.98f)
+ .padding(horizontal = 22.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Box {
+ Artwork(
+ url = friend.avatarUrl,
+ title = friend.userName,
+ modifier = Modifier
+ .size(44.dp)
+ .clip(CircleShape),
+ corner = 22.dp,
+ decodeSize = 44.dp,
+ )
+ // The cover, tucked into the corner of the person. Two pictures of
+ // equal size would be a row about two things; this one is about a
+ // person, and what they are playing is the caption.
+ Artwork(
+ url = friend.artworkUrl,
+ title = friend.trackName,
+ modifier = Modifier
+ .align(Alignment.BottomEnd)
+ .padding(start = 20.dp, top = 20.dp)
+ .size(22.dp),
+ corner = 6.dp,
+ decodeSize = 22.dp,
+ )
+ }
+
+ Column(
+ Modifier
+ .weight(1f)
+ .padding(start = 14.dp),
+ ) {
+ Text(
+ friend.userName,
+ style = MaterialTheme.typography.bodyMedium,
+ fontWeight = FontWeight.Medium,
+ color = Color.White,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ Text(
+ "${friend.trackName} · ${friend.artist}",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.7f),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ // Where they were playing it from, and how long ago. Both are what
+ // makes this activity rather than a list of names.
+ val detail = listOfNotNull(
+ friend.contextName.takeIf { it.isNotEmpty() },
+ ago(friend.at),
+ ).joinToString(" · ")
+ if (detail.isNotEmpty()) {
+ Text(
+ detail,
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.45f),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+ }
+ }
+}
+
+/**
+ * How long ago, in the coarsest unit that still says something.
+ *
+ * Minutes for the last hour, then hours, then days. A timestamp to the second
+ * would be both more precise and less useful: nobody reads this to know when,
+ * only whether it was now.
+ */
+@Composable
+private fun ago(at: Long): String? {
+ val minutes = (System.currentTimeMillis() - at) / 60_000
+ return when {
+ minutes < 0 -> null
+ minutes < 1 -> stringResource(R.string.just_now)
+ minutes < 60 -> stringResource(R.string.minutes_ago, minutes)
+ minutes < 60 * 24 -> stringResource(R.string.hours_ago, minutes / 60)
+ else -> stringResource(R.string.days_ago, minutes / (60 * 24))
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/components/SharedTrackCard.kt b/app/src/main/java/dev/lelonio/square/ui/components/SharedTrackCard.kt
new file mode 100644
index 0000000..e372d68
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/ui/components/SharedTrackCard.kt
@@ -0,0 +1,264 @@
+package dev.lelonio.square.ui.components
+
+import androidx.compose.animation.AnimatedVisibility
+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.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.Icon
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.blur
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.RectangleShape
+import androidx.compose.ui.graphics.vector.ImageVector
+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 com.adamglin.PhosphorIcons
+import com.adamglin.phosphoricons.Fill
+import com.adamglin.phosphoricons.Regular
+import com.adamglin.phosphoricons.fill.Play
+import com.adamglin.phosphoricons.regular.Plus
+import com.kyant.backdrop.Backdrop
+import com.kyant.backdrop.drawBackdrop
+import com.kyant.backdrop.effects.blur
+import dev.lelonio.square.R
+import dev.lelonio.square.data.CatalogTrack
+import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.player.GlassSurface
+import dev.lelonio.square.ui.theme.rememberArtworkPalette
+import dev.lelonio.square.ui.theme.softShadow
+import androidx.compose.ui.res.stringResource
+
+/**
+ * One song, arriving from outside the app.
+ *
+ * The track menu would have done the job and was the wrong thing to reach for:
+ * a link from a friend is not a row somebody long-pressed, and answering it with
+ * the same list of chores made the app look like it had not noticed. What a
+ * shared song wants is to be looked at first. The cover is the card, at the size
+ * a record deserves; its own colours are what the panel glows with; and the two
+ * things anybody does with a song someone sent them — hear it, or keep it — are
+ * the only buttons.
+ *
+ * Drawn at app level like [TrackSheet], and for the same reason: it belongs over
+ * the tab bar and the now-playing bar, not inside a screen.
+ */
+@Composable
+fun BoxScope.SharedTrackCard(
+ visible: Boolean,
+ track: CatalogTrack?,
+ backdrop: Backdrop,
+ onPlay: () -> Unit,
+ onAddToPlaylist: () -> Unit,
+ onDismiss: () -> Unit,
+) {
+ AnimatedVisibility(
+ visible = visible,
+ enter = fadeIn(tween(200)),
+ exit = fadeOut(tween(180)),
+ modifier = Modifier.fillMaxSize(),
+ ) {
+ Box(
+ Modifier
+ .fillMaxSize()
+ .drawBackdrop(
+ backdrop = backdrop,
+ shape = { RectangleShape },
+ effects = { blur(30f.dp.toPx()) },
+ onDrawSurface = { drawRect(Color.Black.copy(alpha = 0.52f)) },
+ )
+ .clickable(interactionSource = null, indication = null, onClick = onDismiss),
+ )
+ }
+
+ AnimatedVisibility(
+ visible = visible,
+ enter = scaleIn(tween(260), initialScale = 0.88f) + fadeIn(tween(180)),
+ exit = scaleOut(tween(170), targetScale = 0.94f) + fadeOut(tween(140)),
+ modifier = Modifier.align(Alignment.Center),
+ ) {
+ val shape = RoundedCornerShape(36.dp)
+ val palette by rememberArtworkPalette(track?.artworkUrl)
+
+ GlassSurface(
+ backdrop = backdrop,
+ shape = shape,
+ surfaceColor = Color.White.copy(alpha = 0.07f),
+ blurRadius = 46.dp,
+ modifier = Modifier
+ .padding(horizontal = 26.dp)
+ .fillMaxWidth()
+ .clip(shape)
+ .softShadow(shape, elevation = 30.dp, spot = 0.4f)
+ .clickable(interactionSource = null, indication = null) {},
+ ) {
+ // The record's own light, thrown on the panel behind it. Blurred
+ // past any shape of its own, so what is left is colour: the card of
+ // a red cover is warm and the card of a blue one is cold, without
+ // either being drawn as anything.
+ if (palette.isNotEmpty()) {
+ Box(
+ Modifier
+ .matchParentSize()
+ .blur(60.dp)
+ .background(
+ Brush.verticalGradient(
+ listOf(
+ palette.first().copy(alpha = 0.55f),
+ palette.getOrElse(1) { palette.first() }.copy(alpha = 0.18f),
+ Color.Transparent,
+ ),
+ ),
+ ),
+ )
+ }
+
+ Column(
+ Modifier.padding(horizontal = 24.dp, vertical = 26.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Text(
+ stringResource(R.string.shared_song),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.55f),
+ letterSpacing = 1.6.sp,
+ )
+
+ Artwork(
+ url = track?.artworkUrl,
+ title = track?.name.orEmpty(),
+ modifier = Modifier
+ .padding(top = 18.dp)
+ .fillMaxWidth()
+ .aspectRatio(1f)
+ .softShadow(RoundedCornerShape(22.dp), elevation = 24.dp, spot = 0.45f),
+ corner = 22.dp,
+ )
+
+ Text(
+ track?.name.orEmpty(),
+ style = MaterialTheme.typography.headlineSmall,
+ fontWeight = FontWeight.Bold,
+ color = Color.White,
+ textAlign = TextAlign.Center,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 22.dp),
+ )
+ Text(
+ track?.artist.orEmpty(),
+ style = MaterialTheme.typography.bodyLarge,
+ color = Color.White.copy(alpha = 0.72f),
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 4.dp),
+ )
+ // The album, quietly. It is what tells two versions of the same
+ // song apart, which is exactly the doubt a link raises.
+ track?.album?.takeIf { it.isNotEmpty() && it != track.name }?.let { album ->
+ Text(
+ album,
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.45f),
+ textAlign = TextAlign.Center,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.padding(top = 6.dp),
+ )
+ }
+
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(top = 26.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ ) {
+ CardButton(
+ label = stringResource(R.string.play),
+ icon = PhosphorIcons.Fill.Play,
+ filled = true,
+ onClick = onPlay,
+ modifier = Modifier.weight(1f),
+ )
+ CardButton(
+ label = stringResource(R.string.save),
+ icon = PhosphorIcons.Regular.Plus,
+ filled = false,
+ onClick = onAddToPlaylist,
+ modifier = Modifier.weight(1f),
+ )
+ }
+ }
+ }
+ }
+}
+
+/**
+ * One of the two answers.
+ *
+ * Filled for the one most people want and clear for the other, which is the
+ * whole of the hierarchy: two buttons of equal weight would make a card that
+ * asks a question rather than one that offers a song.
+ */
+@Composable
+private fun CardButton(
+ label: String,
+ icon: ImageVector,
+ filled: Boolean,
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+) {
+ val shape = RoundedCornerShape(percent = 50)
+ Row(
+ modifier
+ .clip(shape)
+ .background(
+ if (filled) Color.White else Color.White.copy(alpha = 0.12f),
+ shape,
+ )
+ .pressable(onClick = onClick, pressedScale = 0.94f)
+ .padding(vertical = 14.dp),
+ horizontalArrangement = Arrangement.Center,
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Icon(
+ icon,
+ contentDescription = null,
+ tint = if (filled) Color.Black else Color.White,
+ modifier = Modifier.size(18.dp),
+ )
+ Text(
+ label,
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = FontWeight.SemiBold,
+ color = if (filled) Color.Black else Color.White,
+ maxLines = 1,
+ modifier = Modifier.padding(start = 8.dp),
+ )
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
index f0871f0..9233b7f 100644
--- a/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/home/HomeScreen.kt
@@ -11,6 +11,7 @@ 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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
@@ -20,6 +21,7 @@ import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.ui.zIndex
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
@@ -126,6 +128,9 @@ fun HomeScreen(
feed: MainViewModel.FeedState,
onOpenItem: (SearchItem) -> Unit,
onOpenSettings: () -> Unit,
+ /** Friend activity, for the faces beside the account picture. */
+ friends: List<dev.lelonio.square.data.FriendListen> = emptyList(),
+ onOpenFriends: () -> Unit = {},
/** The layer the glass on this page refracts; see the note in SquareApp. */
backdrop: Backdrop,
/**
@@ -248,6 +253,8 @@ fun HomeScreen(
topPadding = contentPadding.calculateTopPadding(),
onFilter = { filter = it },
onOpenSettings = onOpenSettings,
+ friends = friends,
+ onOpenFriends = onOpenFriends,
)
AnimatedContent(
@@ -502,6 +509,9 @@ private fun Header(
topPadding: Dp,
onFilter: (Feed) -> Unit,
onOpenSettings: () -> Unit,
+ /** Who the account follows and what they play; empty hides the control. */
+ friends: List<dev.lelonio.square.data.FriendListen> = emptyList(),
+ onOpenFriends: () -> Unit = {},
/**
* False on a page with no feed to filter.
*
@@ -609,6 +619,17 @@ private fun Header(
// The way into the settings. They have no tab of their own — see
// SettingsScreen — and the account picture is where anyone looks for
// them anyway.
+ // The people the account follows, as a huddle of faces.
+ //
+ // Beside the account's own picture because that is what it is about
+ // — who is listening — and because a list nobody has asked for does
+ // not deserve a tab. Absent rather than empty when nobody is
+ // playing: a control that opens onto nothing is worse than no
+ // control.
+ if (friends.isNotEmpty()) {
+ FriendFaces(friends, onOpenFriends)
+ }
+
Artwork(
url = avatarUrl,
title = name,
@@ -1239,3 +1260,49 @@ private const val CAROUSEL_SIZE = 8
/** With the library filter on, the carousel is the whole point of the page. */
private const val LIBRARY_SIZE = 30
+
+/**
+ * Up to three friends, overlapping, as one control.
+ *
+ * Stacked rather than listed: the header has room for a gesture, not for a row
+ * of names, and overlapping faces are the one shape everybody already reads as
+ * "these people, together". The count is left off deliberately — a badge would
+ * turn a glance into a number to keep at zero.
+ */
+@Composable
+private fun FriendFaces(
+ friends: List<dev.lelonio.square.data.FriendListen>,
+ onClick: () -> Unit,
+) {
+ val shown = friends.take(3)
+ // Measured rather than laid out in a row: each face sits on the one before
+ // it, so the box is one face wide plus what the others peek out by.
+ val width = FACE + FACE_PEEK * (shown.size - 1)
+ Box(
+ Modifier
+ .padding(start = 8.dp)
+ .width(width)
+ .height(FACE)
+ .pressable(onClick, pressedScale = 0.92f),
+ ) {
+ shown.forEachIndexed { index, friend ->
+ Artwork(
+ url = friend.avatarUrl,
+ title = friend.userName,
+ modifier = Modifier
+ .offset(x = FACE_PEEK * index)
+ .size(FACE)
+ .clip(CircleShape)
+ // The first face on top, so the stack leans the way a hand
+ // of cards does rather than away from the reader.
+ .zIndex((shown.size - index).toFloat()),
+ corner = FACE / 2,
+ decodeSize = FACE,
+ )
+ }
+ }
+}
+
+/** One face, and how much of the one behind it is left showing. */
+private val FACE = 30.dp
+private val FACE_PEEK = 20.dp
diff --git a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
index 46a7e23..3f3c93b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/library/LibraryScreen.kt
@@ -29,6 +29,10 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.grid.GridItemSpan
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.layout.width
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
@@ -92,6 +96,9 @@ fun LibraryScreen(
onCreatePlaylist: () -> Unit = {},
/** Long press: rename and delete live in a sheet, like a track's actions. */
onPlaylistMenu: (CatalogPlaylist) -> Unit = {},
+ /** The artists the account follows; empty leaves the shelf out entirely. */
+ artists: List<dev.lelonio.square.data.SearchItem> = emptyList(),
+ onOpenArtist: (dev.lelonio.square.data.SearchItem) -> Unit = {},
backdrop: Backdrop,
) {
when (state) {
@@ -172,6 +179,12 @@ fun LibraryScreen(
verticalArrangement = Arrangement.spacedBy(18.dp),
modifier = Modifier.fillMaxSize(),
) {
+ if (artists.isNotEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }, key = "artists") {
+ ArtistShelf(artists, onOpenArtist)
+ }
+ }
+
items(playlists, key = { it.uri }) { playlist ->
GridTile(
playlist,
@@ -191,6 +204,10 @@ fun LibraryScreen(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.fillMaxSize(),
) {
+ if (artists.isNotEmpty()) {
+ item(key = "artists") { ArtistShelf(artists, onOpenArtist) }
+ }
+
items(playlists, key = { it.uri }) { playlist ->
ListRow(
playlist,
@@ -433,3 +450,56 @@ private fun Centered(content: @Composable () -> Unit) {
/** A harder film for the chip that is on, matching the home page. */
private val SelectedFilm = Color.White.copy(alpha = 0.26f)
+
+/**
+ * The artists the account follows, along the top of the library.
+ *
+ * Round, and in a row that scrolls sideways: it is the shape Spotify made mean
+ * "a person" and the one that keeps a long list from pushing the playlists off
+ * the screen. Part of the list rather than pinned above it, so it scrolls away
+ * with everything else — a shelf that will not leave is a shelf in the way.
+ */
+@Composable
+private fun ArtistShelf(
+ artists: List<dev.lelonio.square.data.SearchItem>,
+ onOpen: (dev.lelonio.square.data.SearchItem) -> Unit,
+) {
+ Column(Modifier.padding(bottom = 18.dp)) {
+ Text(
+ stringResource(R.string.artists_you_follow),
+ style = MaterialTheme.typography.titleSmall,
+ color = Ink,
+ modifier = Modifier.padding(start = 4.dp, bottom = 10.dp),
+ )
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ items(artists, key = { it.uri }) { artist ->
+ Column(
+ Modifier
+ .width(76.dp)
+ .pressable({ onOpen(artist) }),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ ) {
+ Artwork(
+ url = artist.artworkUrl,
+ title = artist.title,
+ modifier = Modifier
+ .size(72.dp)
+ .clip(CircleShape)
+ .softShadow(CircleShape, elevation = 10.dp),
+ corner = 36.dp,
+ decodeSize = 72.dp,
+ )
+ Text(
+ artist.title,
+ style = MaterialTheme.typography.labelMedium,
+ color = Ink,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.padding(top = 8.dp),
+ )
+ }
+ }
+ }
+ }
+}
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.kt
index c966087..690e894 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
@@ -5,6 +5,7 @@ import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -79,6 +80,7 @@ import dev.lelonio.square.ui.components.LazyScrollBar
import dev.lelonio.square.ui.components.SwipeToQueue
import dev.lelonio.square.ui.glass.LiquidButton
import dev.lelonio.square.ui.glass.pressable
+import dev.lelonio.square.ui.theme.InkDim
import dev.lelonio.square.ui.theme.rememberArtworkColor
import dev.lelonio.square.ui.theme.softShadow
import java.util.Locale
@@ -134,6 +136,8 @@ fun PlaylistScreen(
*/
onTrackMenu: (CatalogTrack) -> Unit,
onOpenItem: (dev.lelonio.square.data.SearchItem) -> Unit = {},
+ /** Follows or unfollows the artist this page is about. */
+ onToggleFollow: () -> Unit = {},
/** The remembered track order, and where a change to it is stored. */
storedSort: String? = null,
onSortChange: (String) -> Unit = {},
@@ -302,9 +306,14 @@ fun PlaylistScreen(
.nestedScroll(headerScroll),
contentPadding = PaddingValues(bottom = contentPadding.calculateBottomPadding()),
) {
- if (state.albums.isNotEmpty()) {
- item(contentType = "albums") {
- AlbumStrip(albums = state.albums, onOpen = onOpenItem)
+ if (state.kind == MainViewModel.DetailKind.ARTIST) {
+ item(contentType = "artistAbout") {
+ ArtistAbout(
+ followers = state.followers,
+ genres = state.genres,
+ following = state.following,
+ onToggleFollow = onToggleFollow,
+ )
}
}
@@ -391,6 +400,53 @@ fun PlaylistScreen(
}
}
+ // Everything the artist is in, under the songs they are known for.
+ //
+ // The tracks come first because that is what an artist page is
+ // opened for: a shelf of covers above them made the reader scroll
+ // past the artist to reach the artist. Albums, then singles, then
+ // the records that are somebody else's, then what Spotify built
+ // around them — the order is how much of the artist is in each.
+ if (state.albums.isNotEmpty()) {
+ item(contentType = "albums") {
+ AlbumStrip(
+ albums = state.albums,
+ title = stringResource(R.string.albums),
+ onOpen = onOpenItem,
+ )
+ }
+ }
+
+ if (state.singles.isNotEmpty()) {
+ item(contentType = "singles") {
+ AlbumStrip(
+ albums = state.singles,
+ title = stringResource(R.string.singles_and_eps),
+ onOpen = onOpenItem,
+ )
+ }
+ }
+
+ if (state.appearsOn.isNotEmpty()) {
+ item(contentType = "appearsOn") {
+ AlbumStrip(
+ albums = state.appearsOn,
+ title = stringResource(R.string.appears_on),
+ onOpen = onOpenItem,
+ )
+ }
+ }
+
+ if (state.artistPlaylists.isNotEmpty()) {
+ item(contentType = "artistPlaylists") {
+ AlbumStrip(
+ albums = state.artistPlaylists,
+ title = stringResource(R.string.artist_playlists),
+ onOpen = onOpenItem,
+ )
+ }
+ }
+
// A long playlist arrives a batch at a time and this is the tail of
// it still coming. Deliberately quiet: the list above is already
// readable and playable, and a spinner in the middle of the screen
@@ -756,11 +812,12 @@ private fun CircleAction(
@Composable
private fun AlbumStrip(
albums: List<dev.lelonio.square.data.SearchItem>,
+ title: String,
onOpen: (dev.lelonio.square.data.SearchItem) -> Unit,
) {
Column(Modifier.padding(top = 18.dp)) {
Text(
- stringResource(R.string.albums),
+ title,
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(start = 24.dp, bottom = 10.dp),
)
@@ -1025,3 +1082,81 @@ private fun formatTotal(ms: Long): String {
return if (hours > 0) stringResource(R.string.hours_minutes, hours, minutes)
else stringResource(R.string.minutes_only, minutes)
}
+
+/**
+ * Who the artist is, in the two facts Spotify itself leads with, and the one
+ * thing there is to do about them.
+ *
+ * The follower count is the only number on the page that says how big somebody
+ * is, and the genres are the only words: without them an artist page is a list
+ * of records that could belong to anyone. Both are quiet — this is a caption
+ * under a name, not a dashboard.
+ */
+@Composable
+private fun ArtistAbout(
+ followers: Int,
+ genres: List<String>,
+ following: Boolean?,
+ onToggleFollow: () -> Unit,
+) {
+ Column(Modifier.padding(start = 24.dp, end = 24.dp, top = 14.dp)) {
+ val line = listOfNotNull(
+ followers.takeIf { it > 0 }?.let { stringResource(R.string.followers_count, compact(it)) },
+ genres.take(2).joinToString(" · ") { it.replaceFirstChar(Char::uppercase) }
+ .takeIf { it.isNotEmpty() },
+ ).joinToString(" · ")
+
+ if (line.isNotEmpty()) {
+ Text(
+ line,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
+
+ // Absent until the answer is known: see PlaylistState.following.
+ if (following != null) {
+ val shape = RoundedCornerShape(percent = 50)
+ Row(
+ Modifier
+ .padding(top = 12.dp)
+ .clip(shape)
+ .background(
+ if (following) Color.Transparent else Color.White,
+ shape,
+ )
+ .then(
+ if (following) {
+ Modifier.border(1.dp, Color.White.copy(alpha = 0.4f), shape)
+ } else {
+ Modifier
+ },
+ )
+ .pressable(onToggleFollow, pressedScale = 0.94f)
+ .padding(horizontal = 20.dp, vertical = 9.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ stringResource(if (following) R.string.following else R.string.follow),
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = FontWeight.SemiBold,
+ color = if (following) Color.White else Color.Black,
+ )
+ }
+ }
+ }
+}
+
+/**
+ * A follower count as somebody would say it out loud: 1,2 Mln, 340 mila.
+ *
+ * Spotify shows the exact number and nobody reads it; what the digits are for
+ * is the order of magnitude, and seven of them take a line to say what two do.
+ */
+private fun compact(count: Int): String = when {
+ count >= 1_000_000 -> String.format("%.1fM", count / 1_000_000f)
+ count >= 1_000 -> "${count / 1_000}K"
+ else -> count.toString()
+}
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.kt
index 0772f76..0ad3426 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
@@ -276,6 +276,38 @@ fun SettingsScreen(
}
}
+ if (open == SettingsPage.App && android.os.Build.VERSION.SDK_INT >= 31) {
+ item("links") {
+ Section(stringResource(R.string.spotify_links)) {
+ Text(
+ stringResource(R.string.spotify_links_note),
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
+ )
+ RowDivider()
+ ActionRow(
+ stringResource(R.string.open_by_default),
+ destructive = false,
+ ) {
+ // Android's own screen, because this is Android's own
+ // decision: an app cannot claim a domain it does not
+ // own, and the listener granting it here is the whole
+ // point of the design.
+ runCatching {
+ context.startActivity(
+ android.content.Intent(
+ android.provider.Settings
+ .ACTION_APP_OPEN_BY_DEFAULT_SETTINGS,
+ android.net.Uri.parse("package:${context.packageName}"),
+ ),
+ )
+ }
+ }
+ }
+ }
+ }
+
if (open == SettingsPage.About) item("permissions") {
Section(stringResource(R.string.permissions_asked)) {
Text(
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index b7a3052..92eeb35 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -130,6 +130,23 @@
<string name="scope_private_playlists">Zu privaten Playlists hinzufügen</string>
<string name="scope_public_playlists">Zu öffentlichen Playlists hinzufügen</string>
<string name="enter_client_id">Gib die Client ID ein.</string>
+ <string name="artist_playlists">Playlists mit diesem Künstler</string>
+ <string name="singles_and_eps">Singles und EPs</string>
+ <string name="appears_on">Mit dabei auf</string>
+ <string name="followers_count">%1$s Follower</string>
+ <string name="follow">Folgen</string>
+ <string name="following">Folge ich</string>
+ <string name="artists_you_follow">Künstler, denen du folgst</string>
+ <string name="friends_listening">Freunde</string>
+ <string name="friends_none">Gerade hört niemand, oder niemand, dem du folgst, teilt was er spielt.</string>
+ <string name="just_now">Gerade eben</string>
+ <string name="minutes_ago">vor %1$d Min</string>
+ <string name="hours_ago">vor %1$d Std</string>
+ <string name="days_ago">vor %1$d T</string>
+ <string name="shared_song">GETEILTER SONG</string>
+ <string name="spotify_links">Spotify-Links</string>
+ <string name="spotify_links_note">Links zu Titeln, Alben, Playlists und Künstlern können sich hier öffnen. Android fragt einmal danach, auf seinem eigenen Bildschirm.</string>
+ <string name="open_by_default">Standardmäßig öffnen</string>
<string name="web_api_expired_title">Sitzung abgelaufen</string>
<string name="web_api_expired_body">Melde dich wieder bei deiner Spotify-Anwendung an, damit Suche und Startseite zurückkommen.</string>
<string name="web_api_expired_action">Erneut anmelden</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 92961f2..67387f6 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -130,6 +130,23 @@
<string name="scope_private_playlists">Añadir a playlists privadas</string>
<string name="scope_public_playlists">Añadir a playlists públicas</string>
<string name="enter_client_id">Introduce el client ID.</string>
+ <string name="artist_playlists">Listas con este artista</string>
+ <string name="singles_and_eps">Sencillos y EP</string>
+ <string name="appears_on">Aparece en</string>
+ <string name="followers_count">%1$s seguidores</string>
+ <string name="follow">Seguir</string>
+ <string name="following">Siguiendo</string>
+ <string name="artists_you_follow">Artistas que sigues</string>
+ <string name="friends_listening">Amigos</string>
+ <string name="friends_none">Nadie está escuchando ahora, o nadie a quien sigues comparte lo que reproduce.</string>
+ <string name="just_now">Ahora</string>
+ <string name="minutes_ago">hace %1$d min</string>
+ <string name="hours_ago">hace %1$d h</string>
+ <string name="days_ago">hace %1$d d</string>
+ <string name="shared_song">CANCIÓN COMPARTIDA</string>
+ <string name="spotify_links">Enlaces de Spotify</string>
+ <string name="spotify_links_note">Los enlaces a canciones, álbumes, listas y artistas pueden abrirse aquí. Android lo pregunta una vez, en su propia pantalla.</string>
+ <string name="open_by_default">Abrir de forma predeterminada</string>
<string name="web_api_expired_title">Sesión caducada</string>
<string name="web_api_expired_body">Vuelve a iniciar sesión en tu aplicación de Spotify para recuperar la búsqueda y el inicio.</string>
<string name="web_api_expired_action">Iniciar sesión</string>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index e7ab32f..cbfb3fb 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -130,6 +130,23 @@
<string name="scope_private_playlists">Ajouter aux playlists privées</string>
<string name="scope_public_playlists">Ajouter aux playlists publiques</string>
<string name="enter_client_id">Saisissez le client ID.</string>
+ <string name="artist_playlists">Playlists avec cet artiste</string>
+ <string name="singles_and_eps">Singles et EP</string>
+ <string name="appears_on">Apparaît sur</string>
+ <string name="followers_count">%1$s abonnés</string>
+ <string name="follow">Suivre</string>
+ <string name="following">Abonné</string>
+ <string name="artists_you_follow">Artistes que vous suivez</string>
+ <string name="friends_listening">Amis</string>
+ <string name="friends_none">Personne n’écoute en ce moment, ou personne que vous suivez ne partage ce qu’il joue.</string>
+ <string name="just_now">À l’instant</string>
+ <string name="minutes_ago">il y a %1$d min</string>
+ <string name="hours_ago">il y a %1$d h</string>
+ <string name="days_ago">il y a %1$d j</string>
+ <string name="shared_song">TITRE PARTAGÉ</string>
+ <string name="spotify_links">Liens Spotify</string>
+ <string name="spotify_links_note">Les liens vers des titres, albums, playlists et artistes peuvent s’ouvrir ici. Android le demande une fois, sur son propre écran.</string>
+ <string name="open_by_default">Ouvrir par défaut</string>
<string name="web_api_expired_title">Session expirée</string>
<string name="web_api_expired_body">Reconnectez-vous à votre application Spotify pour retrouver la recherche et l’accueil.</string>
<string name="web_api_expired_action">Se reconnecter</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index 76965ad..0485f32 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -142,6 +142,23 @@
<string name="scope_private_playlists">निजी प्लेलिस्ट में जोड़ना</string>
<string name="scope_public_playlists">सार्वजनिक प्लेलिस्ट में जोड़ना</string>
<string name="enter_client_id">क्लाइंट आईडी डालें।</string>
+ <string name="artist_playlists">इस कलाकार की प्लेलिस्ट</string>
+ <string name="singles_and_eps">सिंगल और EP</string>
+ <string name="appears_on">इनमें शामिल</string>
+ <string name="followers_count">%1$s फ़ॉलोअर</string>
+ <string name="follow">फ़ॉलो करें</string>
+ <string name="following">फ़ॉलो किया</string>
+ <string name="artists_you_follow">आपके फ़ॉलो किए कलाकार</string>
+ <string name="friends_listening">दोस्त</string>
+ <string name="friends_none">अभी कोई नहीं सुन रहा, या आप जिन्हें फ़ॉलो करते हैं वे अपना संगीत साझा नहीं करते।</string>
+ <string name="just_now">अभी</string>
+ <string name="minutes_ago">%1$d मिनट पहले</string>
+ <string name="hours_ago">%1$d घंटे पहले</string>
+ <string name="days_ago">%1$d दिन पहले</string>
+ <string name="shared_song">साझा किया गया गाना</string>
+ <string name="spotify_links">Spotify लिंक</string>
+ <string name="spotify_links_note">ट्रैक, ऐल्बम, प्लेलिस्ट और कलाकार के लिंक यहीं खुल सकते हैं। Android इसकी अनुमति अपनी स्क्रीन पर एक बार पूछता है।</string>
+ <string name="open_by_default">डिफ़ॉल्ट रूप से खोलें</string>
<string name="web_api_expired_title">सत्र समाप्त हो गया</string>
<string name="web_api_expired_body">खोज और होम वापस पाने के लिए अपने Spotify ऐप्लिकेशन में फिर से साइन इन करें।</string>
<string name="web_api_expired_action">फिर से साइन इन करें</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 92bea79..1dd8c57 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -131,6 +131,23 @@
<string name="scope_private_playlists">Aggiungi a playlist private</string>
<string name="scope_public_playlists">Aggiungi a playlist pubbliche</string>
<string name="enter_client_id">Inserisci il client id.</string>
+ <string name="artist_playlists">Playlist con questo artista</string>
+ <string name="singles_and_eps">Singoli ed EP</string>
+ <string name="appears_on">Compare in</string>
+ <string name="followers_count">%1$s follower</string>
+ <string name="follow">Segui</string>
+ <string name="following">Segui già</string>
+ <string name="artists_you_follow">Artisti che segui</string>
+ <string name="friends_listening">Amici</string>
+ <string name="friends_none">Nessuno sta ascoltando ora, o nessuno che segui condivide quello che riproduce.</string>
+ <string name="just_now">Adesso</string>
+ <string name="minutes_ago">%1$d min fa</string>
+ <string name="hours_ago">%1$d h fa</string>
+ <string name="days_ago">%1$d g fa</string>
+ <string name="shared_song">BRANO CONDIVISO</string>
+ <string name="spotify_links">Link Spotify</string>
+ <string name="spotify_links_note">I link a brani, album, playlist e artisti possono aprirsi qui. Android chiede il permesso una volta, dalla sua schermata.</string>
+ <string name="open_by_default">Apertura predefinita</string>
<string name="web_api_expired_title">Sessione scaduta</string>
<string name="web_api_expired_body">Accedi di nuovo alla tua applicazione Spotify per riavere ricerca e home.</string>
<string name="web_api_expired_action">Accedi di nuovo</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index d6604e9..f6425fe 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -130,6 +130,23 @@
<string name="scope_private_playlists">Adicionar a playlists privadas</string>
<string name="scope_public_playlists">Adicionar a playlists públicas</string>
<string name="enter_client_id">Informe o client ID.</string>
+ <string name="artist_playlists">Playlists com este artista</string>
+ <string name="singles_and_eps">Singles e EP</string>
+ <string name="appears_on">Aparece em</string>
+ <string name="followers_count">%1$s seguidores</string>
+ <string name="follow">Seguir</string>
+ <string name="following">A seguir</string>
+ <string name="artists_you_follow">Artistas que segue</string>
+ <string name="friends_listening">Amigos</string>
+ <string name="friends_none">Ninguém está a ouvir agora, ou ninguém que segue partilha o que reproduz.</string>
+ <string name="just_now">Agora</string>
+ <string name="minutes_ago">há %1$d min</string>
+ <string name="hours_ago">há %1$d h</string>
+ <string name="days_ago">há %1$d d</string>
+ <string name="shared_song">MÚSICA PARTILHADA</string>
+ <string name="spotify_links">Links do Spotify</string>
+ <string name="spotify_links_note">Links de músicas, álbuns, playlists e artistas podem abrir aqui. O Android pede permissão uma vez, na tela dele.</string>
+ <string name="open_by_default">Abrir por padrão</string>
<string name="web_api_expired_title">Sessão expirada</string>
<string name="web_api_expired_body">Entre novamente na sua aplicação do Spotify para ter de volta a busca e o início.</string>
<string name="web_api_expired_action">Entrar de novo</string>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index 344ae4a..4a2fcae 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -142,6 +142,23 @@
<string name="scope_private_playlists">Özel çalma listelerine ekleme</string>
<string name="scope_public_playlists">Herkese açık listelere ekleme</string>
<string name="enter_client_id">İstemci kimliğini gir.</string>
+ <string name="artist_playlists">Bu sanatçının çalma listeleri</string>
+ <string name="singles_and_eps">Single ve EP</string>
+ <string name="appears_on">Yer aldığı albümler</string>
+ <string name="followers_count">%1$s takipçi</string>
+ <string name="follow">Takip et</string>
+ <string name="following">Takip ediliyor</string>
+ <string name="artists_you_follow">Takip ettiğin sanatçılar</string>
+ <string name="friends_listening">Arkadaşlar</string>
+ <string name="friends_none">Şu anda kimse dinlemiyor ya da takip ettiğin kimse ne çaldığını paylaşmıyor.</string>
+ <string name="just_now">Az önce</string>
+ <string name="minutes_ago">%1$d dk önce</string>
+ <string name="hours_ago">%1$d sa önce</string>
+ <string name="days_ago">%1$d g önce</string>
+ <string name="shared_song">PAYLAŞILAN PARÇA</string>
+ <string name="spotify_links">Spotify bağlantıları</string>
+ <string name="spotify_links_note">Parça, albüm, çalma listesi ve sanatçı bağlantıları burada açılabilir. Android bunu kendi ekranında bir kez sorar.</string>
+ <string name="open_by_default">Varsayılan olarak aç</string>
<string name="web_api_expired_title">Oturum sona erdi</string>
<string name="web_api_expired_body">Arama ve ana sayfanın geri gelmesi için Spotify uygulamana yeniden giriş yap.</string>
<string name="web_api_expired_action">Yeniden giriş yap</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 6094ea3..50057c6 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -148,6 +148,23 @@
<string name="scope_private_playlists">Add to private playlists</string>
<string name="scope_public_playlists">Add to public playlists</string>
<string name="enter_client_id">Enter the client ID.</string>
+ <string name="artist_playlists">Playlists with this artist</string>
+ <string name="singles_and_eps">Singles and EPs</string>
+ <string name="appears_on">Appears on</string>
+ <string name="followers_count">%1$s followers</string>
+ <string name="follow">Follow</string>
+ <string name="following">Following</string>
+ <string name="artists_you_follow">Artists you follow</string>
+ <string name="friends_listening">Friends</string>
+ <string name="friends_none">Nobody is listening right now, or nobody you follow shares what they play.</string>
+ <string name="just_now">Just now</string>
+ <string name="minutes_ago">%1$d min ago</string>
+ <string name="hours_ago">%1$d h ago</string>
+ <string name="days_ago">%1$d d ago</string>
+ <string name="shared_song">SHARED SONG</string>
+ <string name="spotify_links">Spotify links</string>
+ <string name="spotify_links_note">Links to tracks, albums, playlists and artists can open here. Android asks you to allow it once, on its own screen.</string>
+ <string name="open_by_default">Open by default</string>
<string name="web_api_expired_title">Session expired</string>
<string name="web_api_expired_body">Sign in to your Spotify application again to bring search and the home page back.</string>
<string name="web_api_expired_action">Sign in again</string>
diff --git a/native/src/catalog.rs b/native/src/catalog.rs
index 5b4fbda..737e24f 100644
--- a/native/src/catalog.rs
+++ b/native/src/catalog.rs
@@ -95,6 +95,24 @@ pub fn lyrics(track_uri: &str) -> EngineResult<String> {
})
}
+/// What the people this account follows are listening to, as the access point's
+/// own JSON.
+///
+/// The endpoint behind Spotify's "Friend Activity": one entry per friend, each
+/// with the user, the track, and when they were last heard from.
+pub fn friend_activity() -> EngineResult<String> {
+ let session = with_session(|s| s.clone())?;
+ block_on(async move {
+ let bytes = session
+ .spclient()
+ .request_as_json(&Method::GET, "/presence-view/v1/buddylist", None, None)
+ .await
+ .map_err(|e| format!("buddylist failed: {e}"))?;
+
+ Ok(String::from_utf8(bytes.to_vec()).unwrap_or_else(|_| "null".into()))
+ })
+}
+
/// Track URIs belonging to a context — a playlist, album, or the collection.
///
/// A context can arrive with its pages already filled or as a set of links to
@@ -353,6 +371,33 @@ pub fn playlist_cover(uri: &str) -> EngineResult<String> {
})
}
+/// The title of one playlist, or `null`.
+///
+/// For a playlist arriving as a link there is nowhere else to read it: the
+/// rootlist only holds what the account follows, and the Web API answers 404 for
+/// everything Spotify generates itself. The access point knows them all.
+pub fn playlist_name(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 name = list.attributes.name().trim().to_string();
+ Ok(json!(if name.is_empty() { None } else { Some(name) }).to_string())
+ })
+}
+
/// Accepts either a URL or a `spotify:image:<hex>` URI, and returns a URL.
fn cdn_url(value: &str) -> Option<String> {
if value.is_empty() {
diff --git a/native/src/ffi.rs b/native/src/ffi.rs
index a6cb38a..5b52f29 100644
--- a/native/src/ffi.rs
+++ b/native/src/ffi.rs
@@ -361,6 +361,30 @@ pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeCon
}
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativeFriendActivity(
+ mut env: JNIEnv,
+ _class: JClass,
+) -> jstring {
+ guard_string(&mut env, "FriendActivity", catalog::friend_activity)
+}
+
+#[no_mangle]
+pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaylistName(
+ 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, "PlaylistName", || catalog::playlist_name(&uri))
+}
+
#[no_mangle]
pub extern "system" fn Java_dev_lelonio_square_nativecore_NativeBridge_nativePlaylistCover(
mut env: JNIEnv,