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.

Find a song by the words inside it

Lelonio2efb01ef39d3
diff --git a/app/src/main/java/dev/lelonio/square/SquareApplication.kt b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
index 29e6e6e..f85c1f8 100644
--- a/app/src/main/java/dev/lelonio/square/SquareApplication.kt
+++ b/app/src/main/java/dev/lelonio/square/SquareApplication.kt
@@ -52,6 +52,11 @@ class SquareApplication : Application() {
dev.lelonio.square.auth.EngineCredentials.exist(this)
val recentStore: RecentStore by lazy { RecentStore(this) }
+ /** Songs found by searching and then played; see [SearchHistoryStore]. */
+ val searchHistory: dev.lelonio.square.data.SearchHistoryStore by lazy {
+ dev.lelonio.square.data.SearchHistoryStore(this)
+ }
+
/** Which playlists were opened most recently, for ordering the home page. */
val playlistOrder: PlaylistOrderStore by lazy { PlaylistOrderStore(this) }
diff --git a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
index c6b133f..961490f 100644
--- a/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/MusicBackend.kt
@@ -69,6 +69,15 @@ interface MusicBackend {
suspend fun search(query: String, labels: SearchLabels): SearchResults
+ /**
+ * Whether the last search had nowhere to go.
+ *
+ * Only Spotify can be in this state, and only when the gateway will not
+ * answer and no application has been registered either — the one case
+ * where the screen has something to offer instead of an empty page.
+ */
+ val searchNeedsSetup: Boolean get() = false
+
/** The signed-in account's own playlists; empty when logged out or unsupported. */
suspend fun playlists(): List<CatalogPlaylist>
diff --git a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
index 9efd970..94cf328 100644
--- a/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
+++ b/app/src/main/java/dev/lelonio/square/backend/SpotifyBackend.kt
@@ -34,6 +34,9 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
override val id = BackendId.SPOTIFY
+ override var searchNeedsSetup: Boolean = false
+ private set
+
private val _authState = MutableStateFlow<BackendAuthState>(
if (container.spotifySignedIn) BackendAuthState.Connecting else BackendAuthState.LoggedOut,
)
@@ -66,13 +69,34 @@ class SpotifyBackend(private val container: SquareApplication) : MusicBackend {
}
/**
- * Search goes through the user's own registered application; see
- * [dev.lelonio.square.auth.WebApiAccount] for why it cannot use the
- * playback session's client id.
+ * Spotify's own search, with the Web API behind it.
+ *
+ * The gateway first, for two reasons. It searches the way Spotify's own
+ * clients do, which includes the words *inside* a song — type a line you
+ * remember and the song is the first result — and it answers anyone who is
+ * signed in, where the Web API wants an application the listener has to
+ * register for themselves.
+ *
+ * What it does not offer is any promise of being there tomorrow: the query
+ * is addressed by a hash Spotify retires whenever it rebuilds its web
+ * client. So the registered application stays as the fallback, and a search
+ * only fails when both have nothing; see [dev.lelonio.square.data.Gateway].
*/
override suspend fun search(query: String, labels: SearchLabels): SearchResults {
- if (!container.webApi.isReady) return SearchResults()
- return container.api.search(query.trim()).toResults(
+ val term = query.trim()
+ container.gateway.search(term)
+ ?.let { dev.lelonio.square.data.GatewaySearch.parse(it, labels) }
+ ?.let {
+ searchNeedsSetup = false
+ return it
+ }
+
+ if (!container.webApi.isReady) {
+ searchNeedsSetup = true
+ return SearchResults()
+ }
+ searchNeedsSetup = false
+ return container.api.search(term).toResults(
artistLabel = labels.artist,
albumLabel = labels.album,
playlistLabel = labels.playlist,
diff --git a/app/src/main/java/dev/lelonio/square/data/Gateway.kt b/app/src/main/java/dev/lelonio/square/data/Gateway.kt
index e5e8e57..907fd9c 100644
--- a/app/src/main/java/dev/lelonio/square/data/Gateway.kt
+++ b/app/src/main/java/dev/lelonio/square/data/Gateway.kt
@@ -72,6 +72,47 @@ class Gateway(private val keys: PathfinderKeys) {
.getOrNull()
}
+ /**
+ * Everything the search box asks for, in one query.
+ *
+ * The reason to ask here rather than the Web API is not the quota this
+ * time: Spotify's own search reads the words as a listener would, so a line
+ * of a song finds the song. "Is this the real life" answers with Bohemian
+ * Rhapsody, which no amount of matching titles and artist names will ever
+ * do. It also means a search works for anyone signed in, with no registered
+ * application of their own.
+ *
+ * Null when the gateway will not answer, and the Web API is where the
+ * caller goes then; see SpotifyBackend.
+ */
+ suspend fun search(term: String): String? {
+ if (term.isBlank()) return null
+ keys.refresh()
+ val quoted = org.json.JSONObject.quote(term)
+ return runCatching {
+ query(
+ operation = "searchDesktop",
+ hash = keys.search,
+ // Exactly what the web player asks, values included.
+ //
+ // Not a detail. A query nobody else sends — twenty of every
+ // kind, audiobooks turned off, fields left out — is a caller
+ // that stands out from every other caller of the same query,
+ // and standing out is the one thing this app should never do
+ // here. Ten and five is the web player's own page size, so an
+ // hour of searching from this app reads like an hour of
+ // searching from a browser tab.
+ variables = """{"searchTerm":$quoted,"offset":0,"limit":$SEARCH_LIMIT,""" +
+ """"numberOfTopResults":$TOP_RESULTS,"includeAudiobooks":true,""" +
+ """"includeArtistHasConcertsField":false,"includePreReleases":true,""" +
+ """"includeLocalConcertsField":false,"includeAlbumPreReleases":false,""" +
+ """"includeAuthors":false,"includeEpisodeContentRatingsV2":false}""",
+ )
+ }
+ .onFailure { android.util.Log.i(TAG, "gateway search unavailable: ${it.message}") }
+ .getOrNull()
+ }
+
/**
* Reads a list to its end.
*
@@ -131,5 +172,11 @@ class Gateway(private val keys: PathfinderKeys) {
* maximum for the same lists is a hundred, and fifty for the library.
*/
const val PAGE = 200
+
+ /** What one page of each kind of search result holds, as the web player asks. */
+ const val SEARCH_LIMIT = 10
+
+ /** And how many of the best of everything it asks for; see [search]. */
+ const val TOP_RESULTS = 5
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt b/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt
new file mode 100644
index 0000000..1836f87
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/GatewaySearch.kt
@@ -0,0 +1,117 @@
+package dev.lelonio.square.data
+
+import dev.lelonio.square.backend.SearchLabels
+import org.json.JSONArray
+import org.json.JSONObject
+
+/**
+ * A search as Spotify's own gateway answers it.
+ *
+ * The same shape the Web API path produces, from a different and better
+ * source: this one reads the words the way the listener meant them, so a line
+ * of a song finds the song rather than the handful of tracks that happen to
+ * have those words in their titles. See [Gateway.search].
+ *
+ * Forgiving throughout, like everything else that reads this gateway: a
+ * section that is missing, or an item shaped in a way nobody here recognises,
+ * is left out rather than treated as a failure. Half an answer is worth
+ * showing; there is nothing else to show.
+ */
+internal object GatewaySearch {
+
+ /**
+ * Null only when the gateway did not answer this question at all.
+ *
+ * An answer with nothing in it is still an answer — somebody searched for
+ * something that is not there — and returning null for it would send the
+ * caller off to ask the Web API the same question, or tell a listener with
+ * no registered application that they have to go and register one.
+ */
+ fun parse(raw: String, labels: SearchLabels): SearchResults? {
+ val search = runCatching {
+ JSONObject(raw).getJSONObject("data").getJSONObject("searchV2")
+ }.getOrNull() ?: return null
+
+ val matches = search.items("tracksV2")
+ val lyricMatches = matches.mapNotNullTo(mutableSetOf()) { wrapper ->
+ wrapper.optJSONArray("matchedFields")
+ ?.takeIf { fields ->
+ (0 until fields.length()).any { fields.optString(it) == LYRICS }
+ }
+ ?.let { wrapper.optJSONObject("item")?.optJSONObject("data")?.optString("uri") }
+ ?.takeIf { it.isNotEmpty() }
+ }
+
+ return SearchResults(
+ tracks = matches.mapNotNull { wrapper ->
+ // A track sits one level deeper than everything else: the
+ // section holds a match, and the match holds the track.
+ GatewayTracks.track(wrapper.optJSONObject("item")?.optJSONObject("data"), null)
+ },
+ artists = search.items("artists").mapNotNull { wrapper ->
+ val data = wrapper.optJSONObject("data") ?: return@mapNotNull null
+ SearchItem(
+ uri = data.uriOf("spotify:artist:") ?: return@mapNotNull null,
+ title = data.optJSONObject("profile")?.optString("name").orEmpty(),
+ subtitle = labels.artist,
+ artworkUrl = data.optJSONObject("visuals")
+ ?.optJSONObject("avatarImage").best(),
+ )
+ },
+ albums = search.items("albumsV2").mapNotNull { wrapper ->
+ val data = wrapper.optJSONObject("data") ?: return@mapNotNull null
+ SearchItem(
+ uri = data.uriOf("spotify:album:") ?: return@mapNotNull null,
+ title = data.optString("name"),
+ subtitle = labels.album,
+ artworkUrl = data.optJSONObject("coverArt").best(),
+ )
+ },
+ playlists = search.items("playlists").mapNotNull { wrapper ->
+ val data = wrapper.optJSONObject("data") ?: return@mapNotNull null
+ SearchItem(
+ uri = data.uriOf("spotify:playlist:") ?: return@mapNotNull null,
+ title = data.optString("name"),
+ subtitle = labels.playlist,
+ artworkUrl = data.optJSONObject("images")
+ ?.optJSONArray("items")?.optJSONObject(0).best(),
+ )
+ },
+ lyricMatches = lyricMatches,
+ )
+ }
+
+ /** What Spotify calls a match on the words inside the song. */
+ private const val LYRICS = "LYRICS"
+
+ private fun JSONObject.items(section: String): List<JSONObject> {
+ val items: JSONArray = optJSONObject(section)?.optJSONArray("items") ?: return emptyList()
+ return (0 until items.length()).mapNotNull(items::optJSONObject)
+ }
+
+ /** Only the kind of thing this app can open; a wrapper can hold anything. */
+ private fun JSONObject.uriOf(prefix: String): String? =
+ optString("uri").takeIf { it.startsWith(prefix) }
+
+ /**
+ * The middle picture, or whatever there is.
+ *
+ * The sizes come in no particular order, and these rows are thumbnails, so
+ * a 640px cover for each of twenty results is a great deal of decoding
+ * nobody sees.
+ */
+ private fun JSONObject?.best(): String? {
+ val sources = this?.optJSONArray("sources") ?: return null
+ var fallback: String? = null
+ for (index in 0 until sources.length()) {
+ val source = sources.optJSONObject(index) ?: continue
+ val url = source.optString("url").takeIf { it.isNotEmpty() } ?: continue
+ if (source.optInt("width") in PREFERRED) return url
+ if (fallback == null) fallback = url
+ }
+ return fallback
+ }
+
+ /** What a row is drawn at, give or take: 300 for covers, 320 for faces. */
+ private val PREFERRED = 300..320
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
index da41ad9..4e29e29 100644
--- a/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
+++ b/app/src/main/java/dev/lelonio/square/data/PathfinderKeys.kt
@@ -43,6 +43,9 @@ class PathfinderKeys(context: Context) {
/** And for `areEntitiesInLibrary`, which answers the heart on a track. */
val library: String get() = prefs.getString(KEY_LIBRARY, null) ?: DEFAULT_LIBRARY
+ /** And for `searchDesktop`, which is what the search box asks. */
+ val search: String get() = prefs.getString(KEY_SEARCH, null) ?: DEFAULT_SEARCH
+
/** The web client version the gateway is told about. */
val appVersion: String get() = prefs.getString(KEY_VERSION, null) ?: DEFAULT_VERSION
@@ -71,6 +74,8 @@ class PathfinderKeys(context: Context) {
?.let { edit.putString(KEY_PLAYLIST, it) }
body.optString("library").takeIf { it.length == HASH_LENGTH }
?.let { edit.putString(KEY_LIBRARY, it) }
+ body.optString("search").takeIf { it.length == HASH_LENGTH }
+ ?.let { edit.putString(KEY_SEARCH, it) }
body.optString("appVersion").takeIf { it.isNotEmpty() }
?.let { edit.putString(KEY_VERSION, it) }
edit.apply()
@@ -85,6 +90,7 @@ class PathfinderKeys(context: Context) {
const val KEY_LIKED = "liked_songs"
const val KEY_PLAYLIST = "playlist"
const val KEY_LIBRARY = "library"
+ const val KEY_SEARCH = "search"
const val KEY_VERSION = "app_version"
const val KEY_CHECKED = "checked_at"
@@ -107,6 +113,8 @@ class PathfinderKeys(context: Context) {
"86dde7b9d9356e2369414647cf6950cfed96e778e129cfdfc99aea6c1613b3b0"
const val DEFAULT_LIBRARY =
"134337999233cc6fdd6b1e6dbf94841409f04a946c5c7b744b09ba0dfe5a85ed"
+ const val DEFAULT_SEARCH =
+ "db61238974d27839a136c9dc02bfdbe3fab7635f21cf85976ebff9a1ee281345"
const val DEFAULT_VERSION = "1.2.97.155.g5dd0dcaf-development"
}
}
diff --git a/app/src/main/java/dev/lelonio/square/data/SearchHistoryStore.kt b/app/src/main/java/dev/lelonio/square/data/SearchHistoryStore.kt
new file mode 100644
index 0000000..f58dfb3
--- /dev/null
+++ b/app/src/main/java/dev/lelonio/square/data/SearchHistoryStore.kt
@@ -0,0 +1,64 @@
+package dev.lelonio.square.data
+
+import android.content.Context
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+
+/**
+ * What was found by searching and then played, kept locally.
+ *
+ * Songs rather than the words typed to find them, which is the part worth
+ * keeping: half-typed terms and misspellings say nothing a week later, and the
+ * song they led to is the thing anyone actually wants back. It also means the
+ * list can be tapped — every row is a track, and playing it again is a tap
+ * rather than a search run a second time.
+ *
+ * Local, like [RecentStore], and for the same reason: nothing is sent anywhere
+ * and no quota is spent to keep it.
+ */
+class SearchHistoryStore(context: Context) {
+
+ private val prefs = context.applicationContext
+ .getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private val serializer = ListSerializer(CatalogTrack.serializer())
+
+ private val _tracks = MutableStateFlow(load())
+ val tracks: StateFlow<List<CatalogTrack>> = _tracks.asStateFlow()
+
+ /** Records a play, moving a repeat to the front rather than adding it twice. */
+ suspend fun record(track: CatalogTrack) = withContext(Dispatchers.IO) {
+ save((listOf(track) + _tracks.value.filterNot { it.uri == track.uri }).take(LIMIT))
+ }
+
+ /** Takes one song out, for a search somebody would rather not keep. */
+ suspend fun remove(uri: String) = withContext(Dispatchers.IO) {
+ save(_tracks.value.filterNot { it.uri == uri })
+ }
+
+ suspend fun clear() = withContext(Dispatchers.IO) { save(emptyList()) }
+
+ private fun save(tracks: List<CatalogTrack>) {
+ _tracks.value = tracks
+ prefs.edit().putString(KEY_TRACKS, json.encodeToString(serializer, tracks)).apply()
+ }
+
+ private fun load(): List<CatalogTrack> {
+ val raw = prefs.getString(KEY_TRACKS, null) ?: return emptyList()
+ return runCatching { json.decodeFromString(serializer, raw) }.getOrDefault(emptyList())
+ }
+
+ private companion object {
+ const val FILE_NAME = "square_search_history"
+ const val KEY_TRACKS = "tracks"
+
+ /** A screenful and a half; older than that and it is a different day. */
+ const val LIMIT = 20
+ }
+}
diff --git a/app/src/main/java/dev/lelonio/square/data/SearchResults.kt b/app/src/main/java/dev/lelonio/square/data/SearchResults.kt
index 8c2618a..4dda6b2 100644
--- a/app/src/main/java/dev/lelonio/square/data/SearchResults.kt
+++ b/app/src/main/java/dev/lelonio/square/data/SearchResults.kt
@@ -13,6 +13,15 @@ data class SearchResults(
val artists: List<SearchItem> = emptyList(),
val albums: List<SearchItem> = emptyList(),
val playlists: List<SearchItem> = emptyList(),
+ /**
+ * The tracks that were found by their words rather than their titles.
+ *
+ * Spotify says which those are — a match carries the fields it matched on
+ * — and it is worth showing: a list of songs whose names have nothing to
+ * do with what was typed looks like a broken search until the reason is on
+ * the row. Empty from the Web API, which does not search lyrics at all.
+ */
+ val lyricMatches: Set<String> = emptySet(),
) {
val isEmpty: Boolean
get() = tracks.isEmpty() && artists.isEmpty() && albums.isEmpty() && playlists.isEmpty()
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 0c56f76..d81244c 100644
--- a/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/MainViewModel.kt
@@ -33,6 +33,8 @@ import dev.lelonio.square.playback.EffectPreset
import dev.lelonio.square.playback.PlaybackService
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
+import kotlinx.coroutines.currentCoroutineContext
+import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableSharedFlow
@@ -763,19 +765,17 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
val results: SearchResults = SearchResults(),
val error: String? = null,
/**
- * False until the user has registered their own Spotify application.
- * Search cannot work without one, so the screen offers the setup instead
- * of a search box that would only ever answer 429.
+ * Set when a search had nowhere to go, so the screen can offer the way
+ * out instead of an empty page.
+ *
+ * Rare now: Spotify's own gateway answers anyone who is signed in, and
+ * only a retired query hash sends a search back to the registered
+ * application that used to be the only way in.
*/
val needsSetup: Boolean = false,
)
- private val _search = MutableStateFlow(
- SearchState(
- needsSetup = container.activeBackend.id == BackendId.SPOTIFY &&
- !container.webApi.isReady,
- ),
- )
+ private val _search = MutableStateFlow(SearchState())
val search: StateFlow<SearchState> = _search.asStateFlow()
private var searchJob: Job? = null
@@ -787,14 +787,11 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
*/
fun onSearchQuery(query: String) {
val backend = container.activeBackend
- // Only Spotify needs a registered application to search; YouTube Music
- // is anonymous, so the setup prompt would be asking for nothing.
- val ready = backend.id != BackendId.SPOTIFY || container.webApi.isReady
- _search.value = _search.value.copy(query = query, needsSetup = !ready)
+ _search.value = _search.value.copy(query = query)
searchJob?.cancel()
- if (query.isBlank() || !ready) {
- _search.value = SearchState(query = query, needsSetup = !ready)
+ if (query.isBlank()) {
+ _search.value = SearchState(query = query)
return
}
@@ -812,9 +809,23 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
)
}
.onSuccess { results ->
- _search.value = _search.value.copy(loading = false, results = results)
+ // The answer to a question nobody is asking any more is
+ // not shown: a slow search that was replaced while it ran
+ // would otherwise land on top of the newer one.
+ currentCoroutineContext().ensureActive()
+ _search.value = _search.value.copy(
+ loading = false,
+ results = results,
+ needsSetup = backend.searchNeedsSetup,
+ )
}
.onFailure {
+ // A cancelled search is not a failed one. Every keystroke
+ // cancels the one before it, and runCatching catches that
+ // like anything else — which put "StandaloneCoroutine was
+ // cancelled" on the page while the next search was already
+ // on its way.
+ if (it is kotlinx.coroutines.CancellationException) throw it
android.util.Log.e(TAG, "search failed: ${chain(it)}", it)
_search.value = _search.value.copy(loading = false, error = describe(it))
}
@@ -934,7 +945,8 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
fun disconnectWebApi() {
container.webApi.disconnect()
_webApi.value = _webApi.value.copy(connected = false, error = null)
- _search.value = _search.value.copy(needsSetup = true)
+ // Not needsSetup: search comes from Spotify's own gateway now, and
+ // giving up the registered application only gives up the fallback.
}
/**
@@ -1116,6 +1128,74 @@ class MainViewModel(app: Application) : AndroidViewModel(app) {
container.recentStore.record(track)
}
+ /**
+ * Songs found by searching and played, newest first.
+ *
+ * Filtered by the source in use, like [recent]: a Spotify track is not
+ * something the YouTube Music backend can play, and offering it would be
+ * offering a row that does nothing.
+ */
+ val searchHistory: StateFlow<List<CatalogTrack>> =
+ combine(container.searchHistory.tracks, container.preferences.backend) { tracks, _ ->
+ tracks.filter { container.activeBackend.owns(it.uri) }
+ }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
+
+ private val _credits =
+ MutableStateFlow<dev.lelonio.square.backend.spotify.SpotifyCredits.Credits?>(null)
+
+ /**
+ * Who made the track on screen, once somebody asks.
+ *
+ * Fetched when the panel is opened rather than with the track: it is a page
+ * most listeners never look at, and a request per song for it would be a
+ * request per song nobody wanted.
+ */
+ val credits: StateFlow<dev.lelonio.square.backend.spotify.SpotifyCredits.Credits?> =
+ _credits.asStateFlow()
+
+ private val _creditsLoading = MutableStateFlow(false)
+ val creditsLoading: StateFlow<Boolean> = _creditsLoading.asStateFlow()
+
+ private var creditsFor: String? = null
+ private var creditsJob: Job? = null
+
+ /** Asked for the open track; a repeat for the same one is free. */
+ fun loadCredits(trackUri: String?) {
+ if (trackUri == null || !trackUri.startsWith("spotify:track:")) {
+ creditsJob?.cancel()
+ creditsFor = null
+ _credits.value = null
+ _creditsLoading.value = false
+ return
+ }
+ if (creditsFor == trackUri && (_credits.value != null || _creditsLoading.value)) return
+
+ creditsJob?.cancel()
+ creditsFor = trackUri
+ _credits.value = null
+ _creditsLoading.value = true
+ creditsJob = viewModelScope.launch {
+ val found = dev.lelonio.square.backend.spotify.SpotifyCredits.of(trackUri)
+ if (creditsFor == trackUri) {
+ _credits.value = found
+ _creditsLoading.value = false
+ }
+ }
+ }
+
+ /** Called when a search result is played, rather than when a track starts. */
+ fun recordSearchPlay(track: CatalogTrack) = viewModelScope.launch {
+ container.searchHistory.record(track)
+ }
+
+ fun forgetSearchPlay(uri: String) = viewModelScope.launch {
+ container.searchHistory.remove(uri)
+ }
+
+ fun clearSearchHistory() = viewModelScope.launch {
+ container.searchHistory.clear()
+ }
+
init {
// Everything on screen belongs to one source, so a change of source
// starts the app's data over rather than patching it: the library, the
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 d4e696c..602ef7b 100644
--- a/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/SquareApp.kt
@@ -344,6 +344,7 @@ fun SquareApp(
val accent by rememberArtworkColor(playback.artworkUrl)
val recent by viewModel.recent.collectAsStateWithLifecycle()
val search by viewModel.search.collectAsStateWithLifecycle()
+ val searchHistory by viewModel.searchHistory.collectAsStateWithLifecycle()
val webApi by viewModel.webApi.collectAsStateWithLifecycle()
val reverb by AudioEffects.reverb.collectAsStateWithLifecycle()
val presets by viewModel.effectPresets.collectAsStateWithLifecycle()
@@ -953,8 +954,11 @@ fun SquareApp(
onClientIdChange = viewModel::onWebApiClientIdChange,
onConnectWebApi = { viewModel.connectWebApi() },
onPlayTrack = { tracks, index ->
+ tracks.getOrNull(index)?.let(viewModel::recordSearchPlay)
onPlay(tracks, index, null, false, searchLabel, 0L)
},
+ history = searchHistory,
+ onClearHistory = viewModel::clearSearchHistory,
onEnqueue = onEnqueue,
onTrackMenu = { track ->
trackMenu = TrackMenuRequest(
diff --git a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
index c688539..42a7a17 100644
--- a/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
+++ b/app/src/main/java/dev/lelonio/square/ui/search/SearchScreen.kt
@@ -79,6 +79,14 @@ fun SearchScreen(
onClientIdChange: (String) -> Unit,
onConnectWebApi: () -> Unit,
onPlayTrack: (List<CatalogTrack>, Int) -> Unit,
+ /**
+ * Songs found by searching and played before, newest first.
+ *
+ * Shown in place of the prompt on an empty box, which is where a list of
+ * things somebody already wanted belongs.
+ */
+ history: List<CatalogTrack>,
+ onClearHistory: () -> Unit,
onEnqueue: (CatalogTrack) -> Unit,
/** Opens the same track sheet the library rows open. */
onTrackMenu: (CatalogTrack) -> Unit,
@@ -117,10 +125,38 @@ fun SearchScreen(
StatusBox { Message(state.error) }
}
- state.query.isBlank() -> item(contentType = "status") {
+ state.query.isBlank() && history.isEmpty() -> item(contentType = "status") {
StatusBox { Message(stringResource(R.string.search_prompt)) }
}
+ state.query.isBlank() -> {
+ item(contentType = "history-title") {
+ HistoryTitle(onClear = onClearHistory)
+ }
+ items(
+ count = history.size,
+ key = { "history-${history[it].uri}" },
+ contentType = { "track" },
+ ) { index ->
+ val track = history[index]
+ SwipeToQueue(onQueue = { onEnqueue(track) }) {
+ ResultRow(
+ title = track.name,
+ subtitle = track.artist,
+ artworkUrl = track.artworkUrl,
+ highlighted = track.uri == nowPlayingUri,
+ round = false,
+ // The list itself is the queue, as a playlist would
+ // be: playing the third song leaves the two after it
+ // to follow.
+ onClick = { onPlayTrack(history, index) },
+ onMenu = { onTrackMenu(track) },
+ )
+ }
+ }
+ item(contentType = "tail") { Box(Modifier.height(24.dp)) }
+ }
+
state.results.isEmpty -> item(contentType = "status") {
StatusBox { Message(stringResource(R.string.no_results_for, state.query)) }
}
@@ -151,6 +187,8 @@ fun SearchScreen(
// share about it that the page does not do
// better.
onMenu = { onTrackMenu(track) },
+ badge = stringResource(R.string.lyrics_match)
+ .takeIf { track.uri in state.results.lyricMatches },
)
}
}
@@ -189,6 +227,7 @@ private fun KindRow(selected: Kind, backdrop: Backdrop, onSelect: (Kind) -> Unit
contentHeight = 38.dp,
contentPadding = 18.dp,
surfaceColor = if (isSelected) SelectedFilm else Color.Unspecified,
+ wash = dev.lelonio.square.ui.glass.chipWash(isSelected),
) {
Text(
stringResource(entry.label),
@@ -229,6 +268,32 @@ private fun LazyListScope.section(
}
}
+/** The history's own heading, with the way to empty it beside the name. */
+@Composable
+private fun HistoryTitle(onClear: () -> Unit) {
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .padding(start = 24.dp, end = 12.dp, top = 22.dp, bottom = 6.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ ) {
+ Text(
+ stringResource(R.string.search_history).uppercase(),
+ style = MaterialTheme.typography.labelLarge,
+ color = InkDim,
+ modifier = Modifier.weight(1f),
+ )
+ Text(
+ stringResource(R.string.clear),
+ style = MaterialTheme.typography.labelLarge,
+ color = InkDim,
+ modifier = Modifier
+ .pressable(onClear, shape = RoundedCornerShape(12.dp), pressedScale = 0.96f)
+ .padding(horizontal = 12.dp, vertical = 6.dp),
+ )
+ }
+}
+
@Composable
private fun SectionTitle(text: String) {
Text(
@@ -248,6 +313,14 @@ private fun ResultRow(
round: Boolean,
onClick: () -> Unit,
onMenu: (() -> Unit)?,
+ /**
+ * Why this row is here, when the title does not say it.
+ *
+ * Shown before the artist rather than under it: a row is two lines tall
+ * everywhere in the app, and a third line for some rows and not others
+ * makes a list that was even into a list that jumps.
+ */
+ badge: String? = null,
) {
Row(
Modifier
@@ -277,13 +350,28 @@ private fun ResultRow(
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
- Text(
- subtitle,
- style = MaterialTheme.typography.bodySmall,
- color = InkDim,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- )
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ if (badge != null) {
+ Text(
+ badge,
+ style = MaterialTheme.typography.labelSmall,
+ color = Ink,
+ maxLines = 1,
+ modifier = Modifier
+ .padding(end = 8.dp)
+ .clip(RoundedCornerShape(6.dp))
+ .background(BadgeFilm)
+ .padding(horizontal = 6.dp, vertical = 2.dp),
+ )
+ }
+ Text(
+ subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = InkDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ )
+ }
}
if (onMenu != null) {
Icon(
@@ -324,5 +412,13 @@ private fun StatusBox(content: @Composable () -> Unit) {
/** The chip that is lit, filled a little harder than the rest; see the home page. */
private val SelectedFilm = androidx.compose.ui.graphics.Color.White.copy(alpha = 0.26f)
+/**
+ * The pill behind "lyrics match": lighter than a lit chip.
+ *
+ * It labels a row rather than offering something to press, and at chip
+ * strength a whole page of them reads as a page of buttons.
+ */
+private val BadgeFilm = androidx.compose.ui.graphics.Color.White.copy(alpha = 0.16f)
+
/** How many of each kind the combined page shows before the chips take over. */
private const val TOP_RESULTS = 4
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 7ef7729..7c10e62 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -8,6 +8,14 @@
<string name="cancel">Abbrechen</string>
<string name="save">Speichern</string>
<string name="clear">Löschen</string>
+ <string name="credits">Credits</string>
+ <string name="credits_none">Keine Angaben</string>
+ <string name="credits_source">Quelle</string>
+ <string name="credits_performers">Mitwirkende</string>
+ <string name="credits_writers">Autoren</string>
+ <string name="credits_producers">Produzenten</string>
+ <string name="search_history">Aus deinen Suchen</string>
+ <string name="lyrics_match">Songtext gefunden</string>
<string name="retry">Erneut versuchen</string>
<string name="log_out">Abmelden</string>
<string name="refresh">Aktualisieren</string>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index e90fd79..1b572aa 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -8,6 +8,14 @@
<string name="cancel">Cancelar</string>
<string name="save">Guardar</string>
<string name="clear">Borrar</string>
+ <string name="credits">Créditos</string>
+ <string name="credits_none">Sin créditos</string>
+ <string name="credits_source">Fuente</string>
+ <string name="credits_performers">Intérpretes</string>
+ <string name="credits_writers">Compositores</string>
+ <string name="credits_producers">Productores</string>
+ <string name="search_history">De tus búsquedas</string>
+ <string name="lyrics_match">Coincide la letra</string>
<string name="retry">Reintentar</string>
<string name="log_out">Salir</string>
<string name="refresh">Actualizar</string>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 20b6a8f..f361940 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -8,6 +8,14 @@
<string name="cancel">Annuler</string>
<string name="save">Enregistrer</string>
<string name="clear">Effacer</string>
+ <string name="credits">Crédits</string>
+ <string name="credits_none">Aucun crédit</string>
+ <string name="credits_source">Source</string>
+ <string name="credits_performers">Interprètes</string>
+ <string name="credits_writers">Auteurs</string>
+ <string name="credits_producers">Producteurs</string>
+ <string name="search_history">Depuis tes recherches</string>
+ <string name="lyrics_match">Paroles trouvées</string>
<string name="retry">Réessayer</string>
<string name="log_out">Se déconnecter</string>
<string name="refresh">Actualiser</string>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index f5e70d4..effe0ca 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -13,6 +13,14 @@
<string name="cancel">रद्द करें</string>
<string name="save">सहेजें</string>
<string name="clear">साफ़ करें</string>
+ <string name="credits">श्रेय</string>
+ <string name="credits_none">कोई श्रेय नहीं</string>
+ <string name="credits_source">स्रोत</string>
+ <string name="credits_performers">कलाकार</string>
+ <string name="credits_writers">लेखक</string>
+ <string name="credits_producers">निर्माता</string>
+ <string name="search_history">आपकी खोजों से</string>
+ <string name="lyrics_match">गीत में मिला</string>
<string name="retry">फिर कोशिश करें</string>
<string name="log_out">लॉग आउट</string>
<string name="refresh">रीफ़्रेश करें</string>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 5dc41fa..c35c7f4 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -9,6 +9,14 @@
<string name="cancel">Annulla</string>
<string name="save">Salva</string>
<string name="clear">Cancella</string>
+ <string name="credits">Crediti</string>
+ <string name="credits_none">Nessun credito</string>
+ <string name="credits_source">Fonte</string>
+ <string name="credits_performers">Interpreti</string>
+ <string name="credits_writers">Autori</string>
+ <string name="credits_producers">Produttori</string>
+ <string name="search_history">Dalle tue ricerche</string>
+ <string name="lyrics_match">Testo trovato</string>
<string name="retry">Riprova</string>
<string name="log_out">Esci</string>
<string name="refresh">Aggiorna</string>
diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml
index e0b9067..62c3921 100644
--- a/app/src/main/res/values-pt/strings.xml
+++ b/app/src/main/res/values-pt/strings.xml
@@ -8,6 +8,14 @@
<string name="cancel">Cancelar</string>
<string name="save">Salvar</string>
<string name="clear">Limpar</string>
+ <string name="credits">Créditos</string>
+ <string name="credits_none">Sem créditos</string>
+ <string name="credits_source">Fonte</string>
+ <string name="credits_performers">Intérpretes</string>
+ <string name="credits_writers">Compositores</string>
+ <string name="credits_producers">Produtores</string>
+ <string name="search_history">Das tuas pesquisas</string>
+ <string name="lyrics_match">Letra encontrada</string>
<string name="retry">Tentar de novo</string>
<string name="log_out">Sair</string>
<string name="refresh">Atualizar</string>
diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml
index b8f005b..7d3e2e5 100644
--- a/app/src/main/res/values-tr/strings.xml
+++ b/app/src/main/res/values-tr/strings.xml
@@ -13,6 +13,14 @@
<string name="cancel">Vazgeç</string>
<string name="save">Kaydet</string>
<string name="clear">Temizle</string>
+ <string name="credits">Katkıda bulunanlar</string>
+ <string name="credits_none">Kayıt yok</string>
+ <string name="credits_source">Kaynak</string>
+ <string name="credits_performers">Sanatçılar</string>
+ <string name="credits_writers">Söz yazarları</string>
+ <string name="credits_producers">Prodüktörler</string>
+ <string name="search_history">Aramalarından</string>
+ <string name="lyrics_match">Şarkı sözünde bulundu</string>
<string name="retry">Yeniden dene</string>
<string name="log_out">Çıkış yap</string>
<string name="refresh">Yenile</string>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 4df6f4d..ccb1b36 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -19,6 +19,14 @@
<string name="cancel">Cancel</string>
<string name="save">Save</string>
<string name="clear">Clear</string>
+ <string name="credits">Credits</string>
+ <string name="credits_none">Nobody credited</string>
+ <string name="credits_source">Source</string>
+ <string name="credits_performers">Performers</string>
+ <string name="credits_writers">Writers</string>
+ <string name="credits_producers">Producers</string>
+ <string name="search_history">From your searches</string>
+ <string name="lyrics_match">Lyrics match</string>
<string name="retry">Retry</string>
<string name="log_out">Log out</string>
<string name="refresh">Refresh</string>
diff --git a/pathfinder.json b/pathfinder.json
index 7035944..95cdaab 100644
--- a/pathfinder.json
+++ b/pathfinder.json
@@ -4,5 +4,6 @@
"likedSongs": "c2c53c28f71da143c0753c22dc84d98b315cb4275472ea5a597c29338ae20b23",
"playlist": "86dde7b9d9356e2369414647cf6950cfed96e778e129cfdfc99aea6c1613b3b0",
"library": "134337999233cc6fdd6b1e6dbf94841409f04a946c5c7b744b09ba0dfe5a85ed",
+ "search": "db61238974d27839a136c9dc02bfdbe3fab7635f21cf85976ebff9a1ee281345",
"appVersion": "1.2.97.155.g5dd0dcaf-development"
}