Signer matches the server's md5 scheme (verified against vectors generated by its Python implementation, including unicode). LastFmClient supports auth.getMobileSession, track.scrobble (batched, indexed fields) and track.updateNowPlaying, mapping server errors to LastFmException. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9dac03ccdb
commit
5200ebdb2d
8 files changed
+288
No files matched your search
@@ -1,6 +1,7 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
android {
|
||||
@@ -46,8 +47,13 @@ dependencies {
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.compose.material3)
|
||||
implementation(libs.androidx.navigation.compose)
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
testImplementation(libs.junit)
|
||||
testImplementation(libs.okhttp.mockwebserver)
|
||||
testImplementation(libs.kotlinx.coroutines.test)
|
||||
androidTestImplementation(libs.androidx.espresso.core)
|
||||
androidTestImplementation(libs.androidx.junit)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.int
|
||||
import kotlinx.serialization.json.jsonObject
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.io.IOException
|
||||
|
||||
/** Client for the server's Last.fm-compatible `/2.0/` API. Writes are signed with the app's secret. */
|
||||
class LastFmClient(
|
||||
baseUrl: String,
|
||||
private val apiKey: String,
|
||||
private val secret: String,
|
||||
private val http: OkHttpClient = OkHttpClient(),
|
||||
) {
|
||||
private val endpoint = baseUrl.trimEnd('/').plus("/2.0/").toHttpUrl()
|
||||
|
||||
suspend fun getMobileSession(username: String, password: String): Session {
|
||||
val root = call(
|
||||
mapOf("method" to "auth.getMobileSession", "username" to username, "password" to password),
|
||||
)
|
||||
val session = root["session"]?.jsonObject ?: throw LastFmException(-1, "Malformed session response")
|
||||
return Session(
|
||||
username = session.string("name") ?: username,
|
||||
key = session.string("key") ?: throw LastFmException(-1, "Session response had no key"),
|
||||
)
|
||||
}
|
||||
|
||||
/** Submits up to 50 scrobbles in one call. Duplicates are accepted by the server, so retries are safe. */
|
||||
suspend fun scrobble(sessionKey: String, tracks: List<ScrobbleTrack>): ScrobbleResult {
|
||||
require(tracks.size in 1..50) { "Between 1 and 50 tracks per call" }
|
||||
val params = mutableMapOf("method" to "track.scrobble", "sk" to sessionKey)
|
||||
tracks.forEachIndexed { i, t ->
|
||||
val ts = requireNotNull(t.timestamp) { "Scrobbles need a timestamp" }
|
||||
params["artist[$i]"] = t.artist
|
||||
params["track[$i]"] = t.track
|
||||
params["timestamp[$i]"] = ts.toString()
|
||||
t.optionalFields().forEach { (k, v) -> params["$k[$i]"] = v }
|
||||
}
|
||||
val attr = call(params)["scrobbles"]?.jsonObject?.get("@attr")?.jsonObject
|
||||
?: throw LastFmException(-1, "Malformed scrobble response")
|
||||
return ScrobbleResult(attr.getValue("accepted").jsonPrimitive.int, attr.getValue("ignored").jsonPrimitive.int)
|
||||
}
|
||||
|
||||
suspend fun updateNowPlaying(sessionKey: String, track: ScrobbleTrack) {
|
||||
val params = mutableMapOf(
|
||||
"method" to "track.updateNowPlaying", "sk" to sessionKey,
|
||||
"artist" to track.artist, "track" to track.track,
|
||||
)
|
||||
params += track.optionalFields()
|
||||
call(params)
|
||||
}
|
||||
|
||||
private fun ScrobbleTrack.optionalFields(): Map<String, String> = buildMap {
|
||||
album?.let { put("album", it) }
|
||||
albumArtist?.let { put("albumArtist", it) }
|
||||
durationSeconds?.let { put("duration", it.toString()) }
|
||||
trackNumber?.let { put("trackNumber", it.toString()) }
|
||||
mbid?.let { put("mbid", it) }
|
||||
}
|
||||
|
||||
private suspend fun call(params: Map<String, String>): JsonObject = withContext(Dispatchers.IO) {
|
||||
val signed = params + ("api_key" to apiKey)
|
||||
val body = FormBody.Builder(Charsets.UTF_8).apply {
|
||||
signed.forEach { (k, v) -> add(k, v) }
|
||||
add("api_sig", Signer.sign(signed, secret))
|
||||
add("format", "json")
|
||||
}.build()
|
||||
val text = try {
|
||||
http.newCall(Request.Builder().url(endpoint).post(body).build()).execute().use { it.body?.string().orEmpty() }
|
||||
} catch (e: IOException) {
|
||||
throw LastFmException(-1, e.message ?: "Network error")
|
||||
}
|
||||
val root = try {
|
||||
Json.parseToJsonElement(text).jsonObject
|
||||
} catch (e: Exception) {
|
||||
throw LastFmException(-1, "Unexpected response from server")
|
||||
}
|
||||
root["error"]?.let {
|
||||
throw LastFmException(it.jsonPrimitive.int, root["message"]?.jsonPrimitive?.content ?: "Request failed")
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
private fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.content
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
/** A track to scrobble or announce as now playing. [timestamp] is Unix seconds (scrobbles only). */
|
||||
data class ScrobbleTrack(
|
||||
val artist: String,
|
||||
val track: String,
|
||||
val timestamp: Long? = null,
|
||||
val album: String? = null,
|
||||
val albumArtist: String? = null,
|
||||
val durationSeconds: Int? = null,
|
||||
val trackNumber: Int? = null,
|
||||
val mbid: String? = null,
|
||||
)
|
||||
|
||||
data class Session(val username: String, val key: String)
|
||||
|
||||
data class ScrobbleResult(val accepted: Int, val ignored: Int)
|
||||
|
||||
/** An error reported by the server (Last.fm error code) or a transport/parse failure (code -1). */
|
||||
class LastFmException(val code: Int, message: String) : Exception(message) {
|
||||
/** The session key was rejected; the user must re-authenticate. */
|
||||
val isInvalidSession get() = code == 9
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** Last.fm request signing, matching the server's `scrobbler/lastfm/signature.py`. */
|
||||
object Signer {
|
||||
private val unsigned = setOf("format", "callback", "api_sig")
|
||||
|
||||
fun sign(params: Map<String, String>, secret: String): String {
|
||||
val payload = params.keys.filter { it !in unsigned }.sorted()
|
||||
.joinToString("") { it + params.getValue(it) }
|
||||
return MessageDigest.getInstance("MD5")
|
||||
.digest((payload + secret).toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
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.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.net.URLDecoder
|
||||
|
||||
class LastFmClientTest {
|
||||
private lateinit var server: MockWebServer
|
||||
private lateinit var client: LastFmClient
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().also { it.start() }
|
||||
client = LastFmClient(server.url("/").toString(), apiKey = "key", secret = "secret")
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() = server.shutdown()
|
||||
|
||||
private fun sentParams(): Map<String, String> {
|
||||
val req = server.takeRequest()
|
||||
assertEquals("/2.0/", req.path)
|
||||
assertEquals("POST", req.method)
|
||||
return req.body.readUtf8().split("&").associate {
|
||||
val (k, v) = it.split("=", limit = 2)
|
||||
URLDecoder.decode(k, "UTF-8") to URLDecoder.decode(v, "UTF-8")
|
||||
}
|
||||
}
|
||||
|
||||
private fun assertSigned(p: Map<String, String>) =
|
||||
assertEquals(Signer.sign(p - "api_sig", "secret"), p["api_sig"])
|
||||
|
||||
@Test
|
||||
fun getMobileSessionParsesSessionAndSignsRequest() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"session":{"name":"alice","key":"abc123","subscriber":"0"}}"""))
|
||||
val session = client.getMobileSession("alice", "pw")
|
||||
assertEquals(Session("alice", "abc123"), session)
|
||||
val p = sentParams()
|
||||
assertEquals("auth.getMobileSession", p["method"])
|
||||
assertEquals("json", p["format"])
|
||||
assertEquals("key", p["api_key"])
|
||||
assertSigned(p)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun scrobbleSendsIndexedFieldsAndParsesCounts() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"scrobbles":{"scrobble":{"track":{"#text":"x"}},"@attr":{"accepted":"2","ignored":"0"}}}"""))
|
||||
val result = client.scrobble(
|
||||
"sk1",
|
||||
listOf(
|
||||
ScrobbleTrack("Björk", "Army of Me", timestamp = 100, album = "Post", durationSeconds = 235, mbid = "m"),
|
||||
ScrobbleTrack("B", "T", timestamp = 200),
|
||||
),
|
||||
)
|
||||
assertEquals(ScrobbleResult(2, 0), result)
|
||||
val p = sentParams()
|
||||
assertEquals("sk1", p["sk"])
|
||||
assertEquals("Björk", p["artist[0]"])
|
||||
assertEquals("100", p["timestamp[0]"])
|
||||
assertEquals("Post", p["album[0]"])
|
||||
assertEquals("235", p["duration[0]"])
|
||||
assertEquals("m", p["mbid[0]"])
|
||||
assertEquals("T", p["track[1]"])
|
||||
assertFalse(p.containsKey("album[1]"))
|
||||
assertSigned(p)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun updateNowPlayingSendsUnindexedFields() = runTest {
|
||||
server.enqueue(MockResponse().setBody("""{"nowplaying":{"track":{"corrected":"0","#text":"T"}}}"""))
|
||||
client.updateNowPlaying("sk1", ScrobbleTrack("A", "T", album = "Al"))
|
||||
val p = sentParams()
|
||||
assertEquals("track.updateNowPlaying", p["method"])
|
||||
assertEquals("A", p["artist"])
|
||||
assertEquals("Al", p["album"])
|
||||
assertSigned(p)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun serverErrorBecomesLastFmException() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":9,"message":"Invalid session key"}"""))
|
||||
try {
|
||||
client.scrobble("bad", listOf(ScrobbleTrack("A", "T", timestamp = 1)))
|
||||
fail("expected exception")
|
||||
} catch (e: LastFmException) {
|
||||
assertEquals(9, e.code)
|
||||
assertTrue(e.isInvalidSession)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nonJsonResponseIsReportedNotCrashed() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(502).setBody("<html>Bad gateway</html>"))
|
||||
try {
|
||||
client.updateNowPlaying("sk", ScrobbleTrack("A", "T"))
|
||||
fail("expected exception")
|
||||
} catch (e: LastFmException) {
|
||||
assertEquals(-1, e.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package dev.daubney.scrobbled.data.api
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
/** Expected values were generated by the server's own `signature.sign`. */
|
||||
class SignerTest {
|
||||
@Test
|
||||
fun matchesServerForUnicodeAndIgnoresFormat() {
|
||||
val params = mapOf(
|
||||
"method" to "auth.getMobileSession", "api_key" to "abc", "username" to "alice",
|
||||
"password" to "pässwörd 日本", "format" to "json",
|
||||
)
|
||||
assertEquals("1a636a75e857c12933c3b924378d49a1", Signer.sign(params, "sekret"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun matchesServerForIndexedParams() {
|
||||
val params = mapOf(
|
||||
"method" to "track.scrobble", "api_key" to "k", "sk" to "s",
|
||||
"artist[0]" to "Björk", "track[0]" to "Army of Me", "timestamp[0]" to "1700000000",
|
||||
)
|
||||
assertEquals("defdc0fa2867657d22dcad075c52fe63", Signer.sign(params, "sec"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun apiSigAndCallbackAreExcluded() {
|
||||
val base = mapOf("a" to "1")
|
||||
assertEquals(Signer.sign(base, "s"), Signer.sign(base + ("api_sig" to "x") + ("callback" to "y"), "s"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user