diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3c7d102..393e6c2 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -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) } diff --git a/app/src/main/java/dev/daubney/scrobbled/data/api/LastFmClient.kt b/app/src/main/java/dev/daubney/scrobbled/data/api/LastFmClient.kt new file mode 100644 index 0000000..be71622 --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/api/LastFmClient.kt @@ -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): 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 = 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): 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 +} diff --git a/app/src/main/java/dev/daubney/scrobbled/data/api/Models.kt b/app/src/main/java/dev/daubney/scrobbled/data/api/Models.kt new file mode 100644 index 0000000..5fa109f --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/api/Models.kt @@ -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 +} diff --git a/app/src/main/java/dev/daubney/scrobbled/data/api/Signer.kt b/app/src/main/java/dev/daubney/scrobbled/data/api/Signer.kt new file mode 100644 index 0000000..7a18aa9 --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/api/Signer.kt @@ -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, 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) } + } +} diff --git a/app/src/test/java/dev/daubney/scrobbled/data/api/LastFmClientTest.kt b/app/src/test/java/dev/daubney/scrobbled/data/api/LastFmClientTest.kt new file mode 100644 index 0000000..ae24ea8 --- /dev/null +++ b/app/src/test/java/dev/daubney/scrobbled/data/api/LastFmClientTest.kt @@ -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 { + 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) = + 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("Bad gateway")) + try { + client.updateNowPlaying("sk", ScrobbleTrack("A", "T")) + fail("expected exception") + } catch (e: LastFmException) { + assertEquals(-1, e.code) + } + } +} diff --git a/app/src/test/java/dev/daubney/scrobbled/data/api/SignerTest.kt b/app/src/test/java/dev/daubney/scrobbled/data/api/SignerTest.kt new file mode 100644 index 0000000..83a27cf --- /dev/null +++ b/app/src/test/java/dev/daubney/scrobbled/data/api/SignerTest.kt @@ -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")) + } +} diff --git a/build.gradle.kts b/build.gradle.kts index b546c74..371e867 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,4 +2,5 @@ plugins { alias(libs.plugins.android.application) apply false alias(libs.plugins.kotlin.compose) apply false + alias(libs.plugins.kotlin.serialization) apply false } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 446e5f6..09e7a88 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -9,6 +9,9 @@ navigationCompose = "2.9.0" junit = "4.13.2" junitVersion = "1.1.5" espressoCore = "3.5.1" +okhttp = "4.12.0" +serialization = "1.8.1" +coroutines = "1.10.2" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } @@ -20,6 +23,11 @@ androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "u androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" } androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" } +okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" } +okhttp-mockwebserver = { group = "com.squareup.okhttp3", name = "mockwebserver", version.ref = "okhttp" } +kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" } +kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "coroutines" } +kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" } junit = { group = "junit", name = "junit", version.ref = "junit" } androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" } androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" } @@ -27,3 +35,4 @@ androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-co [plugins] android-application = { id = "com.android.application", version.ref = "agp" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }