Add MusicBrainz recording search
Free-text queries become escaped Lucene (every word must match title, artist or release), requests are spaced at 1/s with an app-identifying User-Agent, and results are mapped to artist/track/album/duration/mbid with same-song duplicates collapsed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
16f701c855
commit
0d016b8020
5 files changed
+298
No files matched your search
@@ -0,0 +1,101 @@
|
||||
package dev.daubney.scrobbled.data.search
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
|
||||
/**
|
||||
* Recording search against the MusicBrainz web service. MusicBrainz asks for at most one request per
|
||||
* second and a User-Agent that says who is calling (an app URL rather than a personal address).
|
||||
*/
|
||||
class MusicBrainzSearch(
|
||||
private val baseUrl: String = "https://musicbrainz.org",
|
||||
private val http: OkHttpClient = OkHttpClient(),
|
||||
private val limiter: RateLimiter = RateLimiter(1_000),
|
||||
) : TrackSearch {
|
||||
|
||||
override suspend fun search(query: String): List<TrackResult> {
|
||||
val lucene = buildQuery(query) ?: return emptyList()
|
||||
val url = "$baseUrl/ws/2/recording".toHttpUrl().newBuilder()
|
||||
.addQueryParameter("query", lucene)
|
||||
.addQueryParameter("fmt", "json")
|
||||
.addQueryParameter("limit", LIMIT.toString())
|
||||
.build()
|
||||
val request = Request.Builder().url(url).header("User-Agent", USER_AGENT).build()
|
||||
val (status, body) = limiter.run {
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
http.newCall(request).execute().use { it.code to it.body?.string().orEmpty() }
|
||||
} catch (e: IOException) {
|
||||
throw SearchException("Couldn't reach MusicBrainz: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
when {
|
||||
status == 503 || status == 429 -> throw SearchException("MusicBrainz is busy. Try again in a moment.")
|
||||
status !in 200..299 -> throw SearchException("MusicBrainz search failed ($status)")
|
||||
}
|
||||
val parsed = try {
|
||||
json.decodeFromString<Response>(body)
|
||||
} catch (e: Exception) {
|
||||
throw SearchException("Unexpected response from MusicBrainz")
|
||||
}
|
||||
return parsed.recordings.mapNotNull { it.toResult() }
|
||||
// The same song is often listed once per release; collapse identical rows.
|
||||
.distinctBy { Triple(it.artist.lowercase(), it.track.lowercase(), it.album?.lowercase()) }
|
||||
}
|
||||
|
||||
@Serializable
|
||||
private data class Response(val recordings: List<Recording> = emptyList())
|
||||
|
||||
@Serializable
|
||||
private data class Recording(
|
||||
val id: String,
|
||||
val title: String = "",
|
||||
val length: Long? = null,
|
||||
@SerialName("artist-credit") val artistCredit: List<Credit> = emptyList(),
|
||||
val releases: List<Release> = emptyList(),
|
||||
)
|
||||
|
||||
@Serializable
|
||||
private data class Credit(val name: String = "", val joinphrase: String = "")
|
||||
|
||||
@Serializable
|
||||
private data class Release(val title: String = "")
|
||||
|
||||
private fun Recording.toResult(): TrackResult? {
|
||||
val artist = artistCredit.joinToString("") { it.name + it.joinphrase }.trim()
|
||||
if (title.isBlank() || artist.isEmpty()) return null
|
||||
return TrackResult(
|
||||
mbid = id, artist = artist, track = title,
|
||||
album = releases.firstOrNull()?.title?.takeIf { it.isNotBlank() },
|
||||
durationSeconds = length?.let { (it / 1000).toInt() },
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val USER_AGENT = "ScrobbledAndroid/1.0 (https://git.daubney.dev/matt/ScrobbledAndroid)"
|
||||
private const val LIMIT = 15
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
private val special = Regex("""([+\-&|!(){}\[\]^"~*?:\\/])""")
|
||||
|
||||
/**
|
||||
* Free text to Lucene: every word must match the title, artist or release, so "radiohead reckoner"
|
||||
* works without field syntax. Special characters are escaped; null when nothing searchable is left.
|
||||
*/
|
||||
fun buildQuery(input: String): String? {
|
||||
val words = input.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
|
||||
if (words.isEmpty()) return null
|
||||
return words.joinToString(" AND ") { w ->
|
||||
val e = special.replace(w, """\\$1""")
|
||||
"(recording:$e OR artist:$e OR release:$e)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package dev.daubney.scrobbled.data.search
|
||||
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/** Spaces calls at least [intervalMs] apart; concurrent callers queue up. Clock and sleep are injectable for tests. */
|
||||
class RateLimiter(
|
||||
private val intervalMs: Long,
|
||||
private val nowMs: () -> Long = { System.nanoTime() / 1_000_000 },
|
||||
private val sleep: suspend (Long) -> Unit = { delay(it) },
|
||||
) {
|
||||
private val mutex = Mutex()
|
||||
private var lastStart: Long? = null
|
||||
|
||||
suspend fun <T> run(block: suspend () -> T): T = mutex.withLock {
|
||||
lastStart?.let { last ->
|
||||
val wait = last + intervalMs - nowMs()
|
||||
if (wait > 0) sleep(wait)
|
||||
}
|
||||
lastStart = nowMs()
|
||||
block()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.daubney.scrobbled.data.search
|
||||
|
||||
data class TrackResult(
|
||||
val mbid: String,
|
||||
val artist: String,
|
||||
val track: String,
|
||||
val album: String?,
|
||||
val durationSeconds: Int?,
|
||||
)
|
||||
|
||||
interface TrackSearch {
|
||||
/** Returns matches best-first; empty for a blank query. Throws [SearchException] with a user-facing message. */
|
||||
suspend fun search(query: String): List<TrackResult>
|
||||
}
|
||||
|
||||
class SearchException(message: String) : Exception(message)
|
||||
@@ -0,0 +1,112 @@
|
||||
package dev.daubney.scrobbled.data.search
|
||||
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.mockwebserver.MockResponse
|
||||
import okhttp3.mockwebserver.MockWebServer
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class MusicBrainzSearchTest {
|
||||
private lateinit var server: MockWebServer
|
||||
private lateinit var search: MusicBrainzSearch
|
||||
|
||||
@Before fun setUp() {
|
||||
server = MockWebServer().also { it.start() }
|
||||
search = MusicBrainzSearch(server.url("/").toString().trimEnd('/'))
|
||||
}
|
||||
@After fun tearDown() = server.shutdown()
|
||||
|
||||
@Test
|
||||
fun mapsRecordingToResult() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"recordings":[{"id":"mbid-1","title":"Reckoner","length":290000,
|
||||
"artist-credit":[{"name":"Radiohead","joinphrase":""}],
|
||||
"releases":[{"title":"In Rainbows"},{"title":"Other"}]}]}"""))
|
||||
val r = search.search("radiohead reckoner").single()
|
||||
assertEquals(TrackResult("mbid-1", "Radiohead", "Reckoner", "In Rainbows", 290), r)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun sendsUserAgentAndQuery() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"recordings":[]}"""))
|
||||
search.search("radiohead reckoner")
|
||||
val req = server.takeRequest()
|
||||
assertEquals(MusicBrainzSearch.USER_AGENT, req.getHeader("User-Agent"))
|
||||
assertEquals("json", req.requestUrl!!.queryParameter("fmt"))
|
||||
assertEquals(
|
||||
"(recording:radiohead OR artist:radiohead OR release:radiohead) AND (recording:reckoner OR artist:reckoner OR release:reckoner)",
|
||||
req.requestUrl!!.queryParameter("query"),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun joinsMultipleArtistCredits() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"recordings":[{"id":"x","title":"Song",
|
||||
"artist-credit":[{"name":"A","joinphrase":" feat. "},{"name":"B","joinphrase":""}]}]}"""))
|
||||
val r = search.search("song").single()
|
||||
assertEquals("A feat. B", r.artist)
|
||||
assertNull(r.album)
|
||||
assertNull(r.durationSeconds)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun collapsesSameSongListedOnManyReleases() = runTest {
|
||||
val rec = { id: String -> """{"id":"$id","title":"Reckoner","artist-credit":[{"name":"Radiohead"}],"releases":[{"title":"In Rainbows"}]}""" }
|
||||
server.enqueue(MockResponse().setBody("""{"recordings":[${rec("a")},${rec("b")},
|
||||
{"id":"c","title":"Reckoner","artist-credit":[{"name":"Radiohead"}],"releases":[{"title":"Live"}]}]}"""))
|
||||
assertEquals(listOf("a", "c"), search.search("reckoner").map { it.mbid })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsRecordingsWithoutArtistOrTitle() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"recordings":[{"id":"x","title":"No artist"},
|
||||
{"id":"y","title":"","artist-credit":[{"name":"A"}]}]}"""))
|
||||
assertEquals(emptyList<TrackResult>(), search.search("x"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun blankQueryMakesNoRequest() = runTest {
|
||||
assertEquals(emptyList<TrackResult>(), search.search(" "))
|
||||
assertEquals(0, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun busyServerGivesFriendlyError() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(503).setBody("""{"error":"slow down"}"""))
|
||||
try { search.search("x"); fail() } catch (e: SearchException) {
|
||||
assertEquals("MusicBrainz is busy. Try again in a moment.", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun garbageResponseIsReportedNotCrashed() = runTest {
|
||||
server.enqueue(MockResponse().setBody("<html>"))
|
||||
try { search.search("x"); fail() } catch (e: SearchException) {
|
||||
assertEquals("Unexpected response from MusicBrainz", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun networkFailureIsReported() = runTest {
|
||||
server.shutdown()
|
||||
try { search.search("x"); fail() } catch (e: SearchException) {
|
||||
assert(e.message!!.startsWith("Couldn't reach MusicBrainz"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun luceneSpecialCharactersAreEscaped() {
|
||||
assertEquals(
|
||||
"""(recording:AC\/DC OR artist:AC\/DC OR release:AC\/DC)""",
|
||||
MusicBrainzSearch.buildQuery("AC/DC"),
|
||||
)
|
||||
assertEquals(
|
||||
"""(recording:what\? OR artist:what\? OR release:what\?) AND (recording:\(live\) OR artist:\(live\) OR release:\(live\))""",
|
||||
MusicBrainzSearch.buildQuery("what? (live)"),
|
||||
)
|
||||
assertNull(MusicBrainzSearch.buildQuery(" "))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.daubney.scrobbled.data.search
|
||||
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class RateLimiterTest {
|
||||
private var clock = 0L
|
||||
private val sleeps = mutableListOf<Long>()
|
||||
private val limiter = RateLimiter(1_000, nowMs = { clock }, sleep = { clock += it; sleeps += it })
|
||||
|
||||
@Test
|
||||
fun firstCallDoesNotWait() = runTest {
|
||||
limiter.run { }
|
||||
assertEquals(emptyList<Long>(), sleeps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backToBackCallsAreSpacedByTheInterval() = runTest {
|
||||
limiter.run { }
|
||||
limiter.run { }
|
||||
assertEquals(listOf(1_000L), sleeps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun onlyWaitsForTheRemainingTime() = runTest {
|
||||
limiter.run { }
|
||||
clock += 600
|
||||
limiter.run { }
|
||||
assertEquals(listOf(400L), sleeps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noWaitAfterEnoughTimePasses() = runTest {
|
||||
limiter.run { }
|
||||
clock += 5_000
|
||||
limiter.run { }
|
||||
assertEquals(emptyList<Long>(), sleeps)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun returnsTheBlockResult() = runTest {
|
||||
assertEquals(42, limiter.run { 42 })
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user