Add MusicBrainz search tab to the Add screen
CI / test (push) Successful in 2m21s

Search results pre-fill the manual form (artist, track, album, MBID and
duration) so they can be corrected before scrobbling. Editing the artist
or track drops the MBID/duration since they describe a specific recording.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-12 11:44:12 +01:00
1 parent 0d016b8020
commit ee34963799
6 files changed
+215 -11

No files matched your search

@@ -30,7 +30,7 @@ class MainActivity : ComponentActivity() {
setContent { setContent {
ScrobbledTheme { ScrobbledTheme {
val state by connectVm.state.collectAsState() val state by connectVm.state.collectAsState()
if (state.connected) ScrobbledApp(app.history, app.scrobbles, onSignOut = connectVm::disconnect) else ConnectScreen(connectVm) if (state.connected) ScrobbledApp(app.history, app.scrobbles, app.trackSearch, onSignOut = connectVm::disconnect) else ConnectScreen(connectVm)
} }
} }
} }
@@ -8,10 +8,13 @@ import dev.daubney.scrobbled.data.history.DefaultHistoryRepository
import dev.daubney.scrobbled.data.history.HistoryRepository import dev.daubney.scrobbled.data.history.HistoryRepository
import dev.daubney.scrobbled.data.scrobble.DefaultScrobbleRepository import dev.daubney.scrobbled.data.scrobble.DefaultScrobbleRepository
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
import dev.daubney.scrobbled.data.search.MusicBrainzSearch
import dev.daubney.scrobbled.data.search.TrackSearch
/** Hand-rolled service locator; small enough that a DI framework isn't worth it yet. */ /** Hand-rolled service locator; small enough that a DI framework isn't worth it yet. */
class ScrobbledApplication : Application() { class ScrobbledApplication : Application() {
val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) } val auth: AuthRepository by lazy { DefaultAuthRepository(KeystoreCredentialStore(this)) }
val history: HistoryRepository by lazy { DefaultHistoryRepository(auth) } val history: HistoryRepository by lazy { DefaultHistoryRepository(auth) }
val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth) } val scrobbles: ScrobbleRepository by lazy { DefaultScrobbleRepository(auth) }
val trackSearch: TrackSearch by lazy { MusicBrainzSearch() }
} }
@@ -19,6 +19,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.navigation.compose.NavHost import androidx.navigation.compose.NavHost
import dev.daubney.scrobbled.data.history.HistoryRepository import dev.daubney.scrobbled.data.history.HistoryRepository
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
import dev.daubney.scrobbled.data.search.TrackSearch
import dev.daubney.scrobbled.ui.add.AddScreen import dev.daubney.scrobbled.ui.add.AddScreen
import dev.daubney.scrobbled.ui.add.AddViewModel import dev.daubney.scrobbled.ui.add.AddViewModel
import dev.daubney.scrobbled.ui.history.HistoryScreen import dev.daubney.scrobbled.ui.history.HistoryScreen
@@ -37,7 +38,7 @@ enum class Destination(val route: String, val label: String) {
} }
@Composable @Composable
fun ScrobbledApp(history: HistoryRepository, scrobbles: ScrobbleRepository, onSignOut: () -> Unit) { fun ScrobbledApp(history: HistoryRepository, scrobbles: ScrobbleRepository, trackSearch: TrackSearch, onSignOut: () -> Unit) {
val nav = rememberNavController() val nav = rememberNavController()
val current by nav.currentBackStackEntryAsState() val current by nav.currentBackStackEntryAsState()
Scaffold( Scaffold(
@@ -65,7 +66,7 @@ fun ScrobbledApp(history: HistoryRepository, scrobbles: ScrobbleRepository, onSi
HistoryScreen(vm) HistoryScreen(vm)
} }
composable(Destination.Add.route) { composable(Destination.Add.route) {
val vm = viewModel<AddViewModel>(factory = viewModelFactory { initializer { AddViewModel(scrobbles) } }) val vm = viewModel<AddViewModel>(factory = viewModelFactory { initializer { AddViewModel(scrobbles, trackSearch) } })
AddScreen(vm) AddScreen(vm)
} }
composable(Destination.Listen.route) { Placeholder(Destination.Listen.label) } composable(Destination.Listen.route) { Placeholder(Destination.Listen.label) }
@@ -1,6 +1,9 @@
package dev.daubney.scrobbled.ui.add package dev.daubney.scrobbled.ui.add
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
@@ -8,36 +11,99 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.PrimaryTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import dev.daubney.scrobbled.data.search.TrackResult
@OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun AddScreen(vm: AddViewModel) { fun AddScreen(vm: AddViewModel) {
val s by vm.state.collectAsState() val s by vm.state.collectAsState()
Column(Modifier.fillMaxSize().statusBarsPadding().imePadding()) {
Text("Add scrobble", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(16.dp))
PrimaryTabRow(selectedTabIndex = s.tab.ordinal) {
AddTab.entries.forEach { t ->
Tab(selected = s.tab == t, onClick = { vm.onTab(t) }, text = { Text(if (t == AddTab.Search) "Search" else "Manual") })
}
}
when (s.tab) {
AddTab.Search -> SearchTab(s, vm)
AddTab.Manual -> ManualTab(s, vm)
}
}
}
@Composable
private fun SearchTab(s: AddState, vm: AddViewModel) {
Column(Modifier.fillMaxSize().padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedTextField(
s.query, vm::onQuery, Modifier.fillMaxWidth().padding(top = 12.dp), singleLine = true,
label = { Text("Search MusicBrainz") }, placeholder = { Text("artist and/or track") },
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { vm.search() }),
)
Button(vm::search, Modifier.fillMaxWidth(), enabled = s.query.isNotBlank() && !s.searching) {
Text(if (s.searching) "Searching…" else "Search")
}
s.searchError?.let { Text(it, color = MaterialTheme.colorScheme.error) }
when {
s.searching -> Box(Modifier.fillMaxWidth().padding(16.dp), contentAlignment = Alignment.Center) { CircularProgressIndicator() }
s.searched && s.results.isEmpty() && s.searchError == null ->
Text("No matches. Try fewer words, or add it manually.", color = MaterialTheme.colorScheme.onSurfaceVariant)
else -> LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
items(s.results, key = { it.mbid }) { ResultRow(it) { vm.pick(it) } }
}
}
}
}
@Composable
private fun ResultRow(r: TrackResult, onClick: () -> Unit) {
Column(Modifier.fillMaxWidth().clickable(onClick = onClick).padding(vertical = 8.dp)) {
Text(r.track, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyLarge)
Text(
listOfNotNull(r.artist, r.album).joinToString(" · "), maxLines = 1, overflow = TextOverflow.Ellipsis,
style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
@Composable
private fun ManualTab(s: AddState, vm: AddViewModel) {
Column( Column(
Modifier.fillMaxSize().statusBarsPadding().imePadding().verticalScroll(rememberScrollState()).padding(16.dp), Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp),
) { ) {
Text("Add scrobble", style = MaterialTheme.typography.headlineSmall)
val caps = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Next) val caps = KeyboardOptions(capitalization = KeyboardCapitalization.Words, imeAction = ImeAction.Next)
OutlinedTextField(s.artist, vm::onArtist, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Artist") }, keyboardOptions = caps) OutlinedTextField(s.artist, vm::onArtist, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Artist") }, keyboardOptions = caps)
OutlinedTextField(s.track, vm::onTrack, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Track") }, keyboardOptions = caps) OutlinedTextField(s.track, vm::onTrack, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Track") }, keyboardOptions = caps)
OutlinedTextField(s.album, vm::onAlbum, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Album (optional)") }, keyboardOptions = caps) OutlinedTextField(s.album, vm::onAlbum, Modifier.fillMaxWidth(), singleLine = true, label = { Text("Album (optional)") }, keyboardOptions = caps)
if (s.mbid.isNotEmpty()) {
Text("Matched on MusicBrainz", style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("Played", style = MaterialTheme.typography.labelLarge) Text("Played", style = MaterialTheme.typography.labelLarge)
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -4,6 +4,10 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
import dev.daubney.scrobbled.data.scrobble.TrackDraft import dev.daubney.scrobbled.data.scrobble.TrackDraft
import dev.daubney.scrobbled.data.search.SearchException
import dev.daubney.scrobbled.data.search.TrackResult
import dev.daubney.scrobbled.data.search.TrackSearch
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
@@ -21,10 +25,23 @@ enum class WhenOption(val label: String, val ago: Duration) {
Yesterday("Yesterday", Duration.ofHours(24)), Yesterday("Yesterday", Duration.ofHours(24)),
} }
enum class AddTab { Search, Manual }
data class AddState( data class AddState(
val tab: AddTab = AddTab.Search,
// Search
val query: String = "",
val results: List<TrackResult> = emptyList(),
val searching: Boolean = false,
val searchError: String? = null,
/** True once a search has returned, so "no results" isn't shown before the first search. */
val searched: Boolean = false,
// The editable track (filled by hand or from a search result)
val artist: String = "", val artist: String = "",
val track: String = "", val track: String = "",
val album: String = "", val album: String = "",
val mbid: String = "",
val durationSeconds: Int? = null,
val whenOption: WhenOption = WhenOption.Now, val whenOption: WhenOption = WhenOption.Now,
val submitting: Boolean = false, val submitting: Boolean = false,
val error: String? = null, val error: String? = null,
@@ -36,23 +53,53 @@ data class AddState(
class AddViewModel( class AddViewModel(
private val scrobbles: ScrobbleRepository, private val scrobbles: ScrobbleRepository,
private val search: TrackSearch,
private val clock: () -> Instant = Instant::now, private val clock: () -> Instant = Instant::now,
) : ViewModel() { ) : ViewModel() {
private val _state = MutableStateFlow(AddState()) private val _state = MutableStateFlow(AddState())
val state: StateFlow<AddState> = _state.asStateFlow() val state: StateFlow<AddState> = _state.asStateFlow()
private var searchJob: Job? = null
private fun edit(f: AddState.() -> AddState) = _state.update { it.f().copy(error = null, message = null) } private fun edit(f: AddState.() -> AddState) = _state.update { it.f().copy(error = null, message = null) }
fun onArtist(v: String) = edit { copy(artist = v) } fun onTab(t: AddTab) = _state.update { it.copy(tab = t) }
fun onTrack(v: String) = edit { copy(track = v) } fun onQuery(v: String) = _state.update { it.copy(query = v) }
// The MusicBrainz id and length describe a specific recording, so they no longer apply once the
// user changes which song this is.
fun onArtist(v: String) = edit { copy(artist = v, mbid = "", durationSeconds = null) }
fun onTrack(v: String) = edit { copy(track = v, mbid = "", durationSeconds = null) }
fun onAlbum(v: String) = edit { copy(album = v) } fun onAlbum(v: String) = edit { copy(album = v) }
fun onWhen(v: WhenOption) = edit { copy(whenOption = v) } fun onWhen(v: WhenOption) = edit { copy(whenOption = v) }
fun search() {
val q = _state.value.query
if (q.isBlank() || _state.value.searching) return
_state.update { it.copy(searching = true, searchError = null) }
searchJob = viewModelScope.launch {
try {
val results = search.search(q)
_state.update { it.copy(results = results, searching = false, searched = true) }
} catch (e: SearchException) {
_state.update { it.copy(searching = false, searchError = e.message) }
}
}
}
/** Copies a search result into the form so it can be corrected before submitting. */
fun pick(r: TrackResult) = edit {
copy(
tab = AddTab.Manual, artist = r.artist, track = r.track, album = r.album.orEmpty(),
mbid = r.mbid, durationSeconds = r.durationSeconds,
)
}
fun submit() { fun submit() {
val s = _state.value val s = _state.value
if (!s.canSubmit) return if (!s.canSubmit) return
val draft = TrackDraft( val draft = TrackDraft(
artist = s.artist, track = s.track, album = s.album, artist = s.artist, track = s.track, album = s.album,
durationSeconds = s.durationSeconds, mbid = s.mbid,
playedAt = clock().minus(s.whenOption.ago), playedAt = clock().minus(s.whenOption.ago),
) )
draft.validate(clock())?.let { err -> _state.update { it.copy(error = err) }; return } draft.validate(clock())?.let { err -> _state.update { it.copy(error = err) }; return }
@@ -60,8 +107,13 @@ class AddViewModel(
viewModelScope.launch { viewModelScope.launch {
try { try {
scrobbles.submit(draft) scrobbles.submit(draft)
// Keep the time choice (adding several older tracks in a row is common), clear the rest. // Keep the time choice and search (adding several tracks in a row is common), clear the form.
_state.value = AddState(whenOption = s.whenOption, message = "Scrobbled ${draft.track.trim()}") _state.update {
it.copy(
artist = "", track = "", album = "", mbid = "", durationSeconds = null,
submitting = false, message = "Scrobbled ${draft.track.trim()}",
)
}
} catch (e: Exception) { } catch (e: Exception) {
_state.update { it.copy(submitting = false, error = e.message ?: "Something went wrong") } _state.update { it.copy(submitting = false, error = e.message ?: "Something went wrong") }
} }
@@ -2,6 +2,9 @@ package dev.daubney.scrobbled.ui.add
import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository import dev.daubney.scrobbled.data.scrobble.ScrobbleRepository
import dev.daubney.scrobbled.data.scrobble.TrackDraft import dev.daubney.scrobbled.data.scrobble.TrackDraft
import dev.daubney.scrobbled.data.search.SearchException
import dev.daubney.scrobbled.data.search.TrackResult
import dev.daubney.scrobbled.data.search.TrackSearch
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher
@@ -25,15 +28,27 @@ private class FakeScrobbles : ScrobbleRepository {
} }
} }
private class FakeSearch : TrackSearch {
var results = listOf(TrackResult("mb1", "Radiohead", "Reckoner", "In Rainbows", 290))
var failure: SearchException? = null
val queries = mutableListOf<String>()
override suspend fun search(query: String): List<TrackResult> {
queries += query
failure?.let { throw it }
return results
}
}
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
class AddViewModelTest { class AddViewModelTest {
private val now = Instant.parse("2026-10-12T12:00:00Z") private val now = Instant.parse("2026-10-12T12:00:00Z")
private val repo = FakeScrobbles() private val repo = FakeScrobbles()
private val search = FakeSearch()
private lateinit var vm: AddViewModel private lateinit var vm: AddViewModel
@Before fun setUp() { @Before fun setUp() {
Dispatchers.setMain(UnconfinedTestDispatcher()) Dispatchers.setMain(UnconfinedTestDispatcher())
vm = AddViewModel(repo) { now } vm = AddViewModel(repo, search) { now }
} }
@After fun tearDown() = Dispatchers.resetMain() @After fun tearDown() = Dispatchers.resetMain()
@@ -99,4 +114,71 @@ class AddViewModelTest {
assertEquals(1, repo.submitted.size) assertEquals(1, repo.submitted.size)
assertNull(vm.state.value.error) assertNull(vm.state.value.error)
} }
@Test
fun searchPopulatesResults() {
vm.onQuery("radiohead reckoner")
vm.search()
assertEquals(listOf("radiohead reckoner"), search.queries)
assertEquals(1, vm.state.value.results.size)
assertTrue(vm.state.value.searched)
assertFalse(vm.state.value.searching)
}
@Test
fun blankQueryDoesNotSearch() {
vm.onQuery(" ")
vm.search()
assertEquals(emptyList<String>(), search.queries)
}
@Test
fun searchErrorIsShownAndResultsKept() {
vm.onQuery("x"); vm.search()
search.failure = SearchException("MusicBrainz is busy. Try again in a moment.")
vm.search()
assertEquals("MusicBrainz is busy. Try again in a moment.", vm.state.value.searchError)
assertEquals(1, vm.state.value.results.size)
assertFalse(vm.state.value.searching)
}
@Test
fun pickingResultFillsFormAndSwitchesToManual() {
vm.pick(search.results.single())
val s = vm.state.value
assertEquals(AddTab.Manual, s.tab)
assertEquals("Radiohead", s.artist)
assertEquals("In Rainbows", s.album)
assertEquals("mb1", s.mbid)
assertEquals(290, s.durationSeconds)
}
@Test
fun pickedResultSubmitsWithMbidAndDuration() {
vm.pick(search.results.single())
vm.submit()
val d = repo.submitted.single()
assertEquals("mb1", d.mbid)
assertEquals(290, d.durationSeconds)
}
@Test
fun changingArtistOrTrackDropsTheMusicBrainzMatch() {
vm.pick(search.results.single())
vm.onTrack("Reckoner (live)")
assertEquals("", vm.state.value.mbid)
assertNull(vm.state.value.durationSeconds)
vm.pick(search.results.single())
vm.onAlbum("Other album") // album tweaks keep the match
assertEquals("mb1", vm.state.value.mbid)
}
@Test
fun successKeepsSearchResultsForTheNextPick() {
vm.onQuery("radiohead"); vm.search()
vm.pick(search.results.single()); vm.submit()
assertEquals("radiohead", vm.state.value.query)
assertEquals(1, vm.state.value.results.size)
assertEquals("", vm.state.value.mbid)
}
} }