Modern Apps git

← Modern-Apps.git

musicbrainz: remove app

Commit
f40df5d4d9ccea7ce171dfce9e193b38af925fe0
Author
vayun-mathur <[email protected]>
When
2026-10-07 21:08 UTC (1 month ago)
Parents
b46c24f

Diff

appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.ktindex d60b81e368..ab3e32dd02 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -24,7 +24,16 @@ enum class AppSource {      * verify-then-commit path with those values, plus the new min-version gate. See      * [com.vayunmathur.appstore.data.accrescent.AccrescentRepository].      */-    ACCRESCENT;+    ACCRESCENT,++    /**+     * This store's own Play mirror: a curated allowlist of free-but-proprietary apps+     * (e.g. WhatsApp) fetched from Google Play by the server, stored on R2, and published+     * as a signed F-Droid-format repo. Consumed exactly like the other offline repos —+     * no Google contact at runtime. Per-version signer keys + APK hashes come from the+     * signed index, so installs verify end to end.+     */+    PROPRIETARY;      companion object {         /**@@ -40,7 +49,7 @@ enum class AppSource {          * signed with this store's own key.          */         val PRIORITY: List<AppSource> =-            listOf(GRAPHENEOS, MODERN_APPS, FDROID, ACCRESCENT, PLAYSTORE)+            listOf(GRAPHENEOS, MODERN_APPS, PROPRIETARY, FDROID, ACCRESCENT, PLAYSTORE)          /**          * Sources the user may switch off, in the order the sources screen lists them.@@ -50,7 +59,7 @@ enum class AppSource {          * they belong to, and which must never be updated from anywhere else — so a switch          * would either do nothing or strand three system packages on a stale build.          */-        val TOGGLEABLE: List<AppSource> = listOf(MODERN_APPS, FDROID, PLAYSTORE, ACCRESCENT)+        val TOGGLEABLE: List<AppSource> = listOf(MODERN_APPS, PROPRIETARY, FDROID, PLAYSTORE, ACCRESCENT)     } } @@ -162,6 +171,12 @@ data class RepoDescriptor(  * check the binary against. The f-droid.org archive is excluded for a different reason:  * it exists to serve superseded versions, which is the opposite of what we want.  *+ * [PROPRIETARY] is the deliberate exception to the no-mirror rule: it is operated by+ * the same party that ships this store (not a third party), serves only an explicit+ * allowlist of free-but-proprietary apps that cannot come from source-built repos,+ * and pins each version's developer signing key + APK hash in the signed index, so+ * the install still verifies end to end.+ *  * Either of these can be switched off (see [AppSource.TOGGLEABLE]); neither can be replaced.  */ object DefaultRepos {@@ -183,7 +198,16 @@ object DefaultRepos {         supportsReproducibilityFeed = false,     ) -    val ALL: List<RepoDescriptor> = listOf(FDROID, MODERN_APPS)+    val PROPRIETARY = RepoDescriptor(+        url = "https://ma.vayunmathur.com/proprietary/repo",+        displayName = "Proprietary",+        pinnedFingerprint =+            "176fcb2525573e5be8e1cb3a496dd97b137e81ca5b887a1d32cb894b4e5717b4",+        source = AppSource.PROPRIETARY,+        supportsReproducibilityFeed = false,+    )++    val ALL: List<RepoDescriptor> = listOf(FDROID, MODERN_APPS, PROPRIETARY)      /** Cache key written by the retired GitHub releases provider. */     const val LEGACY_MODERN_APPS_REPO_KEY = "https://github.com/vayun-mathur/Modern-Apps"
appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.ktindex fbaf9774e1..065c9aedde 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/CatalogRepository.kt@@ -11,7 +11,7 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.withContext  /** Which source a sync run is currently working on, for a progress line. */-enum class SyncStep { FDROID, MODERN_APPS }+enum class SyncStep { FDROID, MODERN_APPS, PROPRIETARY }  /** What one sync run managed to do, per source. */ data class SyncReport(@@ -19,12 +19,14 @@ data class SyncReport(     /** How many F-Droid apps carry the reproducible badge this sync. */     val fdroidReproducible: Int = 0,     val modernCount: Int? = null,+    val proprietaryCount: Int? = null,     /** Sources the user has switched off, which this run skipped rather than attempted. */     val skipped: Set<AppSource> = emptySet(), ) {     val anyFailed: Boolean         get() = (AppSource.FDROID !in skipped && fdroidCount == null) ||-            (AppSource.MODERN_APPS !in skipped && modernCount == null)+            (AppSource.MODERN_APPS !in skipped && modernCount == null) ||+            (AppSource.PROPRIETARY !in skipped && proprietaryCount == null)      /** True when every offline source is switched off, so there was nothing to sync. */     val allSkipped: Boolean@@ -51,6 +53,7 @@ class CatalogRepository(     private val appContext = context.applicationContext     private val fdroidProvider = FDroidAppProvider(db, appContext, DefaultRepos.FDROID)     private val modernProvider = FDroidAppProvider(db, appContext, DefaultRepos.MODERN_APPS)+    private val proprietaryProvider = FDroidAppProvider(db, appContext, DefaultRepos.PROPRIETARY)      val repos: StateFlow<List<RepoEntity>> =         db.repoDao().allFlow().stateIn(scope, SharingStarted.Eagerly, emptyList())@@ -143,12 +146,14 @@ class CatalogRepository(     }      /**-     * Refresh both offline sources.+     * Refresh all offline sources.      *      * Order matters: `packageName` is the cache table's primary key, so when a package is      * published by both sources the *later* upsert wins the row. Modern Apps goes last —      * every app in this repo is also on F-Droid, and the copy signed with this store's own-     * key is the one that can be verified end to end.+     * key is the one that can be verified end to end. Proprietary goes between F-Droid+     * and Modern Apps: its allowlist is curated to avoid F-Droid overlap, and nothing+     * outranks a first-party row.      *      * Each source is independent: one failing leaves the other's rows updated and its own      * previous rows untouched, rather than aborting the whole run.@@ -170,6 +175,13 @@ class CatalogRepository(             null         } +        val proprietary = if (DefaultRepos.PROPRIETARY.source in enabled) {+            onProgress(SyncStep.PROPRIETARY)+            runCatching { proprietaryProvider.syncIntoDb() }.getOrNull()+        } else {+            null+        }+         val modern = if (DefaultRepos.MODERN_APPS.source in enabled) {             onProgress(SyncStep.MODERN_APPS)             runCatching { modernProvider.syncIntoDb() }.getOrNull()@@ -181,6 +193,7 @@ class CatalogRepository(             fdroidCount = fdroid,             fdroidReproducible = fdroidProvider.lastReproducibleCount,             modernCount = modern,+            proprietaryCount = proprietary,             skipped = DefaultRepos.ALL.mapNotNullTo(mutableSetOf()) {                 it.source.takeIf { source -> source !in enabled }             },
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.ktindex 0cf680b91f..961bf5c5e2 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -1,6 +1,7 @@ package com.vayunmathur.appstore.data  import android.content.Context+import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -26,7 +27,24 @@ class FDroidAppProvider(      /** Refresh [descriptor] and replace only that repository's cached rows. */     suspend fun syncIntoDb(): Int = withContext(Dispatchers.IO) {-        val result = fetchVerifiedIndex()+        val result = try {+            fetchVerifiedIndex()+        } catch (expected: Exception) {+            Log.w(TAG, "sync of ${descriptor.displayName} failed", expected)+            throw expected+        }+        Log.i(+            TAG,+            "sync of ${descriptor.displayName}: fetched ${result.apps.size} " ++                "apps (signer ${result.signerSha256.take(16)}…)"+        )+        // A verified-but-empty index is a bad publish window, not an empty store: keep the+        // previous rows so one bad sync cannot wipe the catalogue (issue: "catalogue+        // updated — 0 apps" left the Modern Apps section empty until the next good sync).+        if (result.apps.isEmpty()) {+            Log.w(TAG, "sync of ${descriptor.displayName} parsed 0 apps; keeping cached rows")+            return@withContext 0+        }         val repo = db.repoDao().all().find { it.url == descriptor.url }         db.cachedAppDao().deleteByRepo(descriptor.url)         db.cachedAppDao().upsertAll(result.apps.map { it.toEntity() })@@ -60,6 +78,10 @@ class FDroidAppProvider(         lastReproducibleCount = reproduced         return result     }++    private companion object {+        const val TAG = "FDroidAppProvider"+    } }  fun RepoDescriptor.toEntity(): RepoEntity = RepoEntity(
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex 8bfa958f19..0d8bf4a029 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -171,6 +171,16 @@ class InstallCoordinator(                         ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),                     signerOrigin = "this store",                 )+                // This store's own Play mirror: the same release key signs the index, but+                // the APKs carry the developers' keys, so the per-version signers from+                // the signed index are the anchor — not this store's own certificate.+                AppSource.PROPRIETARY -> InstallRequirement(+                    expectedPackage = app.packageName,+                    requiredSigners = app.expectedSigners.toSet(),+                    expectedSha256 = app.apkSha256+                        ?.let { mapOf("${app.packageName}.apk" to it) } ?: emptyMap(),+                    signerOrigin = "this store's Play mirror",+                )                 else -> InstallRequirement(                     expectedPackage = app.packageName,                     requiredSigners = app.expectedSigners.toSet(),
appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.ktindex be31a8f90b..fca9724cf1 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt@@ -94,7 +94,15 @@ enum class TrustProfile {      * is the pinned repo signing key and, per app, the signing certificate and minimum version      * that key vouches for.      */-    ACCRESCENT;+    ACCRESCENT,++    /**+     * This store's own Play mirror: curated free-but-proprietary APKs fetched from Google+     * Play by the server and published in a signed F-Droid-format index. Trust is the+     * pinned repo signing key and, per version, the developer signing certificate and+     * APK hash that index vouches for.+     */+    PROPRIETARY;      @get:StringRes     val title: Int@@ -104,6 +112,7 @@ enum class TrustProfile {             GRAPHENEOS -> R.string.source_chip_grapheneos             PLAY -> R.string.trust_play_title             ACCRESCENT -> R.string.source_chip_accrescent+            PROPRIETARY -> R.string.source_chip_proprietary         }      /** One line, shown under the heading on the app's page. */@@ -115,6 +124,7 @@ enum class TrustProfile {             GRAPHENEOS -> R.string.trust_grapheneos_summary             PLAY -> R.string.trust_play_summary             ACCRESCENT -> R.string.trust_accrescent_summary+            PROPRIETARY -> R.string.trust_proprietary_summary         }      /** What the source itself does, beyond anything this app can check. */@@ -145,6 +155,11 @@ enum class TrustProfile {                 R.string.trust_accrescent_practice_signed_list,                 R.string.trust_accrescent_practice_min_version,             )+            PROPRIETARY -> listOf(+                R.string.trust_proprietary_practice_curated,+                R.string.trust_proprietary_practice_signed_index,+                R.string.trust_proprietary_practice_play_origin,+            )         }      /** Checks this app performs on the download, on top of [StoreGuarantees.rules]. */@@ -176,6 +191,10 @@ enum class TrustProfile {                 R.string.trust_accrescent_check_key,                 R.string.trust_accrescent_check_min_version,             )+            PROPRIETARY -> listOf(+                R.string.trust_proprietary_check_index_signed,+                R.string.trust_proprietary_check_hash_and_key,+            )         }      /** Where this source is weaker than the others. Every source has one. */@@ -187,6 +206,7 @@ enum class TrustProfile {             GRAPHENEOS -> R.string.trust_grapheneos_limits             PLAY -> R.string.trust_play_limits             ACCRESCENT -> R.string.trust_accrescent_limits+            PROPRIETARY -> R.string.trust_proprietary_limits         }      companion object {@@ -200,6 +220,9 @@ enum class TrustProfile {             // Accrescent apps are signed by their developers, not by Accrescent; trust is the             // ed25519-signed allowlist that pins each app's signing certificate + min version.             AppSource.ACCRESCENT -> ACCRESCENT+            // Mirror apps are signed by their developers too; trust is this store's signed+            // index pinning each version's signing certificate + APK hash.+            AppSource.PROPRIETARY -> PROPRIETARY         }     } }
appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.ktindex 36b03124e7..8a433d576d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt@@ -104,6 +104,7 @@ fun SourceChip(source: AppSource, modifier: Modifier = Modifier) {             AppSource.GRAPHENEOS -> R.string.source_chip_grapheneos             AppSource.PLAYSTORE -> R.string.source_chip_play             AppSource.ACCRESCENT -> R.string.source_chip_accrescent+            AppSource.PROPRIETARY -> R.string.source_chip_proprietary         }     )     Text(
appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.ktindex dced97c64c..f0547a1691 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt@@ -157,6 +157,7 @@ private fun Loading() { internal fun SourceFilter.labelRes(): Int = when (this) {     SourceFilter.ALL -> R.string.filter_all     SourceFilter.MODERN_APPS -> R.string.source_chip_modern_apps+    SourceFilter.PROPRIETARY -> R.string.source_chip_proprietary     SourceFilter.FDROID -> R.string.source_chip_fdroid     SourceFilter.GRAPHENEOS -> R.string.source_chip_grapheneos     SourceFilter.PLAYSTORE -> R.string.source_chip_play
appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.ktindex af5d723624..b647ceda16 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt@@ -54,6 +54,7 @@ fun SourcesPage(     val autoInstallUpdates by viewModel.autoInstallUpdates.collectAsState()     val enabledSources by viewModel.enabledSources.collectAsState()     val fdroid = repos.find { it.url == DefaultRepos.FDROID.url }+    val proprietary = repos.find { it.url == DefaultRepos.PROPRIETARY.url }     val noneEnabled = AppSource.TOGGLEABLE.none { it in enabledSources }     // Sync only refreshes the two offline indexes; with both off it has nothing to fetch.     val nothingToSync = DefaultRepos.ALL.none { it.source in enabledSources }@@ -129,6 +130,17 @@ fun SourcesPage(             enabled = AppSource.FDROID in enabledSources,             onEnabledChange = { viewModel.setSourceEnabled(AppSource.FDROID, it) },         )+        SourceCard(+            title = stringResource(R.string.source_chip_proprietary),+            subtitle = DefaultRepos.PROPRIETARY.url,+            pinLabel = stringResource(R.string.source_proprietary_pin),+            pins = setOfNotNull(+                proprietary?.fingerprint ?: DefaultRepos.PROPRIETARY.pinnedFingerprint+            ),+            lastSync = proprietary?.lastSync ?: 0L,+            enabled = AppSource.PROPRIETARY in enabledSources,+            onEnabledChange = { viewModel.setSourceEnabled(AppSource.PROPRIETARY, it) },+        )         SourceCard(             title = stringResource(R.string.source_play),             subtitle = "play.google.com",
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.ktindex bc85687a65..ca090f69f8 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreHomeOps.kt@@ -168,6 +168,7 @@ fun AppStoreViewModel.syncSources() {                 when (step) {                     SyncStep.FDROID -> R.string.sync_step_fdroid                     SyncStep.MODERN_APPS -> R.string.sync_step_modern_apps+                    SyncStep.PROPRIETARY -> R.string.sync_step_proprietary                 }             )         }@@ -179,11 +180,15 @@ fun AppStoreViewModel.syncSources() {                 report.allSkipped -> context.getString(R.string.sync_all_sources_off)                 !report.anyFailed -> context.getString(                     R.string.sync_done,-                    (report.fdroidCount ?: 0) + (report.modernCount ?: 0),+                    (report.fdroidCount ?: 0) + (report.modernCount ?: 0) ++                        (report.proprietaryCount ?: 0),                 )-                report.fdroidCount == null && report.modernCount == null ->+                report.fdroidCount == null && report.modernCount == null &&+                    report.proprietaryCount == null ->                     context.getString(R.string.sync_failed_all)                 report.fdroidCount == null -> context.getString(R.string.sync_failed_fdroid)+                report.proprietaryCount == null ->+                    context.getString(R.string.sync_failed_proprietary)                 else -> context.getString(R.string.sync_failed_modern_apps)             }         )
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.ktindex 672126c6ba..f7e47ded87 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt@@ -43,6 +43,7 @@ data class AppSection( enum class SourceFilter(val source: AppSource?) {     ALL(null),     MODERN_APPS(AppSource.MODERN_APPS),+    PROPRIETARY(AppSource.PROPRIETARY),     FDROID(AppSource.FDROID),     GRAPHENEOS(AppSource.GRAPHENEOS),     PLAYSTORE(AppSource.PLAYSTORE),
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex 077a2e51d1..618955eb0b 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -26,6 +26,7 @@     <string name="source_chip_grapheneos">GrapheneOS</string>     <string name="source_chip_play">Play Store</string>     <string name="source_chip_accrescent">Accrescent</string>+    <string name="source_chip_proprietary">Proprietary</string>     <string name="filter_all">All</string>     <string name="filter_with_count">%1$s (%2$d)</string> @@ -47,10 +48,12 @@     <string name="sync_in_progress">Syncing…</string>     <string name="sync_step_fdroid">Checking F-Droid builds…</string>     <string name="sync_step_modern_apps">Checking Modern Apps…</string>+    <string name="sync_step_proprietary">Checking proprietary mirror…</string>     <string name="sync_done">Catalogue updated — %1$d apps</string>-    <string name="sync_failed_all">Neither source would sync. Your existing catalogue is unchanged.</string>+    <string name="sync_failed_all">No source would sync. Your existing catalogue is unchanged.</string>     <string name="sync_failed_fdroid">F-Droid didn\'t sync. Its existing apps are unchanged.</string>     <string name="sync_failed_modern_apps">Modern Apps didn\'t sync. Its existing apps are unchanged.</string>+    <string name="sync_failed_proprietary">The proprietary mirror didn\'t sync. Its existing apps are unchanged.</string>     <!-- Message after tapping Sync sources with every source switched off. -->     <string name="sync_all_sources_off">Nothing to sync — every source is switched off.</string>     <string name="play_unavailable">Play Store results unavailable: %1$s</string>@@ -236,6 +239,14 @@     <string name="trust_accrescent_check_min_version">The download\'s version is at or above the minimum the signed list allows</string>     <string name="trust_accrescent_limits">Accrescent publishes no per-file hashes and no reproducible builds, so the guarantee is the signature and minimum version, not source. Listings come from an ordinary server over gRPC; a bad response can only produce a file that fails these checks. Nobody scans the apps.</string> +    <string name="trust_proprietary_summary">Curated free-but-proprietary apps fetched from Google Play by this store\'s own server and published in a signed index naming each version\'s hash and signing key.</string>+    <string name="trust_proprietary_practice_curated">Only an explicit allowlist is mirrored, chosen by the store operator</string>+    <string name="trust_proprietary_practice_signed_index">Versions, file hashes and expected signing keys are published in an index signed with this store\'s release key</string>+    <string name="trust_proprietary_practice_play_origin">The files are the developers\' own Play builds, fetched unchanged rather than rebuilt</string>+    <string name="trust_proprietary_check_index_signed">That signed index is checked against a key built into this store</string>+    <string name="trust_proprietary_check_hash_and_key">Every downloaded file matches the hash and the signing key that index names for it</string>+    <string name="trust_proprietary_limits">These are closed-source apps fetched by the operator, so you trust the operator to have fetched the genuine file, and there is no source to audit and no reproducible build. Nobody scans the apps.</string>+     <!-- Sources page. -->     <string name="repos_sync_sources">Sync sources</string>     <string name="source_modern_apps" translatable="false">Modern Apps</string>@@ -244,4 +255,5 @@     <string name="source_play">Play Store (anonymous)</string>     <string name="source_play_pin">Nothing to pin: Google holds the signing key</string>     <string name="source_accrescent_pin">Pinned to Accrescent\'s repodata signing key (ed25519)</string>+    <string name="source_proprietary_pin">Pinned to this store\'s Play mirror signing key</string> </resources>
metadata_data/appstore.md
diff --git a/metadata_data/appstore.md b/metadata_data/appstore.mdindex 5578be8b69..87f6ddf4a4 100644--- a/metadata_data/appstore.md+++ b/metadata_data/appstore.md@@ -1,7 +1,7 @@ An app store that verifies every install and tells you who could update it  Features:-- Five sources: this project's own repo, F-Droid, GrapheneOS, Accrescent, and Play+- Six sources: this project's own repo, a curated proprietary mirror, F-Droid, GrapheneOS, Accrescent, and Play - Every download is signature-checked before the system installer ever sees it - A security tier per app, saying plainly who could push you a malicious update - F-Droid listings restricted to builds F-Droid's server independently reproduced
metadata_data/photos/appstore/1.png
diff --git a/metadata_data/photos/appstore/1.png b/metadata_data/photos/appstore/1.pngindex 9f7d37530a..9dfc535e8b 100644Binary files a/metadata_data/photos/appstore/1.png and b/metadata_data/photos/appstore/1.png differ
metadata_data/photos/appstore/2.png
diff --git a/metadata_data/photos/appstore/2.png b/metadata_data/photos/appstore/2.pngindex 48d07cd584..4b9195fe13 100644Binary files a/metadata_data/photos/appstore/2.png and b/metadata_data/photos/appstore/2.png differ
metadata_data/photos/appstore/3.png
diff --git a/metadata_data/photos/appstore/3.png b/metadata_data/photos/appstore/3.pngindex 9696441a1d..2177bb367b 100644Binary files a/metadata_data/photos/appstore/3.png and b/metadata_data/photos/appstore/3.png differ
metadata_data/photos/appstore/4.png
diff --git a/metadata_data/photos/appstore/4.png b/metadata_data/photos/appstore/4.pngindex fa1814a2f2..c1f26f4024 100644Binary files a/metadata_data/photos/appstore/4.png and b/metadata_data/photos/appstore/4.png differ
musicbrainz/AGENTS.md
diff --git a/musicbrainz/AGENTS.md b/musicbrainz/AGENTS.mddeleted file mode 100644index d70e48ee72..0000000000--- a/musicbrainz/AGENTS.md+++ /dev/null@@ -1,65 +0,0 @@-# AGENTS.md — musicbrainz/ (':musicbrainz')--> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `musicbrainz/` + allowed shared modules. Do not root-scan.--_Install: ./install musicbrainz (dev by default)._--- Gradle: :musicbrainz / dir: musicbrainz/-- Package roots present: ui, data, domain, platform, network-- Entry files: MainActivity.kt, Route.kt, Navigation.kt, MusicBrainzApplication.kt-- Deps: :library:network, :library:image, :library:media, :youpipe:extractor, :library:room-- Metadata: metadata_data/musicbrainz.md (present)-- Rust: no / screenshotTest: yes--## Key files--- com/vayunmathur/musicbrainz/MainActivity.kt-- com/vayunmathur/musicbrainz/MusicBrainzApplication.kt-- com/vayunmathur/musicbrainz/Navigation.kt-- com/vayunmathur/musicbrainz/Route.kt-- com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt-- com/vayunmathur/musicbrainz/data/MusicBrainzRepository.kt-- com/vayunmathur/musicbrainz/data/download/AudioSource.kt-- com/vayunmathur/musicbrainz/data/download/AudioSources.kt-- com/vayunmathur/musicbrainz/data/download/Lyrics.kt-- com/vayunmathur/musicbrainz/data/download/MbDownloader.kt-- com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt-- com/vayunmathur/musicbrainz/data/download/TidalManifest.kt-- com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt-- com/vayunmathur/musicbrainz/data/library/LibraryIndex.kt-- com/vayunmathur/musicbrainz/data/library/LibraryScanner.kt-- com/vayunmathur/musicbrainz/data/library/TagReader.kt-- com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt-- com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt-- com/vayunmathur/musicbrainz/domain/library/MatchKeys.kt-- com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt-- com/vayunmathur/musicbrainz/network/api/MusicBrainzModels.kt-- com/vayunmathur/musicbrainz/network/api/TidalApi.kt-- com/vayunmathur/musicbrainz/network/api/TidalModels.kt-- com/vayunmathur/musicbrainz/platform/DownloadSource.kt-- com/vayunmathur/musicbrainz/platform/MusicBrainzPrefs.kt-- com/vayunmathur/musicbrainz/platform/MusicBrainzUiContract.kt-- com/vayunmathur/musicbrainz/platform/MusicBrainzViewModel.kt-- com/vayunmathur/musicbrainz/platform/SafTree.kt-- com/vayunmathur/musicbrainz/platform/download/DownloadQueue.kt-- com/vayunmathur/musicbrainz/platform/download/DownloadWorker.kt-- com/vayunmathur/musicbrainz/ui/ArtistScreen.kt-- com/vayunmathur/musicbrainz/ui/DownloadsScreen.kt-- com/vayunmathur/musicbrainz/ui/ReleaseGroupScreen.kt-- com/vayunmathur/musicbrainz/ui/ReleaseScreen.kt-- com/vayunmathur/musicbrainz/ui/SearchScreen.kt-- com/vayunmathur/musicbrainz/ui/SettingsScreen.kt-- com/vayunmathur/musicbrainz/ui/TidalLoginScreen.kt-- com/vayunmathur/musicbrainz/ui/components/CoverArtImage.kt-- com/vayunmathur/musicbrainz/ui/components/DurationLabel.kt-- com/vayunmathur/musicbrainz/ui/components/SecondaryText.kt-- com/vayunmathur/musicbrainz/ui/components/TrackTrailing.kt--## Verify (this module only)-```-./gradlew :musicbrainz:compileDevKotlin-./gradlew :musicbrainz:lint-./gradlew :musicbrainz:checkMetadata-```--
musicbrainz/build.gradle.kts
diff --git a/musicbrainz/build.gradle.kts b/musicbrainz/build.gradle.ktsdeleted file mode 100644index 904a32c116..0000000000--- a/musicbrainz/build.gradle.kts+++ /dev/null@@ -1,29 +0,0 @@-plugins {-    id("common-conventions-app")-    id("common-conventions-preview-metadata")-    alias(libs.plugins.ksp)-}--launcherIcon {-    symbol = "graphic_eq"-}--android {-    defaultConfig {-        applicationId = "com.vayunmathur.musicbrainz"-    }-}--dependencies {-    implementation(project(":library:network"))-    implementation(project(":library:image"))-    implementation(project(":library:media"))-    // The vendored NewPipe fork. Only the JVM extractor is used - the SABR/PO-token-    // machinery that needs QuickJS and a WebView lives in :youpipe itself, and audio-    // resolution works without it.-    implementation(project(":youpipe:extractor"))-    implementation(libs.androidx.work.runtime.ktx)-    implementation(libs.androidx.datastore.preferences)-    implementRoom(libs)-    implementation(project(":library:room"))-}
musicbrainz/src/main/AndroidManifest.xml
diff --git a/musicbrainz/src/main/AndroidManifest.xml b/musicbrainz/src/main/AndroidManifest.xmldeleted file mode 100644index 214be43083..0000000000--- a/musicbrainz/src/main/AndroidManifest.xml+++ /dev/null@@ -1,39 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">--    <uses-permission android:name="android.permission.INTERNET" />-    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />-    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />--    <application-        android:name=".MusicBrainzApplication"-        android:allowBackup="true"-        android:dataExtractionRules="@xml/data_extraction_rules"-        android:icon="@mipmap/ic_launcher"-        android:label="@string/app_name"-        android:roundIcon="@mipmap/ic_launcher"-        android:supportsRtl="true"-        android:theme="@style/Theme.General">-        <activity-            android:name=".MainActivity"-            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"-            android:exported="true"-            android:theme="@style/Theme.General">-            <intent-filter>-                <action android:name="android.intent.action.MAIN" />--                <category android:name="android.intent.category.LAUNCHER" />-            </intent-filter>-            <intent-filter android:autoVerify="true">-                <action android:name="android.intent.action.VIEW" />--                <category android:name="android.intent.category.DEFAULT" />-                <category android:name="android.intent.category.BROWSABLE" />-                <data android:scheme="https" />-                <data android:host="musicbrainz.org" />-                <data android:host="beta.musicbrainz.org" />-            </intent-filter>-        </activity>-    </application>--</manifest>
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.ktdeleted file mode 100644index 60813956ab..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MainActivity.kt+++ /dev/null@@ -1,26 +0,0 @@-package com.vayunmathur.musicbrainz--import android.os.Bundle-import androidx.activity.ComponentActivity-import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.viewModels-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.OfflineAware-import com.vayunmathur.musicbrainz.platform.MusicBrainzViewModel--class MainActivity : ComponentActivity() {-    private val viewModel: MusicBrainzViewModel by viewModels()--    override fun onCreate(savedInstanceState: Bundle?) {-        super.onCreate(savedInstanceState)-        enableEdgeToEdge()-        setContent {-            DynamicTheme {-                OfflineAware {-                    Navigation(viewModel)-                }-            }-        }-    }-}
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.ktdeleted file mode 100644index 602e86c69e..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/MusicBrainzApplication.kt+++ /dev/null@@ -1,21 +0,0 @@-package com.vayunmathur.musicbrainz--import android.app.Application-import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.TrustBundle-import com.vayunmathur.musicbrainz.data.download.MbDownloader-import org.schabi.newpipe.extractor.NewPipe-import org.schabi.newpipe.extractor.localization.Localization-import java.util.Locale--class MusicBrainzApplication : Application() {-    override fun onCreate() {-        super.onCreate()-        // 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.-        NetworkClient.init(this, TrustBundle.MUSICBRAINZ)-        NewPipe.init(MbDownloader(), Localization.fromLocale(Locale.getDefault()))-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.ktdeleted file mode 100644index 40e62b1208..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Navigation.kt+++ /dev/null@@ -1,36 +0,0 @@-package com.vayunmathur.musicbrainz--import androidx.compose.runtime.Composable-import com.vayunmathur.library.util.ListDetailPage-import com.vayunmathur.library.util.ListPage-import com.vayunmathur.library.util.MainNavigation-import com.vayunmathur.library.util.MorphPage-import com.vayunmathur.library.util.rememberNavBackStack-import com.vayunmathur.musicbrainz.platform.MusicBrainzViewModel-import com.vayunmathur.musicbrainz.ui.ArtistPage-import com.vayunmathur.musicbrainz.ui.DownloadsPage-import com.vayunmathur.musicbrainz.ui.ReleaseGroupPage-import com.vayunmathur.musicbrainz.ui.ReleasePage-import com.vayunmathur.musicbrainz.ui.SearchPage-import com.vayunmathur.musicbrainz.ui.SettingsPage-import com.vayunmathur.musicbrainz.ui.TidalLoginPage--@Composable-fun Navigation(viewModel: MusicBrainzViewModel) {-    val backStack = rememberNavBackStack<Route>(Route.Search)-    MainNavigation(backStack) {-        entry<Route.Search>(metadata = ListPage()) { SearchPage(backStack, viewModel) }-        entry<Route.Artist>(metadata = ListDetailPage() + MorphPage()) {-            ArtistPage(backStack, viewModel, it.artistId)-        }-        entry<Route.ReleaseGroup>(metadata = ListDetailPage() + MorphPage()) {-            ReleaseGroupPage(backStack, viewModel, it.releaseGroupId)-        }-        entry<Route.Release>(metadata = ListDetailPage() + MorphPage()) {-            ReleasePage(backStack, viewModel, it.releaseId)-        }-        entry<Route.Downloads>(metadata = ListDetailPage()) { DownloadsPage(backStack, viewModel) }-        entry<Route.Settings>(metadata = ListDetailPage()) { SettingsPage(backStack, viewModel) }-        entry<Route.TidalLogin>(metadata = ListDetailPage()) { TidalLoginPage(backStack, viewModel) }-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.ktdeleted file mode 100644index 7397c5f79e..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/Route.kt+++ /dev/null@@ -1,28 +0,0 @@-package com.vayunmathur.musicbrainz--import com.vayunmathur.library.util.NavKey-import kotlinx.serialization.Serializable--@Serializable-sealed interface Route : NavKey {-    @Serializable-    data object Search : Route--    @Serializable-    data object Downloads : Route--    @Serializable-    data object Settings : Route--    @Serializable-    data object TidalLogin : Route--    @Serializable-    data class Artist(val artistId: String) : Route--    @Serializable-    data class ReleaseGroup(val releaseGroupId: String) : Route--    @Serializable-    data class Release(val releaseId: String) : Route-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.ktdeleted file mode 100644index ed0358f558..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzDatabase.kt+++ /dev/null@@ -1,65 +0,0 @@-package com.vayunmathur.musicbrainz.data--import androidx.room3.Dao-import androidx.room3.Database-import androidx.room3.Entity-import androidx.room3.PrimaryKey-import androidx.room3.Query-import androidx.room3.RoomDatabase-import androidx.room3.Upsert--/**- * One audio file found in the user's music folder.- *- * Keyed by document URI so a rescan updates rows in place. [size] and [lastModified] are- * kept so an unchanged file can be skipped on the next scan without reopening it.- */-@Entity(tableName = "local_track")-data class LocalTrack(-    @PrimaryKey val documentUri: String,-    val fileName: String,-    val size: Long,-    val lastModified: Long,-    val recordingId: String? = null,-    val releaseId: String? = null,-    val releaseTrackId: String? = null,-    val title: String? = null,-    val artist: String? = null,-    val album: String? = null,-    /** Normalised "artist\u0000title", the fallback match for files with no MusicBrainz IDs. */-    val matchKey: String? = null,-    /** Normalised "album\u0000title", so compilations still match when the artist differs. */-    val albumKey: String? = null,-)--@Dao-interface LocalTrackDao {-    @Upsert-    suspend fun upsertAll(tracks: List<LocalTrack>)--    @Query("SELECT * FROM local_track")-    suspend fun all(): List<LocalTrack>--    @Query("SELECT documentUri, size, lastModified FROM local_track")-    suspend fun fingerprints(): List<TrackFingerprint>--    @Query("DELETE FROM local_track WHERE documentUri IN (:uris)")-    suspend fun deleteByUris(uris: List<String>)--    @Query("DELETE FROM local_track")-    suspend fun deleteAll()--    @Query("SELECT COUNT(*) FROM local_track")-    suspend fun count(): Int-}--data class TrackFingerprint(-    val documentUri: String,-    val size: Long,-    val lastModified: Long,-)--@Database(entities = [LocalTrack::class], version = 1, exportSchema = false)-abstract class MusicBrainzDatabase : RoomDatabase() {-    abstract fun localTrackDao(): LocalTrackDao-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzRepository.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzRepository.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzRepository.ktdeleted file mode 100644index 84b0966a65..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/MusicBrainzRepository.kt+++ /dev/null@@ -1,26 +0,0 @@-package com.vayunmathur.musicbrainz.data--import android.content.Context-import com.vayunmathur.library.room.RoomRepository-import com.vayunmathur.musicbrainz.data.library.LibraryScanner--class MusicBrainzRepository private constructor(context: Context) :-    RoomRepository<MusicBrainzDatabase>(context, MusicBrainzDatabase::class, LibraryScanner.DB_NAME) {--    private val dao get() = db.localTrackDao()--    suspend fun upsertAll(tracks: List<LocalTrack>) = dao.upsertAll(tracks)-    suspend fun all(): List<LocalTrack> = dao.all()-    suspend fun fingerprints(): List<TrackFingerprint> = dao.fingerprints()-    suspend fun deleteByUris(uris: List<String>) = dao.deleteByUris(uris)-    suspend fun deleteAll() = dao.deleteAll()-    suspend fun count(): Int = dao.count()--    companion object {-        @Volatile private var instance: MusicBrainzRepository? = null-        fun get(context: Context): MusicBrainzRepository =-            instance ?: synchronized(this) {-                instance ?: MusicBrainzRepository(context).also { instance = it }-            }-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.ktdeleted file mode 100644index 16f891ce99..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSource.kt+++ /dev/null@@ -1,61 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import com.vayunmathur.musicbrainz.platform.DownloadSource--/**- * What a source is asked to find.- *- * Bundled rather than passed as loose parameters so a source that needs a signal the- * others ignore - Tidal matches on [isrcs], YouTube cannot - does not change every- * signature between here and the worker.- */-data class AudioQuery(-    val artist: String,-    val title: String,-    val album: String?,-    /**-     * The MusicBrainz recording length. Search alone happily returns hour-long-     * compilations and sped-up edits of the same title, and duration is the one signal-     * every source can use to separate them from the actual track.-     */-    val durationMs: Int?,-    /**-     * The recording's ISRCs. An exact identity match when the source catalogues them,-     * which beats every other signal; empty for recordings MusicBrainz has none for.-     */-    val isrcs: List<String> = emptyList(),-)--/** A resolved, directly fetchable audio stream. */-data class ResolvedAudio(-    /**-     * The stream's parts, in order, to be concatenated. A progressive stream is a-     * one-element list; a DASH stream is one entry per segment.-     */-    val urls: List<String>,-    val suffix: String,-    val mimeType: String,-    val bitrate: Int,-    val sourceTitle: String,-    val source: DownloadSource,-    /**-     * True when the stream is already 48 kHz Opus, just in a WebM container, so it only needs-     * remuxing to Ogg rather than transcoding. Re-encoding it would be a second lossy-     * generation for no gain, so this is the one stream that keeps its bits.-     */-    val isOpusPassthrough: Boolean = false,-)--/**- * One place a track's audio can be fetched from.- *- * The seam exists so the sources stay independent of the download pipeline: everything- * after [resolve] - buffered fetch, tagging, SAF write, index upsert - is the same- * whichever source produced the URLs.- */-interface AudioSource {-    val id: DownloadSource--    /** Returns null when this source has no match, so the caller can try the next one. */-    suspend fun resolve(query: AudioQuery): ResolvedAudio?-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.ktdeleted file mode 100644index 7396313225..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/AudioSources.kt+++ /dev/null@@ -1,21 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import android.content.Context-import com.vayunmathur.musicbrainz.platform.DownloadSource--/**- * The download-source fallback policy, in one place.- *- * Tidal is a catalogue lookup, so it can simply not carry a recording, and a subscription- * can lapse. It is therefore always backed by YouTube: a download quietly falling through- * to a lossy source is better than one disappearing.- */-object AudioSources {--    /** The sources to try, in order, for a user who prefers [preferred]. */-    fun ordered(context: Context, preferred: DownloadSource): List<AudioSource> =-        when (preferred) {-            DownloadSource.Tidal -> listOf(TidalAudioSource(context), YouTubeAudioSource)-            DownloadSource.YouTube -> listOf(YouTubeAudioSource)-        }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Lyrics.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Lyrics.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Lyrics.ktdeleted file mode 100644index 5127455374..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/Lyrics.kt+++ /dev/null@@ -1,89 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import com.vayunmathur.library.network.NetworkClient-import kotlinx.serialization.Serializable-import kotlin.math.abs--@Serializable-private data class LrcLibResponse(-    val duration: Double? = null,-    val syncedLyrics: String? = null,-    val plainLyrics: String? = null,-) {-    /** Synced lyrics are preferred; plain text is the fallback. Null when neither is set. */-    fun best(): String? =-        syncedLyrics?.takeIf { it.isNotBlank() } ?: plainLyrics?.takeIf { it.isNotBlank() }-}--/**- * Fetches lyrics from LRCLIB.- *- * Synced lyrics are preferred so players that support them can follow along, with plain- * text as the fallback. Failures are silent - lyrics are a nicety, and a missing set is- * not a reason to fail a download.- */-object Lyrics {--    private const val GET = "https://lrclib.net/api/get"-    private const val SEARCH = "https://lrclib.net/api/search"-    private val headers = mapOf(-        "User-Agent" to "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )",-    )--    suspend fun fetch(artist: String, title: String, album: String?, durationMs: Int?): String? =-        getExact(artist, title, album, durationMs) ?: search(artist, title, durationMs)--    /**-     * The exact-match endpoint. Fast and precise, but LRCLIB requires the duration to line-     * up within a couple of seconds, so a track whose audio length differs from the-     * MusicBrainz figure - common for YouTube sources - returns nothing here.-     */-    private suspend fun getExact(-        artist: String,-        title: String,-        album: String?,-        durationMs: Int?,-    ): String? {-        val url = buildString {-            append(GET)-            append("?artist_name=").append(encode(artist))-            append("&track_name=").append(encode(title))-            if (!album.isNullOrBlank()) append("&album_name=").append(encode(album))-            if (durationMs != null && durationMs > 0) append("&duration=").append(durationMs / 1000)-        }-        return try {-            NetworkClient.getJson<LrcLibResponse>(url, headers = headers).best()-        } catch (_: Exception) {-            null-        }-    }--    /**-     * The fuzzy fallback. It ignores duration, so it recovers the many tracks the exact-     * lookup misses; when a duration is known the candidate closest to it is chosen so a-     * different edit or a live version does not win over the album cut.-     */-    private suspend fun search(artist: String, title: String, durationMs: Int?): String? {-        val url = buildString {-            append(SEARCH)-            append("?artist_name=").append(encode(artist))-            append("&track_name=").append(encode(title))-        }-        val results = try {-            NetworkClient.getJson<List<LrcLibResponse>>(url, headers = headers)-        } catch (_: Exception) {-            return null-        }-        val withLyrics = results.filter { it.best() != null }-        if (withLyrics.isEmpty()) return null-        val target = durationMs?.takeIf { it > 0 }?.let { it / 1000.0 }-        val pick = if (target != null) {-            withLyrics.minByOrNull { abs((it.duration ?: Double.MAX_VALUE) - target) }-        } else {-            withLyrics.first()-        }-        return pick?.best()-    }--    private fun encode(value: String): String = java.net.URLEncoder.encode(value, "UTF-8")-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/MbDownloader.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/MbDownloader.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/MbDownloader.ktdeleted file mode 100644index 6c099e2692..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/MbDownloader.kt+++ /dev/null@@ -1,89 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import com.vayunmathur.library.network.NetworkClient-import kotlinx.coroutines.runBlocking-import org.schabi.newpipe.extractor.downloader.Downloader-import org.schabi.newpipe.extractor.downloader.Request-import org.schabi.newpipe.extractor.downloader.Response-import org.schabi.newpipe.extractor.downloader.StreamingResponse-import org.schabi.newpipe.extractor.localization.Localization--/**- * The [Downloader] the extractor calls out through, on top of `NetworkClient`.- *- * A near-copy of YouPipe's, kept here rather than shared because the two apps are- * otherwise independent and `:youpipe:extractor` is the only thing they have in common.- * The browser User-Agent is not cosmetic: the InnerTube endpoints reject the default.- */-class MbDownloader : Downloader() {-    override fun execute(request: Request): Response = runBlocking {-        val response = NetworkClient.performRequest(-            url = request.url,-            method = request.httpMethod,-            headers = withDefaultHeaders(request.headers),-            body = request.dataToSend,-        )-        Response(-            response.status,-            response.statusMessage,-            response.headers,-            response.body,-            response.url,-        )-    }--    override fun getStreaming(-        url: String,-        headers: Map<String, List<String>>?,-        localization: Localization?,-    ): StreamingResponse = runBlocking { streaming(url, "GET", headers, null, null) }--    override fun getStreaming(-        url: String,-        headers: Map<String, List<String>>?,-        localization: Localization?,-        timeoutMs: Long,-    ): StreamingResponse = runBlocking {-        streaming(url, "GET", headers, null, timeoutMs.coerceAtLeast(1))-    }--    override fun postStreaming(-        url: String,-        headers: Map<String, List<String>>?,-        dataToSend: ByteArray?,-        localization: Localization?,-    ): StreamingResponse = runBlocking { streaming(url, "POST", headers, dataToSend, null) }--    private suspend fun streaming(-        url: String,-        method: String,-        headers: Map<String, List<String>>?,-        data: ByteArray?,-        timeoutMs: Long?,-    ): StreamingResponse {-        val (code, respHeaders, stream) = NetworkClient.performRequestInputStream(-            url = url,-            method = method,-            headers = withDefaultHeaders(headers),-            body = data,-            timeoutMs = timeoutMs,-        )-        return StreamingResponse(code, respHeaders, stream)-    }--    private fun withDefaultHeaders(-        headers: Map<String, List<String>>?,-    ): Map<String, List<String>> {-        val result = LinkedHashMap<String, List<String>>()-        if (headers != null) result.putAll(headers)-        if (result.keys.none { it.equals("User-Agent", ignoreCase = true) }) {-            result["User-Agent"] = listOf(DEFAULT_USER_AGENT)-        }-        return result-    }--    private companion object {-        const val DEFAULT_USER_AGENT =-            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0"-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.ktdeleted file mode 100644index 978ab02495..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalAudioSource.kt+++ /dev/null@@ -1,133 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import android.content.Context-import com.vayunmathur.musicbrainz.data.tidal.TidalSession-import com.vayunmathur.musicbrainz.network.api.TidalApi-import com.vayunmathur.musicbrainz.network.api.TidalTrack-import com.vayunmathur.musicbrainz.platform.DownloadSource-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import kotlin.math.abs--/**- * Finds a downloadable stream on Tidal for a signed-in subscriber.- *- * Tidal is a catalogue with structured metadata, so matching is far surer than YouTube's:- * a track carries its ISRC, which is an exact identity match, and failing that its real- * album title and an exact duration. When no session exists this returns null immediately- * so [AudioSources] falls straight through to YouTube without a wasted request.- */-class TidalAudioSource(context: Context) : AudioSource {--    override val id = DownloadSource.Tidal--    private val appContext = context.applicationContext-    private val session = TidalSession(appContext)--    override suspend fun resolve(query: AudioQuery): ResolvedAudio? = withContext(Dispatchers.IO) {-        val token = session.accessToken() ?: return@withContext null-        val country = session.countryCode() ?: return@withContext null--        val results = runCatching {-            TidalApi.search(searchQuery(query), token, country).tracks.items-        }.getOrNull().orEmpty()-        if (results.isEmpty()) return@withContext null--        val match = pick(results, query) ?: return@withContext null-        val stream = bestStream(match.id, token, country) ?: return@withContext null--        ResolvedAudio(-            urls = stream.urls,-            suffix = stream.suffix,-            mimeType = stream.mimeType,-            bitrate = 0,-            sourceTitle = match.title,-            source = id,-        )-    }--    /**-     * Walks down the quality ladder until a stream comes back that can actually be decoded.-     *-     * The ladder is capped at `HIGH`, so the lossless and hi-res tiers are never requested.-     * Everything is re-encoded to a fixed-bitrate Opus file afterwards, and the tiers above-     * `HIGH` cost far more bandwidth than that re-encode can preserve. Tidal downgrades-     * server-side when the subscription or the track cannot serve the ask and reports what it-     * really returned, so the first rung usually succeeds. The remaining rung matters when-     * `playbackInfo` itself fails, or when the manifest that comes back is encrypted or-     * DRM-protected and [TidalManifest] rejects it - dropping a rung is better than losing-     * the download.-     */-    private suspend fun bestStream(trackId: Int, token: String, country: String): TidalStream? {-        for (quality in QUALITY_LADDER) {-            val playback = runCatching {-                TidalApi.playbackInfo(trackId, quality, token, country)-            }.getOrNull() ?: continue-            val stream = runCatching {-                TidalManifest.decode(-                    playback.manifestMimeType,-                    playback.manifest,-                    playback.audioQuality,-                )-            }.getOrNull()-            if (stream != null) return stream-        }-        return null-    }--    private fun searchQuery(query: AudioQuery): String = "${query.artist} ${query.title}".trim()--    /**-     * Picks the best candidate, strongest signal first.-     *-     * An ISRC match is an exact identity match and is taken outright. Otherwise the album-     * title breaks ties - the right album's pressing is almost always what the user wants --     * and duration rejects anything too far off, reusing the same thresholds as the YouTube-     * source so both reject a mismatch alike. Tidal durations are seconds, not ms.-     */-    internal fun pick(candidates: List<TidalTrack>, query: AudioQuery): TidalTrack? {-        val isrcs = query.isrcs.map { it.uppercase() }.toSet()-        if (isrcs.isNotEmpty()) {-            candidates.firstOrNull { it.isrc?.uppercase() in isrcs }?.let { return it }-        }--        val targetSeconds = query.durationMs?.takeIf { it > 0 }?.let { it / 1000L }-        val scored = candidates.withIndex().map { (index, track) ->-            val delta = if (targetSeconds != null && track.duration > 0) {-                abs(track.duration - targetSeconds)-            } else {-                Long.MAX_VALUE-            }-            val albumMatch = query.album != null &&-                track.album?.title?.equals(query.album, ignoreCase = true) == true-            ScoredTrack(track, delta, albumMatch, index)-        }--        val withinTolerance = scored.filter {-            targetSeconds == null || it.delta <= YouTubeAudioSource.MAX_DURATION_DIFF_SECONDS-        }-        val pool = withinTolerance.ifEmpty { scored }--        return pool.sortedWith(-            compareByDescending<ScoredTrack> { it.albumMatch }-                .thenBy { if (it.delta <= YouTubeAudioSource.MATCH_TOLERANCE_SECONDS) 0L else it.delta }-                .thenBy { it.index },-        ).firstOrNull()?.track-    }--    private data class ScoredTrack(-        val track: TidalTrack,-        val delta: Long,-        val albumMatch: Boolean,-        val index: Int,-    )--    private companion object {-        /**-         * Tidal's own `audioquality` values, best first, capped at `HIGH`.-         *-         * `HIGH` is AAC in an m4a container, so downloads never come back as FLAC.-         */-        val QUALITY_LADDER = listOf("HIGH", "LOW")-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.ktdeleted file mode 100644index 2f8e625736..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/TidalManifest.kt+++ /dev/null@@ -1,146 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonArray-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonPrimitive-import org.xml.sax.InputSource-import java.io.StringReader-import java.util.Base64-import javax.xml.parsers.DocumentBuilderFactory--/** A decoded Tidal stream: the segment URLs in order, and the file extension to save under. */-data class TidalStream(-    val urls: List<String>,-    val suffix: String,-    val mimeType: String,-)--/**- * Decodes a Tidal playback manifest into fetchable URLs.- *- * Ported from tiddl's `core/utils/parse.py`. Tidal returns the manifest base64-encoded in- * one of two shapes, distinguished by the response's `manifestMimeType`:- *- * | Quality         | Container | manifestMimeType          |- * | --------------- | --------- | ------------------------- |- * | LOW / HIGH      | m4a (AAC) | application/vnd.tidal.bts |- * | LOSSLESS        | flac      | application/vnd.tidal.bts |- * | HI_RES_LOSSLESS | m4a       | application/dash+xml      |- *- * The BTS shape is a small JSON blob with the URLs already listed; DASH is an MPD whose- * segment template has to be expanded into one URL per segment.- *- * A manifest whose `encryptionType` is anything other than `NONE` is rejected: the app has- * no key to decrypt it, so the bytes would be unplayable, and writing them into the user's- * music folder is worse than failing the download.- */-object TidalManifest {--    private val DOLBY_CODECS = setOf("eac3", "ac4")-    private val json = Json { ignoreUnknownKeys = true; isLenient = true }--    /**-     * @param audioQuality the quality Tidal actually served (its own value, e.g. `LOSSLESS`),-     *   which decides whether a FLAC-codec hi-res stream is filed as `.flac` or `.m4a`.-     * @throws IllegalArgumentException on an encrypted or unrecognised manifest.-     */-    fun decode(manifestMimeType: String, manifestBase64: String, audioQuality: String): TidalStream {-        val decoded = String(Base64.getDecoder().decode(manifestBase64), Charsets.UTF_8)-        return when (manifestMimeType) {-            "application/vnd.tidal.bts" -> decodeBts(decoded, audioQuality)-            "application/dash+xml" -> decodeDash(decoded, audioQuality)-            else -> throw IllegalArgumentException("Unknown Tidal manifest type: $manifestMimeType")-        }-    }--    private fun decodeBts(manifest: String, audioQuality: String): TidalStream {-        val root = json.parseToJsonElement(manifest) as JsonObject-        val encryption = (root["encryptionType"] as? kotlinx.serialization.json.JsonPrimitive)-            ?.contentOrNull-        if (encryption != null && encryption != "NONE") {-            throw IllegalArgumentException("Tidal stream is encrypted ($encryption)")-        }-        val codecs = (root["codecs"] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull.orEmpty()-        val urls = (root["urls"] as? JsonArray)-            ?.mapNotNull { it.jsonPrimitive.contentOrNull }-            .orEmpty()-        require(urls.isNotEmpty()) { "Tidal BTS manifest has no URLs" }-        return TidalStream(urls, suffixFor(codecs, audioQuality), mimeFor(codecs, audioQuality))-    }--    private fun decodeDash(manifest: String, audioQuality: String): TidalStream {-        val (codecs, urls) = parseMpd(manifest)-        require(urls.isNotEmpty()) { "Tidal DASH manifest has no segments" }-        return TidalStream(urls, suffixFor(codecs, audioQuality), mimeFor(codecs, audioQuality))-    }--    /**-     * Expands a Tidal MPD into segment URLs.-     *-     * Tidal's MPD has a single Representation with a SegmentTemplate: an initialization plus-     * a `media` URL containing `$Number$`, and a SegmentTimeline whose `S` elements each-     * describe one segment plus an optional `r` repeat count. The total is every `S` plus-     * its repeats, and `$Number$` runs `0..total` inclusive - the first index is the-     * initialization segment.-     */-    private fun parseMpd(xml: String): Pair<String, List<String>> {-        val doc = parseXml(xml) ?: throw IllegalArgumentException("Tidal DASH manifest is not XML")-        val codecs = mpdCodecs(doc)-        val mediaTemplate = mpdMediaTemplate(doc)-        val total = mpdSegmentCount(doc)-        val urls = (0..total).map { mediaTemplate.replace("\$Number\$", it.toString()) }-        return codecs to urls-    }--    private fun parseXml(xml: String): org.w3c.dom.Document? {-        val factory = DocumentBuilderFactory.newInstance().apply {-            isNamespaceAware = false-        }-        return runCatching {-            factory.newDocumentBuilder().parse(InputSource(StringReader(xml)))-        }.getOrNull()-    }--    private fun mpdCodecs(doc: org.w3c.dom.Document): String {-        val representation = doc.getElementsByTagName("Representation").item(0)-            ?: throw IllegalArgumentException("Tidal DASH manifest has no Representation")-        // Reject DRM the same way the BTS path rejects a non-NONE encryptionType: a protected-        // stream would download into an unplayable file, which is worse than failing.-        if (doc.getElementsByTagName("ContentProtection").length > 0) {-            throw IllegalArgumentException("Tidal DASH stream is protected")-        }-        return representation.attributes?.getNamedItem("codecs")?.nodeValue.orEmpty()-    }--    private fun mpdMediaTemplate(doc: org.w3c.dom.Document): String =-        doc.getElementsByTagName("SegmentTemplate").item(0)?.attributes-            ?.getNamedItem("media")?.nodeValue-            ?: throw IllegalArgumentException("Tidal DASH manifest has no SegmentTemplate")--    private fun mpdSegmentCount(doc: org.w3c.dom.Document): Int {-        val timeline = doc.getElementsByTagName("S")-        var total = 0-        for (i in 0 until timeline.length) {-            total += 1-            val repeat = timeline.item(i).attributes?.getNamedItem("r")?.nodeValue?.toIntOrNull()-            if (repeat != null) total += repeat-        }-        return total-    }--    private fun suffixFor(codecs: String, audioQuality: String): String = when {-        codecs.equals("flac", ignoreCase = true) ->-            if (audioQuality == "HI_RES_LOSSLESS") "m4a" else "flac"-        codecs.startsWith("mp4", ignoreCase = true) -> "m4a"-        codecs.lowercase() in DOLBY_CODECS -> "m4a"-        else -> throw IllegalArgumentException("Unknown Tidal codecs: $codecs")-    }--    private fun mimeFor(codecs: String, audioQuality: String): String =-        when (suffixFor(codecs, audioQuality)) {-            "flac" -> "audio/flac"-            else -> "audio/mp4"-        }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.ktdeleted file mode 100644index 383c689744..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/download/YouTubeAudioSource.kt+++ /dev/null@@ -1,146 +0,0 @@-package com.vayunmathur.musicbrainz.data.download--import com.vayunmathur.musicbrainz.platform.DownloadSource-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import org.schabi.newpipe.extractor.MediaFormat-import org.schabi.newpipe.extractor.ServiceList-import org.schabi.newpipe.extractor.stream.AudioStream-import org.schabi.newpipe.extractor.stream.DeliveryMethod-import org.schabi.newpipe.extractor.stream.StreamInfoItem-import kotlin.math.abs--/**- * Finds a downloadable audio stream on YouTube, via the extractor YouPipe already vendors.- *- * The source of last resort: it needs no account and carries almost everything, but a- * YouTube upload is a lossy re-encode of unknown provenance and matching a MusicBrainz- * recording to one is guesswork, so duration does most of the work in [rank].- *- * Only progressive streams are used. YouTube also serves audio over SABR, which needs a- * stateful session and the PO-token machinery that lives in the YouPipe app; a track that- * is SABR-only is reported as unavailable rather than dragging that whole stack in here.- */-object YouTubeAudioSource : AudioSource {--    override val id = DownloadSource.YouTube--    private const val SEARCH_RESULTS_CONSIDERED = 8--    // Two uploads within this many seconds are treated as an equal-length match, so YouTube's-    // own relevance order breaks the tie rather than an insignificantly closer runtime.-    internal const val MATCH_TOLERANCE_SECONDS = 3L--    // A candidate whose runtime differs from the catalogued length by more than this is taken-    // to be a different thing - a compilation, an extended mix, a sped-up edit - and dropped,-    // because synced lyrics timed to the real track would drift audibly against it.-    internal const val MAX_DURATION_DIFF_SECONDS = 15L--    override suspend fun resolve(query: AudioQuery): ResolvedAudio? = withContext(Dispatchers.IO) {-        val candidates = search(buildQuery(query.artist, query.title, query.album))-        if (candidates.isEmpty()) return@withContext null-        val ordered = rank(candidates, query.durationMs)-        for (candidate in ordered) {-            val audio = audioFor(candidate.url) ?: continue-            return@withContext audio.copy(sourceTitle = candidate.name)-        }-        null-    }--    private fun buildQuery(artist: String, title: String, album: String?): String = buildString {-        append(artist)-        append(" - ")-        append(title)-        if (!album.isNullOrBlank() && !title.contains(album, ignoreCase = true)) {-            append(' ')-            append(album)-        }-    }--    private fun search(query: String): List<StreamInfoItem> = try {-        val extractor = ServiceList.YouTube.getSearchExtractor(query)-        extractor.fetchPage()-        extractor.getInitialPage()-            .getItems()-            .filterIsInstance<StreamInfoItem>()-            .take(SEARCH_RESULTS_CONSIDERED)-    } catch (_: Exception) {-        emptyList()-    }--    /**-     * Orders candidates by how close their runtime is to the catalogued one, dropping any-     * that are too far off to be the same recording.-     *-     * Matches within a few seconds are treated as equally good and left in YouTube's own-     * relevance order, which is a better tie-breaker than an arbitrarily closer duration.-     * Candidates beyond [MAX_DURATION_DIFF_SECONDS] are rejected outright so a compilation or-     * a sped-up edit is never downloaded; only if nothing qualifies does the closest survive,-     * so an unusual track still downloads rather than failing.-     */-    private fun rank(candidates: List<StreamInfoItem>, durationMs: Int?): List<StreamInfoItem> {-        if (durationMs == null || durationMs <= 0) return candidates-        val target = durationMs / 1000L-        val scored = candidates.withIndex().map { (index, item) ->-            val duration = item.getDuration()-            val delta = if (duration > 0) abs(duration - target) else Long.MAX_VALUE-            Triple(item, delta, index)-        }-        val close = scored.filter { it.second <= MAX_DURATION_DIFF_SECONDS }-        return (if (close.isNotEmpty()) close else scored)-            .sortedWith(-                compareBy(-                    { if (it.second <= MATCH_TOLERANCE_SECONDS) 0L else it.second },-                    { it.third },-                ),-            )-            .map { it.first }-    }--    private fun audioFor(videoUrl: String): ResolvedAudio? = try {-        val extractor = ServiceList.YouTube.getStreamExtractor(videoUrl)-        extractor.fetchPage()-        val progressive = extractor.getAudioStreams().filter {-            it.getDeliveryMethod() == DeliveryMethod.PROGRESSIVE_HTTP &&-                it.isUrl() &&-                it.getContent().isNotBlank()-        }-        // Prefer the highest-bitrate Opus: YouTube's itag 251 Opus (~160 kbps) beats the-        // best progressive AAC (itag 140, 128 kbps), and it is already 48 kHz Opus, so-        // remuxing WebM to Ogg is a lossless stream copy where transcoding would not be.-        val opus = progressive.filter { it.isOpus() }.maxByOrNull { it.effectiveBitrate() }-        if (opus != null) {-            return ResolvedAudio(-                urls = listOf(opus.getContent()),-                suffix = "opus",-                mimeType = "audio/ogg",-                bitrate = opus.effectiveBitrate(),-                sourceTitle = "",-                source = id,-                isOpusPassthrough = true,-            )-        }-        // Fallback: no Opus stream, so keep the best available and let the transcode path-        // re-encode it to Opus like every other lossy-source download.-        val best = progressive.maxByOrNull { it.effectiveBitrate() }-        best?.let {-            val format = it.getFormat()-            ResolvedAudio(-                urls = listOf(it.getContent()),-                suffix = format?.getSuffix() ?: "m4a",-                mimeType = format?.mimeType ?: "audio/mp4",-                bitrate = it.effectiveBitrate(),-                sourceTitle = "",-                source = id,-            )-        }-    } catch (_: Exception) {-        null-    }--    private fun AudioStream.isOpus(): Boolean =-        getFormat() == MediaFormat.OPUS || getFormat() == MediaFormat.WEBMA_OPUS--    private fun AudioStream.effectiveBitrate(): Int =-        getAverageBitrate().takeIf { it > 0 } ?: getBitrate()-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryIndex.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryIndex.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryIndex.ktdeleted file mode 100644index 7091137f74..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryIndex.kt+++ /dev/null@@ -1,80 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import com.vayunmathur.musicbrainz.data.LocalTrack-import com.vayunmathur.musicbrainz.domain.library.MatchKeys-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.StateFlow-import kotlinx.coroutines.flow.asStateFlow--/**- * An immutable view of what the user already has, built from the scanned tags.- *- * Held as sets rather than queried per row because the browse screens ask about every- * track on a release as they draw it.- */-class LibrarySnapshot(-    private val recordingIds: Set<String> = emptySet(),-    private val releaseTrackIds: Set<String> = emptySet(),-    private val releaseIds: Set<String> = emptySet(),-    private val trackKeys: Set<String> = emptySet(),-    private val albumKeys: Set<String> = emptySet(),-    val trackCount: Int = 0,-) {-    /**-     * Whether a MusicBrainz track is already on device.-     *-     * The identifier checks come first and are exact. The text fallbacks exist because-     * music that was not tagged by Picard carries no MusicBrainz IDs at all, which is-     * most libraries - without them the app would report almost everything as missing.-     */-    fun hasTrack(-        recordingId: String?,-        releaseTrackId: String?,-        artist: String?,-        album: String?,-        title: String?,-    ): Boolean {-        if (releaseTrackId != null && releaseTrackId in releaseTrackIds) return true-        if (recordingId != null && recordingId in recordingIds) return true-        MatchKeys.trackKey(artist, title)?.let { if (it in trackKeys) return true }-        MatchKeys.albumKey(album, title)?.let { if (it in albumKeys) return true }-        return false-    }--    fun hasRelease(releaseId: String?): Boolean = releaseId != null && releaseId in releaseIds--    companion object {-        val Empty = LibrarySnapshot()--        fun from(tracks: List<LocalTrack>): LibrarySnapshot = LibrarySnapshot(-            recordingIds = tracks.mapNotNullTo(HashSet()) { it.recordingId },-            releaseTrackIds = tracks.mapNotNullTo(HashSet()) { it.releaseTrackId },-            releaseIds = tracks.mapNotNullTo(HashSet()) { it.releaseId },-            trackKeys = tracks.mapNotNullTo(HashSet()) { it.matchKey },-            albumKeys = tracks.mapNotNullTo(HashSet()) { it.albumKey },-            trackCount = tracks.size,-        )-    }-}--/**- * Process-wide holder for the scanned library.- *- * A singleton so the scan worker and the UI share one copy: the scan runs outside the- * ViewModel's lifetime and the browse screens need the result the moment it lands.- */-object LibraryIndex {-    private val _snapshot = MutableStateFlow(LibrarySnapshot.Empty)-    val snapshot: StateFlow<LibrarySnapshot> = _snapshot.asStateFlow()--    private val _scanning = MutableStateFlow(false)-    val scanning: StateFlow<Boolean> = _scanning.asStateFlow()--    fun publish(tracks: List<LocalTrack>) {-        _snapshot.value = LibrarySnapshot.from(tracks)-    }--    fun setScanning(value: Boolean) {-        _scanning.value = value-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryScanner.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryScanner.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryScanner.ktdeleted file mode 100644index eb44b076ff..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/LibraryScanner.kt+++ /dev/null@@ -1,99 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import android.content.Context-import androidx.core.net.toUri-import com.vayunmathur.musicbrainz.data.LocalTrack-import com.vayunmathur.musicbrainz.data.MusicBrainzRepository-import com.vayunmathur.musicbrainz.domain.library.MatchKeys-import com.vayunmathur.musicbrainz.platform.MusicBrainzPrefs-import com.vayunmathur.musicbrainz.platform.SafTree-import com.vayunmathur.musicbrainz.platform.DocEntry-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext--/**- * Walks the user's music folder and records what is in it.- *- * Deliberately tag-driven rather than a ledger of what this app downloaded: the point is- * to recognise music the user already had, however it got there.- *- * Files whose size and modification time are unchanged since the last scan are skipped- * without being reopened, which is what keeps a rescan of a large library cheap.- */-object LibraryScanner {--    suspend fun scan(context: Context): Int = withContext(Dispatchers.IO) {-        val treeUri = MusicBrainzPrefs(context).musicFolderUri() ?: return@withContext 0-        val repo = MusicBrainzRepository.get(context)--        LibraryIndex.setScanning(true)-        try {-            val known = repo.fingerprints().associateBy { it.documentUri }-            val files = ArrayList<DocEntry>()-            SafTree.walkFiles(context, treeUri.toUri()) { entry ->-                if (TagReader.isAudioFile(entry.name)) files.add(entry)-            }--            val seen = HashSet<String>(files.size)-            val updates = ArrayList<LocalTrack>()-            for (entry in files) {-                val key = entry.uri.toString()-                seen.add(key)-                val previous = known[key]-                if (previous != null &&-                    previous.size == entry.size &&-                    previous.lastModified == entry.lastModified-                ) {-                    continue-                }-                val tags = TagReader.read(context, entry.uri, entry.name)-                updates.add(-                    LocalTrack(-                        documentUri = key,-                        fileName = entry.name,-                        size = entry.size,-                        lastModified = entry.lastModified,-                        recordingId = tags.recordingId,-                        releaseId = tags.releaseId,-                        releaseTrackId = tags.releaseTrackId,-                        title = tags.title,-                        artist = tags.artist,-                        album = tags.album,-                        // Files with no usable tags still get a key from the filename, which-                        // is the only thing an untagged rip has to identify it.-                        matchKey = MatchKeys.trackKey(-                            tags.artist ?: tags.albumArtist,-                            tags.title ?: entry.name.substringBeforeLast('.'),-                        ),-                        albumKey = MatchKeys.albumKey(tags.album, tags.title),-                    ),-                )-                // Flushed in batches so an interrupted scan still leaves progress behind.-                if (updates.size >= BATCH_SIZE) {-                    repo.upsertAll(updates.toList())-                    updates.clear()-                }-            }--            if (updates.isNotEmpty()) repo.upsertAll(updates)--            val removed = known.keys - seen-            if (removed.isNotEmpty()) repo.deleteByUris(removed.toList())--            val all = repo.all()-            LibraryIndex.publish(all)-            all.size-        } finally {-            LibraryIndex.setScanning(false)-        }-    }--    /** Loads the last scan result so the browse screens have data before a rescan finishes. */-    suspend fun loadCached(context: Context) = withContext(Dispatchers.IO) {-        val repo = MusicBrainzRepository.get(context)-        LibraryIndex.publish(repo.all())-    }--    const val DB_NAME = "musicbrainz-db"-    private const val BATCH_SIZE = 200-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagCommon.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagCommon.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagCommon.ktdeleted file mode 100644index c193086c1e..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagCommon.kt+++ /dev/null@@ -1,104 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import java.io.InputStream-import java.nio.ByteBuffer-import java.nio.ByteOrder--internal const val MAX_MOOV_BYTES = 16 * 1024 * 1024-internal const val MAX_ID3_BYTES = 4 * 1024 * 1024--// Large enough to hold an Opus comment header that embeds cover art: the app writes the-// front cover into the `OpusTags` packet, and the identifying tags parsed here sit in-// that same packet, so the whole of it has to be scanned to read them back.-internal const val OGG_SCAN_BYTES = 1024 * 1024--internal const val BYTE_MASK = 0xff-internal const val SYNCHSAFE_MASK = 0x7f-internal const val FLAG_LAST_MASK = 0x80-internal const val BLOCK_TYPE_MASK = 0x7f-internal const val SHIFT_SHORT_HIGH = 16-internal const val SHIFT_BYTE_MID = 8-internal const val SHIFT_BYTE_HIGH = 24-internal const val SHIFT_SYNCH_3 = 21-internal const val SHIFT_SYNCH_2 = 14-internal const val SHIFT_SYNCH_1 = 7-internal const val INT_BYTES = 4-internal const val MAGIC_TEXT_LENGTH = 4-internal const val MP4_BOX_HEADER = 8-internal const val MP4_LARGE_HEADER = 16-internal const val MP4_LARGE_MARKER = 1L-internal const val MP4_SELF_MARKER = 0L-internal const val MP4_MIN_BOX = 8L-internal const val UINT_MASK = 0xffffffffL-internal const val META_FULL_BOX_SKIP = 12-internal const val OGG_PAGE_HEADER_MIN = 27-internal const val OGG_SEGMENT_COUNT_OFFSET = 26-internal const val OGG_SEGMENT_TERMINATOR = 255-internal const val ID3_HEADER_LENGTH = 10-internal const val ID3_TAG_OFFSET = 6-internal const val ID3_MAGIC_LENGTH = 3-internal const val ID3_FRAME_HEADER = 10-internal const val ID3_MIN_MAJOR = 3-internal const val ID3_V24_MAJOR = 4-internal const val FLAC_BLOCK_HEADER = 4-internal const val FLAC_COMMENT_BLOCK = 4-internal const val VORBIS_COMMENT_LIMIT = 10_000-internal const val OPUS_TAGS_LENGTH = 8-internal const val OPUS_TAGS_SKIP = 8-internal const val VORBIS_MAGIC_LENGTH = 7-internal const val VORBIS_MAGIC_OFFSET = 1-internal const val VORBIS_MAGIC_TEXT_LENGTH = 6-internal const val DATA_BOX_HEADER_SKIP = 16-internal const val NAME_BOX_HEADER_SKIP = 12-internal const val COMMENT_PACKET_INDEX = 1-internal const val ID3_TEXT_MIN = 2-internal const val SHORT_HIGH_INDEX = 1-internal const val SHORT_MID_HIGH_INDEX = 2-internal const val SHORT_LOW_INDEX = 3-internal const val ID3_MAJOR_INDEX = 3--internal const val FRAME_TITLE = "TIT2"-internal const val FRAME_ARTIST = "TPE1"-internal const val FRAME_ALBUM = "TALB"-internal const val FRAME_ALBUM_ARTIST = "TPE2"-internal const val FRAME_USER_TEXT = "TXXX"-internal const val FRAME_UNIQUE_ID = "UFID"-internal const val MB_OWNER_MARKER = "musicbrainz.org"--internal val AUDIO_EXTENSIONS = setOf(-    "mp3", "m4a", "m4b", "mp4", "aac", "flac", "ogg", "oga", "opus", "wav", "wma",-)--internal val TEXT_FRAME_IDS = setOf(FRAME_TITLE, FRAME_ARTIST, FRAME_ALBUM, FRAME_ALBUM_ARTIST)--internal fun readInt(buf: ByteArray, offset: Int): Int =-    ((buf[offset].toInt() and BYTE_MASK) shl SHIFT_BYTE_HIGH) or-        ((buf[offset + SHORT_HIGH_INDEX].toInt() and BYTE_MASK) shl SHIFT_SHORT_HIGH) or-        ((buf[offset + SHORT_MID_HIGH_INDEX].toInt() and BYTE_MASK) shl SHIFT_BYTE_MID) or-        (buf[offset + SHORT_LOW_INDEX].toInt() and BYTE_MASK)--internal fun readIntLe(buf: ByteArray, offset: Int): Int =-    ByteBuffer.wrap(buf, offset, INT_BYTES).order(ByteOrder.LITTLE_ENDIAN).int--/** ID3 sizes drop the high bit of each byte so they can never look like a frame sync. */-internal fun synchsafe(buf: ByteArray, offset: Int): Int =-    ((buf[offset].toInt() and SYNCHSAFE_MASK) shl SHIFT_SYNCH_3) or-        ((buf[offset + SHORT_HIGH_INDEX].toInt() and SYNCHSAFE_MASK) shl SHIFT_SYNCH_2) or-        ((buf[offset + SHORT_MID_HIGH_INDEX].toInt() and SYNCHSAFE_MASK) shl SHIFT_SYNCH_1) or-        (buf[offset + SHORT_LOW_INDEX].toInt() and SYNCHSAFE_MASK)--internal fun ByteArray.indexOfZero(from: Int, to: Int): Int {-    for (i in from until minOf(to, size)) if (this[i].toInt() == 0) return i-    return -1-}--internal fun InputStream.readNBytesCompat(count: Int): ByteArray {-    val out = ByteArray(count)-    var read = 0-    while (read < count) {-        val n = read(out, read, count - read)-        if (n < 0) break-        read += n-    }-    return if (read == count) out else out.copyOf(read)-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagId3.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagId3.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagId3.ktdeleted file mode 100644index 9b15e8eb25..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagId3.kt+++ /dev/null@@ -1,168 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import java.io.InputStream--internal object TagId3 {--    fun readId3(input: InputStream): AudioTags {-        val body = readId3Body(input) ?: return AudioTags()-        return collectId3Frames(body)-    }--    private fun collectId3Frames(body: Id3Body): AudioTags {-        val values = HashMap<String, String>()-        val frames = collectFrames(body)-        val recordingId = frames.ufid-        for (frame in frames.text) consumeFrame(body.bytes, frame, values)-        return AudioTags(-            title = values[FRAME_TITLE],-            artist = values[FRAME_ARTIST],-            album = values[FRAME_ALBUM],-            albumArtist = values[FRAME_ALBUM_ARTIST],-            recordingId = recordingId ?: values["MusicBrainz Track Id"],-            releaseId = values["MusicBrainz Album Id"],-            releaseTrackId = values["MusicBrainz Release Track Id"],-        )-    }--    private class CollectedFrames(val text: List<FrameRange>, val ufid: String?)--    private fun collectFrames(body: Id3Body): CollectedFrames {-        val text = ArrayList<FrameRange>()-        var recordingId: String? = null-        var offset = 0-        val bytes = body.bytes-        while (offset + ID3_FRAME_HEADER <= bytes.size) {-            val frame = readFrameHeader(bytes, offset, body.major)-            if (frame == null || frame.isPadding) break-            if (frame.id == FRAME_UNIQUE_ID) {-                recordingId = readUfid(bytes, frame) ?: recordingId-            } else {-                text.add(frame)-            }-            offset = frame.frameEnd-        }-        return CollectedFrames(text, recordingId)-    }--    private class Id3Body(val bytes: ByteArray, val major: Int)--    private class FrameRange(-        val id: String,-        val frameStart: Int,-        val frameSize: Int,-        val frameEnd: Int,-        val isPadding: Boolean,-    )--    private fun readId3Body(input: InputStream): Id3Body? {-        val header = input.readNBytesCompat(ID3_HEADER_LENGTH)-        if (header.size < ID3_HEADER_LENGTH) return null-        if (String(header, 0, ID3_MAGIC_LENGTH, Charsets.ISO_8859_1) != "ID3") return null-        val major = header[ID3_MAJOR_INDEX].toInt() and BYTE_MASK-        if (major < ID3_MIN_MAJOR) return null-        val tagSize = synchsafe(header, ID3_TAG_OFFSET)-        if (tagSize <= 0 || tagSize > MAX_ID3_BYTES) return null-        return Id3Body(input.readNBytesCompat(tagSize), major)-    }--    private fun readFrameHeader(body: ByteArray, offset: Int, major: Int): FrameRange? {-        val id = String(body, offset, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1)-        if (id[0] == '\u0000') return FrameRange(id, 0, 0, 0, true)-        // v2.4 made frame sizes synchsafe; v2.3 left them as plain big-endian ints.-        val frameSize = if (major >= ID3_V24_MAJOR) {-            synchsafe(body, offset + INT_BYTES)-        } else {-            readInt(body, offset + INT_BYTES)-        }-        if (frameSize <= 0 || offset + ID3_FRAME_HEADER + frameSize > body.size) return null-        val frameStart = offset + ID3_FRAME_HEADER-        return FrameRange(id, frameStart, frameSize, frameStart + frameSize, false)-    }--    private fun consumeFrame(-        body: ByteArray,-        frame: FrameRange,-        values: HashMap<String, String>,-    ) {-        if (frame.id in TEXT_FRAME_IDS) {-            decodeTextFrame(body, frame.frameStart, frame.frameSize)?.let {-                values[frame.id] = it-            }-            return-        }-        if (frame.id == FRAME_USER_TEXT) {-            decodeUserTextFrame(body, frame.frameStart, frame.frameSize)-                ?.let { (key, value) -> values[key] = value }-        }-    }--    private fun readUfid(body: ByteArray, frame: FrameRange): String? {-        if (frame.id != FRAME_UNIQUE_ID) return null-        val ownerEnd = body.indexOfZero(frame.frameStart, frame.frameStart + frame.frameSize)-        if (ownerEnd <= 0) return null-        val owner = String(body, frame.frameStart, ownerEnd - frame.frameStart, Charsets.ISO_8859_1)-        if (!owner.contains(MB_OWNER_MARKER)) return null-        return String(-            body,-            ownerEnd + 1,-            frame.frameStart + frame.frameSize - ownerEnd - 1,-            Charsets.ISO_8859_1,-        ).trim().ifEmpty { null }-    }--    private fun decodeTextFrame(buf: ByteArray, start: Int, size: Int): String? {-        if (size < ID3_TEXT_MIN) return null-        return decodeString(buf, start + 1, start + size, buf[start].toInt() and BYTE_MASK)-            .trimEnd('\u0000')-            .trim()-            .ifEmpty { null }-    }--    /** `TXXX` is a description and a value, both in the frame's declared encoding. */-    private fun decodeUserTextFrame(buf: ByteArray, start: Int, size: Int): Pair<String, String>? {-        if (size < ID3_TEXT_MIN) return null-        val encoding = buf[start].toInt() and BYTE_MASK-        val end = start + size-        val separator = findTextSeparator(buf, start + 1, end, encoding) ?: return null-        val description = decodeString(buf, start + 1, separator, encoding).trim()-        val valueStart = separator + separatorWidth(encoding)-        val value = decodeString(buf, valueStart, end, encoding).trimEnd('\u0000').trim()-        if (description.isEmpty() || value.isEmpty()) return null-        return description to value-    }--    private fun separatorWidth(encoding: Int): Int = if (isWideEncoding(encoding)) 2 else 1--    private fun isWideEncoding(encoding: Int): Boolean = encoding == 1 || encoding == 2--    private fun findTextSeparator(buf: ByteArray, from: Int, end: Int, encoding: Int): Int? {-        var scan = from-        while (scan < end) {-            if (isWideEncoding(encoding)) {-                if (isWideZero(buf, scan, end)) return scan-                scan += 2-            } else {-                if (buf[scan].toInt() == 0) return scan-                scan++-            }-        }-        return null-    }--    private fun isWideZero(buf: ByteArray, scan: Int, end: Int): Boolean =-        scan + 1 < end && buf[scan].toInt() == 0 && buf[scan + 1].toInt() == 0--    private fun decodeString(buf: ByteArray, start: Int, end: Int, encoding: Int): String {-        if (start >= end) return ""-        val charset = when (encoding) {-            1 -> Charsets.UTF_16-            2 -> Charsets.UTF_16BE-            3 -> Charsets.UTF_8-            else -> Charsets.ISO_8859_1-        }-        return String(buf, start, end - start, charset)-    }--}-
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagMp4.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagMp4.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagMp4.ktdeleted file mode 100644index 98f13d0a7c..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagMp4.kt+++ /dev/null@@ -1,214 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import java.nio.ByteBuffer-import java.nio.channels.FileChannel--internal object TagMp4 {--    /**-     * Pulls `moov` out of the file and parses its `udta.meta.ilst` in memory.-     *-     * `moov` is walked box by box from the channel rather than read wholesale because it-     * sits after the audio data in files that were never prepared for streaming, and in-     * an album-length track that means skipping tens of megabytes to reach it.-     */-    fun readMp4(channel: FileChannel): AudioTags {-        val moov = findMoov(channel) ?: return AudioTags()-        return parseIlst(findIlst(moov) ?: return AudioTags())-    }--    private fun findMoov(channel: FileChannel): ByteArray? {-        val size = channel.size()-        var position = 0L-        while (position < size) {-            val header = readBoxHeader(channel, position, size) ?: break-            if (header.type == "moov") return readBoxPayload(channel, header)-            position = header.end-        }-        return null-    }--    private fun readBoxPayload(channel: FileChannel, header: BoxHeader): ByteArray? {-        val payloadSize = header.end - header.contentStart-        if (payloadSize <= 0 || payloadSize > MAX_MOOV_BYTES) return null-        val buffer = ByteBuffer.allocate(payloadSize.toInt())-        channel.position(header.contentStart)-        while (buffer.hasRemaining()) {-            if (channel.read(buffer) < 0) return null-        }-        return buffer.array()-    }--    private class BoxHeader(val type: String, val contentStart: Long, val end: Long)--    private fun readBoxHeader(channel: FileChannel, position: Long, fileSize: Long): BoxHeader? {-        if (position + MP4_BOX_HEADER > fileSize) return null-        val head = ByteBuffer.allocate(MP4_BOX_HEADER)-        channel.position(position)-        while (head.hasRemaining()) {-            if (channel.read(head) < 0) return null-        }-        head.flip()-        val declared = head.int.toLong() and UINT_MASK-        val type = String(ByteArray(MAGIC_TEXT_LENGTH) { head.get() }, Charsets.ISO_8859_1)-        val end = boxEnd(channel, position, fileSize, declared) ?: return null-        return BoxHeader(type, position + MP4_BOX_HEADER, end)-    }--    private fun boxEnd(channel: FileChannel, position: Long, fileSize: Long, declared: Long): Long? {-        if (declared == MP4_LARGE_MARKER) return readLargeBoxEnd(channel, position, fileSize)-        if (declared == MP4_SELF_MARKER) return fileSize-        if (declared < MP4_MIN_BOX) return null-        return (position + declared).coerceAtMost(fileSize)-    }--    private fun readLargeBoxEnd(channel: FileChannel, position: Long, fileSize: Long): Long? {-        val ext = ByteBuffer.allocate(MP4_BOX_HEADER)-        channel.position(position + MP4_BOX_HEADER)-        while (ext.hasRemaining()) {-            if (channel.read(ext) < 0) return null-        }-        ext.flip()-        val large = ext.long-        if (large < MP4_LARGE_HEADER) return null-        return (position + large).coerceAtMost(fileSize)-    }--    /**-     * Locates the `ilst` payload inside a `moov` blob.-     *-     * `meta` is a full box, so its four version/flags bytes have to be stepped over before-     * its children start - treating it like a plain container is the usual reason a tag-     * parser sees nothing here.-     */-    private fun findIlst(moov: ByteArray): ByteArray? =-        descendBoxes(moov, 0, moov.size, listOf("udta", "meta", "ilst"))--    private fun descendBoxes(buf: ByteArray, start: Int, end: Int, path: List<String>): ByteArray? {-        var offset = start-        while (offset + MP4_BOX_HEADER <= end) {-            val size = readInt(buf, offset)-            val type = String(buf, offset + INT_BYTES, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1)-            val boxEnd = if (size == 0) end else offset + size-            if (size < MP4_BOX_HEADER || boxEnd > end) return null-            matchBoxLevel(buf, offset, boxEnd, type, path)?.let { return it }-            offset = boxEnd-        }-        return null-    }--    private fun matchBoxLevel(-        buf: ByteArray,-        offset: Int,-        boxEnd: Int,-        type: String,-        path: List<String>,-    ): ByteArray? {-        if (type != path.first()) return null-        val contentStart = if (type == "meta") {-            offset + META_FULL_BOX_SKIP-        } else {-            offset + MP4_BOX_HEADER-        }-        if (path.size == 1) {-            return buf.copyOfRange(contentStart.coerceAtMost(boxEnd), boxEnd)-        }-        return descendBoxes(buf, contentStart, boxEnd, path.drop(1))-    }--    private fun parseIlst(ilst: ByteArray): AudioTags {-        val values = HashMap<String, String>()-        var offset = 0-        while (offset + MP4_BOX_HEADER <= ilst.size) {-            val size = readInt(ilst, offset)-            if (size < MP4_BOX_HEADER || offset + size > ilst.size) break-            val type = String(ilst, offset + INT_BYTES, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1)-            val entryEnd = offset + size-            collectIlstEntry(ilst, offset, entryEnd, type, values)-            offset = entryEnd-        }-        return AudioTags(-            title = values["\u00A9nam"],-            artist = values["\u00A9ART"],-            album = values["\u00A9alb"],-            albumArtist = values["aART"],-            recordingId = values["MusicBrainz Track Id"],-            releaseId = values["MusicBrainz Album Id"],-            releaseTrackId = values["MusicBrainz Release Track Id"],-        )-    }--    private fun collectIlstEntry(-        ilst: ByteArray,-        offset: Int,-        entryEnd: Int,-        type: String,-        values: HashMap<String, String>,-    ) {-        if (type == "----") {-            parseFreeform(ilst, offset + MP4_BOX_HEADER, entryEnd)?.let { (key, value) ->-                values[key] = value-            }-        } else {-            dataPayload(ilst, offset + MP4_BOX_HEADER, entryEnd)?.let { values[type] = it }-        }-    }--    /** Reads the `mean`/`name`/`data` triplet an iTunes-style custom tag is made of. */-    private fun parseFreeform(buf: ByteArray, start: Int, end: Int): Pair<String, String>? {-        var offset = start-        var name: String? = null-        var value: String? = null-        while (offset + MP4_BOX_HEADER <= end) {-            val size = readInt(buf, offset)-            if (size < MP4_BOX_HEADER || offset + size > end) break-            val type = String(buf, offset + INT_BYTES, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1)-            if (type == "name") name = freeformName(buf, offset, size)-            if (type == "data") value = freeformValue(buf, offset, size)-            offset += size-        }-        val key = name ?: return null-        val v = value ?: return null-        return key to v-    }--    private fun freeformName(buf: ByteArray, offset: Int, size: Int): String? {-        if (offset + NAME_BOX_HEADER_SKIP > offset + size) return null-        return String(buf, offset + NAME_BOX_HEADER_SKIP, size - NAME_BOX_HEADER_SKIP, Charsets.UTF_8)-    }--    private fun freeformValue(buf: ByteArray, offset: Int, size: Int): String? {-        if (offset + DATA_BOX_HEADER_SKIP > offset + size) return null-        return String(-            buf,-            offset + DATA_BOX_HEADER_SKIP,-            size - DATA_BOX_HEADER_SKIP,-            Charsets.UTF_8,-        )-    }--    private fun dataPayload(buf: ByteArray, start: Int, end: Int): String? {-        var offset = start-        while (offset + MP4_BOX_HEADER <= end) {-            val size = readInt(buf, offset)-            if (size < MP4_BOX_HEADER || offset + size > end) return null-            if (String(buf, offset + INT_BYTES, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1) == "data") {-                return dataText(buf, offset, size)-            }-            offset += size-        }-        return null-    }--    private fun dataText(buf: ByteArray, offset: Int, size: Int): String? {-        val payloadStart = offset + DATA_BOX_HEADER_SKIP-        val payloadEnd = offset + size-        if (payloadStart >= payloadEnd) return null-        return String(buf, payloadStart, payloadEnd - payloadStart, Charsets.UTF_8)-            .trim()-            .ifEmpty { null }-    }---}-
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagReader.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagReader.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagReader.ktdeleted file mode 100644index 678165faf4..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagReader.kt+++ /dev/null@@ -1,73 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import android.content.Context-import android.net.Uri-import java.io.FileInputStream--/** The tags the library index cares about. Every field is absent on files that lack it. */-data class AudioTags(-    val title: String? = null,-    val artist: String? = null,-    val album: String? = null,-    val albumArtist: String? = null,-    val recordingId: String? = null,-    val releaseId: String? = null,-    val releaseTrackId: String? = null,-) {-    val isEmpty: Boolean-        get() = title == null && artist == null && album == null &&-            recordingId == null && releaseId == null-}--/**- * Reads identifying tags out of audio files, so the app can tell what the user already- * owns without keeping its own download ledger.- *- * There is no tag library in the repo and adding one would pull in a large third-party- * dependency for what amounts to four container formats, so the parsers live alongside:- * MP4 in [TagMp4], ID3 in [TagId3], Vorbis/FLAC/Ogg in [TagVorbis], shared bits in- * [TagCommon]. Each one reads only the metadata region and stops - a library scan touches- * every file, and reading whole albums of audio to find a title would make it unusable.- *- * MusicBrainz IDs are the reliable signal but only Picard-tagged files carry them, so- * plain title/artist/album are read too and the matching falls back to those.- */-object TagReader {--    fun isAudioFile(name: String): Boolean =-        name.substringAfterLast('.', "").lowercase() in AUDIO_EXTENSIONS--    /** Returns whatever could be read; a malformed or unsupported file yields empty tags. */-    fun read(context: Context, uri: Uri, fileName: String): AudioTags = try {-        readUnsafe(context, uri, fileName)-    } catch (_: IllegalArgumentException) {-        AudioTags()-    } catch (_: IllegalStateException) {-        AudioTags()-    } catch (_: SecurityException) {-        AudioTags()-    }--    internal fun readId3(input: java.io.InputStream): AudioTags = TagId3.readId3(input)--    internal fun readMp4(channel: java.nio.channels.FileChannel): AudioTags = TagMp4.readMp4(channel)--    internal fun readFlac(input: java.io.InputStream): AudioTags = TagVorbis.readFlac(input)--    internal fun readOgg(input: java.io.InputStream): AudioTags = TagVorbis.readOgg(input)--    private fun readUnsafe(context: Context, uri: Uri, fileName: String): AudioTags {-        context.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->-            FileInputStream(pfd.fileDescriptor).use { input ->-                return when (fileName.substringAfterLast('.', "").lowercase()) {-                    "mp3", "aac" -> readId3(input)-                    "m4a", "m4b", "mp4" -> readMp4(input.channel)-                    "flac" -> readFlac(input)-                    "ogg", "oga", "opus" -> readOgg(input)-                    else -> AudioTags()-                }-            }-        }-        return AudioTags()-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagVorbis.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagVorbis.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagVorbis.ktdeleted file mode 100644index 60ac28ac0d..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/library/TagVorbis.kt+++ /dev/null@@ -1,160 +0,0 @@-package com.vayunmathur.musicbrainz.data.library--import java.io.InputStream--internal object TagVorbis {--    fun readFlac(input: InputStream): AudioTags {-        val magic = input.readNBytesCompat(MAGIC_TEXT_LENGTH)-        if (magic.size < MAGIC_TEXT_LENGTH || String(magic, Charsets.ISO_8859_1) != "fLaC") {-            return AudioTags()-        }-        while (true) {-            val block = nextFlacBlock(input) ?: return AudioTags()-            if (block.isComment) return parseVorbisComments(block.payload, 0)-            if (block.isLast) return AudioTags()-        }-    }--    private class FlacBlock(val isLast: Boolean, val isComment: Boolean, val payload: ByteArray)--    private fun nextFlacBlock(input: InputStream): FlacBlock? {-        val header = input.readNBytesCompat(FLAC_BLOCK_HEADER)-        if (header.size < FLAC_BLOCK_HEADER) return null-        val flags = header[0].toInt() and BYTE_MASK-        val isLast = flags and FLAG_LAST_MASK != 0-        val blockType = flags and BLOCK_TYPE_MASK-        val length = ((header[1].toInt() and BYTE_MASK) shl SHIFT_SHORT_HIGH) or-            ((header[SHORT_MID_HIGH_INDEX].toInt() and BYTE_MASK) shl SHIFT_BYTE_MID) or-            (header[SHORT_LOW_INDEX].toInt() and BYTE_MASK)-        if (length < 0 || length > MAX_ID3_BYTES) return null-        val block = input.readNBytesCompat(length)-        if (block.size < length) return null-        return FlacBlock(isLast, blockType == FLAC_COMMENT_BLOCK, block)-    }--    /**-     * Ogg keeps its comment header in the second packet, so the pages are reassembled-     * until that packet is complete. Only the head of the file is scanned - if the-     * comments are not there the file is not one we can read anyway.-     */-    fun readOgg(input: InputStream): AudioTags {-        val data = input.readNBytesCompat(OGG_SCAN_BYTES)-        var offset = 0-        var packetIndex = 0-        val packet = java.io.ByteArrayOutputStream()-        while (offset + OGG_PAGE_HEADER_MIN <= data.size) {-            val next = consumeOggPage(data, offset, packet) ?: break-            offset = next.first-            val completed = next.second-            if (completed != null) {-                if (packetIndex == COMMENT_PACKET_INDEX) return parseOggCommentPacket(completed)-                packetIndex++-            }-        }-        return AudioTags()-    }--    private fun consumeOggPage(-        data: ByteArray,-        offset: Int,-        packet: java.io.ByteArrayOutputStream,-    ): Pair<Int, ByteArray?>? {-        if (String(data, offset, MAGIC_TEXT_LENGTH, Charsets.ISO_8859_1) != "OggS") return null-        val segmentCount = data[offset + OGG_SEGMENT_COUNT_OFFSET].toInt() and BYTE_MASK-        val tableStart = offset + OGG_PAGE_HEADER_MIN-        if (tableStart + segmentCount > data.size) return null-        val payloadSize = oggPayloadSize(data, tableStart, segmentCount)-        val packetEnds = oggPacketEnds(data, tableStart, segmentCount)-        val payloadStart = tableStart + segmentCount-        if (payloadStart + payloadSize > data.size) return null-        packet.write(data, payloadStart, payloadSize)-        val completed = if (packetEnds) {-            val bytes = packet.toByteArray()-            packet.reset()-            bytes-        } else {-            null-        }-        return (payloadStart + payloadSize) to completed-    }--    private fun oggPayloadSize(data: ByteArray, tableStart: Int, segmentCount: Int): Int {-        var payloadSize = 0-        for (i in 0 until segmentCount) {-            payloadSize += data[tableStart + i].toInt() and BYTE_MASK-        }-        return payloadSize-    }--    private fun oggPacketEnds(data: ByteArray, tableStart: Int, segmentCount: Int): Boolean {-        for (i in 0 until segmentCount) {-            val segment = data[tableStart + i].toInt() and BYTE_MASK-            if (segment < OGG_SEGMENT_TERMINATOR) return true-        }-        return false-    }--    private fun parseOggCommentPacket(packet: ByteArray): AudioTags = when {-        packet.size > OPUS_TAGS_LENGTH &&-            String(packet, 0, OPUS_TAGS_LENGTH, Charsets.ISO_8859_1) == "OpusTags" ->-            parseVorbisComments(packet, OPUS_TAGS_SKIP)-        packet.size > VORBIS_MAGIC_LENGTH &&-            String(-                packet,-                VORBIS_MAGIC_OFFSET,-                VORBIS_MAGIC_TEXT_LENGTH,-                Charsets.ISO_8859_1,-            ) == "vorbis" ->-            parseVorbisComments(packet, VORBIS_MAGIC_LENGTH)-        else -> AudioTags()-    }--    private fun parseVorbisComments(buf: ByteArray, start: Int): AudioTags {-        val values = readVorbisValues(buf, start) ?: return AudioTags()-        return AudioTags(-            title = values["TITLE"],-            artist = values["ARTIST"],-            album = values["ALBUM"],-            albumArtist = values["ALBUMARTIST"],-            recordingId = values["MUSICBRAINZ_TRACKID"],-            releaseId = values["MUSICBRAINZ_ALBUMID"],-            releaseTrackId = values["MUSICBRAINZ_RELEASETRACKID"],-        )-    }--    private fun readVorbisValues(buf: ByteArray, start: Int): Map<String, String>? {-        var offset = start-        if (offset + INT_BYTES > buf.size) return null-        val vendorLength = readIntLe(buf, offset)-        offset += INT_BYTES + vendorLength-        if (offset + INT_BYTES > buf.size || vendorLength < 0) return null-        val count = readIntLe(buf, offset)-        offset += INT_BYTES-        if (count < 0 || count > VORBIS_COMMENT_LIMIT) return null-        val values = HashMap<String, String>()-        repeat(count) {-            val entry = readVorbisEntry(buf, offset) ?: return null-            offset = entry.second-            collectVorbisEntry(entry.first, values)-        }-        return values-    }--    private fun readVorbisEntry(buf: ByteArray, offset: Int): Pair<String, Int>? {-        if (offset + INT_BYTES > buf.size) return null-        val length = readIntLe(buf, offset)-        val start = offset + INT_BYTES-        if (length < 0 || start + length > buf.size) return null-        val entry = String(buf, start, length, Charsets.UTF_8)-        return entry to (start + length)-    }--    private fun collectVorbisEntry(entry: String, values: HashMap<String, String>) {-        val separator = entry.indexOf('=')-        if (separator <= 0) return-        values[entry.substring(0, separator).uppercase()] = entry.substring(separator + 1)-    }--}-
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.ktdeleted file mode 100644index 89978c04fd..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalAuth.kt+++ /dev/null@@ -1,215 +0,0 @@-package com.vayunmathur.musicbrainz.data.tidal--import com.vayunmathur.library.network.NetworkClient-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.longOrNull-import java.net.URLEncoder-import java.util.Base64--/** The tokens a successful sign-in yields, plus who they belong to. */-data class TidalTokens(-    val accessToken: String,-    val refreshToken: String?,-    val expiresAtMs: Long,-    val userId: String,-    val countryCode: String,-    val username: String,-)--/** The device code and where to enter it, from the start of the sign-in. */-data class TidalDeviceCode(-    val deviceCode: String,-    val userCode: String,-    val verificationUri: String,-    val intervalSeconds: Int,-    val expiresInSeconds: Int,-)--/** One poll's outcome while the user completes sign-in on another device. */-sealed interface TidalPollResult {-    /** The user has not finished yet; keep polling. */-    data object Pending : TidalPollResult--    /** The device code's lifetime ran out before the user finished. */-    data object Expired : TidalPollResult--    /** Poll interval was too short; back off before the next poll. */-    data object SlowDown : TidalPollResult--    data class Success(val tokens: TidalTokens) : TidalPollResult--    data class Error(val message: String) : TidalPollResult-}--/**- * Tidal OAuth 2.0 device authorization grant.- *- * Chosen over the redirect/PKCE flow the email app uses because it needs no intent-filter- * or redirect activity: the user enters a short code at [TidalDeviceCode.verificationUri]- * and this polls for the token. Ported from tiddl's `core/auth`, including its well-known- * client credentials - Tidal has no public app registration, so every open client uses- * the same pair, stored base64-encoded the way tiddl does.- *- * [NetworkClient.callJson] throws on any non-2xx, but `authorization_pending` - the normal- * idle response of a device-code poll - comes back as HTTP 400, so this uses- * [NetworkClient.performRequest] and reads the JSON body by hand instead.- */-object TidalAuth {--    private const val AUTH_URL = "https://auth.tidal.com/v1/oauth2"-    private const val LOGOUT_URL = "https://api.tidal.com/v1/logout"-    private const val SCOPE = "r_usr+w_usr+w_sub"-    private const val DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"--    // client_id;client_secret, base64-encoded exactly as tiddl stores it.-    private const val CREDENTIALS =-        "NE4zbjZRMXg5NUxMNUs3cDtvS09YZkpXMzcxY1g2eGFaMFB5aGdHTkJkTkxsQlpkNEFLS1lvdWdNamlrPQ=="--    private val clientId: String-    private val clientSecret: String--    init {-        val pair = String(Base64.getDecoder().decode(CREDENTIALS), Charsets.UTF_8).split(";", limit = 2)-        clientId = pair[0]-        clientSecret = pair.getOrElse(1) { "" }-    }--    private const val DEFAULT_POLL_INTERVAL_SECONDS = 2-    private const val DEFAULT_CODE_LIFETIME_SECONDS = 300-    private const val MILLIS_PER_SECOND = 1000L--    private val json = Json { ignoreUnknownKeys = true; isLenient = true }--    private val formHeaders = mapOf(-        "Content-Type" to "application/x-www-form-urlencoded",-        "Accept" to "application/json",-    )--    private val basicAuthHeaders = formHeaders + mapOf(-        "Authorization" to "Basic " + Base64.getEncoder()-            .encodeToString("$clientId:$clientSecret".toByteArray(Charsets.UTF_8)),-    )--    /** Begins sign-in. Throws on a network or protocol failure. */-    suspend fun requestDeviceCode(): TidalDeviceCode {-        val body = form("client_id" to clientId, "scope" to SCOPE)-        val response = NetworkClient.performRequest(-            "$AUTH_URL/device_authorization",-            method = "POST",-            headers = formHeaders,-            body = body,-        )-        if (!response.isSuccess) {-            throw java.io.IOException("Tidal device auth failed: HTTP ${response.status}")-        }-        val root = json.parseToJsonElement(response.body).jsonObject()-        return TidalDeviceCode(-            deviceCode = root.string("deviceCode").orEmpty(),-            userCode = root.string("userCode").orEmpty(),-            verificationUri = root.string("verificationUriComplete")-                ?.let { if (it.startsWith("http")) it else "https://$it" }-                .orEmpty(),-            intervalSeconds = root.int("interval", DEFAULT_POLL_INTERVAL_SECONDS),-            expiresInSeconds = root.int("expiresIn", DEFAULT_CODE_LIFETIME_SECONDS),-        )-    }--    /** Polls once for the token belonging to [deviceCode]. */-    suspend fun poll(deviceCode: String): TidalPollResult {-        val body = form(-            "client_id" to clientId,-            "device_code" to deviceCode,-            "grant_type" to DEVICE_GRANT,-            "scope" to SCOPE,-        )-        // A network blip mid-sign-in must not end the flow: report it as pending so the-        // caller keeps polling until the device code's own deadline.-        val response = runCatching {-            NetworkClient.performRequest(-                "$AUTH_URL/token",-                method = "POST",-                headers = basicAuthHeaders,-                body = body,-            )-        }.getOrNull() ?: return TidalPollResult.Pending-        val root = runCatching { json.parseToJsonElement(response.body).jsonObject() }.getOrNull()-        if (response.isSuccess && root != null) {-            return TidalPollResult.Success(tokens(root))-        }-        return when (root?.string("error")) {-            "authorization_pending" -> TidalPollResult.Pending-            "slow_down" -> TidalPollResult.SlowDown-            "expired_token" -> TidalPollResult.Expired-            null -> TidalPollResult.Error("HTTP ${response.status}")-            else -> TidalPollResult.Error(-                root.string("error_description") ?: root.string("error").orEmpty(),-            )-        }-    }--    /** Exchanges a refresh token for a fresh access token, or null on failure. */-    suspend fun refresh(refreshToken: String): TidalTokens? {-        val body = form(-            "client_id" to clientId,-            "refresh_token" to refreshToken,-            "grant_type" to "refresh_token",-            "scope" to SCOPE,-        )-        val response = NetworkClient.performRequest(-            "$AUTH_URL/token",-            method = "POST",-            headers = basicAuthHeaders,-            body = body,-        )-        if (!response.isSuccess) return null-        val root = runCatching { json.parseToJsonElement(response.body).jsonObject() }.getOrNull()-            ?: return null-        // A refresh response carries no refresh_token of its own, so the caller keeps the old one.-        return tokens(root, fallbackRefresh = refreshToken)-    }--    /** Tells Tidal to drop the session. Best-effort; failures are ignored. */-    suspend fun logout(accessToken: String) {-        runCatching {-            NetworkClient.performRequest(-                LOGOUT_URL,-                method = "POST",-                headers = mapOf("Authorization" to "Bearer $accessToken"),-            )-        }-    }--    private fun tokens(root: JsonObject, fallbackRefresh: String? = null): TidalTokens {-        val user = (root["user"] as? JsonObject)-        val expiresIn = root.long("expires_in") ?: DEFAULT_TOKEN_LIFETIME_SECONDS-        return TidalTokens(-            accessToken = root.string("access_token").orEmpty(),-            refreshToken = root.string("refresh_token") ?: fallbackRefresh,-            expiresAtMs = System.currentTimeMillis() + expiresIn * MILLIS_PER_SECOND,-            userId = root.string("user_id") ?: user?.string("userId").orEmpty(),-            countryCode = user?.string("countryCode").orEmpty(),-            username = user?.string("username")-                ?: user?.string("email")-                ?: user?.string("nickname").orEmpty(),-        )-    }--    private fun form(vararg pairs: Pair<String, String>): String =-        pairs.joinToString("&") { (k, v) ->-            "${URLEncoder.encode(k, "UTF-8")}=${URLEncoder.encode(v, "UTF-8")}"-        }--    private fun kotlinx.serialization.json.JsonElement.jsonObject(): JsonObject = this as JsonObject--    private fun JsonObject.string(key: String): String? =-        (this[key] as? kotlinx.serialization.json.JsonPrimitive)?.contentOrNull--    private fun JsonObject.long(key: String): Long? =-        (this[key] as? kotlinx.serialization.json.JsonPrimitive)?.longOrNull--    private fun JsonObject.int(key: String, default: Int): Int = long(key)?.toInt() ?: default--    private const val DEFAULT_TOKEN_LIFETIME_SECONDS = 86_400L-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.ktdeleted file mode 100644index 8dbdde1ee8..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/data/tidal/TidalSession.kt+++ /dev/null@@ -1,44 +0,0 @@-package com.vayunmathur.musicbrainz.data.tidal--import android.content.Context-import com.vayunmathur.musicbrainz.platform.MusicBrainzPrefs-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLock--/**- * Hands out a valid Tidal access token, refreshing it when it is about to expire.- *- * An album downloads as one worker per track, all running at once, so without the [mutex]- * they would each notice the same near-expiry token and fire off a wave of refreshes. The- * lock funnels that to one: the losers re-read the token the winner just persisted.- */-class TidalSession(context: Context) {--    private val appContext = context.applicationContext-    private val prefs = MusicBrainzPrefs(appContext)--    /** A usable access token, or null when there is no session or the refresh failed. */-    suspend fun accessToken(): String? = mutex.withLock {-        val account = prefs.tidalAccount.first() ?: return null-        if (account.expiresAtMs > System.currentTimeMillis() + EXPIRY_MARGIN_MS &&-            account.accessToken.isNotBlank()-        ) {-            return account.accessToken-        }-        val refresh = account.refreshToken?.takeIf { it.isNotBlank() }-            ?: return account.accessToken.ifBlank { null }-        val refreshed = TidalAuth.refresh(refresh) ?: return account.accessToken.ifBlank { null }-        prefs.updateTidalTokens(refreshed.accessToken, refreshed.refreshToken, refreshed.expiresAtMs)-        refreshed.accessToken.ifBlank { null }-    }--    /** The account's country code, needed on nearly every Tidal API call. */-    suspend fun countryCode(): String? = prefs.tidalAccount.first()?.countryCode?.ifBlank { null }--    private companion object {-        // Refresh a little early so a token cannot expire mid-download.-        const val EXPIRY_MARGIN_MS = 60_000L-        val mutex = Mutex()-    }-}
musicbrainz/src/main/java/com/vayunmathur/musicbrainz/domain/library/MatchKeys.kt
diff --git a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/domain/library/MatchKeys.kt b/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/domain/library/MatchKeys.ktdeleted file mode 100644index 31f864e9f0..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/domain/library/MatchKeys.kt+++ /dev/null@@ -1,70 +0,0 @@-package com.vayunmathur.musicbrainz.domain.library--import java.text.Normalizer--/**- * Turns titles and artist names into comparison keys.- *- * Only files tagged by Picard carry MusicBrainz IDs, so most of a real library has to be- * matched on text. That means deciding which differences are the same recording and which- * are not: reissue noise like "Remastered" is dropped, while "Live", "Remix" and- * "Acoustic" are kept, because those genuinely are different recordings and folding them- * together would mark tracks as owned that the user does not have.- */-object MatchKeys {--    private val NOISE_QUALIFIERS = listOf(-        "remaster", "remastered", "remastered version", "deluxe", "deluxe edition",-        "bonus track", "bonus", "explicit", "clean", "album version", "single version",-        "original mix", "mono", "stereo", "digital remaster", "anniversary edition",-    )--    private val BRACKETED = Regex("[\\[(]([^\\[\\]()]*)[\\])]")-    /** Dropped outright rather than turned into a space, so "Don't" matches "Dont". */-    private val APOSTROPHES = Regex("['\u2019\u02BC\u055A`]")-    private val NON_ALPHANUMERIC = Regex("[^\\p{L}\\p{Nd} ]")-    private val WHITESPACE = Regex("\\s+")-    private val COMBINING_MARKS = Regex("\\p{Mn}+")--    /** Splits off collaborators so "A feat. B" and "A" compare equal. */-    private val ARTIST_SEPARATORS = Regex(-        "\\s+(?:feat\\.?|featuring|ft\\.?|with|vs\\.?|&|x|and)\\s+|,\\s*",-        RegexOption.IGNORE_CASE,-    )--    fun normalize(value: String?): String? {-        if (value.isNullOrBlank()) return null-        var text = value.lowercase()-        text = BRACKETED.replace(text) { match ->-            val inner = match.groupValues[1].trim()-            if (NOISE_QUALIFIERS.any { inner.contains(it) }) "" else " $inner "-        }-        text = Normalizer.normalize(text, Normalizer.Form.NFD)-        text = COMBINING_MARKS.replace(text, "")-        text = APOSTROPHES.replace(text, "")-        text = NON_ALPHANUMERIC.replace(text, " ")-        text = WHITESPACE.replace(text, " ").trim()-        for (qualifier in NOISE_QUALIFIERS) {-            if (text.endsWith(" $qualifier")) text = text.removeSuffix(" $qualifier").trim()-        }-        return text.ifEmpty { null }-    }--    /** The first credited artist, which is the part two taggings of a track agree on. */-    fun primaryArtist(artist: String?): String? {-        if (artist.isNullOrBlank()) return null-        return ARTIST_SEPARATORS.split(artist).firstOrNull { it.isNotBlank() }?.trim()-    }--    fun trackKey(artist: String?, title: String?): String? {-        val normalizedArtist = normalize(primaryArtist(artist)) ?: return null-        val normalizedTitle = normalize(title) ?: return null-        return "$normalizedArtist\u0000$normalizedTitle"-    }--    fun albumKey(album: String?, title: String?): String? {-        val normalizedAlbum = normalize(album) ?: return null-        val normalizedTitle = normalize(title) ?: return null-        return "$normalizedAlbum\u0000$normalizedTitle"-    }-}
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.ktdeleted file mode 100644index 1ff097c585..0000000000--- a/musicbrainz/src/main/java/com/vayunmathur/musicbrainz/network/api/MusicBrainzApi.kt+++ /dev/null@@ -1,163 +0,0 @@-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.URLEncoder--/**- * Client for the MusicBrainz WS/2 API.- *- * 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.- *- * That one request per second is a hard ceiling, so the app's job is to spend it well:- * deduplication and caching live above this object, in- * [com.vayunmathur.musicbrainz.domain.cache.ResponseCache].- */-object MusicBrainzApi {--    private const val BASE = "https://musicbrainz.org/ws/2"-    private const val HTTP_SUCCESS_MIN = 200-    private const val HTTP_SUCCESS_MAX = 299-    private const val ERROR_BODY_LIMIT = 500-    private const val USER_AGENT =-        "ModernAppsMusicBrainz/1.0 ( https://ma.vayunmathur.com/apps/musicbrainz )"--    /** A little over a second, so clock jitter cannot round two requests into one second. */-    internal 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",-    )--    /**-     * `coerceInputValues` makes an explicit `null` fall back to the declared default instead-     * of aborting the decode. Every field in the wire models has a default, but a default only-     * applies to a key that is ABSENT - a `null` on one of the non-nullable fields would-     * otherwise turn one unset value into a blank screen.-     *-     * WS/2 does emit `null` for absent values rather than omitting the key, so this is load-     * bearing rather than defensive. It can only turn a decode that would have thrown into one-     * that succeeds with the declared default, so it cannot change how a response that already-     * decodes is read.-     *-     * 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-    }--    /**-     * The failure for a non-2xx status, or null when the response is fine.-     *-     * Split out from [get] so `MusicBrainzApiErrorTest` can pin the mapping without a server.-     * WS/2 answers 503 when a client outruns the rate limit, which [gate] exists to prevent;-     * it is reported like any other failure because there is nothing extra for the user to do-     * about it.-     */-    internal fun failureFor(status: Int, body: String): IOException? =-        if (status in HTTP_SUCCESS_MIN..HTTP_SUCCESS_MAX) {-            null-        } else {-            IOException("HTTP $status: ${body.take(ERROR_BODY_LIMIT)}")-        }--    /**-     * How long to wait bef

Diff truncated.