Modern Apps git

← Modern-Apps.git

musicbrainz: point at self-hosted API, drop rate limiter

Commit
15e58688211bec23c08fdb53ba066375273b1ead
Author
vayun-mathur <[email protected]>
When
2026-08-20 21:09 UTC (3 months ago)
Parents
c6fcc7a

Diff

musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.ktindex dfd8b6bcd7..602e86c69e 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt@@ -11,7 +11,7 @@ import java.util.Locale class MusicBrainzApplication : Application() {     override fun onCreate() {         super.onCreate()-        // MUSICBRAINZ rather than STANDARD: musicbrainz.org and lrclib.net are ISRG,+        // MUSICBRAINZ rather than STANDARD: api.vayunmathur.com and lrclib.net are ISRG,         // coverartarchive.org redirects to archive.org / ia*.us.archive.org on GoDaddy certs,         // and Tidal's Fastly-fronted audio CDN is GlobalSign - the last of which is the one         // root STANDARD does not carry.
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.ktindex c408280f4a..77e96db910 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/VorbisComments.kt@@ -10,6 +10,10 @@ import java.util.Base64  * base64-encoded into a `METADATA_BLOCK_PICTURE` comment wrapping a FLAC-style picture  * block. The keys match what [com.vayunmathur.musicbrainz.data.library.TagReader] reads back,  * so a download is recognised as owned on the next library scan.+ *+ * `MUSICBRAINZ_RELEASETRACKID` is deliberately not among them: the catalogue carries no+ * per-track MBID, so there is never a value to write. TagReader still reads it, because+ * files downloaded before the switch carry it and must keep matching.  */ internal object VorbisComments { @@ -44,7 +48,6 @@ internal object VorbisComments {         tags.discNumber?.let { add("DISCNUMBER", it.toString()) }         add("MUSICBRAINZ_TRACKID", tags.recordingId)         add("MUSICBRAINZ_ALBUMID", tags.releaseId)-        add("MUSICBRAINZ_RELEASETRACKID", tags.releaseTrackId)         add("LYRICS", tags.lyrics)         tags.coverArt?.takeIf { it.isNotEmpty() }?.let {             add(
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.ktindex 5f0cadfcff..72e39fdd37 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt@@ -1,46 +1,69 @@ package com.vayunmathur.musicbrainz.network.api  import com.vayunmathur.library.network.NetworkClient-import kotlinx.coroutines.delay-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.json.Json+import java.io.IOException+import java.net.HttpURLConnection import java.net.URLEncoder  /**- * Client for the MusicBrainz WS/2 API.+ * The server has a catalogue to serve, but not yet: either the data pack was never+ * imported or an import is still running.  *- * MusicBrainz allows one request per second per client and blocks callers that ignore- * that, so every request funnels through [gate]. It also rejects requests without an- * identifying User-Agent, which is why [USER_AGENT] names the app and links the source.+ * Kept apart from an ordinary failure because it resolves on its own, so the UI can tell+ * the user to come back shortly instead of reporting a fault they cannot act on.+ */+class CatalogueNotReadyException(message: String) : IOException(message)++/**+ * Client for the self-hosted MusicBrainz mirror.+ *+ * The mirror speaks WS/2's URL grammar and JSON shapes, so the requests below are the same+ * ones the public API takes. What it does not have is the public API's one-request-per-second+ * limit, so requests go straight out and callers are free to run them concurrently.  */ object MusicBrainzApi { -    private const val BASE = "https://musicbrainz.org/ws/2"+    private const val BASE = "https://api.vayunmathur.com/api/mb/ws/2"++    /** Named so the mirror's own logs can tell this client apart from anything else. */     private const val USER_AGENT =         "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )"-    private const val MIN_REQUEST_SPACING_MS = 1_100L--    private val rateLimit = Mutex()-    private var lastRequestAt = 0L      private val headers = mapOf(         "User-Agent" to USER_AGENT,         "Accept" to "application/json",     ) -    /** Serialises requests and spaces them out so the shared rate limit is respected. */-    private suspend fun <T> gate(block: suspend () -> T): T = rateLimit.withLock {-        val since = System.currentTimeMillis() - lastRequestAt-        if (since < MIN_REQUEST_SPACING_MS) delay(MIN_REQUEST_SPACING_MS - since)-        try {-            block()-        } finally {-            lastRequestAt = System.currentTimeMillis()-        }+    /**+     * `coerceInputValues` is the load-bearing setting: every field in the wire models is+     * declared with a default, but a default only applies to a key that is absent. An+     * explicit `null` on one of the non-nullable fields would otherwise abort the whole+     * decode, turning one unset field into a blank screen.+     *+     * Internal rather than private so `MusicBrainzModelsTest` decodes through the real+     * configuration instead of a copy of it.+     */+    internal val json = Json {+        ignoreUnknownKeys = true+        isLenient = true+        coerceInputValues = true     } -    private suspend inline fun <reified T> get(path: String): T =-        gate { NetworkClient.getJson<T>("$BASE/$path", headers = headers) }+    /**+     * A 503 is the mirror saying it has no catalogue loaded yet, which is a wait rather+     * than a fault; every other non-2xx is a real failure.+     */+    private suspend inline fun <reified T> get(path: String): T {+        val response = NetworkClient.performRequest("$BASE/$path", headers = headers)+        if (response.status == HttpURLConnection.HTTP_UNAVAILABLE) {+            throw CatalogueNotReadyException("HTTP 503: ${response.body.take(200)}")+        }+        if (!response.isSuccess) {+            throw IOException("HTTP ${response.status}: ${response.body.take(500)}")+        }+        return json.decodeFromString<T>(response.body)+    }      private fun encode(value: String): String = URLEncoder.encode(value, "UTF-8") 
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.ktindex 91693c61cf..44f28f1f2d 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt@@ -51,7 +51,16 @@ data class RecordingRow(  /** A track on a release, plus whether it is already owned or currently downloading. */ data class TrackRow(-    val releaseTrackId: String,+    /**+     * Unique within the release and stable across reloads, which is what a lazy list needs+     * as a key. Built from the track's place in the response rather than its MBID, because+     * the catalogue does not carry one and a column of identical keys crashes the list.+     */+    val rowKey: String,+    /** Which medium of the release this came from, as an index into `MbRelease.media`. */+    val mediumIndex: Int,+    /** The release-track MBID, absent unless the catalogue happens to carry one. */+    val releaseTrackId: String?,     val recordingId: String?,     val position: Int,     val title: String,@@ -62,13 +71,23 @@ data class TrackRow(     val isrcs: List<String> = emptyList(),     val onDevice: Boolean = false,     val download: DownloadItem? = null,-)+) {+    /**+     * The queue identity for this track, which has to agree with+     * [com.vayunmathur.musicbrainz.platform.download.DownloadRequest.key] or a row cannot+     * find the download it started. Covered by `DownloadKeyTest`.+     */+    fun downloadKey(album: String?): String =+        releaseTrackId ?: recordingId ?: "$artist\u0000$album\u0000$title"+}  data class SearchUiState(     val query: String = "",     val tab: SearchTab = SearchTab.Releases,     val loading: Boolean = false,     val error: String? = null,+    /** The catalogue is still importing, so this is a wait rather than a fault. */+    val notReady: Boolean = false,     val hasSearched: Boolean = false,     val artists: List<ArtistRow> = emptyList(),     val releaseGroups: List<ReleaseGroupRow> = emptyList(),@@ -78,6 +97,8 @@ data class SearchUiState( data class ArtistUiState(     val loading: Boolean = true,     val error: String? = null,+    /** The catalogue is still importing, so this is a wait rather than a fault. */+    val notReady: Boolean = false,     val name: String = "",     val subtitle: String? = null,     val releaseGroups: List<ReleaseGroupRow> = emptyList(),@@ -86,6 +107,8 @@ data class ArtistUiState( data class ReleaseGroupUiState(     val loading: Boolean = true,     val error: String? = null,+    /** The catalogue is still importing, so this is a wait rather than a fault. */+    val notReady: Boolean = false,     val title: String = "",     val artist: String = "",     val coverUrl: String? = null,@@ -95,6 +118,8 @@ data class ReleaseGroupUiState( data class ReleaseUiState(     val loading: Boolean = true,     val error: String? = null,+    /** The catalogue is still importing, so this is a wait rather than a fault. */+    val notReady: Boolean = false,     val id: String = "",     val title: String = "",     val artist: String = "",
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.ktindex 0190d96ab4..96666dda6a 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt@@ -10,6 +10,7 @@ import com.vayunmathur.musicbrainz.data.library.LibraryScanner import com.vayunmathur.musicbrainz.data.library.LibrarySnapshot import com.vayunmathur.musicbrainz.data.tidal.TidalAuth import com.vayunmathur.musicbrainz.data.tidal.TidalPollResult+import com.vayunmathur.musicbrainz.network.api.CatalogueNotReadyException import com.vayunmathur.musicbrainz.network.api.CoverArt import com.vayunmathur.musicbrainz.network.api.MbRecording import com.vayunmathur.musicbrainz.network.api.MbRelease@@ -20,6 +21,8 @@ import com.vayunmathur.musicbrainz.platform.download.DownloadQueue import com.vayunmathur.musicbrainz.platform.download.DownloadRequest import com.vayunmathur.musicbrainz.platform.SafTree import kotlinx.coroutines.Job+import kotlinx.coroutines.async+import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow@@ -33,9 +36,8 @@ import kotlinx.coroutines.launch /**  * Drives the browse, search and download screens.  *- * Fetched pages are cached by MusicBrainz id: the API allows one request per second, so- * without a cache going back a screen would stall for a visible beat before redrawing- * something the app already had.+ * Fetched pages are cached by MusicBrainz id so going back a screen redraws immediately+ * from what the app already had rather than making the round trip again.  */ class MusicBrainzViewModel(application: Application) : AndroidViewModel(application), MusicBrainzActions { @@ -89,7 +91,7 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat                             album = state.title,                             title = track.title,                         ),-                        download = downloads[track.downloadKey()],+                        download = downloads[track.downloadKey(state.title)],                     )                 },             )@@ -138,7 +140,12 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat         if (query.isEmpty()) return         searchJob?.cancel()         searchJob = viewModelScope.launch {-            _search.value = _search.value.copy(loading = true, error = null, hasSearched = true)+            _search.value = _search.value.copy(+                loading = true,+                error = null,+                notReady = false,+                hasSearched = true,+            )             try {                 when (_search.value.tab) {                     SearchTab.Artists -> {@@ -174,7 +181,11 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat                     }                 }             } catch (e: Exception) {-                _search.value = _search.value.copy(loading = false, error = e.readableMessage())+                _search.value = _search.value.copy(+                    loading = false,+                    error = e.readableMessage(),+                    notReady = e is CatalogueNotReadyException,+                )             }         }     }@@ -188,29 +199,45 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat             _artist.value = it             return         }-        _artist.value = ArtistUiState(loading = true)+        // The user tapped a row that already told them the artist's name, so carry it over+        // and let the title read straight away instead of sitting blank until the fetch lands.+        val tapped = _search.value.artists.firstOrNull { it.id == id }+        _artist.value = ArtistUiState(+            loading = true,+            name = tapped?.name.orEmpty(),+            subtitle = tapped?.subtitle,+        )         viewModelScope.launch {             try {-                val artist = MusicBrainzApi.artist(id)-                val groups = MusicBrainzApi.releaseGroupsOfArtist(id)-                val state = ArtistUiState(-                    loading = false,-                    name = artist.name,-                    subtitle = listOfNotNull(-                        artist.disambiguation?.takeIf { it.isNotBlank() },-                        artist.type,-                        artist.area?.name,-                        artist.lifeSpan?.begin,-                    ).joinToString(" \u00B7 ").ifEmpty { null },-                    // Newest first, which is how a discography is usually read.-                    releaseGroups = groups-                        .sortedByDescending { it.firstReleaseDate.orEmpty() }-                        .map { it.toRow(includeArtist = false) },-                )+                // Two independent lookups against a mirror with no rate limit, so the page+                // costs one round trip rather than two.+                val state = coroutineScope {+                    val artist = async { MusicBrainzApi.artist(id) }+                    val groups = async { MusicBrainzApi.releaseGroupsOfArtist(id) }+                    val details = artist.await()+                    ArtistUiState(+                        loading = false,+                        name = details.name,+                        subtitle = listOfNotNull(+                            details.disambiguation?.takeIf { it.isNotBlank() },+                            details.type,+                            details.area?.name,+                            details.lifeSpan?.begin,+                        ).joinToString(" \u00B7 ").ifEmpty { null },+                        // Newest first, which is how a discography is usually read.+                        releaseGroups = groups.await()+                            .sortedByDescending { it.firstReleaseDate.orEmpty() }+                            .map { it.toRow(includeArtist = false) },+                    )+                }                 artistCache[id] = state                 _artist.value = state             } catch (e: Exception) {-                _artist.value = ArtistUiState(loading = false, error = e.readableMessage())+                _artist.value = _artist.value.copy(+                    loading = false,+                    error = e.readableMessage(),+                    notReady = e is CatalogueNotReadyException,+                )             }         }     }@@ -223,43 +250,51 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat         _releaseGroup.value = ReleaseGroupUiState(loading = true)         viewModelScope.launch {             try {-                val group = MusicBrainzApi.releaseGroup(id)-                val releases = MusicBrainzApi.releasesOfReleaseGroup(id)-                val state = ReleaseGroupUiState(-                    loading = false,-                    title = group.title,-                    artist = group.artistCredit.display().orEmpty(),-                    coverUrl = CoverArt.releaseGroup(id),-                    // Official pressings first: they are what a user normally wants, and a-                    // release group can carry dozens of promos and bootlegs otherwise.-                    releases = releases-                        .sortedWith(-                            compareByDescending<com.vayunmathur.musicbrainz.network.api.MbReleaseSummary> {-                                it.status == "Official"-                            }.thenBy { it.date.orEmpty() },-                        )-                        .map { summary ->-                            ReleaseRow(-                                id = summary.id,-                                title = summary.title,-                                subtitle = listOfNotNull(-                                    summary.date?.takeIf { it.isNotBlank() },-                                    summary.country,-                                    summary.media.firstOrNull()?.format,-                                    summary.media.sumOf { it.trackCount }-                                        .takeIf { it > 0 }-                                        ?.let { "$it tracks" },-                                    summary.disambiguation?.takeIf { it.isNotBlank() },-                                ).joinToString(" \u00B7 ").ifEmpty { null },-                                coverUrl = CoverArt.release(summary.id),-                                fallbackCoverUrl = CoverArt.releaseGroup(id),+                // Same shape as loadArtist: two independent lookups, overlapped.+                val state = coroutineScope {+                    val group = async { MusicBrainzApi.releaseGroup(id) }+                    val releases = async { MusicBrainzApi.releasesOfReleaseGroup(id) }+                    val details = group.await()+                    ReleaseGroupUiState(+                        loading = false,+                        title = details.title,+                        artist = details.artistCredit.display().orEmpty(),+                        coverUrl = CoverArt.releaseGroup(id),+                        // Official pressings first: they are what a user normally wants, and a+                        // release group can carry dozens of promos and bootlegs otherwise.+                        releases = releases.await()+                            .sortedWith(+                                compareByDescending<com.vayunmathur.musicbrainz.network.api.MbReleaseSummary> {+                                    it.status == "Official"+                                }.thenBy { it.date.orEmpty() },                             )-                        },-                )+                            .map { summary ->+                                ReleaseRow(+                                    id = summary.id,+                                    title = summary.title,+                                    subtitle = listOfNotNull(+                                        summary.date?.takeIf { it.isNotBlank() },+                                        summary.country,+                                        summary.media.firstOrNull()?.format,+                                        summary.media.sumOf { it.trackCount }+                                            .takeIf { it > 0 }+                                            ?.let { "$it tracks" },+                                        summary.disambiguation?.takeIf { it.isNotBlank() },+                                    ).joinToString(" \u00B7 ").ifEmpty { null },+                                    coverUrl = CoverArt.release(summary.id),+                                    fallbackCoverUrl = CoverArt.releaseGroup(id),+                                )+                            },+                    )+                }                 releaseGroupCache[id] = state                 _releaseGroup.value = state             } catch (e: Exception) {-                _releaseGroup.value = ReleaseGroupUiState(loading = false, error = e.readableMessage())+                _releaseGroup.value = ReleaseGroupUiState(+                    loading = false,+                    error = e.readableMessage(),+                    notReady = e is CatalogueNotReadyException,+                )             }         }     }@@ -277,7 +312,11 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat                 releaseCache[id] = release                 _release.value = release.toUiState()             } catch (e: Exception) {-                _release.value = ReleaseUiState(loading = false, error = e.readableMessage())+                _release.value = ReleaseUiState(+                    loading = false,+                    error = e.readableMessage(),+                    notReady = e is CatalogueNotReadyException,+                )             }         }     }@@ -326,9 +365,10 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat     override fun clearFinishedDownloads() = DownloadQueue.clearFinished()      private fun requestFor(release: MbRelease, track: TrackRow): DownloadRequest? {-        val medium = release.media.firstOrNull { medium ->-            medium.tracks.any { it.id == track.releaseTrackId }-        } ?: return null+        // Indexed rather than matched: the track MBID is gone, and matching on disc position+        // would fall back to disc one for every track whenever the catalogue omits `position`,+        // stamping disc one's track total onto the whole of a multi-disc release.+        val medium = release.media.getOrNull(track.mediumIndex) ?: return null         return DownloadRequest(             recordingId = track.recordingId,             releaseTrackId = track.releaseTrackId,@@ -488,11 +528,15 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat         ).joinToString(" \u00B7 ").ifEmpty { null },         coverUrl = CoverArt.release(id),         fallbackCoverUrl = releaseGroup?.id?.let { CoverArt.releaseGroup(it) },-        tracks = media.flatMap { medium ->-            medium.tracks.map { track ->+        tracks = media.flatMapIndexed { mediumIndex, medium ->+            medium.tracks.mapIndexed { trackIndex, track ->                 TrackRow(-                    releaseTrackId = track.id,-                    recordingId = track.recording?.id,+                    // Positional, so it is unique whatever the catalogue sends: an id it+                    // repeated - or omitted for every track - would crash the list.+                    rowKey = "$mediumIndex/$trackIndex",+                    mediumIndex = mediumIndex,+                    releaseTrackId = track.id.ifBlank { null },+                    recordingId = track.recording?.id?.ifBlank { null },                     position = track.position,                     title = track.title.ifBlank { track.recording?.title.orEmpty() },                     // Track credits beat release credits: on a compilation the release is@@ -541,9 +585,6 @@ class MusicBrainzViewModel(application: Application) : AndroidViewModel(applicat         title = row.title,     ) -    private fun TrackRow.downloadKey(): String =-        releaseTrackId.ifEmpty { recordingId ?: title }-     private fun Exception.readableMessage(): String =         message?.takeIf { it.isNotBlank() }?.take(200) ?: "Something went wrong" 
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.ktindex 784303119b..dd3764d338 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ArtistScreen.kt@@ -16,7 +16,6 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.EmptyState-import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.LoadingState import com.vayunmathur.library.ui.MaterialTheme@@ -25,6 +24,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.musicbrainz.R import com.vayunmathur.musicbrainz.Route import com.vayunmathur.musicbrainz.ui.components.CoverArtImage+import com.vayunmathur.musicbrainz.ui.components.LoadFailureState import com.vayunmathur.musicbrainz.ui.components.SecondaryText import com.vayunmathur.musicbrainz.platform.ArtistUiState import com.vayunmathur.musicbrainz.platform.MusicBrainzActions@@ -50,10 +50,10 @@ fun ArtistScreen(     ) { padding ->         when {             state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))-            state.error != null -> ErrorState(-                title = stringResource(R.string.load_failed),+            state.error != null -> LoadFailureState(+                error = state.error,+                notReady = state.notReady,                 modifier = Modifier.fillMaxSize().padding(padding),-                message = state.error,             )             state.releaseGroups.isEmpty() -> EmptyState(                 title = stringResource(R.string.no_releases),
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.ktindex 8976f3d397..6673d42361 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.kt@@ -17,7 +17,6 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.IconCheckCircle import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.LoadingState@@ -27,6 +26,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.musicbrainz.R import com.vayunmathur.musicbrainz.Route import com.vayunmathur.musicbrainz.ui.components.CoverArtImage+import com.vayunmathur.musicbrainz.ui.components.LoadFailureState import com.vayunmathur.musicbrainz.ui.components.SecondaryText import com.vayunmathur.musicbrainz.platform.MusicBrainzViewModel import com.vayunmathur.musicbrainz.platform.ReleaseGroupUiState@@ -61,10 +61,10 @@ fun ReleaseGroupScreen(     ) { padding ->         when {             state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))-            state.error != null -> ErrorState(-                title = stringResource(R.string.load_failed),+            state.error != null -> LoadFailureState(+                error = state.error,+                notReady = state.notReady,                 modifier = Modifier.fillMaxSize().padding(padding),-                message = state.error,             )             else -> LazyColumn(                 Modifier.fillMaxSize(),
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.ktindex 48df160e74..853dd77df4 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt@@ -16,7 +16,6 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.ExtendedFloatingActionButton import com.vayunmathur.library.ui.IconDownload import com.vayunmathur.library.ui.ListItem@@ -27,6 +26,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.musicbrainz.R import com.vayunmathur.musicbrainz.Route import com.vayunmathur.musicbrainz.ui.components.CoverArtImage+import com.vayunmathur.musicbrainz.ui.components.LoadFailureState import com.vayunmathur.musicbrainz.ui.components.durationLabel import com.vayunmathur.musicbrainz.ui.components.TrackTrailing import com.vayunmathur.musicbrainz.ui.components.SecondaryText@@ -71,10 +71,10 @@ fun ReleaseScreen(     ) { padding ->         when {             state.loading -> LoadingState(Modifier.fillMaxSize().padding(padding))-            state.error != null -> ErrorState(-                title = stringResource(R.string.load_failed),+            state.error != null -> LoadFailureState(+                error = state.error,+                notReady = state.notReady,                 modifier = Modifier.fillMaxSize().padding(padding),-                message = state.error,             )             else -> LazyColumn(                 Modifier.fillMaxSize(),@@ -99,7 +99,7 @@ fun ReleaseScreen(                         )                     }                 }-                items(state.tracks, key = { it.releaseTrackId }) { track ->+                items(state.tracks, key = { it.rowKey }) { track ->                     ListItem(                         headlineContent = { Text(track.title) },                         modifier = Modifier.fillMaxWidth(),@@ -124,7 +124,7 @@ fun ReleaseScreen(                                 onDevice = track.onDevice,                                 download = track.download,                                 onDownload = { actions.downloadTrack(track) },-                                onCancel = { actions.cancelDownload(track.releaseTrackId) },+                                onCancel = { actions.cancelDownload(track.downloadKey(state.title)) },                             )                         },                     )
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SearchScreen.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SearchScreen.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SearchScreen.ktindex 0362411a89..1fad4fa97c 100644--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SearchScreen.kt+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/SearchScreen.kt@@ -16,7 +16,6 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.EmptyState-import com.vayunmathur.library.ui.ErrorState import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconDownload@@ -34,6 +33,7 @@ import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.musicbrainz.R import com.vayunmathur.musicbrainz.Route import com.vayunmathur.musicbrainz.ui.components.CoverArtImage+import com.vayunmathur.musicbrainz.ui.components.LoadFailureState import com.vayunmathur.musicbrainz.ui.components.durationLabel import com.vayunmathur.musicbrainz.ui.components.TrackTrailing import com.vayunmathur.musicbrainz.ui.components.SecondaryText@@ -70,8 +70,8 @@ fun SearchScreen(     ) { padding ->         Column(Modifier.fillMaxSize().padding(padding)) {             // The input field rather than CommonSearchBar: that one filters a local list-            // as you type, and every keystroke here would be a rate-limited network-            // request. This one submits on the keyboard's search key.+            // as you type, and every keystroke here would be a network request. This one+            // submits on the keyboard's search key.             SearchBarInputField(                 query = state.query,                 onQueryChange = actions::onQueryChange,@@ -98,10 +98,11 @@ fun SearchScreen(             }             when {                 state.loading -> LoadingState(Modifier.fillMaxSize())-                state.error != null -> ErrorState(-                    title = stringResource(R.string.search_failed),+                state.error != null -> LoadFailureState(+                    error = state.error,+                    notReady = state.notReady,                     modifier = Modifier.fillMaxSize(),-                    message = state.error,+                    title = stringResource(R.string.search_failed),                     retryLabel = stringResource(R.string.retry),                     onRetry = actions::search,                 )
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/LoadFailureState.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/LoadFailureState.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/LoadFailureState.ktnew file mode 100644index 0000000000..8929334db1--- /dev/null+++ b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/ui/components/LoadFailureState.kt@@ -0,0 +1,50 @@+package com.vayunmathur.musicbrainz.ui.components++import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.EmptyState+import com.vayunmathur.library.ui.ErrorState+import com.vayunmathur.library.ui.Text+import com.vayunmathur.musicbrainz.R++/**+ * The terminal state for a page that has nothing to show.+ *+ * A catalogue that has not finished importing is drawn apart from a failure because it is a+ * wait, not a fault: reporting it as an error sends the user hunting for a problem at their+ * end, and there is no fallback source to fall back to. Either way this is a settled state+ * rather than a spinner, so the screen never sits there implying progress it is not making.+ */+@Composable+fun LoadFailureState(+    error: String?,+    notReady: Boolean,+    modifier: Modifier = Modifier,+    title: String = stringResource(R.string.load_failed),+    retryLabel: String? = null,+    onRetry: (() -> Unit)? = null,+) {+    if (notReady) {+        EmptyState(+            title = stringResource(R.string.catalogue_not_ready),+            modifier = modifier,+            message = stringResource(R.string.catalogue_not_ready_message),+            // The message tells the user to try again, so keep the button that does it.+            action = if (onRetry != null && retryLabel != null) {+                { Button(onClick = onRetry) { Text(retryLabel) } }+            } else {+                null+            },+        )+    } else {+        ErrorState(+            title = title,+            modifier = modifier,+            message = error,+            retryLabel = retryLabel,+            onRetry = onRetry,+        )+    }+}
musicbrainz/src/main/res/values/strings.xml
diff --git a/musicbrainz/src/main/res/values/strings.xml b/musicbrainz/src/main/res/values/strings.xmlindex e83052a3ed..7ab9032ea0 100644--- a/musicbrainz/src/main/res/values/strings.xml+++ b/musicbrainz/src/main/res/values/strings.xml@@ -24,6 +24,10 @@     <string name="search_failed">Search failed</string>     <!-- Error title shown when a page could not be loaded. -->     <string name="load_failed">Could not load</string>+    <!-- Title shown when the server has no music catalogue loaded yet. Not an error: it is still being prepared. -->+    <string name="catalogue_not_ready">Catalogue not ready</string>+    <!-- Body shown when the server has no music catalogue loaded yet, telling the user it is temporary. -->+    <string name="catalogue_not_ready_message">The music catalogue is still being prepared on the server. Browsing will work once it is ready \u2014 try again in a few minutes.</string>     <!-- Button: retries a failed request. Verb. -->     <string name="retry">Retry</string> 
musicbrainz/src/screenshotTest/kotlin/com/vayunmathur/musicbrainz/ui/MetadataPreviews.kt
diff --git a/musicbrainz/src/screenshotTest/kotlin/com/vayunmathur/musicbrainz/ui/MetadataPreviews.kt b/musicbrainz/src/screenshotTest/kotlin/com/vayunmathur/musicbrainz/ui/MetadataPreviews.ktindex 62fa5391f6..a058e671b4 100644--- a/musicbrainz/src/screenshotTest/kotlin/com/vayunmathur/musicbrainz/ui/MetadataPreviews.kt+++ b/musicbrainz/src/screenshotTest/kotlin/com/vayunmathur/musicbrainz/ui/MetadataPreviews.kt@@ -44,7 +44,9 @@ class MetadataPreviews {         onDevice: Boolean = false,         download: DownloadItem? = null,     ) = TrackRow(-        releaseTrackId = "track-$position",+        rowKey = "0/$position",+        mediumIndex = 0,+        releaseTrackId = null,         recordingId = "recording-$position",         position = position,         title = title,
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggOpusTaggerTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggOpusTaggerTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggOpusTaggerTest.ktindex 34d17729d0..e3df0db8a9 100644--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggOpusTaggerTest.kt+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/download/OggOpusTaggerTest.kt@@ -140,7 +140,10 @@ class OggOpusTaggerTest {         assertEquals("The Neon Owls", tags.albumArtist)         assertEquals("11111111-2222-3333-4444-555555555555", tags.recordingId)         assertEquals("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", tags.releaseId)-        assertEquals("99999999-8888-7777-6666-555555555555", tags.releaseTrackId)+        // Not written any more: the catalogue has no per-track MBID, so the tagger drops the+        // key even when handed a value. TagReader still parses it for files written earlier,+        // which `TagReaderTest` covers.+        assertNull(tags.releaseTrackId)     }      /**@@ -199,4 +202,4 @@ class OggOpusTaggerTest {         assertNull(tags.recordingId)     } }-+
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.ktindex f6e23d5ef5..635d5a72da 100644--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/MatchingTest.kt@@ -181,5 +181,125 @@ class MatchingTest {         )         assertEquals(3, snapshot.trackCount)     }++    // ------------------------------------------------------------------+    // Matching without a release-track id+    // ------------------------------------------------------------------++    /**+     * The catalogue no longer carries a per-track MBID, so every browse row now asks with+     * `releaseTrackId = null`. A library scanned before that change still holds the id on its+     * rows, and those files must keep reporting as owned - the recording id is what carries+     * the match now, and it is exact.+     */+    @Test+    fun `a legacy row with a release track id still matches when the catalogue supplies none`() {+        val snapshot = LibrarySnapshot.from(+            listOf(+                localTrack(+                    "Weird Fishes",+                    "Radiohead",+                    album = "In Rainbows",+                    recordingId = "rec-1",+                    releaseTrackId = "legacy-trk-1",+                ),+            ),+        )+        assertTrue(+            snapshot.hasTrack(+                recordingId = "rec-1",+                releaseTrackId = null,+                artist = "Radiohead",+                album = "In Rainbows",+                title = "Weird Fishes",+            ),+        )+    }++    /**+     * The worse legacy case: a file whose only MusicBrainz id was the release-track one. With+     * nothing to compare it against, the text keys are the whole of the match, which is the+     * same path an untagged file takes.+     */+    @Test+    fun `a legacy row whose only id was the release track id still matches on text`() {+        val snapshot = LibrarySnapshot.from(+            listOf(+                localTrack(+                    "Weird Fishes",+                    "Radiohead",+                    album = "In Rainbows",+                    releaseTrackId = "legacy-trk-1",+                ),+            ),+        )+        assertTrue(+            snapshot.hasTrack(+                recordingId = null,+                releaseTrackId = null,+                artist = "Radiohead",+                album = "In Rainbows",+                title = "Weird Fishes",+            ),+        )+        // Still not a licence to match anything: a different recording must stay missing.+        assertFalse(+            snapshot.hasTrack(null, null, "Radiohead", "In Rainbows", "Videotape"),+        )+    }++    /** A file the app writes now: no release-track id on either side of the comparison. */+    @Test+    fun `a new row without a release track id matches on the recording id`() {+        val snapshot = LibrarySnapshot.from(+            listOf(+                localTrack(+                    "Reckoner",+                    "Radiohead",+                    album = "In Rainbows",+                    recordingId = "rec-2",+                    releaseId = "rel-2",+                    releaseTrackId = null,+                ),+            ),+        )+        assertTrue(snapshot.hasTrack("rec-2", null, null, null, null))+        assertTrue(snapshot.hasRelease("rel-2"))+        assertFalse(snapshot.hasTrack("rec-other", null, null, null, null))+    }++    /**+     * A real library after the switch is a mix: older files carry the release-track id, newer+     * ones do not. One snapshot has to answer for both, and a null on either side must never+     * be treated as a wildcard that matches everything.+     */+    @Test+    fun `a library holding both legacy and new rows matches each of them`() {+        val snapshot = LibrarySnapshot.from(+            listOf(+                localTrack(+                    "Nude",+                    "Radiohead",+                    album = "In Rainbows",+                    recordingId = "rec-legacy",+                    releaseTrackId = "legacy-trk",+                ),+                localTrack(+                    "Videotape",+                    "Radiohead",+                    album = "In Rainbows",+                    recordingId = "rec-new",+                    releaseTrackId = null,+                ),+            ),+        )+        assertTrue(snapshot.hasTrack("rec-legacy", null, null, null, null))+        assertTrue(snapshot.hasTrack("rec-new", null, null, null, null))+        // The legacy id still works for anything that does happen to know it.+        assertTrue(snapshot.hasTrack(null, "legacy-trk", null, null, null))+        // A null release-track id does not match the row that has one.+        assertFalse(snapshot.hasTrack(null, null, null, null, null))+        assertFalse(snapshot.hasTrack("rec-absent", null, "Radiohead", "In Rainbows", "Bloom"))+    } } 
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/TagReaderTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/TagReaderTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/TagReaderTest.ktindex e278ee9443..856307ca79 100644--- a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/TagReaderTest.kt+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/data/library/TagReaderTest.kt@@ -257,6 +257,99 @@ class TagReaderTest {         assertTrue(TagReader.readOgg(ByteArrayInputStream("not ogg".toByteArray())).isEmpty)     } +    // ------------------------------------------------------------------+    // The legacy release-track id+    // ------------------------------------------------------------------++    /**+     * Nothing writes `MUSICBRAINZ_RELEASETRACKID` any more - the catalogue carries no+     * per-track MBID - but every file downloaded before that change still has it, and it is+     * the strongest signal those files carry. Dropping the read would make a library that+     * already matched exactly fall back to comparing text, so it stays.+     */+    @Test+    fun `still reads the legacy release track id from vorbis comments`() {+        val comments = vorbisComments(+            "TITLE" to "Nude",+            "ARTIST" to "Radiohead",+            "MUSICBRAINZ_RELEASETRACKID" to "legacy-release-track-mbid",+        )+        val out = ByteArrayOutputStream()+        out.write("fLaC".toByteArray(Charsets.ISO_8859_1))+        out.write(0x80 or 4)+        out.write(+            byteArrayOf(+                (comments.size shr 16).toByte(),+                (comments.size shr 8).toByte(),+                comments.size.toByte(),+            ),+        )+        out.write(comments)++        val tags = TagReader.readFlac(ByteArrayInputStream(out.toByteArray()))+        assertEquals("legacy-release-track-mbid", tags.releaseTrackId)+    }++    /** The same for a `.opus` file, which is the format the app's own downloads are in. */+    @Test+    fun `still reads the legacy release track id from an opus file`() {+        val identification = "OpusHead".toByteArray(Charsets.ISO_8859_1) + ByteArray(11)+        val comments = "OpusTags".toByteArray(Charsets.ISO_8859_1) + vorbisComments(+            "TITLE" to "Reckoner",+            "ARTIST" to "Radiohead",+            "MUSICBRAINZ_TRACKID" to "legacy-recording-mbid",+            "MUSICBRAINZ_RELEASETRACKID" to "legacy-release-track-mbid",+        )+        val file = ByteArrayOutputStream()+        file.write(oggPage(identification, 0))+        file.write(oggPage(comments, 1))++        val tags = TagReader.readOgg(ByteArrayInputStream(file.toByteArray()))+        assertEquals("legacy-recording-mbid", tags.recordingId)+        assertEquals("legacy-release-track-mbid", tags.releaseTrackId)+    }++    /** And from an MP3 tagged by Picard, where it is a `TXXX` frame. */+    @Test+    fun `still reads the legacy release track id from an id3 tag`() {+        val frames = ByteArrayOutputStream()+        frames.write(frame("TIT2", textBody("Nude"), 4))+        frames.write(+            frame("TXXX", txxxBody("MusicBrainz Release Track Id", "legacy-mbid"), 4),+        )++        val tags = TagReader.readId3(ByteArrayInputStream(id3(4, frames.toByteArray())))+        assertEquals("legacy-mbid", tags.releaseTrackId)+    }++    /**+     * The shape of a file the app writes now: no release-track id at all. Everything else+     * still has to come through, because that is all the matching has left to work with.+     */+    @Test+    fun `reads a file written without a release track id`() {+        val identification = "OpusHead".toByteArray(Charsets.ISO_8859_1) + ByteArray(11)+        val comments = "OpusTags".toByteArray(Charsets.ISO_8859_1) + vorbisComments(+            "TITLE" to "Weird Fishes",+            "ARTIST" to "Radiohead",+            "ALBUM" to "In Rainbows",+            "MUSICBRAINZ_TRACKID" to "recording-mbid",+            "MUSICBRAINZ_ALBUMID" to "release-mbid",+        )+        val file = ByteArrayOutputStream()+        file.write(oggPage(identification, 0))+        file.write(oggPage(comments, 1))++        val tags = TagReader.readOgg(ByteArrayInputStream(file.toByteArray()))+        assertNull(tags.releaseTrackId)+        assertEquals("Weird Fishes", tags.title)+        assertEquals("Radiohead", tags.artist)+        assertEquals("In Rainbows", tags.album)+        assertEquals("recording-mbid", tags.recordingId)+        assertEquals("release-mbid", tags.releaseId)+        assertTrue(!tags.isEmpty)+    }+     // ------------------------------------------------------------------      @Test
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModelsTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModelsTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModelsTest.ktnew file mode 100644index 0000000000..ad1c49c09b--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzModelsTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.musicbrainz.network.api++import kotlinx.serialization.SerializationException+import kotlinx.serialization.json.Json+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Decodes the shapes the self-hosted catalogue actually returns, through the same [Json]+ * the app uses.+ *+ * The catalogue mirrors WS/2 but not exactly, and a decode failure here does not look like a+ * decode failure to the user - it surfaces as "Could not load" on a screen that worked+ * yesterday. Neither the build nor a test of any other layer catches that, so the wire+ * shapes are pinned here.+ */+class MusicBrainzModelsTest {++    private inline fun <reified T> decode(json: String): T =+        MusicBrainzApi.json.decodeFromString<T>(json)++    /**+     * Every field in every model is declared with a default, so an empty object has to decode.+     * This is what lets the catalogue omit anything it does not hold.+     */+    @Test+    fun `every model decodes from an empty object`() {+        assertEquals("", decode<MbArtist>("{}").id)+        assertEquals("", decode<MbArtistRef>("{}").id)+        assertEquals("", decode<MbArtistCredit>("{}").name)+        assertEquals("", decode<MbReleaseGroup>("{}").title)+        assertEquals("", decode<MbRelease>("{}").title)+        assertEquals("", decode<MbReleaseSummary>("{}").title)+        assertEquals("", decode<MbRecording>("{}").title)+        assertEquals("", decode<MbRecordingRef>("{}").title)+        assertEquals("", decode<MbTrack>("{}").title)+        assertEquals(1, decode<MbMedium>("{}").position)+        assertEquals(0, decode<MbMediumSummary>("{}").trackCount)+        assertNull(decode<MbLifeSpan>("{}").begin)+        assertNull(decode<MbArea>("{}").name)+        assertTrue(decode<MbArtistSearch>("{}").artists.isEmpty())+        assertTrue(decode<MbReleaseGroupSearch>("{}").releaseGroups.isEmpty())+        assertTrue(decode<MbRecordingSearch>("{}").recordings.isEmpty())+        assertTrue(decode<MbReleaseGroupBrowse>("{}").releaseGroups.isEmpty())+        assertTrue(decode<MbReleaseBrowse>("{}").releases.isEmpty())+    }++    /**+     * The shape that matters: a release whose tracks carry no `id`, because the catalogue has+     * no per-track MBID to give. The recording id survives, which is what the matching and the+     * download key then run on.+     */+    @Test+    fun `decodes a release whose tracks have no track mbid`() {+        val release = decode<MbRelease>(+            """+            {+              "id": "rel-1",+              "title": "In Rainbows",+              "media": [+                {+                  "position": 1,+                  "track-count": 2,+                  "tracks": [+                    {+                      "title": "15 Step",+                      "position": 1,+                      "length": 237000,+                      "recording": { "id": "rec-1", "title": "15 Step" }+                    },+                    {+                      "title": "Bodysnatchers",+                      "position": 2,+                      "recording": { "id": "rec-2", "title": "Bodysnatchers" }+                    }+                  ]+                }+              ]+            }+            """,+        )+        val tracks = release.media.single().tracks+        assertEquals(2, tracks.size)+        assertEquals("", tracks[0].id)+        assertEquals("rec-1", tracks[0].recording?.id)+        assertEquals("15 Step", tracks[0].title)+        assertEquals(237000, tracks[0].length)+        assertEquals("rec-2", tracks[1].recording?.id)+        assertNull(tracks[1].length)+    }++    /**+     * A default only applies to a key that is absent, so an explicit `null` on a non-nullable+     * field would abort the whole decode and blank the screen over one unset value.+     * `coerceInputValues` is what stops that; `MbTrack.id` is the field most likely to arrive+     * this way, since it is the one the catalogue no longer has.+     */+    @Test+    fun `survives explicit nulls on non-nullable fields`() {+        val track = decode<MbTrack>(+            """{ "id": null, "title": "Nude", "position": null, "artist-credit": null }""",+        )+        assertEquals("", track.id)+        assertEquals("Nude", track.title)+        assertEquals(0, track.position)+        assertTrue(track.artistCredit.isEmpty())++        val release = decode<MbRelease>("""{ "id": null, "title": null, "media": null }""")+        assertEquals("", release.id)+        assertEquals("", release.title)+        assertTrue(release.media.isEmpty())++        val browse = decode<MbReleaseGroupBrowse>(+            """{ "release-group-count": null, "release-groups": null }""",+        )+        assertEquals(0, browse.count)+        assertTrue(browse.releaseGroups.isEmpty())+    }++    /**+     * The reason the setting above is not optional. Decoded with the configuration the shared+     * client uses, the very same payload fails - so "the field has a default" is not on its own+     * enough to make an omitted field safe, and a catalogue that nulls a field instead of+     * leaving it out would take a screen down.+     */+    @Test+    fun `the same payload fails without coercion`() {+        val strict = Json {+            ignoreUnknownKeys = true+            isLenient = true+        }+        assertFailsWith<SerializationException> {+            strict.decodeFromString<MbTrack>("""{ "id": null, "title": "Nude" }""")+        }+        assertFailsWith<SerializationException> {+            strict.decodeFromString<MbRelease>("""{ "media": null }""")+        }+    }++    /** Fields the app does not draw must not stop it decoding the ones it does. */+    @Test+    fun `ignores fields the app does not declare`() {+        val artist = decode<MbArtist>(+            """{ "id": "a-1", "name": "Radiohead", "rating": { "value": 4.5 }, "tags": [] }""",+        )+        assertEquals("a-1", artist.id)+        assertEquals("Radiohead", artist.name)+    }++    /** The hyphenated WS/2 keys the models rename, which are easy to get wrong server-side. */+    @Test+    fun `maps the hyphenated wire keys`() {+        val group = decode<MbReleaseGroup>(+            """+            {+              "id": "rg-1",+              "title": "In Rainbows",+              "primary-type": "Album",+              "secondary-types": ["Live"],+              "first-release-date": "2007-10-10",+              "artist-credit": [{ "name": "Radiohead", "joinphrase": "" }]+            }+            """,+        )+        assertEquals("Album", group.primaryType)+        assertEquals(listOf("Live"), group.secondaryTypes)+        assertEquals("2007-10-10", group.firstReleaseDate)+        assertEquals("Radiohead", group.artistCredit.display())++        val browse = decode<MbReleaseBrowse>(+            """{ "release-count": 3, "releases": [{ "id": "r-1", "title": "T" }] }""",+        )+        assertEquals(3, browse.count)+        assertEquals("r-1", browse.releases.single().id)+    }+}
musicbrainz/src/test/java/com/vayunmathur/musicbrainz/platform/DownloadKeyTest.kt
diff --git a/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/platform/DownloadKeyTest.kt b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/platform/DownloadKeyTest.ktnew file mode 100644index 0000000000..621d8476a0--- /dev/null+++ b/musicbrainz/src/test/java/com/vayunmathur/musicbrainz/platform/DownloadKeyTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.musicbrainz.platform++import com.vayunmathur.musicbrainz.platform.download.DownloadRequest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals++/**+ * Pins [TrackRow.downloadKey] to [DownloadRequest.key].+ *+ * A release row looks its own download up by key, and the queue files it under the key the+ * request computed. The two formulas live in different files, so if they drift the progress+ * spinner and the cancel button simply stop finding anything - no crash, no failed build.+ *+ * This got sharper when the catalogue stopped carrying per-track MBIDs: the release-track id+ * used to be present on every row and made both sides agree trivially, and now the fallbacks+ * are what actually run.+ */+class DownloadKeyTest {++    private fun trackRow(releaseTrackId: String?, recordingId: String?) = TrackRow(+        rowKey = "0/0",+        mediumIndex = 0,+        releaseTrackId = releaseTrackId,+        recordingId = recordingId,+        position = 1,+        title = TITLE,+        artist = ARTIST,+    )++    private fun request(releaseTrackId: String?, recordingId: String?) = DownloadRequest(+        recordingId = recordingId,+        releaseTrackId = releaseTrackId,+        releaseId = null,+        releaseGroupId = null,+        title = TITLE,+        artist = ARTIST,+        album = ALBUM,+        albumArtist = ARTIST,+        date = null,+        trackNumber = 1,+        trackTotal = null,+        discNumber = null,+        durationMs = null,+    )++    @Test+    fun `agrees with the download request for every combination of ids`() {+        val combinations = listOf(+            "trk-1" to "rec-1",+            null to "rec-1",+            "trk-1" to null,+            null to null,+        )+        for ((releaseTrackId, recordingId) in combinations) {+            assertEquals(+                request(releaseTrackId, recordingId).key,+                trackRow(releaseTrackId, recordingId).downloadKey(ALBUM),+                "key disagreed for releaseTrackId=$releaseTrackId recordingId=$recordingId",+            )+        }+    }++    /** The case the catalogue now produces: no track MBID, so the recording id carries it. */+    @Test+    fun `falls back to the recording id when there is no release track id`() {+        assertEquals("rec-1", trackRow(null, "rec-1").downloadKey(ALBUM))+    }++    /**+     * With neither id the key is the text triple. The album has to be part of it, or the same+     * song on two albums would collapse into one queue entry and one download would replace+     * the other.+     */+    @Test+    fun `distinguishes the same untagged song on two albums`() {+        val row = trackRow(null, null)+        assertEquals("$ARTIST\u0000$ALBUM\u0000$TITLE", row.downloadKey(ALBUM))+        assertNotEquals(row.downloadKey(ALBUM), row.downloadKey("A Different Album"))+    }++    private companion object {+        const val TITLE = "Weird Fishes"+        const val ARTIST = "Radiohead"+        const val ALBUM = "In Rainbows"+    }+}