Add ACRCloud recognizer and encrypted recognition config

AcrCloudRecognizer calls the HTTP identify API (HMAC-SHA1 signed multipart
with a WAV-wrapped clip) and maps results, including MusicBrainz ids when
present and actionable errors for bad keys, limits and no match. Config is
stored encrypted via a shared KeystoreBox extracted from the credential
store (existing installs stay signed in).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-12 12:28:30 +01:00
1 parent f80494241b
commit c5eeb4e1d2
6 files changed
+398 -51

No files matched your search

@@ -0,0 +1,58 @@
package dev.daubney.scrobbled.data.auth
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/** One string stored encrypted with an AES-GCM key held in the Android Keystore. */
class KeystoreBox(context: Context, prefsName: String, private val alias: String, private val prefKey: String = "blob") {
private val prefs = context.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
fun load(): String? {
val encoded = prefs.getString(prefKey, null) ?: return null
return try {
val blob = Base64.decode(encoded, Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORM)
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, blob.copyOfRange(0, IV_SIZE)))
String(cipher.doFinal(blob, IV_SIZE, blob.size - IV_SIZE))
} catch (e: Exception) {
// Key invalidated or data corrupt: treat as empty rather than crash.
clear()
null
}
}
fun save(plain: String) {
val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
val blob = cipher.iv + cipher.doFinal(plain.toByteArray())
prefs.edit().putString(prefKey, Base64.encodeToString(blob, Base64.NO_WRAP)).apply()
}
fun clear() {
prefs.edit().remove(prefKey).apply()
}
private fun secretKey(): SecretKey {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(ks.getKey(alias, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(
KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build(),
)
}.generateKey()
}
private companion object {
const val TRANSFORM = "AES/GCM/NoPadding"
const val IV_SIZE = 12
}
}
@@ -1,61 +1,16 @@
package dev.daubney.scrobbled.data.auth
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import kotlinx.serialization.json.Json
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
/** Stores [Credentials] encrypted with an AES-GCM key held in the Android Keystore. */
/** Stores [Credentials] encrypted at rest. Names match the original implementation so existing installs stay signed in. */
class KeystoreCredentialStore(context: Context) : CredentialStore {
private val prefs = context.getSharedPreferences("credentials", Context.MODE_PRIVATE)
private val box = KeystoreBox(context, prefsName = "credentials", alias = "scrobbled_credentials")
override fun load(): Credentials? {
val encoded = prefs.getString(KEY_BLOB, null) ?: return null
return try {
val blob = Base64.decode(encoded, Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORM)
cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(128, blob.copyOfRange(0, IV_SIZE)))
Json.decodeFromString<Credentials>(String(cipher.doFinal(blob, IV_SIZE, blob.size - IV_SIZE)))
} catch (e: Exception) {
// Key invalidated or data corrupt: treat as signed out rather than crash.
clear()
null
}
override fun load(): Credentials? = box.load()?.let {
try { Json.decodeFromString<Credentials>(it) } catch (e: Exception) { box.clear(); null }
}
override fun save(credentials: Credentials) {
val cipher = Cipher.getInstance(TRANSFORM).apply { init(Cipher.ENCRYPT_MODE, secretKey()) }
val blob = cipher.iv + cipher.doFinal(Json.encodeToString(Credentials.serializer(), credentials).toByteArray())
prefs.edit().putString(KEY_BLOB, Base64.encodeToString(blob, Base64.NO_WRAP)).apply()
}
override fun clear() {
prefs.edit().remove(KEY_BLOB).apply()
}
private fun secretKey(): SecretKey {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply {
init(
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build(),
)
}.generateKey()
}
private companion object {
const val ALIAS = "scrobbled_credentials"
const val KEY_BLOB = "blob"
const val TRANSFORM = "AES/GCM/NoPadding"
const val IV_SIZE = 12
}
override fun save(credentials: Credentials) = box.save(Json.encodeToString(Credentials.serializer(), credentials))
override fun clear() = box.clear()
}
@@ -0,0 +1,124 @@
package dev.daubney.scrobbled.data.recognition
import dev.daubney.scrobbled.data.search.TrackResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
/** Identifies music with ACRCloud's HTTP "identify" API (https://docs.acrcloud.com/reference/identification-api). */
class AcrCloudRecognizer(
private val config: () -> RecognitionConfig?,
private val http: OkHttpClient = OkHttpClient(),
private val baseUrlFor: (host: String) -> String = { "https://$it" },
private val nowSeconds: () -> Long = { System.currentTimeMillis() / 1000 },
) : Recognizer {
override suspend fun recognize(clip: AudioClip): TrackResult? {
val cfg = config()?.takeIf { it.isComplete } ?: throw ListenException("ACRCloud isn't set up. Add your keys in Settings.")
val wav = clip.toWav()
val timestamp = nowSeconds().toString()
val body = MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("access_key", cfg.accessKey)
.addFormDataPart("data_type", DATA_TYPE)
.addFormDataPart("signature_version", SIGNATURE_VERSION)
.addFormDataPart("signature", sign(cfg.accessKey, cfg.accessSecret, timestamp))
.addFormDataPart("timestamp", timestamp)
.addFormDataPart("sample_bytes", wav.size.toString())
.addFormDataPart("sample", "sample.wav", wav.toRequestBody("audio/wav".toMediaType()))
.build()
val request = Request.Builder().url("${baseUrlFor(cfg.host)}$URI").post(body).build()
val text = withContext(Dispatchers.IO) {
try {
http.newCall(request).execute().use { it.body?.string().orEmpty() }
} catch (e: IOException) {
throw ListenException("Couldn't reach ACRCloud: ${e.message}")
}
}
return parse(text)
}
private fun parse(text: String): TrackResult? {
val root = try {
Json.parseToJsonElement(text).jsonObject
} catch (e: Exception) {
throw ListenException("Unexpected response from ACRCloud")
}
val status = root["status"]?.jsonObject
val code = status?.get("code")?.jsonPrimitive?.longOrNull?.toInt() ?: throw ListenException("Unexpected response from ACRCloud")
val message = status["msg"].str().orEmpty()
when (code) {
0 -> Unit
1001, 2004 -> return null // no match / nothing fingerprintable (e.g. silence)
3001, 3002, 3014 -> throw ListenException("ACRCloud rejected your keys. Check them in Settings.")
3003 -> throw ListenException("ACRCloud request limit reached.")
else -> throw ListenException("ACRCloud error $code: $message")
}
val music = root["metadata"]?.jsonObject?.get("music")?.jsonArray?.firstOrNull()?.jsonObject ?: return null
val title = music["title"].str()?.takeIf { it.isNotBlank() } ?: return null
val artist = music["artists"]?.jsonArray?.mapNotNull { it.jsonObject["name"].str() }?.joinToString(", ").orEmpty()
if (artist.isBlank()) return null
return TrackResult(
mbid = musicBrainzId(music).orEmpty(),
artist = artist,
track = title,
album = (music["album"] as? JsonObject)?.get("name").str()?.takeIf { it.isNotBlank() },
durationSeconds = (music["duration_ms"] as? JsonPrimitive)?.longOrNull?.let { (it / 1000).toInt() },
)
}
/** ACRCloud includes MusicBrainz ids in `external_metadata.musicbrainz` for projects with that source enabled. */
private fun musicBrainzId(music: JsonObject): String? {
val mb = (music["external_metadata"] as? JsonObject)?.get("musicbrainz")
val first = when (mb) {
is JsonObject -> mb
is kotlinx.serialization.json.JsonArray -> mb.firstOrNull() as? JsonObject
else -> null
}
return ((first?.get("track") as? JsonObject)?.get("id")).str()
}
private fun kotlinx.serialization.json.JsonElement?.str() = (this as? JsonPrimitive)?.contentOrNull
companion object {
private const val URI = "/v1/identify"
private const val DATA_TYPE = "audio"
private const val SIGNATURE_VERSION = "1"
/** `base64(hmac_sha1(secret, "POST\n/v1/identify\n{key}\naudio\n1\n{timestamp}"))`. */
fun sign(accessKey: String, secret: String, timestamp: String): String {
val toSign = listOf("POST", URI, accessKey, DATA_TYPE, SIGNATURE_VERSION, timestamp).joinToString("\n")
val mac = Mac.getInstance("HmacSHA1").apply { init(SecretKeySpec(secret.toByteArray(Charsets.UTF_8), "HmacSHA1")) }
return java.util.Base64.getEncoder().encodeToString(mac.doFinal(toSign.toByteArray(Charsets.UTF_8)))
}
}
}
/** Wraps the raw 16-bit mono PCM in a canonical 44-byte WAV header. */
fun AudioClip.toWav(): ByteArray {
val dataSize = pcm.size
val out = java.io.ByteArrayOutputStream(44 + dataSize)
fun int(v: Int) = out.write(byteArrayOf(v.toByte(), (v shr 8).toByte(), (v shr 16).toByte(), (v shr 24).toByte()))
fun short(v: Int) = out.write(byteArrayOf(v.toByte(), (v shr 8).toByte()))
out.write("RIFF".toByteArray()); int(36 + dataSize); out.write("WAVE".toByteArray())
out.write("fmt ".toByteArray()); int(16); short(1) /* PCM */; short(1) /* mono */
int(sampleRate); int(sampleRate * 2); short(2); short(16)
out.write("data".toByteArray()); int(dataSize)
out.write(pcm)
return out.toByteArray()
}
@@ -0,0 +1,35 @@
package dev.daubney.scrobbled.data.recognition
import android.content.Context
import dev.daubney.scrobbled.data.auth.KeystoreBox
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
/** ACRCloud project credentials, from the project's page in the ACRCloud console. */
@Serializable
data class RecognitionConfig(val host: String, val accessKey: String, val accessSecret: String) {
val isComplete get() = host.isNotBlank() && accessKey.isNotBlank() && accessSecret.isNotBlank()
/** Tidies what users paste: "https://identify-eu-west-1.acrcloud.com/" becomes the bare host. */
fun normalized() = copy(
host = host.trim().removePrefix("https://").removePrefix("http://").trimEnd('/'),
accessKey = accessKey.trim(), accessSecret = accessSecret.trim(),
)
}
interface RecognitionConfigStore {
fun load(): RecognitionConfig?
fun save(config: RecognitionConfig)
fun clear()
}
class KeystoreRecognitionConfigStore(context: Context) : RecognitionConfigStore {
private val box = KeystoreBox(context, prefsName = "recognition", alias = "scrobbled_recognition")
override fun load(): RecognitionConfig? = box.load()?.let {
try { Json.decodeFromString<RecognitionConfig>(it).takeIf { c -> c.isComplete } } catch (e: Exception) { box.clear(); null }
}
override fun save(config: RecognitionConfig) = box.save(Json.encodeToString(RecognitionConfig.serializer(), config.normalized()))
override fun clear() = box.clear()
}
@@ -0,0 +1,155 @@
package dev.daubney.scrobbled.data.recognition
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.assertTrue
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
class AcrCloudRecognizerTest {
private lateinit var server: MockWebServer
private var config: RecognitionConfig? = RecognitionConfig("unused.example", "accesskey123", "s3cr3t-äö")
private lateinit var recognizer: AcrCloudRecognizer
private val clip = AudioClip(ByteArray(160) { it.toByte() }, 8000)
@Before fun setUp() {
server = MockWebServer().also { it.start() }
recognizer = AcrCloudRecognizer({ config }, baseUrlFor = { server.url("/").toString().trimEnd('/') }, nowSeconds = { 1_700_000_000 })
}
@After fun tearDown() = server.shutdown()
private fun respond(body: String) = server.enqueue(MockResponse().setBody(body))
@Test
fun signatureMatchesReferenceValue() {
// Expected value computed independently with Python's hmac/hashlib/base64.
assertEquals("jy7SsBkRtn2iahO5ebTbRIVPXhI=", AcrCloudRecognizer.sign("accesskey123", "s3cr3t-äö", "1700000000"))
}
@Test
fun wavHasCanonicalHeader() {
val wav = clip.toWav()
assertEquals(44 + 160, wav.size)
assertEquals("RIFF", String(wav, 0, 4))
assertEquals("WAVE", String(wav, 8, 4))
assertEquals("data", String(wav, 36, 4))
fun le32(o: Int) = (wav[o].toInt() and 0xFF) or ((wav[o + 1].toInt() and 0xFF) shl 8) or
((wav[o + 2].toInt() and 0xFF) shl 16) or ((wav[o + 3].toInt() and 0xFF) shl 24)
assertEquals(36 + 160, le32(4))
assertEquals(8000, le32(24))
assertEquals(16_000, le32(28))
assertEquals(160, le32(40))
}
@Test
fun successMapsTrack() = runTest {
respond("""{"status":{"msg":"Success","code":0,"version":"1.0"},"metadata":{"music":[
{"title":"Reckoner","duration_ms":290000,"artists":[{"name":"Radiohead"}],"album":{"name":"In Rainbows"},
"external_metadata":{"musicbrainz":{"track":{"id":"mb-123"}}}}]}}""")
val r = recognizer.recognize(clip)!!
assertEquals("Radiohead", r.artist)
assertEquals("Reckoner", r.track)
assertEquals("In Rainbows", r.album)
assertEquals(290, r.durationSeconds)
assertEquals("mb-123", r.mbid)
}
@Test
fun missingOptionalFieldsAreFine() = runTest {
respond("""{"status":{"code":0},"metadata":{"music":[{"title":"Song","artists":[{"name":"A"},{"name":"B"}]}]}}""")
val r = recognizer.recognize(clip)!!
assertEquals("A, B", r.artist)
assertNull(r.album)
assertNull(r.durationSeconds)
assertEquals("", r.mbid)
}
@Test
fun musicBrainzIdAsArrayIsAccepted() = runTest {
respond("""{"status":{"code":0},"metadata":{"music":[{"title":"S","artists":[{"name":"A"}],
"external_metadata":{"musicbrainz":[{"track":{"id":"mb-9"}}]}}]}}""")
assertEquals("mb-9", recognizer.recognize(clip)!!.mbid)
}
@Test
fun noMatchReturnsNull() = runTest {
respond("""{"status":{"msg":"No result","code":1001,"version":"1.0"}}""")
assertNull(recognizer.recognize(clip))
}
@Test
fun silenceCannotBeFingerprintedAndCountsAsNoMatch() = runTest {
respond("""{"status":{"msg":"Can't generate fingerprint","code":2004}}""")
assertNull(recognizer.recognize(clip))
}
@Test
fun badKeysGiveActionableMessage() = runTest {
respond("""{"status":{"msg":"invalid access key","code":3001}}""")
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertEquals("ACRCloud rejected your keys. Check them in Settings.", e.message)
}
}
@Test
fun limitReachedIsReported() = runTest {
respond("""{"status":{"msg":"limit exceeded","code":3003}}""")
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertEquals("ACRCloud request limit reached.", e.message)
}
}
@Test
fun unknownErrorCodeIncludesServiceMessage() = runTest {
respond("""{"status":{"msg":"Something odd","code":4000}}""")
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertEquals("ACRCloud error 4000: Something odd", e.message)
}
}
@Test
fun garbageResponseIsReported() = runTest {
respond("<html>")
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertEquals("Unexpected response from ACRCloud", e.message)
}
}
@Test
fun unreachableServiceIsReported() = runTest {
server.shutdown()
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertTrue(e.message!!.startsWith("Couldn't reach ACRCloud"))
}
}
@Test
fun missingConfigAsksUserToSetItUp() = runTest {
config = null
try { recognizer.recognize(clip); fail() } catch (e: ListenException) {
assertTrue(e.message!!.contains("Settings"))
}
assertEquals(0, server.requestCount)
}
@Test
fun requestIsSignedMultipartToIdentifyEndpoint() = runTest {
respond("""{"status":{"code":1001}}""")
recognizer.recognize(clip)
val req = server.takeRequest()
assertEquals("/v1/identify", req.path)
assertTrue(req.getHeader("Content-Type")!!.startsWith("multipart/form-data"))
val body = req.body.readUtf8()
for (part in listOf("access_key", "data_type", "signature_version", "signature", "timestamp", "sample_bytes", "sample")) {
assertTrue("missing part $part", body.contains("name=\"$part\""))
}
assertTrue(body.contains("jy7SsBkRtn2iahO5ebTbRIVPXhI="))
assertTrue(body.contains("1700000000"))
assertTrue(body.contains("RIFF"))
}
}
@@ -0,0 +1,20 @@
package dev.daubney.scrobbled.data.recognition
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RecognitionConfigTest {
@Test fun completeNeedsAllThreeFields() {
assertTrue(RecognitionConfig("h", "k", "s").isComplete)
assertFalse(RecognitionConfig("h", "", "s").isComplete)
assertFalse(RecognitionConfig(" ", "k", "s").isComplete)
assertFalse(RecognitionConfig("h", "k", "").isComplete)
}
@Test fun normalizedTidiesPastedValues() {
val c = RecognitionConfig(" https://identify-eu-west-1.acrcloud.com/ ", " key ", " secret\n").normalized()
assertEquals(RecognitionConfig("identify-eu-west-1.acrcloud.com", "key", "secret"), c)
}
}