Add TrackDraft and scrobble submission
TrackDraft is the editable track shared by all add paths, validated against the server's 14-day / 5-minute window. ScrobbleRepository submits via track.scrobble with the stored session key, treating an "ignored" result or an invalid session as errors. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
01b17fd179
commit
e4c19cc9ac
4 files changed
+205
No files matched your search
@@ -0,0 +1,31 @@
|
||||
package dev.daubney.scrobbled.data.scrobble
|
||||
|
||||
import dev.daubney.scrobbled.data.api.LastFmClient
|
||||
import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.history.SessionExpiredException
|
||||
|
||||
interface ScrobbleRepository {
|
||||
/** Submits one scrobble; throws if it can't be accepted. */
|
||||
suspend fun submit(draft: TrackDraft)
|
||||
}
|
||||
|
||||
class DefaultScrobbleRepository(
|
||||
private val auth: AuthRepository,
|
||||
private val lastFmFor: (url: String, key: String, secret: String) -> LastFmClient =
|
||||
{ url, key, secret -> LastFmClient(url, key, secret) },
|
||||
) : ScrobbleRepository {
|
||||
|
||||
override suspend fun submit(draft: TrackDraft) {
|
||||
draft.validate()?.let { throw IllegalArgumentException(it) }
|
||||
val creds = auth.current() ?: throw SessionExpiredException()
|
||||
val result = try {
|
||||
lastFmFor(creds.serverUrl, creds.apiKey, creds.apiSecret)
|
||||
.scrobble(creds.sessionKey, listOf(draft.toScrobbleTrack()))
|
||||
} catch (e: LastFmException) {
|
||||
throw if (e.isInvalidSession) SessionExpiredException() else e
|
||||
}
|
||||
// The server reports bad or stale tracks as "ignored" rather than as an error.
|
||||
if (result.accepted < 1) throw IllegalStateException("The server didn't accept this scrobble")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package dev.daubney.scrobbled.data.scrobble
|
||||
|
||||
import dev.daubney.scrobbled.data.api.ScrobbleTrack
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
|
||||
/**
|
||||
* An editable track about to be scrobbled. Every way of adding one (manual entry, MusicBrainz
|
||||
* search, audio recognition) ends up as a draft the user can correct before submitting.
|
||||
*/
|
||||
data class TrackDraft(
|
||||
val artist: String = "",
|
||||
val track: String = "",
|
||||
val album: String = "",
|
||||
val albumArtist: String = "",
|
||||
val durationSeconds: Int? = null,
|
||||
val mbid: String = "",
|
||||
val playedAt: Instant = Instant.now(),
|
||||
) {
|
||||
/** A user-facing problem with this draft, or null if it can be submitted. */
|
||||
fun validate(now: Instant = Instant.now()): String? = when {
|
||||
artist.isBlank() -> "Enter an artist"
|
||||
track.isBlank() -> "Enter a track title"
|
||||
playedAt.isAfter(now.plus(MAX_FUTURE)) -> "The play time can't be in the future"
|
||||
playedAt.isBefore(now.minus(MAX_AGE)) -> "The server only accepts plays from the last 14 days"
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun toScrobbleTrack() = ScrobbleTrack(
|
||||
artist = artist.trim(),
|
||||
track = track.trim(),
|
||||
timestamp = playedAt.epochSecond,
|
||||
album = album.trim().ifEmpty { null },
|
||||
albumArtist = albumArtist.trim().ifEmpty { null },
|
||||
durationSeconds = durationSeconds,
|
||||
mbid = mbid.trim().ifEmpty { null },
|
||||
)
|
||||
|
||||
companion object {
|
||||
// Server limits (scrobbler/config.py): at most 14 days old and 5 minutes in the future.
|
||||
val MAX_AGE: Duration = Duration.ofDays(14)
|
||||
val MAX_FUTURE: Duration = Duration.ofMinutes(5)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package dev.daubney.scrobbled.data.scrobble
|
||||
|
||||
import dev.daubney.scrobbled.data.api.LastFmClient
|
||||
import dev.daubney.scrobbled.data.api.LastFmException
|
||||
import dev.daubney.scrobbled.data.auth.AuthRepository
|
||||
import dev.daubney.scrobbled.data.auth.Credentials
|
||||
import dev.daubney.scrobbled.data.history.SessionExpiredException
|
||||
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.assertTrue
|
||||
import org.junit.Assert.fail
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
import java.net.URLDecoder
|
||||
import java.time.Instant
|
||||
|
||||
class ScrobbleRepositoryTest {
|
||||
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: DefaultScrobbleRepository
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
server = MockWebServer().also { it.start() }
|
||||
creds = Credentials(server.url("/").toString().trimEnd('/'), "alice", "tok", "key", "secret", "sess")
|
||||
repo = DefaultScrobbleRepository(auth) { url, key, secret -> LastFmClient(url, key, secret) }
|
||||
}
|
||||
|
||||
@After fun tearDown() = server.shutdown()
|
||||
|
||||
private val draft get() = TrackDraft(artist = "A", track = "T", album = "Al", playedAt = Instant.now())
|
||||
private fun ok(accepted: Int, ignored: Int) = MockResponse().setBody(
|
||||
"""{"scrobbles":{"scrobble":[],"@attr":{"accepted":"$accepted","ignored":"$ignored"}}}""")
|
||||
|
||||
@Test
|
||||
fun submitSendsSessionKeyAndFields() = runTest {
|
||||
server.enqueue(ok(1, 0))
|
||||
repo.submit(draft)
|
||||
val body = URLDecoder.decode(server.takeRequest().body.readUtf8(), "UTF-8")
|
||||
assertTrue(body.contains("sk=sess"))
|
||||
assertTrue(body.contains("artist[0]=A"))
|
||||
assertTrue(body.contains("album[0]=Al"))
|
||||
assertTrue(body.contains("api_key=key"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun ignoredScrobbleIsAnError() = runTest {
|
||||
server.enqueue(ok(0, 1))
|
||||
try { repo.submit(draft); fail() } catch (e: IllegalStateException) {
|
||||
assertEquals("The server didn't accept this scrobble", e.message)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidSessionBecomesSessionExpired() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":9,"message":"Invalid session key"}"""))
|
||||
try { repo.submit(draft); fail() } catch (e: SessionExpiredException) { }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun otherServerErrorsPropagate() = runTest {
|
||||
server.enqueue(MockResponse().setResponseCode(500).setBody("""{"error":8,"message":"Operation failed"}"""))
|
||||
try { repo.submit(draft); fail() } catch (e: LastFmException) { assertEquals(8, e.code) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun invalidDraftNeverHitsTheNetwork() = runTest {
|
||||
try { repo.submit(TrackDraft(artist = "", track = "T")); fail() } catch (e: IllegalArgumentException) { }
|
||||
assertEquals(0, server.requestCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noCredentialsIsSessionExpired() = runTest {
|
||||
creds = null
|
||||
try { repo.submit(draft); fail() } catch (e: SessionExpiredException) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.daubney.scrobbled.data.scrobble
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotNull
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Test
|
||||
import java.time.Duration
|
||||
import java.time.Instant
|
||||
|
||||
class TrackDraftTest {
|
||||
private val now = Instant.parse("2026-10-12T12:00:00Z")
|
||||
private fun draft(playedAt: Instant = now, artist: String = "A", track: String = "T") =
|
||||
TrackDraft(artist = artist, track = track, playedAt = playedAt)
|
||||
|
||||
@Test fun validDraftHasNoError() = assertNull(draft().validate(now))
|
||||
@Test fun blankArtistRejected() = assertEquals("Enter an artist", draft(artist = " ").validate(now))
|
||||
@Test fun blankTrackRejected() = assertEquals("Enter a track title", draft(track = "").validate(now))
|
||||
|
||||
@Test
|
||||
fun fiveMinutesAheadAllowedButNotMore() {
|
||||
assertNull(draft(now.plus(Duration.ofMinutes(5))).validate(now))
|
||||
assertNotNull(draft(now.plus(Duration.ofMinutes(6))).validate(now))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun fourteenDaysOldAllowedButNotMore() {
|
||||
assertNull(draft(now.minus(Duration.ofDays(14))).validate(now))
|
||||
assertNotNull(draft(now.minus(Duration.ofDays(14)).minusSeconds(1)).validate(now))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toScrobbleTrackTrimsAndOmitsBlanks() {
|
||||
val t = TrackDraft(
|
||||
artist = " Björk ", track = " Army of Me ", album = " ", albumArtist = "", mbid = " ",
|
||||
durationSeconds = 235, playedAt = now,
|
||||
).toScrobbleTrack()
|
||||
assertEquals("Björk", t.artist)
|
||||
assertEquals("Army of Me", t.track)
|
||||
assertNull(t.album)
|
||||
assertNull(t.albumArtist)
|
||||
assertNull(t.mbid)
|
||||
assertEquals(235, t.durationSeconds)
|
||||
assertEquals(now.epochSecond, t.timestamp)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user