diff --git a/app/src/main/java/dev/daubney/scrobbled/data/api/ScrobblerApi.kt b/app/src/main/java/dev/daubney/scrobbled/data/api/ScrobblerApi.kt index 0f48413..b2d9e36 100644 --- a/app/src/main/java/dev/daubney/scrobbled/data/api/ScrobblerApi.kt +++ b/app/src/main/java/dev/daubney/scrobbled/data/api/ScrobblerApi.kt @@ -3,8 +3,14 @@ package dev.daubney.scrobbled.data.api import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonArray +import dev.daubney.scrobbled.data.history.NowPlaying +import dev.daubney.scrobbled.data.history.RecentScrobble +import dev.daubney.scrobbled.data.history.ScrobblePage +import dev.daubney.scrobbled.data.history.Summary import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonArray @@ -17,6 +23,7 @@ import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody import java.io.IOException +import java.time.OffsetDateTime data class ApiApp(val name: String, val apiKey: String, val sharedSecret: String) @@ -47,13 +54,43 @@ class ScrobblerApi( suspend fun createApp(token: String, name: String): ApiApp = send("apps", token, buildJsonObject { put("name", name) }).jsonObject.toApp() + suspend fun nowPlaying(token: String): NowPlaying? { + val np = send("me/now-playing", token, null).jsonObject["now_playing"] as? JsonObject ?: return null + return NowPlaying( + artist = np.req("artist"), track = np.req("track"), album = np.str("album"), + durationSeconds = np.int("duration"), + startedAt = np.instant("started_at") ?: return null, + expiresAt = np.instant("expires_at") ?: return null, + ) + } + + suspend fun recent(token: String, page: Int, limit: Int): ScrobblePage { + val root = send("me/recent?page=$page&limit=$limit", token, null).jsonObject + val items = root["items"]?.jsonArray.orEmpty().mapNotNull { + val o = it.jsonObject + RecentScrobble(o.req("artist"), o.req("track"), o.str("album"), o.instant("played_at") ?: return@mapNotNull null) + } + return ScrobblePage(items, root.int("page") ?: page, root.int("total_pages") ?: page, root.int("total") ?: items.size) + } + + suspend fun summary(token: String): Summary { + val o = send("me/summary", token, null).jsonObject + return Summary(o.int("scrobbles") ?: 0, o.int("artists") ?: 0, o.int("tracks") ?: 0, o.instant("first_scrobble_at")) + } + private fun JsonObject.toApp() = ApiApp( name = str("name").orEmpty(), apiKey = str("api_key") ?: throw ApiException(-1, null, "App had no api_key"), sharedSecret = str("shared_secret") ?: throw ApiException(-1, null, "App had no shared_secret"), ) - private fun JsonObject.str(key: String) = this[key]?.jsonPrimitive?.content + /** Null for missing keys and JSON nulls (`jsonPrimitive.content` would give the string "null"). */ + private fun JsonObject.str(key: String) = (this[key] as? JsonPrimitive)?.takeIf { it !is JsonNull }?.content + + private fun JsonObject.req(key: String) = str(key) ?: throw ApiException(-1, null, "Missing $key in response") + private fun JsonObject.int(key: String) = (this[key] as? JsonPrimitive)?.intOrNull + private fun JsonObject.instant(key: String) = + str(key)?.let { runCatching { OffsetDateTime.parse(it).toInstant() }.getOrNull() } /** GET when [body] is null, otherwise POST JSON. */ private suspend fun send(path: String, token: String?, body: JsonObject?): JsonElement = diff --git a/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryModels.kt b/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryModels.kt new file mode 100644 index 0000000..507be1d --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryModels.kt @@ -0,0 +1,30 @@ +package dev.daubney.scrobbled.data.history + +import java.time.Instant + +data class NowPlaying( + val artist: String, + val track: String, + val album: String?, + val durationSeconds: Int?, + val startedAt: Instant, + val expiresAt: Instant, +) + +data class RecentScrobble( + val artist: String, + val track: String, + val album: String?, + val playedAt: Instant, +) { + /** Scrobbles are unique per (artist, track, playedAt) on the server. */ + val key get() = "$artist\u0000$track\u0000${playedAt.epochSecond}" +} + +data class ScrobblePage(val items: List, val page: Int, val totalPages: Int, val total: Int) { + val hasMore get() = page < totalPages +} + +data class Summary(val scrobbles: Int, val artists: Int, val tracks: Int, val firstScrobbleAt: Instant?) + +class SessionExpiredException : Exception("Your session has expired. Sign out and sign in again.") diff --git a/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryRepository.kt b/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryRepository.kt new file mode 100644 index 0000000..659fa3c --- /dev/null +++ b/app/src/main/java/dev/daubney/scrobbled/data/history/HistoryRepository.kt @@ -0,0 +1,35 @@ +package dev.daubney.scrobbled.data.history + +import dev.daubney.scrobbled.data.api.ApiException +import dev.daubney.scrobbled.data.api.ScrobblerApi +import dev.daubney.scrobbled.data.auth.AuthRepository + +interface HistoryRepository { + suspend fun nowPlaying(): NowPlaying? + suspend fun recent(page: Int, limit: Int = PAGE_SIZE): ScrobblePage + suspend fun summary(): Summary + + companion object { + const val PAGE_SIZE = 50 + } +} + +/** Reads the signed-in user's data with the stored bearer token. A 401 means the 30-day token lapsed. */ +class DefaultHistoryRepository( + private val auth: AuthRepository, + private val apiFor: (String) -> ScrobblerApi = { ScrobblerApi(it) }, +) : HistoryRepository { + + override suspend fun nowPlaying() = call { api, token -> api.nowPlaying(token) } + override suspend fun recent(page: Int, limit: Int) = call { api, token -> api.recent(token, page, limit) } + override suspend fun summary() = call { api, token -> api.summary(token) } + + private suspend fun call(block: suspend (ScrobblerApi, String) -> T): T { + val creds = auth.current() ?: throw SessionExpiredException() + try { + return block(apiFor(creds.serverUrl), creds.bearerToken) + } catch (e: ApiException) { + throw if (e.status == 401) SessionExpiredException() else e + } + } +} diff --git a/app/src/test/java/dev/daubney/scrobbled/data/history/HistoryRepositoryTest.kt b/app/src/test/java/dev/daubney/scrobbled/data/history/HistoryRepositoryTest.kt new file mode 100644 index 0000000..ec841c5 --- /dev/null +++ b/app/src/test/java/dev/daubney/scrobbled/data/history/HistoryRepositoryTest.kt @@ -0,0 +1,115 @@ +package dev.daubney.scrobbled.data.history + +import dev.daubney.scrobbled.data.api.ApiException +import dev.daubney.scrobbled.data.auth.AuthRepository +import dev.daubney.scrobbled.data.auth.Credentials +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.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test +import java.time.Instant + +class HistoryRepositoryTest { + private lateinit var server: MockWebServer + private var creds: Credentials? = null + + private val auth = object : AuthRepository { + override fun current() = creds + override suspend fun connect(serverUrl: String, username: String, password: String) = error("unused") + override fun disconnect() {} + } + private lateinit var repo: DefaultHistoryRepository + + @Before + fun setUp() { + server = MockWebServer().also { it.start() } + creds = Credentials(server.url("/").toString().trimEnd('/'), "alice", "tok", "k", "s", "sk") + repo = DefaultHistoryRepository(auth) + } + + @After + fun tearDown() = server.shutdown() + + @Test + fun nowPlayingParsesTrackAndSendsBearer() = runTest { + server.enqueue(MockResponse().setBody( + """{"now_playing":{"artist":"Radiohead","track":"Reckoner","album":null,"duration":290, + "started_at":"2026-10-12T10:00:00+00:00","expires_at":"2026-10-12T10:04:50+00:00"}}""")) + val np = repo.nowPlaying()!! + assertEquals("Radiohead", np.artist) + assertNull(np.album) // JSON null must not become the string "null" + assertEquals(290, np.durationSeconds) + assertEquals(Instant.parse("2026-10-12T10:00:00Z"), np.startedAt) + val req = server.takeRequest() + assertEquals("/api/v1/me/now-playing", req.path) + assertEquals("Bearer tok", req.getHeader("Authorization")) + } + + @Test + fun nowPlayingNullWhenNothingPlaying() = runTest { + server.enqueue(MockResponse().setBody("""{"now_playing":null}""")) + assertNull(repo.nowPlaying()) + } + + @Test + fun recentParsesPage() = runTest { + server.enqueue(MockResponse().setBody( + """{"items":[{"artist":"A","track":"T","album":"Al","album_artist":null,"duration":null, + "played_at":"2026-10-12T10:15:02.494847+00:00"}],"page":2,"per_page":50,"total":120,"total_pages":3}""")) + val page = repo.recent(2, 50) + assertEquals("/api/v1/me/recent?page=2&limit=50", server.takeRequest().path) + assertEquals(1, page.items.size) + assertEquals("Al", page.items[0].album) + assertEquals(Instant.parse("2026-10-12T10:15:02Z").epochSecond, page.items[0].playedAt.epochSecond) + assertEquals(2, page.page) + assertEquals(120, page.total) + assertTrue(page.hasMore) + } + + @Test + fun lastPageHasNoMore() = runTest { + server.enqueue(MockResponse().setBody("""{"items":[],"page":3,"per_page":50,"total":120,"total_pages":3}""")) + assertFalse(repo.recent(3).hasMore) + } + + @Test + fun summaryParses() = runTest { + server.enqueue(MockResponse().setBody( + """{"scrobbles":10,"artists":4,"tracks":7,"first_scrobble_at":"2026-01-01T00:00:00+00:00"}""")) + assertEquals(Summary(10, 4, 7, Instant.parse("2026-01-01T00:00:00Z")), repo.summary()) + } + + @Test + fun summaryForNewUserHasNoFirstScrobble() = runTest { + server.enqueue(MockResponse().setBody("""{"scrobbles":0,"artists":0,"tracks":0,"first_scrobble_at":null}""")) + assertNull(repo.summary().firstScrobbleAt) + } + + @Test + fun unauthorizedBecomesSessionExpired() = runTest { + server.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":{"code":"unauthorized","message":"no"}}""")) + try { repo.summary(); fail() } catch (e: SessionExpiredException) { } + } + + @Test + fun noCredentialsIsSessionExpired() = runTest { + creds = null + try { repo.recent(1); fail() } catch (e: SessionExpiredException) { } + } + + @Test + fun otherServerErrorsPropagate() = runTest { + server.enqueue(MockResponse().setResponseCode(500).setBody("""{"error":{"code":"boom","message":"Kaput"}}""")) + try { repo.summary(); fail() } catch (e: ApiException) { + assertEquals(500, e.status) + assertEquals("Kaput", e.message) + } + } +}