diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..9a16fd0 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,64 @@ +name: Android release + +on: + push: + tags: ['v*'] + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + - uses: android-actions/setup-android@v3 + with: + packages: 'platform-tools platforms;android-35 build-tools;36.0.0' + - name: Test and assemble release + run: ./gradlew --no-daemon :app:testDebugUnitTest :app:assembleRelease + - name: Sign and verify APK + id: sign + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + run: bash ci/sign-release.sh + - uses: actions/upload-artifact@v3 + with: + name: furumi-android + path: ${{ steps.sign.outputs.apk }} + if-no-files-found: error + + publish: + needs: build + runs-on: ubuntu-latest + permissions: + contents: read + releases: write + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/download-artifact@v3 + with: + name: furumi-android + path: dist + - name: Install jq if missing + shell: bash + run: | + if ! command -v jq >/dev/null; then + elevate=() + if (( EUID != 0 )); then elevate=(sudo); fi + "${elevate[@]}" apt-get update + "${elevate[@]}" apt-get install -y --no-install-recommends jq + fi + - name: Attach signed APK to the Gitea release + shell: bash + env: + RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN || secrets.GITHUB_TOKEN }} + run: bash ci/publish-release.sh "dist/furumi-android-${GITHUB_REF_NAME#v}.apk" diff --git a/README.md b/README.md new file mode 100644 index 0000000..5aa830e --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# Furumi Android + +После успешной публикации версии 1.4 файл `furumi-android-1.4.apk` появится в разделе **Releases** репозитория на `gt.hexor.cy`. + +## Переход с 1.3 на 1.4 + +Ключ подписи версии 1.3 утерян. Версия 1.4 сохраняет идентификатор `cy.hexor.furumi` и использует новый сертификат. Для перехода скачайте APK версии 1.4, удалите приложение версии 1.3 и установите новый APK. Удаление сотрёт настройки входа и офлайн-загрузки на этом телефоне. Потребуется снова войти и скачать музыку. Начиная с 1.4, релизы с одним ключом можно устанавливать поверх предыдущей версии с сохранением данных. + +## Подпись релизов + +Перед первым выпуском с новым сертификатом один раз создайте постоянное хранилище PKCS12 вне репозитория. Следующие команды запускаются локально с установленным JDK. Введите стойкий пароль по запросу `keytool`. У единственного ключа и хранилища должен быть один пароль. + +```sh +umask 077 +mkdir -p "$HOME/.furumi-signing" +keytool -genkeypair -storetype PKCS12 \ + -keystore "$HOME/.furumi-signing/furumi-release.p12" \ + -alias furumi -keyalg RSA -keysize 3072 -validity 10000 +``` + +Сохраните резервную копию хранилища в зашифрованном виде, а пароль — в менеджере паролей. В Gitea на `gt.hexor.cy` откройте **Settings → Actions → Secrets** репозитория и добавьте два секрета. + +| Секрет | Значение | +| --- | --- | +| `ANDROID_KEYSTORE_BASE64` | Содержимое файла PKCS12, закодированное в Base64 | +| `ANDROID_KEYSTORE_PASSWORD` | Пароль хранилища и ключа | + +Для публикации токен задания Gitea Actions должен иметь право записи релизов в этом репозитории. С этим правом задание создаёт релиз и прикрепляет подписанный APK. + +## Выпуск версии + +1. В `gradle.properties` задайте `furumi.versionName` и увеличьте `furumi.versionCode` относительно предыдущего опубликованного APK. Для 1.4 это `1.4` и `4`. +2. Закоммитьте изменения и поставьте на релизный коммит тег `v`, например `v1.4`. Для запуска сборки отправьте тег в репозиторий с настроенными секретами Actions. +3. После успешной сборки скачайте подписанный `furumi-android-.apk` из **Releases** для этого тега. diff --git a/app/src/androidTest/java/cy/hexor/furumi/data/local/OfflineCatalogTest.kt b/app/src/androidTest/java/cy/hexor/furumi/data/local/OfflineCatalogTest.kt new file mode 100644 index 0000000..f88191e --- /dev/null +++ b/app/src/androidTest/java/cy/hexor/furumi/data/local/OfflineCatalogTest.kt @@ -0,0 +1,245 @@ +package cy.hexor.furumi.data.local + +import android.content.Context +import android.content.ContextWrapper +import android.database.sqlite.SQLiteDatabase +import android.net.Uri +import cy.hexor.furumi.data.remote.FederatedAudioResolver +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import okio.Buffer +import org.json.JSONObject +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import com.squareup.moshi.Moshi +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import cy.hexor.furumi.data.remote.model.OfflineManifestPlaylistResponse +import cy.hexor.furumi.data.remote.model.OfflineManifestTrackResponse +import cy.hexor.furumi.domain.model.ArtistCard +import cy.hexor.furumi.domain.model.ArtistRef +import cy.hexor.furumi.domain.model.AuthSession +import cy.hexor.furumi.domain.model.AuthTokens +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.domain.model.User +import java.io.File +import java.util.UUID +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class OfflineCatalogTest { + private val context = object : ContextWrapper(InstrumentationRegistry.getInstrumentation().targetContext) { + private val prefix = "catalog-test-${UUID.randomUUID()}" + override fun getApplicationContext(): Context = this + override fun getSharedPreferences(name: String, mode: Int) = baseContext.getSharedPreferences("$prefix-$name", mode) + override fun getFilesDir(): File = File(baseContext.cacheDir, prefix).apply { mkdirs() } + override fun getDatabasePath(name: String): File = File(filesDir, name) + } + private val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() + private var sessions = AuthSessionStorage(context, moshi) + private val artist = ArtistCard(3, "Artist", null, 1, 1) + private val track = TrackCard(10, "Song", 1, 1, 90, listOf(artist.name), + artistRefs = listOf(ArtistRef(artist.id, artist.name)), releaseId = 4, releaseTitle = "Release", + coverUrl = "https://music.invalid/cover", streamUrl = "https://music.invalid/audio", + metadataUpdatedAt = "v1") + private val manifest = OfflineManifestTrackResponse(track.id, "v1", track.streamUrl) + private val playlist = OfflineManifestPlaylistResponse(6, "Mix", trackIds = listOf(track.id)) + + private fun signIn(server: String = "https://music.invalid", user: Int = 8) { + sessions.saveSession(AuthSession(server, User(user, "User $user", "user"), AuthTokens("a", "r", expiresInSeconds = 3600))) + } + + private fun store() = OfflineLibraryStore(context, OfflineAccountScope(context, sessions), moshi) + + @Test + fun failedSnapshotsKeepPriorVersionPlaylistAndPersonalMembership() { + signIn() + val db = store() + db.publishCatalog(listOf(manifest), listOf(track), emptySet(), listOf(playlist), setOf(track.id), listOf(artist)) + val changed = listOf(manifest.copy(updatedAt = "v2")) + assertTrue(runCatching { + db.publishCatalog(changed, emptyList(), emptySet(), emptyList(), emptySet(), emptyList()) + }.isFailure) + // A constraint failure late in the transaction must also roll back its earlier writes. + assertTrue(runCatching { + db.publishCatalog(changed, listOf(track.copy(metadataUpdatedAt = "v2")), emptySet(), emptyList(), + emptySet(), listOf(artist, artist)) + }.isFailure) + assertEquals("v1", db.catalogVersions().getValue(track.id).updatedAt) + assertEquals(listOf(track.id), db.getPlaylistDetail(playlist.id)!!.tracks.map { it.id }) + assertEquals(setOf(track.id), db.getLikedTrackIds()) + assertEquals(listOf(artist), db.getArtists(1, 60, mine = true).items) + val other = track.copy(id = 20, artists = listOf("Other"), artistRefs = listOf(ArtistRef(7, "Other"))) + db.upsertTracks(listOf(other)) + assertEquals(2, db.getArtists(1, 1, mine = false).total.toInt()) + assertEquals("Other", db.getArtists(2, 1, mine = false).items.single().name) + assertEquals(1, db.getArtists(1, 1, mine = true).total.toInt()) + assertEquals(listOf(track.coverUrl), db.getPlaylists().single().coverUrls) + } + + @Test + fun changedMediaHashesInvalidateOnlyTheirOwnFileEvenWithUnchangedMetadata() { + signIn() + val db = store() + val first = manifest.copy(audioHash = "audio-1", coverHash = "cover-1") + fun publish(item: OfflineManifestTrackResponse) = db.publishCatalog( + listOf(item), listOf(track), emptySet(), listOf(playlist), emptySet(), emptyList() + ) + publish(first) + val file = File(context.filesDir, "saved").apply { writeText("old") } + db.markAudioCached(track.id, file.path, file.length()) + db.markCoverCached(track.id, file.path, file.length()) + val newCover = first.copy(coverHash = "cover-2") + assertTrue(!db.catalogVersions().getValue(track.id).matches(newCover)) + publish(newCover) + assertTrue(db.getTrack(track.id)!!.isAudioCached) + assertEquals(null, db.getTrack(track.id)!!.localCoverPath) + val newAudio = newCover.copy(audioHash = "audio-2") + assertTrue(!db.catalogVersions().getValue(track.id).matches(newAudio)) + publish(newAudio) + assertTrue(!db.getTrack(track.id)!!.isAudioCached) + db.upsertTracks(listOf(track.copy(audioHash = first.audioHash, coverHash = first.coverHash))) + assertTrue(db.catalogVersions().getValue(track.id).matches(newAudio)) + } + + @Test + fun scopedDatabaseAndMediaReturnOnlyForSameServerAndUser() { + signIn() + val scope = OfflineAccountScope(context, sessions) + val store = OfflineLibraryStore(context, scope, moshi) + val firstDirectory = scope.mediaDirectory + store.upsertTracks(listOf(track)) + store.enqueueOfflineDownloadTracks(listOf(track)) + signIn(user = 9) + assertNotEquals(firstDirectory, scope.mediaDirectory) + assertTrue(store.getTrack(track.id) == null && store.offlineDownloadQueueState().activeTrackIds.isEmpty()) + signIn(server = "https://elsewhere.invalid") + assertNotEquals(firstDirectory, scope.mediaDirectory) + assertTrue(store.getTrack(track.id) == null && store.offlineDownloadQueueState().activeTrackIds.isEmpty()) + signIn() + assertEquals(firstDirectory, scope.mediaDirectory) + assertEquals(track.title, store.getTrack(track.id)?.title) + assertEquals(setOf(track.id), store.offlineDownloadQueueState().activeTrackIds) + } + + @Test + fun progressIncludesCachedTracksAndRestoresAfterFailureAndRestart() { + signIn() + val db = store() + val fresh = track.copy(id = 11, title = "New track") + val failed = track.copy(id = 12, title = "Timed out track") + val members = listOf(track, fresh, failed) + db.upsertTracks(members) + val file = File(context.filesDir, "ready").apply { writeText("saved") } + db.markAudioCached(track.id, file.path, file.length()) + val queued = db.enqueueOfflineDownloadTracks(members) + assertEquals(members.map { it.id }.toSet(), queued.batchTrackIds) + assertEquals(setOf(track.id), queued.completedTrackIds) + db.markOfflineDownloadRunning(fresh.id) + assertEquals(fresh.id, store().offlineDownloadQueueState().runningTrackId) + db.markAudioCached(fresh.id, file.path, file.length()) + db.markOfflineDownloadCompleted(fresh.id) + db.markOfflineDownloadFailed(failed.id, "Audio: timeout") + + val restored = store() + val before = restored.offlineDownloadQueueState() + assertEquals(setOf(track.id, fresh.id), before.completedTrackIds) + assertEquals("Timed out track", before.trackTitles[failed.id]) + assertEquals("The server took too long to send the track. Retry later.", before.errors[failed.id]) + val retry = restored.enqueueOfflineDownloadTracks(listOf(failed)) + assertEquals(queued.batchTrackIds, retry.batchTrackIds) + assertEquals(before.completedTrackIds, retry.completedTrackIds) + assertEquals(setOf(failed.id), retry.activeTrackIds) + // A cover failure leaves the audio complete and exposes the next optional cover. + val cover = restored.nextOfflineDownloadCover()!! + restored.markOfflineCoverFailed(cover.id) + assertEquals(before.completedTrackIds, restored.offlineDownloadQueueState().completedTrackIds) + assertNotEquals(cover.id, restored.nextOfflineDownloadCover()?.id) + } + + @Test + fun remoteDownloadUsesExactJsonContentTypeAndRediscoversAnUnavailableSource() = runBlocking { + signIn() + val accounts = OfflineAccountScope(context, sessions) + val uri = Uri.Builder().scheme("furumi-fed").authority("track") + .appendQueryParameter("account", accounts.key) + .appendQueryParameter("content", "b3:test").appendQueryParameter("owner", "old-peer") + .appendQueryParameter("item", "old-item").build() + var requests = 0 + val client = OkHttpClient.Builder().addInterceptor { chain -> + requests++ + val request = chain.request() + val body = requireNotNull(request.body) + assertEquals("/api/player/federation/tracks/prepare", request.url.encodedPath) + assertEquals("application/json", body.contentType().toString()) + val data = JSONObject(Buffer().apply { body.writeTo(this) }.readUtf8()) + assertEquals("b3:test", data.getString("content_id")) + val event = if (requests == 1) { + assertEquals("old-peer", data.getString("owner")) + assertEquals("old-item", data.getString("item_id")) + """{"kind":"failed","error":"peer offline"}""" + } else { + assertTrue(!data.has("owner") && !data.has("item_id")) + """{"kind":"completed","stream_url":"/api/player/federation/cache/test"}""" + } + Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200).message("OK") + .body((event + "\n").toResponseBody()).build() + }.build() + val resolver = FederatedAudioResolver(sessions, accounts, OfflineFileDownloader(client)) + assertEquals("https://music.invalid/api/player/federation/cache/test", resolver.resolve(uri)) + assertEquals(2, requests) + } + + @Test + fun versionTwoUpgradeKeepsDownloadedAudioWithTheAccountSignedInAtUpgrade() { + signIn() + // Simulate the pre-scope app, which has a session but no ownership marker. + context.getSharedPreferences("offline_storage_migration", Context.MODE_PRIVATE).edit().clear().commit() + sessions = AuthSessionStorage(context, moshi) + val legacyAudio = File(context.filesDir, "offline/audio/10").apply { + parentFile!!.mkdirs() + writeBytes(byteArrayOf(1, 2, 3)) + } + SQLiteDatabase.openOrCreateDatabase(context.getDatabasePath("furumi_offline.db"), null).use { db -> + db.execSQL(""" + CREATE TABLE offline_tracks( + track_id INTEGER PRIMARY KEY, title TEXT, title_sort TEXT, artists_sort TEXT, + release_id INTEGER, release_title TEXT, release_year INTEGER, duration_seconds INTEGER, + cover_url TEXT, remote_cover_url TEXT, stream_url TEXT, remote_stream_url TEXT, track_json TEXT, + updated_at TEXT, audio_hash TEXT, audio_size_bytes INTEGER, audio_mime_type TEXT, audio_updated_at TEXT, + cover_hash TEXT, cover_updated_at TEXT, local_audio_path TEXT, audio_status TEXT DEFAULT 'none', + local_cover_path TEXT, cover_status TEXT DEFAULT 'none', cached_audio_bytes INTEGER DEFAULT 0, + cached_cover_bytes INTEGER DEFAULT 0, last_accessed_at INTEGER DEFAULT 0, play_count INTEGER DEFAULT 0, + audio_pinned INTEGER DEFAULT 0) + """.trimIndent()) + db.execSQL(""" + CREATE TABLE offline_playlists( + playlist_id INTEGER PRIMARY KEY, title TEXT, description TEXT, updated_at TEXT, is_own INTEGER, + owner_name TEXT, is_public INTEGER, is_saved INTEGER, kind TEXT, track_ids_json TEXT) + """.trimIndent()) + db.execSQL("CREATE TABLE offline_likes(track_id INTEGER PRIMARY KEY)") + db.execSQL(""" + INSERT INTO offline_tracks(track_id, track_json, updated_at, local_audio_path, audio_status) + VALUES (?, ?, 'v1', ?, 'ready') + """.trimIndent(), arrayOf(track.id, moshi.adapter(TrackCard::class.java).toJson(track), legacyAudio.path)) + db.version = 2 + } + + val store = store() + assertEquals(legacyAudio.path, store.getTrack(track.id)?.localAudioPath) + assertEquals(listOf(artist.id), store.getArtists(1, 1, mine = false).items.map { it.id }) + assertEquals(null, store.catalogVersions().getValue(track.id).updatedAt) + assertTrue(store.offlineDownloadQueueState().activeTrackIds.isEmpty()) + sessions.clearSession() + signIn(user = 11) + assertTrue(store.getTrack(track.id) == null) + signIn() + assertEquals(legacyAudio.path, store.getTrack(track.id)?.localAudioPath) + } +} diff --git a/app/src/androidTest/java/cy/hexor/furumi/offline/OfflinePlaybackAcceptanceTest.kt b/app/src/androidTest/java/cy/hexor/furumi/offline/OfflinePlaybackAcceptanceTest.kt new file mode 100644 index 0000000..75e57d2 --- /dev/null +++ b/app/src/androidTest/java/cy/hexor/furumi/offline/OfflinePlaybackAcceptanceTest.kt @@ -0,0 +1,408 @@ +package cy.hexor.furumi.offline + +import android.os.SystemClock +import androidx.lifecycle.ViewModelProvider +import androidx.test.core.app.ActivityScenario +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import cy.hexor.furumi.MainActivity +import cy.hexor.furumi.data.local.OfflineDownloadJobScheduler +import cy.hexor.furumi.data.remote.model.federationTrackId +import cy.hexor.furumi.ui.player.LyricsUiState +import cy.hexor.furumi.ui.login.LoginViewModel +import cy.hexor.furumi.ui.player.PlayerViewModel +import java.io.Closeable +import java.io.File +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.runBlocking +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Assume.assumeFalse +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class OfflinePlaybackAcceptanceTest { + @Test fun playingBrowserKeepsItsQueue() = runScenario(paused = false) + @Test fun pausedBrowserKeepsItsQueue() = runScenario(paused = true) + + @Test + fun playlistRetainsLibraryCoversWhenDetailLoadsAndReopens() { + PlayerFixture(paused = true).use { server -> + ActivityScenario.launch(MainActivity::class.java).use { activity -> + val player = signIn(activity, server) + try { + activity.onActivity { player.loadPlaylists() } + await("playlist in Library") { player.uiState.value.playlists.any { it.id == 17L } } + val card = player.uiState.value.playlists.single { it.id == 17L } + val covers = listOf("${server.url}/covers/city", "${server.url}/covers/sky") + assertEquals(covers, card.coverUrls) + + activity.onActivity { + player.openPlaylist(card) + assertEquals(covers, player.uiState.value.selectedPlaylist?.coverUrls) + } + await("playlist tracks") { player.uiState.value.playlistDetail?.tracks?.size == 1 } + val firstTrack = player.uiState.value.playlistDetail!!.tracks.single() + assertEquals("${server.url}/covers/track-1", firstTrack.coverUrl) + assertEquals(covers, player.uiState.value.selectedPlaylist?.coverUrls) + + activity.onActivity { + player.closePlaylistDetail() + player.openPlaylist(card) + assertEquals(covers, player.uiState.value.selectedPlaylist?.coverUrls) + assertEquals(firstTrack.id, player.uiState.value.playlistDetail?.tracks?.single()?.id) + } + assertEquals(1, server.requests.count { it == "/api/player/playlists/17" }) + } finally { + activity.onActivity { player.logout() } + await("fixture logout") { player.uiState.value.isLoggedOut } + } + } + } + } + + @Test + fun lyricsBrowsingPreservesPlaybackAndTappingASyncedLineSeeksThePausedBrowser() { + PlayerFixture(paused = true).use { server -> + ActivityScenario.launch(MainActivity::class.java).use { activity -> + val player = signIn(activity, server) + try { + await("browser playback") { player.uiState.value.connectedDevicesState?.remotePlaybackState?.track != null } + val playing = player.uiState.value.connectedDevicesState!!.remotePlaybackState!!.track!! + activity.onActivity { player.openNowPlayingLyrics(playing) } + await("timed lyrics") { player.uiState.value.lyricsState is LyricsUiState.Content } + val timed = (player.uiState.value.lyricsState as LyricsUiState.Content).versions.single() + assertEquals(listOf(0L, 2500L), timed.lines.map { it.startMs }) + assertTrue(player.uiState.value.followPlayingLyrics) + + val contentId = "b3:" + "a".repeat(64) + val other = playing.copy(id = federationTrackId(contentId), title = "Other track", preparedContentId = contentId) + activity.onActivity { player.openLyrics(other) } + await("plain lyrics") { player.uiState.value.lyricsState is LyricsUiState.Content } + val plain = (player.uiState.value.lyricsState as LyricsUiState.Content).versions.single() + assertEquals("Fixture text", plain.plainText) + assertTrue(plain.lines.isEmpty()) + assertFalse(player.uiState.value.followPlayingLyrics) + assertTrue("/api/player/federation/tracks/lyrics" in server.requests) + + activity.onActivity { + player.seekToLyricsLine(other, 9_000L) + player.seekToLyricsLine(playing, 8_000L) + player.openLyrics(playing.copy(id = 903L)) + } + await("retryable lyrics error") { player.uiState.value.lyricsState is LyricsUiState.Error } + activity.onActivity { player.retryLyrics() } + await("track with no lyrics") { (player.uiState.value.lyricsState as? LyricsUiState.Content)?.versions?.isEmpty() == true } + + activity.onActivity { + player.closeLyrics() + assertNull(player.uiState.value.lyricsTrack) + player.openLyrics(playing) + assertEquals(timed, (player.uiState.value.lyricsState as LyricsUiState.Content).versions.single()) + } + assertEquals(1, server.requests.count { it == "/api/player/lyrics/902" }) + assertEquals(playing.id, player.uiState.value.connectedDevicesState?.remotePlaybackState?.track?.id) + assertTrue(server.deviceWrites.isEmpty()) + + activity.onActivity { player.seekToLyricsLine(playing, timed.lines.last().startMs) } + await("browser confirms lyric timestamp") { + player.uiState.value.connectedDevicesState?.remotePlaybackState?.positionSeconds == 2.5 + } + val command = server.deviceCommands.single() + assertEquals("browser", command.getString("target_device_id")) + assertEquals("seek", command.getString("command")) + val payload = command.getJSONObject("payload") + assertEquals(setOf("time"), payload.keys().asSequence().toSet()) + assertEquals(2.5, payload.getDouble("time"), 0.0) + val devices = player.uiState.value.connectedDevicesState!! + assertEquals("browser", devices.remoteControlTargetId) + val remote = devices.remotePlaybackState!! + assertTrue(remote.paused) + assertEquals(listOf(901L, 902L), remote.tracks.map { it.id }) + assertEquals(playing.id, remote.track?.id) + assertEquals(listOf("/api/player/devices/command"), server.deviceWrites.toList()) + } finally { + activity.onActivity { player.logout() } + await("fixture logout") { player.uiState.value.isLoggedOut } + } + } + } + } + + private fun signIn(activity: ActivityScenario, server: PlayerFixture): PlayerViewModel { + lateinit var login: LoginViewModel + activity.onActivity { login = ViewModelProvider(it)[LoginViewModel::class.java] } + assumeFalse("This acceptance test uses a signed-out app", login.uiState.value.isAuthenticated) + activity.onActivity { + login.onServerUrlChange(server.url) + login.onLoginChange("fixture") + login.onPasswordChange("fixture") + login.login() + } + await("fixture login") { login.uiState.value.isAuthenticated } + lateinit var player: PlayerViewModel + activity.onActivity { player = ViewModelProvider(it)[PlayerViewModel::class.java] } + return player + } + + private fun runScenario(paused: Boolean) { + PlayerFixture(paused).use { server -> + ActivityScenario.launch(MainActivity::class.java).use { activity -> + val player = signIn(activity, server) + fun waitFor(label: String, timeoutMs: Long = 25_000, condition: () -> Boolean) { + await(label, timeoutMs, details = { + val state = player.uiState.value + val q = state.offlineQueue + "playlists=${state.playlists.map { it.id }}, playlistError=${state.playlistsError}, " + + "synced=${state.offlineState.lastSyncedAtMs}, catalogError=${state.offlineState.lastError}, " + + "fallback=${state.offlineState.isUsingNetworkFallback}, remote=${state.connectedDevicesState?.remoteControlTargetId}, " + + "deviceError=${state.connectedDevicesError}, cached=${q.cachedTrackIds.size}, " + + "running=${q.runningTrackId}, failed=${q.errors}, routes=${server.requests.takeLast(12)}" + }, condition = condition) + } + try { + activity.onActivity { player.loadPlaylists() } + waitFor("likes, first catalog and remote device") { + val state = player.uiState.value + state.playlists.any { it.id == -1L } && state.offlineState.lastSyncedAtMs > 0 && + state.connectedDevicesState?.remoteControlTargetId == "browser" + } + val likes = player.uiState.value.playlists.single { it.id == -1L } + activity.onActivity { player.openPlaylist(likes) } + waitFor("all liked tracks") { player.uiState.value.playlistDetail?.tracks?.size == server.count } + activity.onActivity { player.downloadPlaylistForOffline() } + // A UIDT job normally runs immediately. Force an already-scheduled job on slower AVDs. + if (!server.interrupted.await(5, TimeUnit.SECONDS)) { + val instrumentation = InstrumentationRegistry.getInstrumentation() + val id = OfflineDownloadJobScheduler.OFFLINE_DOWNLOAD_JOB_ID + instrumentation.uiAutomation.executeShellCommand( + "cmd jobscheduler run -f ${instrumentation.targetContext.packageName} $id" + ).close() + } + assertTrue("Audio transfer never started", server.interrupted.await(30, TimeUnit.SECONDS)) + waitFor("first completed file and persisted batch") { + val q = player.uiState.value.offlineQueue + 1L in q.cachedTrackIds && q.batchTrackIds.size == server.count + } + if (paused) { + activity.onActivity { player.setOfflineModeEnabled(true) } + } else { + waitFor("network fallback from a failed device poll") { player.uiState.value.offlineState.isUsingNetworkFallback } + } + activity.onActivity { + player.closePlaylistDetail() + player.openPlaylist(likes) + } + waitFor("offline detail") { + player.uiState.value.playlistDetail?.tracks?.firstOrNull()?.isAudioCached == true + } + val ready = runBlocking { player.getDownloadedTracks(setOf(1L)) }.single() + assertArrayEquals(server.audio(1), File(requireNotNull(ready.localAudioPath)).readBytes()) + activity.onActivity { player.addToQueueEnd(ready) } + waitFor("playing the cached track offline") { + val local = player.uiState.value.playback + local.isPlaying && local.currentTrack?.id == 1L + } + val polls = server.pollCount.get() + server.reconnect.countDown() + if (paused) activity.onActivity { player.setOfflineModeEnabled(false) } + waitFor("remote ownership after reconnect") { + server.pollCount.get() > polls && player.uiState.value.connectedDevicesState?.remoteControlTargetId == "browser" + } + waitFor("all files downloaded", 90_000) { + val q = player.uiState.value.offlineQueue + q.cachedTrackIds.size == server.count && q.activeTrackIds.isEmpty() + } + activity.onActivity { player.closePlaylistDetail(); player.openPlaylist(likes) } + waitFor("restored playlist counter") { + val state = player.uiState.value + state.playlistDetail?.tracks?.size == server.count && + state.offlineQueue.completedTrackIds.size == server.count + } + assertTrue(player.uiState.value.offlineQueue.failedTrackIds.isEmpty()) + val resumed = runBlocking { player.getDownloadedTracks(setOf(2L)) }.single() + assertArrayEquals(server.audio(2), File(requireNotNull(resumed.localAudioPath)).readBytes()) + assertTrue("No resume request", server.ranges.isNotEmpty()) + assertTrue("Unexpected resume headers: ${server.ranges}", server.ranges.all { it == ("bytes=8192-" to "\"version-2\"") }) + val remote = player.uiState.value.connectedDevicesState!!.remotePlaybackState!! + assertEquals(listOf(901L, 902L), remote.tracks.map { it.id }) + assertEquals(902L, remote.track!!.id) + assertEquals(37.0, remote.positionSeconds, 0.001) + assertEquals(paused, remote.paused) + assertTrue("Unexpected device writes: ${server.deviceWrites}", server.deviceWrites.isEmpty()) + } finally { + server.reconnect.countDown() + activity.onActivity { player.logout() } + waitFor("fixture logout") { player.uiState.value.isLoggedOut } + } + } + } + } + + private fun await(label: String, timeoutMs: Long = 25_000, details: () -> String = { "" }, condition: () -> Boolean) { + val end = SystemClock.elapsedRealtime() + timeoutMs + while (!condition()) { + if (SystemClock.elapsedRealtime() >= end) fail("Timed out waiting for $label. ${details()}") + SystemClock.sleep(50) + } + } +} + +private class PlayerFixture(private val paused: Boolean) : Closeable { + private val socket = ServerSocket(0, 32, InetAddress.getByName("127.0.0.1")) + private val workers = Executors.newCachedThreadPool() + val url = "http://127.0.0.1:${socket.localPort}" + val count = 74 + val interrupted = CountDownLatch(1) + val reconnect = CountDownLatch(1) + private val first = AtomicBoolean(true) + val pollCount = AtomicInteger() + val ranges = CopyOnWriteArrayList>() + val deviceWrites = CopyOnWriteArrayList() + val deviceCommands = CopyOnWriteArrayList() + val requests = CopyOnWriteArrayList() + + init { + workers.execute { + while (!socket.isClosed) { + val client = try { socket.accept() } catch (_: IOException) { break } + workers.execute { try { client.use(::respond) } catch (_: IOException) { } } + } + } + } + + fun audio(id: Int): ByteArray { + // Playable silent PCM; the first sample distinguishes similarly sized tracks during verification. + val samples = 80_000 + return ByteBuffer.allocate(44 + samples).order(ByteOrder.LITTLE_ENDIAN).apply { + put("RIFF".toByteArray()).putInt(36 + samples).put("WAVEfmt ".toByteArray()).putInt(16) + putShort(1).putShort(1).putInt(8_000).putInt(16_000).putShort(2).putShort(16) + put("data".toByteArray()).putInt(samples).putShort(id.toShort()) + }.array() + } + private fun track(id: Int) = JSONObject().put("id", id).put("title", "Track $id").put("stream_url", "/audio/$id") + private val playlist = JSONObject().put("id", -1).put("title", "Favorites").put("kind", "likes").put("track_count", count) + private val ids = (1..count).toList() + private val tracks = JSONArray(ids.map(::track)) + + private fun respond(client: Socket) { + val reader = client.getInputStream().bufferedReader(Charsets.US_ASCII) + val path = reader.readLine()?.split(' ')?.getOrNull(1)?.substringBefore('?') ?: return + requests.add(path) + val headers = mutableMapOf() + while (true) { + val line = reader.readLine()?.takeUnless { it.isEmpty() } ?: break + headers[line.substringBefore(':').lowercase()] = line.substringAfter(':').trim() + } + val length = headers["content-length"]?.toIntOrNull() ?: 0 + val body = CharArray(length) + var read = 0 + while (read < length) { + val n = reader.read(body, read, length - read) + if (n < 0) return + read += n + } + val request = if (length > 0) JSONObject(String(body)) else JSONObject() + val out = client.getOutputStream() + if (path.startsWith("/audio/")) { + val id = path.substringAfterLast('/').toInt() + val bytes = audio(id) + val etag = "\"version-$id\"" + if (id == 2 && first.getAndSet(false)) { + out.write("HTTP/1.1 200 OK\r\nContent-Length: ${bytes.size}\r\nETag: $etag\r\nConnection: close\r\n\r\n".toByteArray()) + out.write(bytes, 0, 8192) + out.flush() + interrupted.countDown() + return + } + val range = headers["range"] + val offset = range?.removePrefix("bytes=")?.removeSuffix("-")?.toInt() ?: 0 + if (id == 2) { + ranges.add(range to headers["if-range"]) + if (!reconnect.await(20, TimeUnit.SECONDS)) return + } + val status = if (range == null) "200 OK" else "206 Partial Content" + val contentRange = if (range == null) "" else "Content-Range: bytes $offset-${bytes.lastIndex}/${bytes.size}\r\n" + out.write("HTTP/1.1 $status\r\n${contentRange}Content-Length: ${bytes.size - offset}\r\nETag: $etag\r\nConnection: close\r\n\r\n".toByteArray()) + out.write(bytes, offset, bytes.size - offset) + return + } + + // Close API connections during the interrupted transfer so the normal poll observes an I/O failure. + if (interrupted.count == 0L && reconnect.count != 0L) return + var status = "200 OK" + val result: Any = when { + path == "/api/auth/password" -> JSONObject("""{"user":{"id":1,"name":"Fixture","role":"user"},"tokens":{"access_token":"fixture","refresh_token":"fixture","token_type":"Bearer","expires_in_seconds":3600}}""") + path == "/api/auth/logout" -> JSONObject().put("success", true) + path == "/api/player/artists" -> JSONObject("""{"items":[],"total":0,"page":1,"per_page":200,"has_more":false}""") + path == "/api/player/playlists" -> JSONArray().put(playlist).put( + JSONObject().put("id", 17).put("title", "City mix").put("track_count", 1) + .put("cover_urls", JSONArray(listOf("/covers/city", "/covers/sky"))) + ) + path == "/api/player/playlists/17" -> JSONObject().put("id", 17).put("title", "City mix") + .put("tracks", JSONArray().put(track(1).put("cover_url", "/covers/track-1"))) + path == "/api/player/playlists/-1" -> JSONObject().put("playlist", playlist).put("tracks", tracks) + path.endsWith("/federation-tracks") -> JSONArray() + path == "/api/player/lyrics/902" -> JSONObject("""{"versions":[{"id":"manual:1","source":"manual","label":"Timed","synced_lrc":"[00:00.00]First line\n[00:02.50]Second line","instrumental":false}]}""") + path == "/api/player/federation/tracks/lyrics" -> JSONObject("""{"versions":[{"id":"manual:2","source":"manual","label":"Plain","plain_text":"Fixture text","instrumental":false}]}""") + .put("content_id", "b3:" + "a".repeat(64)) + path == "/api/player/lyrics/903" && requests.count { it == path } == 1 -> { + status = "503 Service Unavailable" + JSONObject() + } + path == "/api/player/lyrics/903" -> JSONObject().put("versions", JSONArray()) + path == "/api/player/likes" -> JSONObject().put("track_ids", JSONArray(ids)) + path == "/api/player/tracks/content/like" -> JSONArray() + path == "/api/player/offline/manifest" -> JSONObject().put("generated_at", "v1") + .put("tracks", JSONArray(ids.map { track(it).put("updated_at", "v1") })) + .put("playlists", JSONArray().put(JSONObject(playlist.toString()).put("track_ids", JSONArray(ids)))) + .put("liked_track_ids", JSONArray(ids)) + path == "/api/player/tracks-by-ids" -> tracks + path == "/api/player/devices/command" -> { + deviceWrites.add(path) + deviceCommands.add(request) + JSONObject().put("success", true) + } + path == "/api/player/devices/poll" -> { + pollCount.incrementAndGet() + if (!request.isNull("playback_state")) deviceWrites.add(request.toString()) + val seek = deviceCommands.lastOrNull { + it.optString("target_device_id") == "browser" && it.optString("command") == "seek" + } + val position = seek?.optJSONObject("payload")?.optDouble("time", 37.0) ?: 37.0 + val playback = JSONObject().put("track", track(902)).put("tracks", JSONArray().put(track(901)).put(track(902))) + .put("index", 1).put("position_seconds", position).put("paused", paused) + JSONObject().put("device_id", request.getString("device_id")).put("active_device_id", "browser") + .put("devices", JSONArray().put(JSONObject("""{"id":"browser","name":"Browser","kind":"web","is_active":true}"""))) + .put("playback_state", playback) + } + else -> { + if (path.startsWith("/api/player/devices/")) deviceWrites.add(path) + status = "404 Not Found" + JSONObject() + } + } + val bytes = result.toString().toByteArray() + out.write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${bytes.size}\r\nConnection: close\r\n\r\n".toByteArray()) + out.write(bytes) + } + + override fun close() { + reconnect.countDown() + socket.close() + workers.shutdownNow() + } +} diff --git a/app/src/androidTest/java/cy/hexor/furumi/ui/player/FullPlayerInteractionTest.kt b/app/src/androidTest/java/cy/hexor/furumi/ui/player/FullPlayerInteractionTest.kt new file mode 100644 index 0000000..3954d39 --- /dev/null +++ b/app/src/androidTest/java/cy/hexor/furumi/ui/player/FullPlayerInteractionTest.kt @@ -0,0 +1,114 @@ +package cy.hexor.furumi.ui.player + +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.click +import androidx.compose.ui.test.onAllNodesWithText +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performScrollToKey +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipe +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.playback.AudioPlaybackState +import cy.hexor.furumi.ui.theme.FurumiTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test + +class FullPlayerInteractionTest { + @get:Rule + val compose = createAndroidComposeRule() + + @Test + fun scrubbingSeeksOnceAndScrollingRequestsQueueArtworkOnDemand() { + val tracks = (1L..220L).map { id -> + TrackCard( + id = id, title = "Track $id", trackNumber = null, discNumber = null, + durationSeconds = 120, artists = listOf("Artist"), releaseTitle = null, + coverUrl = "/cover/$id", streamUrl = "/stream/$id" + ) + } + val images = mutableSetOf() + val seeks = mutableListOf() + var selected: Pair? = null + var nowPlayingLyrics: Long? = null + var trackLyrics: Long? = null + var visible by mutableStateOf(true) + var playback by mutableStateOf( + AudioPlaybackState(queue = tracks, currentIndex = 3, durationMs = 120_000L, positionMs = 24_000L) + ) + compose.setContent { + FurumiTheme { + if (visible) { + FullPlayerOverlay( + playback = playback, coverBitmap = null, mediaImages = emptyMap(), likedTrackIds = emptySet(), + onMediaImageNeeded = { url -> url?.let(images::add) }, + dragOffsetY = 0f, onDragOffsetChange = {}, onDismiss = { visible = false }, + onPlayPause = { playback = playback.copy(isPlaying = !playback.isPlaying) }, + onPrevious = {}, onNext = {}, onToggleShuffle = {}, onCycleRepeatMode = {}, + onSeekToProgress = { seeks.add(it) }, + onNowPlayingLyrics = { nowPlayingLyrics = it.id }, + onLyrics = { trackLyrics = it.id }, + onQueueTrackClick = { track, index -> selected = track.id to index }, + onToggleLike = {}, onPlayNext = {}, onPlayLast = {}, onShare = {}, onAddToPlaylist = {}, + offlineDownloadedTrackIds = emptySet(), offlineDownloadingTrackIds = emptySet(), + canDownloadForOffline = true, onDownloadForOffline = {}, onArtistClick = {}, + connectedDevicesState = null, connectedDevicesError = null, onDeviceClick = {}, + onCreateJam = {}, onJoinJam = {}, onLeaveJam = {}, jamInviteQuery = "", + jamInviteUsers = emptyList(), isJamInviteSearchLoading = false, + onJamInviteQueryChange = {}, onInviteToJam = { _, _ -> } + ) + } + } + } + + compose.onNodeWithContentDescription("Play").performScrollTo().performClick() + compose.onNodeWithContentDescription("Pause").assertIsDisplayed() + compose.onNodeWithContentDescription("Playback position").performScrollTo().performTouchInput { + swipe(Offset(width * 0.2f, centerY), Offset(width * 0.8f, centerY), durationMillis = 500) + } + compose.runOnIdle { + assertEquals(1, seeks.size) + assertTrue(seeks.single() in 0.70f..0.90f) + assertTrue("/cover/4" in images) + assertFalse("/cover/201" in images) + } + + compose.onNodeWithText("Lyrics").performScrollTo().performClick() + compose.runOnIdle { assertEquals(4L, nowPlayingLyrics) } + + val queue = compose.onNode(SemanticsMatcher.keyIsDefined(SemanticsActions.ScrollToIndex)) + queue.performScrollToKey("queue-200") + compose.onNodeWithText("Track 201", useUnmergedTree = true) + .assertIsDisplayed().performTouchInput { click(center) } + compose.runOnIdle { + assertTrue("/cover/201" in images) + assertEquals(201L to 200, selected) + } + queue.performScrollToKey("queue-201") + compose.onNodeWithContentDescription("More options for Track 202").performClick() + compose.onNodeWithText("Lyrics").performClick() + compose.waitUntil(timeoutMillis = 5_000) { + compose.onAllNodesWithText("Play next").fetchSemanticsNodes().isEmpty() + } + compose.runOnIdle { + assertEquals(202L, trackLyrics) + assertEquals(201L to 200, selected) + } + queue.performScrollToKey("player-controls") + compose.onNodeWithContentDescription("Close player").performClick() + compose.onNodeWithText("Now playing").assertDoesNotExist() + } +} diff --git a/app/src/androidTest/java/cy/hexor/furumi/ui/player/LibraryInteractionTest.kt b/app/src/androidTest/java/cy/hexor/furumi/ui/player/LibraryInteractionTest.kt new file mode 100644 index 0000000..7b4402c --- /dev/null +++ b/app/src/androidTest/java/cy/hexor/furumi/ui/player/LibraryInteractionTest.kt @@ -0,0 +1,275 @@ +package cy.hexor.furumi.ui.player + +import android.graphics.Bitmap +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.SemanticsMatcher +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performScrollToKey +import androidx.compose.ui.test.performScrollToNode +import androidx.compose.ui.test.performTextReplacement +import cy.hexor.furumi.domain.model.OfflineDownloadQueueState +import cy.hexor.furumi.domain.model.OfflineTransferProgress +import cy.hexor.furumi.domain.model.OfflineTransferStage +import cy.hexor.furumi.domain.model.PlaylistCard +import cy.hexor.furumi.domain.model.PlaylistDetail +import cy.hexor.furumi.domain.model.ReleaseCard +import cy.hexor.furumi.domain.model.SearchResults +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.ui.theme.FurumiTheme +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test + +class LibraryInteractionTest { + @get:Rule + val compose = createAndroidComposeRule() + + private val collection + get() = compose.onNode(SemanticsMatcher.keyIsDefined(SemanticsActions.ScrollToIndex)) + + private fun searchFor(query: String) { + collection.performScrollToNode(hasSetTextAction()) + compose.onNode(hasSetTextAction()).performTextReplacement(query) + } + + private fun clearSearch() { + collection.performScrollToNode(hasSetTextAction()) + compose.onNodeWithContentDescription("Clear search").performClick() + } + + @Test + fun librarySearchFiltersPlaylistNamesAndClears() { + val morning = PlaylistCard(7L, "Morning radio", 8, isPublic = false) + val evening = PlaylistCard(8L, "Evening drive", 3, isPublic = false) + val state = PlayerUiState(playlists = listOf(morning, evening)) + var opened: PlaylistCard? = null + compose.setContent { + FurumiTheme { + LibraryContent( + uiState = state, showDownloads = false, onShowDownloadsChange = {}, + onProfileClick = {}, onLoadLibrary = {}, onRetryPlaylists = {}, onRetryArtists = {}, + onLoadMoreArtists = {}, onCreatePlaylistClick = {}, getDownloadedTracks = { emptyList() }, + onPlayDownloaded = { _, _ -> }, onLyrics = {}, onStorageLimitChange = {}, + onClearDownloads = {}, onRetryFailed = {}, onPlaylistClick = { opened = it }, + onArtistImageNeeded = {}, onArtistClick = {} + ) + } + } + + searchFor(" dRiV ") + collection.performScrollToNode(hasText(evening.title)) + compose.onNodeWithText(morning.title).assertDoesNotExist() + compose.onNodeWithText(evening.title).performClick() + compose.runOnIdle { assertEquals(evening, opened) } + + searchFor("missing playlist") + collection.performScrollToNode(hasText("No matching playlists")) + compose.onNodeWithText(evening.title).assertDoesNotExist() + clearSearch() + collection.performScrollToNode(hasText(morning.title)) + compose.onNodeWithText(morning.title).performClick() + compose.runOnIdle { assertEquals(morning, opened) } + } + + @Test + fun trackSearchMatchesMetadataAndPlaysTheSelectedTrack() { + val intro = TrackCard( + id = 101L, title = "Intro", trackNumber = null, discNumber = null, durationSeconds = 120, + artists = listOf("North"), releaseTitle = null, coverUrl = null, streamUrl = "/stream/101" + ) + val broadcast = intro.copy(id = 202L, title = "Broadcast", releaseTitle = "Tides", streamUrl = "/stream/202") + val live = intro.copy(id = 303L, title = "Live session", artists = listOf("Echo"), streamUrl = "/stream/303") + val playlist = PlaylistCard(8L, "Evening drive", 3, isPublic = false) + val state = PlayerUiState( + playlistDetail = PlaylistDetail(playlist, null, listOf(intro, broadcast, live)), + offlineDownloadedTrackIds = setOf(intro.id) + ) + var played: TrackCard? = null + compose.setContent { + FurumiTheme { + PlaylistDetailContent( + uiState = state, onBack = {}, onRetry = {}, onMediaImageNeeded = {}, + onPlayClick = {}, onShuffleClick = {}, onTrackClick = { played = it }, onToggleLike = {}, + onPlayNext = {}, onPlayLast = {}, onLyrics = {}, onShare = {}, onAddToPlaylist = {}, + onDownloadForOffline = {}, onDownloadPlaylistClick = {}, onRetryFailed = {}, + onDeletePlaylistClick = {} + ) + } + } + + for (query in listOf("bRoAd", " tIdEs ")) { + searchFor(query) + collection.performScrollToNode(hasText(broadcast.title)) + compose.onNodeWithText(intro.title).assertDoesNotExist() + compose.onNodeWithText(live.title).assertDoesNotExist() + } + searchFor("eChO") + collection.performScrollToNode(hasText(live.title)) + compose.onNodeWithText(live.title).performClick() + compose.runOnIdle { assertEquals(live, played) } + collection.performScrollToNode(hasText("1 of 3 downloaded")) + + searchFor("missing track") + collection.performScrollToNode(hasText("No matching tracks")) + compose.onNodeWithText(live.title).assertDoesNotExist() + clearSearch() + collection.performScrollToNode(hasText(intro.title)) + compose.onNodeWithText(intro.title).assertIsDisplayed() + } + + @Test + fun reopeningFavoritesShowsItsOwnRetryAndLoadsThumbnailsOnScroll() { + val tracks = (1L..220L).map { id -> + TrackCard( + id = id, title = "Track $id", trackNumber = null, discNumber = null, + durationSeconds = 120, artists = listOf("Artist"), releaseTitle = null, + coverUrl = "/cover/$id", streamUrl = "/stream/$id" + ) + } + val likes = PlaylistCard(-1L, "Favorites", tracks.size, isPublic = false, kind = "likes") + val queue = OfflineDownloadQueueState( + activeTrackIds = setOf(2L), runningTrackId = 2L, failedTrackIds = setOf(3L, 901L), + trackTitles = mapOf(2L to "Track 2", 3L to "Track 3", 901L to "Other playlist"), + errors = mapOf(3L to "Audio timed out"), cachedTrackIds = setOf(1L), + transferProgress = OfflineTransferProgress( + trackId = 2L, stage = OfflineTransferStage.DOWNLOADING, + receivedBytes = 524_288L, totalBytes = 1_048_576L + ) + ) + val state = PlayerUiState( + playlists = listOf(likes), isPlaylistsLoading = true, playlistDetail = PlaylistDetail(likes, null, tracks), + offlineQueue = queue, offlineDownloadedTrackIds = queue.cachedTrackIds + ) + val images = mutableSetOf() + var retried = emptySet() + var showPlaylist by mutableStateOf(false) + var showDownloads by mutableStateOf(true) + compose.setContent { + FurumiTheme { + if (showPlaylist) { + PlaylistDetailContent( + uiState = state, onBack = { showPlaylist = false }, onRetry = {}, + onMediaImageNeeded = { url -> url?.let(images::add) }, + onPlayClick = {}, onShuffleClick = {}, onTrackClick = {}, onToggleLike = {}, + onPlayNext = {}, onPlayLast = {}, onLyrics = {}, onShare = {}, onAddToPlaylist = {}, + onDownloadForOffline = {}, onDownloadPlaylistClick = {}, + onRetryFailed = { retried = it }, onDeletePlaylistClick = {} + ) + } else { + LibraryContent( + showDownloads = showDownloads, onShowDownloadsChange = { showDownloads = it }, + uiState = state, onProfileClick = {}, onLoadLibrary = {}, onRetryPlaylists = {}, + onRetryArtists = {}, onLoadMoreArtists = {}, onCreatePlaylistClick = {}, + getDownloadedTracks = { emptyList() }, onPlayDownloaded = { _, _ -> }, onLyrics = {}, + onStorageLimitChange = {}, onClearDownloads = {}, onRetryFailed = {}, + onPlaylistClick = { showPlaylist = true }, + onArtistImageNeeded = {}, onArtistClick = {} + ) + } + } + } + + compose.onNodeWithText("On device").assertIsDisplayed() + compose.runOnIdle { compose.activity.onBackPressedDispatcher.onBackPressed() } + compose.onNodeWithText("Your Library").assertIsDisplayed() + + fun openFavorites() { + collection.performScrollToKey("playlist--1") + compose.onNodeWithText("Favorites").performClick() + } + + openFavorites() + compose.onNodeWithText("1 of 220 downloaded").performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Downloading Track 2").performScrollTo().assertIsDisplayed() + compose.onNodeWithText("Saving to phone · 512 KiB / 1 MiB").performScrollTo().assertIsDisplayed() + collection.performScrollToKey("1:0") + compose.runOnIdle { + assertTrue("/cover/1" in images) + assertFalse("/cover/190" in images) + } + collection.performScrollToKey("190:189") + compose.onNodeWithText("Track 190").assertIsDisplayed() + compose.runOnIdle { assertTrue("/cover/190" in images) } + collection.performScrollToKey("header") + compose.onNodeWithText("Library").performClick() + + openFavorites() + compose.onNodeWithText("1 failed · View details").performScrollTo().performClick() + compose.onNodeWithText("Audio timed out").assertIsDisplayed() + compose.onNodeWithText("Other playlist").assertDoesNotExist() + compose.onNodeWithText("Retry failed downloads").performClick() + compose.runOnIdle { assertEquals(setOf(3L), retried) } + } + + @Test + fun playlistHeaderKeepsBothLibraryCoversAfterTracksAppear() { + val covers = listOf("/covers/city", "/covers/sky") + val card = PlaylistCard(17L, "City mix", 1, isPublic = false, coverUrls = covers) + val track = TrackCard( + id = 1L, title = "First track", trackNumber = null, discNumber = null, durationSeconds = 120, + artists = listOf("Artist"), releaseTitle = null, coverUrl = "/different-art", streamUrl = "/stream/1" + ) + val bitmap = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888) + var state by mutableStateOf(PlayerUiState( + selectedPlaylist = card, playlists = listOf(card), + mediaImages = (covers + "/different-art").associate { canonicalMediaImageResource(it) to bitmap } + )) + compose.setContent { + FurumiTheme { + PlaylistDetailContent( + uiState = state, onBack = {}, onRetry = {}, onMediaImageNeeded = {}, + onPlayClick = {}, onShuffleClick = {}, onTrackClick = {}, onToggleLike = {}, + onPlayNext = {}, onPlayLast = {}, onLyrics = {}, onShare = {}, onAddToPlaylist = {}, + onDownloadForOffline = {}, onDownloadPlaylistClick = {}, onRetryFailed = {}, + onDeletePlaylistClick = {} + ) + } + } + fun assertLibraryCoversVisible() { + compose.onNodeWithContentDescription("City mix cover 1").assertIsDisplayed() + compose.onNodeWithContentDescription("City mix cover 2").assertIsDisplayed() + } + assertLibraryCoversVisible() + compose.runOnIdle { + state = state.copy(playlistDetail = PlaylistDetail(card.copy(coverUrls = emptyList()), null, listOf(track))) + } + assertLibraryCoversVisible() + } + + @Test + fun albumOnlyResultRemainsSelectableDuringRefresh() { + val release = ReleaseCard(7L, "Night Music", "album", 2024, null, 8) + val state = PlayerUiState( + searchQuery = "Night", + searchResults = SearchResults(emptyList(), emptyList(), emptyList(), listOf(release)), + isSearchLoading = true + ) + var opened: ReleaseCard? = null + compose.setContent { + FurumiTheme { + SearchContent( + uiState = state, onProfileClick = {}, onQueryChange = {}, onRetry = {}, + onReleaseClick = { opened = it }, onArtistClick = {}, onMediaImageNeeded = {}, + onTrackClick = {}, onToggleLike = {}, onPlayNext = {}, onPlayLast = {}, + onLyrics = {}, onShare = {}, onAddToPlaylist = {}, onDownloadForOffline = {} + ) + } + } + compose.onNodeWithText("Albums").assertIsDisplayed() + compose.onNodeWithText("Night Music").performClick() + compose.runOnIdle { assertEquals(release, opened) } + } +} diff --git a/app/src/androidTest/java/cy/hexor/furumi/ui/player/LyricsScreenTest.kt b/app/src/androidTest/java/cy/hexor/furumi/ui/player/LyricsScreenTest.kt new file mode 100644 index 0000000..df125f9 --- /dev/null +++ b/app/src/androidTest/java/cy/hexor/furumi/ui/player/LyricsScreenTest.kt @@ -0,0 +1,143 @@ +package cy.hexor.furumi.ui.player + +import android.os.SystemClock +import androidx.activity.ComponentActivity +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.test.assertHasNoClickAction +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotSelected +import androidx.compose.ui.test.assertIsSelected +import androidx.compose.ui.test.hasScrollAction +import androidx.compose.ui.test.hasText +import androidx.compose.ui.test.isSelected +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollToIndex +import androidx.compose.ui.test.performTouchInput +import androidx.compose.ui.test.swipeUp +import cy.hexor.furumi.domain.model.LyricsLine +import cy.hexor.furumi.domain.model.LyricsVersion +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.playback.AudioPlaybackState +import cy.hexor.furumi.ui.theme.FurumiTheme +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test + +class LyricsScreenTest { + @get:Rule + val compose = createAndroidComposeRule() + + private val track = TrackCard(1L, "Song", null, null, 120, listOf("Artist"), releaseTitle = null, + coverUrl = null, streamUrl = "/audio/1") + private val original = LyricsVersion("one", "Original", "Library", "en", null, + (1L..80L).map { LyricsLine(it * 1000, "Line $it") }, instrumental = false) + + @Test + fun linesAdvanceBetweenPositionReportsAndStayStillWhenPaused() { + val cues = listOf(LyricsLine(0, "Opening"), LyricsLine(120, "Middle"), LyricsLine(260, "Final")) + val content = LyricsUiState.Content(listOf(original.copy(lines = cues))) + var playing by mutableStateOf(true) + compose.setContent { + FurumiTheme { + // The remote device supplies the same playhead throughout this test. + val playback = AudioPlaybackState(queue = listOf(track), currentIndex = 0, positionMs = 0, isPlaying = playing) + LyricsScreen(track, content, playback, {}, {}, { playing = !playing }, onSeekToLine = {}) + } + } + + compose.onNodeWithContentDescription("Pause").performClick() + compose.onNodeWithText("Opening").assertIsSelected() + val pausedAt = SystemClock.elapsedRealtime() + compose.waitUntil(timeoutMillis = 10_000) { SystemClock.elapsedRealtime() - pausedAt >= cues.last().startMs } + compose.onNodeWithText("Opening").assertIsSelected() + compose.onNodeWithText("Final").assertIsNotSelected() + + compose.onNodeWithContentDescription("Play").performClick() + compose.waitUntil(timeoutMillis = 10_000) { + compose.onAllNodes(hasText("Final") and isSelected()).fetchSemanticsNodes().isNotEmpty() + } + compose.onNodeWithText("Final").assertIsDisplayed() + } + + @Test + fun seekingFollowsTheSongUntilTheReaderScrollsAndResumesFollowing() { + var playback by mutableStateOf(AudioPlaybackState(queue = listOf(track), currentIndex = 0)) + compose.setContent { + FurumiTheme { + LyricsScreen(track, LyricsUiState.Content(listOf(original)), playback, {}, {}, {}, onSeekToLine = {}) + } + } + compose.onNodeWithText("Line 1").assertIsNotSelected() + compose.runOnIdle { playback = playback.copy(positionMs = 34_500) } + compose.onNodeWithText("Line 34").assertIsSelected().assertIsDisplayed() + compose.onNode(hasScrollAction()).performTouchInput { swipeUp() } + compose.onNodeWithText("Back to current line").assertIsDisplayed() + compose.runOnIdle { playback = playback.copy(positionMs = 2_100) } + compose.onNodeWithText("Line 2").assertDoesNotExist() + compose.onNodeWithText("Back to current line").performClick() + compose.onNodeWithText("Line 2").assertIsSelected().assertIsDisplayed() + compose.runOnIdle { playback = playback.copy(queue = listOf(track.copy(id = 2L)), positionMs = 30_000) } + compose.onNodeWithText("Line 2").assertIsNotSelected().assertHasNoClickAction() + compose.onNodeWithContentDescription("Play").assertDoesNotExist() + } + + @Test + fun tappingABrowsedLineSeeksToItsExactTimeAndResumesFollowing() { + val cues = (0..60).map { LyricsLine(it * 1000L + 251, "Cue $it") } + val content = LyricsUiState.Content(listOf(original.copy(lines = cues))) + val seeks = mutableListOf() + var playback by mutableStateOf(AudioPlaybackState(queue = listOf(track), currentIndex = 0, positionMs = 251)) + compose.setContent { + FurumiTheme { + LyricsScreen(track, content, playback, {}, {}, {}, onSeekToLine = { seeks.add(it) }) + } + } + compose.onNodeWithText("Cue 0").assertIsSelected() + val list = compose.onNode(hasScrollAction()) + list.performTouchInput { swipeUp() } + compose.onNodeWithText("Back to current line").assertIsDisplayed() + list.performScrollToIndex(38) + compose.onNodeWithText("Cue 38").assertIsDisplayed().performClick() + + // A connected player acknowledges the seek on its next poll. + compose.onNodeWithText("Cue 38").assertIsDisplayed() + compose.onNodeWithText("Back to current line").assertDoesNotExist() + compose.runOnIdle { + assertEquals(listOf(38_251L), seeks) + playback = playback.copy(positionMs = seeks.single()) + } + compose.onNodeWithText("Cue 38").assertIsSelected().assertIsDisplayed() + compose.runOnIdle { playback = playback.copy(positionMs = 12_251) } + compose.onNodeWithText("Cue 12").assertIsSelected().assertIsDisplayed() + } + + @Test + fun browsingAnotherTrackDisplaysAlternativesAndRetryWithoutPlaybackControls() { + val translated = LyricsVersion("two", "Translation", "Library", "it", "First verse\n\nFinal verse", + emptyList(), instrumental = false) + var state by mutableStateOf(LyricsUiState.Error("Could not load lyrics")) + var retries = 0 + compose.setContent { + FurumiTheme { + LyricsScreen(track, state, AudioPlaybackState(), {}, { + retries++ + state = LyricsUiState.Content(listOf(original, translated)) + }, {}, onSeekToLine = {}) + } + } + compose.onNodeWithText("Could not load lyrics").assertIsDisplayed() + compose.onNodeWithText("Retry").performClick() + compose.runOnIdle { assertEquals(1, retries) } + compose.onNodeWithText("Original").performClick() + compose.onNodeWithText("Translation").performClick() + compose.onNodeWithText("First verse").assertIsDisplayed().assertHasNoClickAction() + compose.onNodeWithContentDescription("Play").assertDoesNotExist() + compose.runOnIdle { state = LyricsUiState.Content(emptyList()) } + compose.onNodeWithText("Lyrics are unavailable for this track").assertIsDisplayed() + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c2fc4d0..02079f7 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -3,6 +3,7 @@ xmlns:tools="http://schemas.android.com/tools"> + diff --git a/app/src/main/java/cy/hexor/furumi/MainActivity.kt b/app/src/main/java/cy/hexor/furumi/MainActivity.kt index 1e41d70..3c2ebb0 100644 --- a/app/src/main/java/cy/hexor/furumi/MainActivity.kt +++ b/app/src/main/java/cy/hexor/furumi/MainActivity.kt @@ -29,6 +29,7 @@ import dagger.hilt.android.AndroidEntryPoint class MainActivity : ComponentActivity() { private var deepLinkUri by mutableStateOf(null) + private var openDownloads by mutableStateOf(false) private val notificationPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { } @@ -41,6 +42,7 @@ class MainActivity : ComponentActivity() { ) requestNotificationPermissionIfNeeded() + openDownloads = savedInstanceState?.getBoolean(PENDING_DOWNLOADS) ?: (intent.action == ACTION_OPEN_DOWNLOADS) if (deepLinkUri == null) { deepLinkUri = intent?.data } @@ -49,6 +51,8 @@ class MainActivity : ComponentActivity() { FurumiTheme { FurumiApp( deepLinkUri = deepLinkUri, + openDownloads = openDownloads, + onDownloadsOpened = { openDownloads = false }, onDeepLinkHandled = { deepLinkUri = null } ) } @@ -58,7 +62,18 @@ class MainActivity : ComponentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) - deepLinkUri = intent.data + if (intent.action == ACTION_OPEN_DOWNLOADS) openDownloads = true + else deepLinkUri = intent.data + } + + override fun onSaveInstanceState(outState: Bundle) { + outState.putBoolean(PENDING_DOWNLOADS, openDownloads) + super.onSaveInstanceState(outState) + } + + companion object { + internal const val ACTION_OPEN_DOWNLOADS = "cy.hexor.furumi.action.OPEN_DOWNLOADS" + private const val PENDING_DOWNLOADS = "pending_offline_downloads" } private fun requestNotificationPermissionIfNeeded() { @@ -71,7 +86,12 @@ class MainActivity : ComponentActivity() { } @Composable -fun FurumiApp(deepLinkUri: Uri?, onDeepLinkHandled: () -> Unit) { +fun FurumiApp( + deepLinkUri: Uri?, + openDownloads: Boolean = false, + onDownloadsOpened: () -> Unit = {}, + onDeepLinkHandled: () -> Unit +) { val navController = rememberNavController() NavHost(navController = navController, startDestination = "login") { @@ -97,6 +117,8 @@ fun FurumiApp(deepLinkUri: Uri?, onDeepLinkHandled: () -> Unit) { } composable("player") { PlayerScreen( + openDownloads = openDownloads, + onDownloadsOpened = onDownloadsOpened, onLoggedOut = { navController.navigate("login") { popUpTo("player") { inclusive = true } diff --git a/app/src/main/java/cy/hexor/furumi/data/local/AuthSessionStorage.kt b/app/src/main/java/cy/hexor/furumi/data/local/AuthSessionStorage.kt index ce97ff9..f05169a 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/AuthSessionStorage.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/AuthSessionStorage.kt @@ -7,6 +7,9 @@ import cy.hexor.furumi.domain.model.AuthSession import cy.hexor.furumi.domain.model.AuthTokens import cy.hexor.furumi.domain.model.User import com.squareup.moshi.Moshi +import java.security.MessageDigest +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow class AuthSessionStorage(context: Context, moshi: Moshi) { private val masterKey = MasterKey.Builder(context) @@ -23,6 +26,27 @@ class AuthSessionStorage(context: Context, moshi: Moshi) { private val userAdapter = moshi.adapter(User::class.java) + private val accountKey = MutableStateFlow(getSession()?.offlineKey()) + val accountKeys = accountKey.asStateFlow() + + // Older installations used one DB and absolute paths. Reserve them for the session + // present at upgrade, including across logout and subsequent process restarts. + internal val legacyOfflineOwner: String? = context.getSharedPreferences( + "offline_storage_migration", Context.MODE_PRIVATE + ).let { migration -> + if (!migration.contains("owner")) { + check(migration.edit().putString("owner", accountKey.value.orEmpty()).commit()) + } + migration.getString("owner", null)?.takeIf { it.isNotEmpty() } + } + + private fun AuthSession.offlineKey(): String { + val identity = serverBaseUrl.trimEnd('/') + "\n" + user.id + return MessageDigest.getInstance("SHA-256").digest(identity.toByteArray()) + .joinToString("") { "%02x".format(it) } + } + + @Synchronized fun saveSession(session: AuthSession) { prefs.edit() .putString(KEY_BASE_URL, session.serverBaseUrl) @@ -34,8 +58,10 @@ class AuthSessionStorage(context: Context, moshi: Moshi) { .putString(KEY_USER_DATA, userAdapter.toJson(session.user)) .remove(KEY_PENDING_SSO_BASE_URL) .apply() + accountKey.value = session.offlineKey() } + @Synchronized fun saveTokens(tokens: AuthTokens) { prefs.edit() .putString(KEY_ACCESS_TOKEN, tokens.accessToken) @@ -87,10 +113,13 @@ class AuthSessionStorage(context: Context, moshi: Moshi) { return runCatching { userAdapter.fromJson(json) }.getOrNull() } + @Synchronized fun clear() { prefs.edit().clear().apply() + accountKey.value = null } + @Synchronized fun clearSession() { prefs.edit() .remove(KEY_ACCESS_TOKEN) @@ -101,6 +130,7 @@ class AuthSessionStorage(context: Context, moshi: Moshi) { .remove(KEY_PENDING_SSO_BASE_URL) .remove(KEY_USER_DATA) .apply() + accountKey.value = null } companion object { diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineAccountScope.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineAccountScope.kt new file mode 100644 index 0000000..c953205 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineAccountScope.kt @@ -0,0 +1,55 @@ +package cy.hexor.furumi.data.local + +import android.content.Context +import dagger.hilt.android.qualifiers.ApplicationContext +import java.io.File +import javax.inject.Inject +import javax.inject.Singleton +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.cancel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.asContextElement +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.withContext + +@Singleton +class OfflineAccountScope @Inject constructor( + @ApplicationContext private val context: Context, + private val sessions: AuthSessionStorage +) { + private val pinnedKey = ThreadLocal() + + val keys: StateFlow get() = sessions.accountKeys + val key: String? get() = keys.value + internal val storageKey: String get() = pinnedKey.get() ?: key ?: "signed-out" + internal val isLegacyOwner: Boolean get() = storageKey == sessions.legacyOfflineOwner + + internal val databaseName: String get() = + if (isLegacyOwner) "furumi_offline.db" else "furumi_offline_${storageKey}.db" + + val mediaDirectory: File get() = File( + context.filesDir, if (isLegacyOwner) "offline" else "offline_${storageKey}" + ) + + fun matches(key: String?): Boolean = key != null && key == this.key + + suspend fun withAccount(key: String, block: suspend () -> T): T = + withContext(Dispatchers.IO + pinnedKey.asContextElement(key)) { + if (!matches(key)) throw CancellationException("Offline account changed") + coroutineScope { + val monitor = launch(start = CoroutineStart.UNDISPATCHED) { + keys.first { it != key } + this@coroutineScope.cancel("Offline account changed") + } + try { + block() + } finally { + monitor.cancel() + } + } + } +} diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadJobScheduler.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadJobScheduler.kt index 03237f2..671e121 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadJobScheduler.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadJobScheduler.kt @@ -5,6 +5,7 @@ import android.app.job.JobScheduler import android.content.ComponentName import android.content.Context import android.os.Build +import android.os.PersistableBundle import cy.hexor.furumi.domain.model.AuthException import cy.hexor.furumi.offline.OfflineDownloadJobService import dagger.hilt.android.qualifiers.ApplicationContext @@ -17,25 +18,45 @@ class OfflineDownloadJobScheduler @Inject constructor( ) { private val jobScheduler = context.getSystemService(JobScheduler::class.java) - fun schedule(estimatedDownloadBytes: Long) { - if (jobScheduler.allPendingJobs.any { it.id == OFFLINE_DOWNLOAD_JOB_ID }) return + // JobScheduler can briefly report a job that has already been finished. An enqueue + // racing its last item must be allowed to replace that stale record. + private var justFinished = false - val result = jobScheduler.schedule(buildJobInfo(userInitiated = true, estimatedDownloadBytes)) - if (result == JobScheduler.RESULT_SUCCESS) return + @Synchronized + fun finished(finish: () -> Unit) { + justFinished = true + finish() + } - val fallbackResult = jobScheduler.schedule(buildJobInfo(userInitiated = false, estimatedDownloadBytes)) + @Synchronized + fun schedule(estimatedDownloadBytes: Long, account: String, userInitiated: Boolean = true) { + if (!justFinished && jobScheduler.allPendingJobs.any { + it.id == OFFLINE_DOWNLOAD_JOB_ID && it.extras.getString(ACCOUNT_KEY) == account + }) return + justFinished = false + + if (userInitiated) { + val result = try { + jobScheduler.schedule(buildJobInfo(true, estimatedDownloadBytes, account)) + } catch (_: IllegalStateException) { + JobScheduler.RESULT_FAILURE + } + if (result == JobScheduler.RESULT_SUCCESS) return + } + val fallbackResult = jobScheduler.schedule(buildJobInfo(false, estimatedDownloadBytes, account)) if (fallbackResult != JobScheduler.RESULT_SUCCESS) { throw AuthException("Unable to schedule offline download") } } - private fun buildJobInfo(userInitiated: Boolean, estimatedDownloadBytes: Long): JobInfo { + private fun buildJobInfo(userInitiated: Boolean, estimatedDownloadBytes: Long, account: String): JobInfo { val builder = JobInfo.Builder( OFFLINE_DOWNLOAD_JOB_ID, ComponentName(context, OfflineDownloadJobService::class.java) ) + .setExtras(PersistableBundle().apply { putString(ACCOUNT_KEY, account) }) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) - .setRequiresStorageNotLow(true) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) builder.setRequiresStorageNotLow(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && estimatedDownloadBytes > 0L) { builder.setEstimatedNetworkBytes(estimatedDownloadBytes, 0L) @@ -50,6 +71,7 @@ class OfflineDownloadJobScheduler @Inject constructor( } companion object { + const val ACCOUNT_KEY = "offline_account" const val OFFLINE_DOWNLOAD_JOB_ID = 0x4675_0D1 } } diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadQueueStore.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadQueueStore.kt index 358d33c..6e3325a 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadQueueStore.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineDownloadQueueStore.kt @@ -1,7 +1,14 @@ package cy.hexor.furumi.data.local import cy.hexor.furumi.domain.model.OfflineDownloadQueueState +import cy.hexor.furumi.domain.model.OfflineTransferProgress import cy.hexor.furumi.domain.model.TrackCard +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.launch +import android.util.Log import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -10,40 +17,111 @@ import javax.inject.Singleton @Singleton class OfflineDownloadQueueStore @Inject constructor( - private val libraryStore: OfflineLibraryStore + private val libraryStore: OfflineLibraryStore, + private val accountScope: OfflineAccountScope, + private val scheduler: OfflineDownloadJobScheduler ) { - private val _state = MutableStateFlow(libraryStore.offlineDownloadQueueState()) + private val _state = MutableStateFlow(OfflineDownloadQueueState()) val state: StateFlow = _state.asStateFlow() + init { + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + accountScope.keys.collectLatest { key -> + reset() + if (key != null) accountScope.withAccount(key) { + libraryStore.repairOfflineDownloadState() + refresh() + if (state.value.isDownloading || nextCover() != null) { + try { + scheduler.schedule(0, key, userInitiated = false) + } catch (error: Exception) { + Log.w("OfflineDownloads", "Could not restore download job", error) + } + } + } + } + } + } + @Synchronized fun enqueueDownloads(tracks: List): OfflineDownloadQueueState { - _state.value = libraryStore.enqueueOfflineDownloadTracks(tracks) + publishSnapshot(libraryStore.enqueueOfflineDownloadTracks(tracks)) return _state.value } @Synchronized fun nextPendingDownloadTrack(): TrackCard? { - return libraryStore.nextPendingOfflineDownloadTrack() + val next = libraryStore.nextPendingOfflineDownloadTrack() + if (next == null && state.value.activeTrackIds.isNotEmpty()) refresh() + return next } + @Synchronized + fun nextCover(): TrackCard? = libraryStore.nextOfflineDownloadCover() + @Synchronized fun markRunning(trackId: Long) { - _state.value = libraryStore.markOfflineDownloadRunning(trackId) + libraryStore.markOfflineDownloadRunning(trackId) + publish(state.value.copy(runningTrackId = trackId, transferProgress = null)) + } + + @Synchronized + fun updateTransfer(progress: OfflineTransferProgress) { + val current = state.value + if (current.runningTrackId == progress.trackId) publish(current.copy(transferProgress = progress)) } @Synchronized fun markCompleted(trackId: Long) { - _state.value = libraryStore.markOfflineDownloadCompleted(trackId) + libraryStore.markOfflineDownloadCompleted(trackId) + val current = state.value + if (trackId in current.activeTrackIds) { + publish(current.copy( + runningTrackId = null, transferProgress = null, + activeTrackIds = current.activeTrackIds - trackId, + cachedTrackIds = current.cachedTrackIds + trackId, + completedTrackIds = current.completedTrackIds + trackId + )) + } } @Synchronized fun markFailed(trackId: Long, error: String?) { - _state.value = libraryStore.markOfflineDownloadFailed(trackId, error) + libraryStore.markOfflineDownloadFailed(trackId, error) + val current = state.value + publish(current.copy( + runningTrackId = current.runningTrackId?.takeUnless { it == trackId }, + transferProgress = current.transferProgress?.takeUnless { it.trackId == trackId }, + activeTrackIds = current.activeTrackIds - trackId, + failedTrackIds = current.failedTrackIds + trackId, + errors = current.errors + (trackId to (error ?: "Download failed")) + )) } @Synchronized fun refresh() { - _state.value = libraryStore.offlineDownloadQueueState() + publishSnapshot(libraryStore.offlineDownloadQueueState()) + } + + @Synchronized + fun pauseTransfer(account: String?) { + if (accountScope.matches(account)) _state.value = state.value.copy(runningTrackId = null, transferProgress = null) + } + + private fun publishSnapshot(snapshot: OfflineDownloadQueueState) { + // A persisted RUNNING row is eligible for resume after a stop or process death. + // Only a live worker may identify a track as downloading on screen. + val running = state.value.runningTrackId?.takeIf { it in snapshot.activeTrackIds } + publish(snapshot.copy(runningTrackId = running, transferProgress = state.value.transferProgress?.takeIf { it.trackId == running })) + } + + private fun publish(state: OfflineDownloadQueueState) { + if (accountScope.matches(accountScope.storageKey)) _state.value = state + } + + @Synchronized + fun reset() { + _state.value = OfflineDownloadQueueState() } } diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineFileDownloader.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineFileDownloader.kt new file mode 100644 index 0000000..135f740 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineFileDownloader.kt @@ -0,0 +1,166 @@ +package cy.hexor.furumi.data.local + +import cy.hexor.furumi.data.remote.AccessTokenInterceptor.AuthenticatedAccount +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import javax.inject.Inject +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response + +internal open class OfflineTransferException(message: String, val retryable: Boolean = false) : IOException(message) + +internal class OfflineStorageLimitException : OfflineTransferException( + "Offline storage limit reached. Raise the limit in Library → On device and retry." +) + +internal class OfflineHttpException(status: Int, stage: String = "Audio download") : OfflineTransferException( + offlineHttpFailureMessage(status, stage), + retryable = status == 408 || status == 429 || status in 500..599 +) + +internal const val DOWNLOAD_TIMEOUT_MESSAGE = "The server took too long to send the track. Retry later." + +internal fun offlineHttpFailureMessage(status: Int, stage: String = "Audio download"): String { + val reason = when (status) { + 400 -> "the server rejected the request" + 401 -> "sign in again to download" + 403 -> "access to this track was denied" + 404, 410 -> "the file is no longer available on the server" + 408, 504 -> "the server timed out" + 429 -> "the server is busy, try again later" + in 500..599 -> "the server could not complete the request" + else -> "unexpected server response" + } + return "$stage: $reason (HTTP $status)" +} + +/** Commit only a complete representation. The server can return 206 even when If-Range is stale. */ +class OfflineFileDownloader @Inject constructor(private val client: OkHttpClient) { + suspend fun download( + url: String, + target: File, + resume: Boolean, + account: String? = null, + maxBytes: Long = Long.MAX_VALUE, + onProgress: ((Long, Long?) -> Unit)? = null + ): Long { + target.parentFile?.mkdirs() + val partial = File(target.parentFile, "${target.name}.tmp") + val version = File(target.parentFile, "${target.name}.etag") + val validator = if (resume && partial.isFile && version.isFile) version.readText() else "" + val offset = if (validator.isNotBlank()) partial.length() else 0L + val request = Request.Builder().url(url).header("Accept-Encoding", "identity") + .tag(AuthenticatedAccount::class.java, account?.let(::AuthenticatedAccount)) + if (offset > 0) { + request.header("Range", "bytes=$offset-").header("If-Range", validator) + } + val committed = transfer(request.build()) { response -> + when { + response.code == 416 && offset > 0 -> false + response.code == 206 -> { + val range = PARTIAL_RANGE.matchEntire(response.header("Content-Range").orEmpty()) + val start = range?.groupValues?.get(1)?.toLongOrNull() + val end = range?.groupValues?.get(2)?.toLongOrNull() + val total = range?.groupValues?.get(3)?.toLongOrNull() + if (offset == 0L || start != offset || end == null || total == null || + end < offset || end != total - 1 || response.header("ETag") != validator + ) { + false + } else { + save(response, partial, version, target, offset, total, maxBytes, onProgress) + true + } + } + response.code == 200 -> { + save(response, partial, version, target, 0, response.body?.contentLength() ?: -1, maxBytes, onProgress) + true + } + else -> throw OfflineHttpException(response.code) + } + } + if (!committed) { + version.delete() + partial.delete() + if (offset == 0L) throw IOException("Invalid response to a full download") + return download(url, target, resume = false, account = account, maxBytes = maxBytes, onProgress = onProgress) + } + return target.length() + } + + private suspend fun save( + response: Response, partial: File, version: File, target: File, offset: Long, total: Long, maxBytes: Long, + onProgress: ((Long, Long?) -> Unit)? + ) { + fun checkSize(bytes: Long) { + if (bytes <= maxBytes) return + partial.delete() + version.delete() + throw OfflineStorageLimitException() + } + checkSize(maxOf(total, offset)) + var written = offset + val knownTotal = total.takeIf { it > 0 } + onProgress?.invoke(written, knownTotal) + val body = response.body ?: throw IOException("Empty download response") + FileOutputStream(partial, offset > 0).use { output -> + if (offset == 0L) { + version.delete() + response.header("ETag")?.takeIf { it.startsWith('"') && it.endsWith('"') } + ?.let(version::writeText) + } + val context = currentCoroutineContext() + body.byteStream().use { input -> + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + while (true) { + context.ensureActive() + val count = input.read(buffer) + if (count < 0) break + written += count + checkSize(written) + output.write(buffer, 0, count) + onProgress?.invoke(written, knownTotal) + } + } + } + if (partial.length() == 0L || (total >= 0 && partial.length() != total)) { + throw IOException("Incomplete file (${partial.length()} of $total bytes)") + } + if (!partial.renameTo(target)) throw IOException("Cannot commit downloaded file") + version.delete() + } + + // A peer connection can be silent while the server locates a remote copy. + private val preparationClient by lazy { + client.newBuilder().readTimeout(60, java.util.concurrent.TimeUnit.SECONDS).build() + } + + internal suspend fun transfer( + request: Request, preparingRemoteTrack: Boolean = false, block: suspend (Response) -> T + ): T = coroutineScope { + val call = (if (preparingRemoteTrack) preparationClient else client).newCall(request) + val cancellation = launch(kotlinx.coroutines.Dispatchers.Unconfined, start = CoroutineStart.UNDISPATCHED) { + try { + awaitCancellation() + } finally { + call.cancel() + } + } + try { + call.execute().use { response -> block(response) } + } finally { + cancellation.cancel() + } + } + + private companion object { + val PARTIAL_RANGE = Regex("""bytes (\d+)-(\d+)/(\d+)""") + } +} diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineLibraryStore.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineLibraryStore.kt index bafb24d..855bc4c 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/OfflineLibraryStore.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineLibraryStore.kt @@ -27,10 +27,15 @@ import javax.inject.Singleton @Singleton class OfflineLibraryStore @Inject constructor( - @ApplicationContext context: Context, + @ApplicationContext private val context: Context, + private val accountScope: OfflineAccountScope, moshi: Moshi ) { - private val dbHelper = OfflineDbHelper(context.applicationContext) + private val helpers = mutableMapOf() + private val dbHelper: OfflineDbHelper get() = synchronized(helpers) { + val name = accountScope.databaseName + helpers.getOrPut(name) { OfflineDbHelper(context, name).apply { setWriteAheadLoggingEnabled(true) } } + } private val trackAdapter = moshi.adapter(TrackCard::class.java) fun upsertTracks(tracks: List) { @@ -40,17 +45,54 @@ class OfflineLibraryStore @Inject constructor( } } - fun upsertManifestTracks(tracks: List) { + internal fun catalogVersions(): Map = dbHelper.readableDatabase.query( + TABLE_TRACKS, VERSION_COLUMNS + COL_TRACK_ID, + "in_catalog = 1 AND $COL_TRACK_ID > 0 AND $COL_TRACK_JSON IS NOT NULL", null, null, null, null + ).use { cursor -> + buildMap { while (cursor.moveToNext()) put(cursor.getLong(COL_TRACK_ID), cursor.catalogVersion()) } + } + + fun publishCatalog( + changed: List, + details: List, + removedIds: Set, + playlists: List, + likes: Set, + myArtists: List + ) { + require(changed.map { it.id }.toSet() == details.map { it.id }.toSet()) { "Incomplete track details" } + dbHelper.writableDatabase.transaction { + upsertManifestTracks(changed) + upsertTracks(details) + removedIds.forEach { id -> + execSQL("UPDATE $TABLE_TRACKS SET in_catalog = 0 WHERE $COL_TRACK_ID = ?", arrayOf(id)) + } + replacePlaylists(playlists) + replaceLikedTrackIds(likes + getLikedTrackIds().filter { it < 0 }) + delete("offline_my_artists", null, null) + myArtists.forEachIndexed { index, artist -> + insertOrThrow("offline_my_artists", null, ContentValues().apply { + put("artist_id", artist.id) + put("artist_name", artist.name) + put("image_url", artist.imageUrl) + put("release_count", artist.releaseCount) + put("track_count", artist.trackCount) + put("sort_order", index) + }) + } + } + } + + private fun upsertManifestTracks(tracks: List) { if (tracks.isEmpty()) return dbHelper.writableDatabase.transaction { tracks.forEach { manifest -> val existing = getTrackRecordLocked(this, manifest.id) - val audioChanged = existing?.audioHash != null && - existing.audioHash != manifest.audioHash - val coverChanged = existing?.coverHash != null && - existing.coverHash != manifest.coverHash + val audioChanged = existing?.audioChanged(manifest) == true + val coverChanged = existing?.coverChanged(manifest) == true val values = ContentValues().apply { put(COL_TRACK_ID, manifest.id) + put("in_catalog", 1) put(COL_UPDATED_AT, manifest.updatedAt) put(COL_STREAM_URL, manifest.streamUrl) put(COL_REMOTE_STREAM_URL, manifest.streamUrl) @@ -89,15 +131,31 @@ class OfflineLibraryStore @Inject constructor( put(COL_PLAYLIST_IS_SAVED, playlist.isSaved.toInt()) put(COL_PLAYLIST_KIND, playlist.kind) put(COL_PLAYLIST_TRACK_IDS, detail.tracks.map { it.id }.toJsonArrayString()) + put("track_count", detail.tracks.size) }) + savePreviewTracks(this, playlist.id, detail.tracks.asSequence().map { it.id to it.coverUrl }) } } - fun replacePlaylists(playlists: List) { + private fun replacePlaylists(playlists: List) { dbHelper.writableDatabase.transaction { + val federated = rawQuery( + "SELECT $COL_PLAYLIST_ID, $COL_PLAYLIST_TRACK_IDS FROM $TABLE_PLAYLISTS", null + ).use { cursor -> + buildMap { + while (cursor.moveToNext()) { + val ids = cursor.getString(1).longListFromJson().filter { it < 0 } + if (ids.isNotEmpty()) put(cursor.getLong(0), ids) + } + } + } + val covers = trackCoverUrls(this) delete(TABLE_PLAYLISTS, null, null) + delete("offline_playlist_previews", null, null) playlists.forEach { playlist -> - insert(TABLE_PLAYLISTS, null, ContentValues().apply { + val ids = playlist.trackIds + federated[playlist.id].orEmpty() + savePreviewTracks(this, playlist.id, ids.asSequence().map { it to covers[it] }) + insertOrThrow(TABLE_PLAYLISTS, null, ContentValues().apply { put(COL_PLAYLIST_ID, playlist.id) put(COL_PLAYLIST_TITLE, playlist.title) put(COL_PLAYLIST_DESCRIPTION, playlist.description) @@ -107,7 +165,8 @@ class OfflineLibraryStore @Inject constructor( put(COL_PLAYLIST_IS_PUBLIC, playlist.isPublic.toInt()) put(COL_PLAYLIST_IS_SAVED, playlist.isSaved.toInt()) put(COL_PLAYLIST_KIND, playlist.kind) - put(COL_PLAYLIST_TRACK_IDS, playlist.trackIds.toJsonArrayString()) + put(COL_PLAYLIST_TRACK_IDS, ids.toJsonArrayString()) + put("track_count", ids.size) }) } } @@ -117,13 +176,34 @@ class OfflineLibraryStore @Inject constructor( dbHelper.writableDatabase.transaction { delete(TABLE_LIKES, null, null) trackIds.forEach { trackId -> - insert(TABLE_LIKES, null, ContentValues().apply { + insertOrThrow(TABLE_LIKES, null, ContentValues().apply { put(COL_LIKE_TRACK_ID, trackId) }) } } } + fun setTrackLiked(id: Long, liked: Boolean, track: TrackCard?) { + dbHelper.writableDatabase.transaction { + if (track != null) upsertTrackLocked(this, track) + if (liked) { + insertWithOnConflict(TABLE_LIKES, null, ContentValues().apply { put(COL_LIKE_TRACK_ID, id) }, + SQLiteDatabase.CONFLICT_IGNORE) + } else { + delete(TABLE_LIKES, "$COL_LIKE_TRACK_ID = ?", arrayOf(id.toString())) + } + val cached = query(TABLE_PLAYLISTS, arrayOf(COL_PLAYLIST_TRACK_IDS), "$COL_PLAYLIST_ID = -1", + null, null, null, null).use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0).longListFromJson() else null + } + if (cached != null) { + val members = if (liked) (listOf(id) + cached).distinct() else cached - id + update(TABLE_PLAYLISTS, ContentValues().apply { put(COL_PLAYLIST_TRACK_IDS, members.toJsonArrayString()) }, + "$COL_PLAYLIST_ID = -1", null) + } + } + } + fun getLikedTrackIds(): Set { return dbHelper.readableDatabase.query( TABLE_LIKES, @@ -140,10 +220,37 @@ class OfflineLibraryStore @Inject constructor( } } + private fun trackCoverUrls(db: SQLiteDatabase): Map = db.rawQuery( + "SELECT $COL_TRACK_ID, $COL_COVER_URL FROM $TABLE_TRACKS WHERE $COL_COVER_URL IS NOT NULL", null + ).use { cursor -> + buildMap { while (cursor.moveToNext()) put(cursor.getLong(0), cursor.getString(1)) } + } + + private fun savePreviewTracks(db: SQLiteDatabase, playlistId: Long, tracks: Sequence>) { + db.delete("offline_playlist_previews", "playlist_id = ?", arrayOf(playlistId.toString())) + tracks.filter { it.second != null }.distinctBy { it.second }.take(4).forEachIndexed { index, (id, _) -> + db.execSQL("INSERT INTO offline_playlist_previews VALUES (?, ?, ?)", arrayOf(playlistId, index.toLong(), id)) + } + } + fun getPlaylists(): List { - return dbHelper.readableDatabase.query( + val db = dbHelper.readableDatabase + val covers = mutableMapOf>() + db.rawQuery(""" + SELECT p.playlist_id, t.$COL_LOCAL_COVER_PATH, t.$COL_COVER_URL, t.$COL_COVER_STATUS + FROM offline_playlist_previews p JOIN $TABLE_TRACKS t ON t.$COL_TRACK_ID = p.track_id + ORDER BY p.playlist_id, p.position + """.trimIndent(), null).use { cursor -> + while (cursor.moveToNext()) { + val local = cursor.getString(1)?.takeIf { cursor.getString(3) == STATUS_READY && File(it).isFile } + val url = local?.let { Uri.fromFile(File(it)).toString() } ?: cursor.getString(2) + if (url != null) covers.getOrPut(cursor.getLong(0)) { mutableListOf() }.add(url) + } + } + return db.query( TABLE_PLAYLISTS, - null, + arrayOf(COL_PLAYLIST_ID, COL_PLAYLIST_TITLE, COL_PLAYLIST_IS_OWN, COL_PLAYLIST_OWNER_NAME, + COL_PLAYLIST_IS_PUBLIC, COL_PLAYLIST_IS_SAVED, COL_PLAYLIST_KIND, "track_count"), null, null, null, @@ -152,8 +259,8 @@ class OfflineLibraryStore @Inject constructor( ).useCursor { cursor -> buildList { while (cursor.moveToNext()) { - val trackIds = cursor.getString(COL_PLAYLIST_TRACK_IDS).longListFromJson() - add(cursor.toPlaylistCard(trackIds.size)) + val card = cursor.toPlaylistCard(cursor.getInt("track_count")) + add(card.copy(coverUrls = covers[card.id].orEmpty())) } } } @@ -189,7 +296,7 @@ class OfflineLibraryStore @Inject constructor( val tracks = dbHelper.readableDatabase.query( TABLE_TRACKS, null, - "$COL_TITLE_SORT LIKE ? OR lower($COL_RELEASE_TITLE) LIKE ? OR $COL_ARTISTS_SORT LIKE ?", + "in_catalog = 1 AND ($COL_TITLE_SORT LIKE ? OR lower($COL_RELEASE_TITLE) LIKE ? OR $COL_ARTISTS_SORT LIKE ?)", arrayOf(pattern, pattern, pattern), null, null, @@ -220,61 +327,71 @@ class OfflineLibraryStore @Inject constructor( } ) } - return SearchResults( - artistMatches = artistMatches, - trackArtists = artistMatches, - tracks = tracks - ) - } - - fun getArtists(page: Int, limit: Int): ArtistPage { - val tracks = getAllTracks(preferLocalMedia = true) - val artists = tracks - .flatMap { track -> - track.artistRefs.map { ArtistSeed(it) }.ifEmpty { - track.artists.map { ArtistSeed(it) } + val releases = dbHelper.readableDatabase.rawQuery( + """SELECT $COL_RELEASE_ID, $COL_RELEASE_TITLE, MAX($COL_RELEASE_YEAR), COUNT(*), + MAX($COL_COVER_URL), MAX(CASE WHEN $COL_COVER_STATUS = ? THEN $COL_LOCAL_COVER_PATH END) + FROM $TABLE_TRACKS + WHERE in_catalog = 1 AND $COL_RELEASE_ID IS NOT NULL AND lower($COL_RELEASE_TITLE) LIKE ? + GROUP BY $COL_RELEASE_ID ORDER BY $COL_RELEASE_TITLE COLLATE NOCASE, $COL_RELEASE_ID LIMIT ?""", + arrayOf(STATUS_READY, pattern, limit.toString()) + ).useCursor { cursor -> + buildList { + while (cursor.moveToNext()) { + val localCover = cursor.getString(5)?.let(::File)?.takeIf { it.isFile } + add(ReleaseCard(cursor.getLong(0), cursor.getString(1), null, + if (cursor.isNull(2)) null else cursor.getInt(2), + localCover?.let { Uri.fromFile(it).toString() } ?: cursor.getString(4), cursor.getInt(3))) } } - .groupBy { it.artistIdOrName } - .map { (_, seeds) -> - val seed = seeds.first() - ArtistCard( - id = seed.artistId, - name = seed.artistName, - imageUrl = null, - releaseCount = tracks - .filter { track -> - track.artistRefs.any { it.id == seed.artistId } || - track.artists.any { it.equals(seed.artistName, ignoreCase = true) } - } - .mapNotNull { it.releaseId ?: it.releaseTitle?.hashCode()?.toLong() } - .distinct() - .size, - trackCount = seeds.size - ) - } - .sortedBy { it.name.lowercase() } + } + return SearchResults(artistMatches, artistMatches, tracks, releases) + } + + fun getArtists(page: Int, limit: Int, mine: Boolean): ArtistPage { val safePage = page.coerceAtLeast(1) - val from = ((safePage - 1) * limit).coerceAtMost(artists.size) - val to = (from + limit).coerceAtMost(artists.size) - return ArtistPage( - items = artists.subList(from, to), - total = artists.size.toLong(), - page = safePage, - perPage = limit, - hasMore = to < artists.size - ) + val pageSize = limit.coerceIn(1, 200) + val offset = (safePage - 1L) * pageSize + val cards = if (mine) { + "SELECT * FROM offline_my_artists" + } else { + """ + SELECT a.artist_id, MIN(a.artist_name) AS artist_name, NULL AS image_url, + COUNT(DISTINCT a.release_id) AS release_count, COUNT(*) AS track_count, + MIN(a.artist_name) COLLATE NOCASE AS sort_order + FROM offline_track_artists a JOIN $TABLE_TRACKS t ON t.$COL_TRACK_ID = a.track_id + WHERE t.in_catalog = 1 + GROUP BY a.artist_id + """.trimIndent() + } + val sql = """ + WITH cards AS ($cards) + SELECT p.artist_id, p.artist_name, p.image_url, p.release_count, p.track_count, n.total + FROM (SELECT COUNT(*) AS total FROM cards) n + LEFT JOIN (SELECT * FROM cards ORDER BY sort_order, artist_id LIMIT ? OFFSET ?) p ON 1=1 + ORDER BY p.sort_order, p.artist_id + """.trimIndent() + return dbHelper.readableDatabase.rawQuery(sql, arrayOf(pageSize.toString(), offset.toString())).use { cursor -> + var total = 0L + val items = buildList { + while (cursor.moveToNext()) { + total = cursor.getLong(5) + if (!cursor.isNull(0)) add(ArtistCard( + cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getInt(3), cursor.getInt(4) + )) + } + } + ArtistPage(items, total, safePage, pageSize, offset + items.size < total) + } } fun getArtistDetail(artistId: Long): ArtistDetail? { - val tracks = getAllTracks(preferLocalMedia = true).filter { track -> - track.artistRefs.any { it.id == artistId } || - (artistId < 0 && track.artists.any { it.hashCode().toLong() == -artistId }) - } + val tracks = queryCatalogTracks( + "$COL_TRACK_ID IN (SELECT track_id FROM offline_track_artists WHERE artist_id = ?)", artistId + ) if (tracks.isEmpty()) return null val name = tracks.firstNotNullOfOrNull { track -> - track.artistRefs.firstOrNull { it.id == artistId }?.name - } ?: tracks.first().artists.firstOrNull().orEmpty() + (track.artistRefs + track.featuredArtistRefs).firstOrNull { it.id == artistId }?.name + } ?: tracks.first().artists.firstOrNull { -it.hashCode().toLong() == artistId }.orEmpty() val releases = tracks .groupBy { it.releaseId ?: it.releaseTitle?.hashCode()?.toLong() ?: it.id } .map { (releaseId, releaseTracks) -> @@ -302,9 +419,7 @@ class OfflineLibraryStore @Inject constructor( } fun getReleaseDetail(releaseId: Long): ReleaseDetail? { - val tracks = getAllTracks(preferLocalMedia = true).filter { track -> - track.releaseId == releaseId - } + val tracks = queryCatalogTracks("$COL_RELEASE_ID = ?", releaseId) if (tracks.isEmpty()) return null val release = ReleaseCard( id = releaseId, @@ -329,6 +444,19 @@ class OfflineLibraryStore @Inject constructor( return ReleaseDetail(release = release, artists = artists, tracks = tracks) } + fun getDownloadedTracks(ids: Set?): List { + if (ids != null) return getTracksByIds(ids.toList()).filter { it.isAudioCached } + return dbHelper.readableDatabase.query( + TABLE_TRACKS, null, "$COL_AUDIO_STATUS = ?", arrayOf(STATUS_READY), null, null, COL_TITLE_SORT + ).useCursor { cursor -> + buildList { + while (cursor.moveToNext()) { + cursor.toTrackCard(preferLocalMedia = true)?.takeIf { it.isAudioCached }?.let(::add) + } + } + } + } + fun getTrack(trackId: Long, preferLocalMedia: Boolean = true): TrackCard? { return dbHelper.readableDatabase.query( TABLE_TRACKS, @@ -346,7 +474,18 @@ class OfflineLibraryStore @Inject constructor( fun getTracksByIds(trackIds: List, preferLocalMedia: Boolean = true): List { if (trackIds.isEmpty()) return emptyList() - return trackIds.mapNotNull { getTrack(it, preferLocalMedia) } + val cards = buildMap { + for (ids in trackIds.distinct().chunked(500)) { + val placeholders = ids.joinToString(",") { "?" } + dbHelper.readableDatabase.rawQuery( + "SELECT * FROM $TABLE_TRACKS WHERE $COL_TRACK_ID IN ($placeholders)", + ids.map(Long::toString).toTypedArray() + ).use { cursor -> + while (cursor.moveToNext()) cursor.toTrackCard(preferLocalMedia)?.let { put(it.id, it) } + } + } + } + return trackIds.mapNotNull(cards::get) } fun markTrackAccessed(trackId: Long) { @@ -418,20 +557,23 @@ class OfflineLibraryStore @Inject constructor( } fun clearCachedMedia() { - dbHelper.writableDatabase.update( - TABLE_TRACKS, - ContentValues().apply { - putNull(COL_LOCAL_AUDIO_PATH) - put(COL_AUDIO_STATUS, STATUS_NONE) - put(COL_CACHED_AUDIO_BYTES, 0L) - put(COL_AUDIO_PINNED, 0) - putNull(COL_LOCAL_COVER_PATH) - put(COL_COVER_STATUS, STATUS_NONE) - put(COL_CACHED_COVER_BYTES, 0L) - }, - null, - null - ) + dbHelper.writableDatabase.transaction { + delete(TABLE_DOWNLOAD_QUEUE, null, null) + update( + TABLE_TRACKS, + ContentValues().apply { + putNull(COL_LOCAL_AUDIO_PATH) + put(COL_AUDIO_STATUS, STATUS_NONE) + put(COL_CACHED_AUDIO_BYTES, 0L) + put(COL_AUDIO_PINNED, 0) + putNull(COL_LOCAL_COVER_PATH) + put(COL_COVER_STATUS, STATUS_NONE) + put(COL_CACHED_COVER_BYTES, 0L) + }, + null, + null + ) + } } fun cachedAudioEntriesForEviction(): List { @@ -441,6 +583,8 @@ class OfflineLibraryStore @Inject constructor( COL_TRACK_ID, COL_LOCAL_AUDIO_PATH, COL_CACHED_AUDIO_BYTES, + COL_LOCAL_COVER_PATH, + COL_CACHED_COVER_BYTES, COL_LAST_ACCESSED_AT, COL_PLAY_COUNT ), @@ -457,6 +601,8 @@ class OfflineLibraryStore @Inject constructor( trackId = cursor.getLong(COL_TRACK_ID), path = cursor.getString(COL_LOCAL_AUDIO_PATH), sizeBytes = cursor.getLong(COL_CACHED_AUDIO_BYTES), + coverPath = cursor.getStringOrNull(COL_LOCAL_COVER_PATH), + coverBytes = cursor.getLong(COL_CACHED_COVER_BYTES), lastAccessedAtMs = cursor.getLong(COL_LAST_ACCESSED_AT), playCount = cursor.getInt(COL_PLAY_COUNT) ) @@ -511,17 +657,47 @@ class OfflineLibraryStore @Inject constructor( } } + fun repairOfflineDownloadState() { + dbHelper.writableDatabase.transaction { + query(TABLE_TRACKS, arrayOf(COL_TRACK_ID, COL_LOCAL_AUDIO_PATH, COL_CACHED_AUDIO_BYTES), + "$COL_AUDIO_STATUS = ?", arrayOf(STATUS_READY), null, null, null).useCursor { cursor -> + while (cursor.moveToNext()) { + val path = cursor.getString(1)?.let(::File) + val recorded = cursor.getLong(2) + if (path == null || !path.isFile || path.length() == 0L || (recorded > 0L && path.length() != recorded)) { + markAudioRemoved(cursor.getLong(0)) + } else if (recorded == 0L) { + markAudioCached(cursor.getLong(0), path.absolutePath, path.length()) + } + } + } + // Older workers could report failed after the audio had already been pinned. + execSQL("UPDATE $TABLE_DOWNLOAD_QUEUE SET $COL_DOWNLOAD_STATUS = ?, $COL_DOWNLOAD_ERROR = NULL " + + "WHERE $COL_DOWNLOAD_STATUS = ? AND $COL_DOWNLOAD_TRACK_ID IN " + + "(SELECT $COL_TRACK_ID FROM $TABLE_TRACKS WHERE $COL_AUDIO_STATUS = ? AND $COL_AUDIO_PINNED = 1)", + arrayOf(STATUS_READY, STATUS_FAILED, STATUS_READY)) + } + } + fun enqueueOfflineDownloadTracks(tracks: List): OfflineDownloadQueueState { if (tracks.isEmpty()) return offlineDownloadQueueState() val now = System.currentTimeMillis() dbHelper.writableDatabase.transaction { + val current = offlineDownloadQueueState() + // Enqueues that overlap an active transfer or retry a batch keep its denominator. + val continuing = current.activeTrackIds.isNotEmpty() || tracks.any { it.id in current.failedTrackIds } + val batch = if (continuing) current.batchStartedAt ?: now else now + if (!continuing) delete(TABLE_DOWNLOAD_QUEUE, "$COL_DOWNLOAD_STATUS = ?", arrayOf(STATUS_READY)) tracks.distinctBy { it.id }.forEach { track -> + if (track.id in current.activeTrackIds) return@forEach upsertTrackLocked(this, track) + val ready = track.id in current.cachedTrackIds + if (ready) markAudioPinned(track.id, true) insertOrUpdate(TABLE_DOWNLOAD_QUEUE, COL_DOWNLOAD_TRACK_ID, track.id, ContentValues().apply { put(COL_DOWNLOAD_TRACK_ID, track.id) - put(COL_DOWNLOAD_STATUS, STATUS_PENDING) + put(COL_DOWNLOAD_STATUS, if (ready) STATUS_READY else STATUS_PENDING) putNull(COL_DOWNLOAD_ERROR) - put(COL_DOWNLOAD_ENQUEUED_AT, now) + put(COL_DOWNLOAD_ENQUEUED_AT, batch) put(COL_DOWNLOAD_UPDATED_AT, now) }) } @@ -529,84 +705,101 @@ class OfflineLibraryStore @Inject constructor( return offlineDownloadQueueState() } + fun hasPendingOfflineDownload(trackId: Long): Boolean = dbHelper.readableDatabase.rawQuery( + "SELECT 1 FROM $TABLE_DOWNLOAD_QUEUE WHERE $COL_DOWNLOAD_TRACK_ID = ? " + + "AND $COL_DOWNLOAD_STATUS IN (?, ?)", + arrayOf(trackId.toString(), STATUS_PENDING, STATUS_RUNNING) + ).use { it.moveToFirst() } + fun nextPendingOfflineDownloadTrack(): TrackCard? { - val trackIds = dbHelper.readableDatabase.query( - TABLE_DOWNLOAD_QUEUE, - arrayOf(COL_DOWNLOAD_TRACK_ID), - "$COL_DOWNLOAD_STATUS IN (?, ?)", - arrayOf(STATUS_PENDING, STATUS_RUNNING), - null, - null, - "$COL_DOWNLOAD_ENQUEUED_AT ASC" - ).useCursor { cursor -> - buildList { - while (cursor.moveToNext()) add(cursor.getLong(COL_DOWNLOAD_TRACK_ID)) + while (true) { + val unreadable = dbHelper.readableDatabase.rawQuery( + "SELECT t.* FROM $TABLE_DOWNLOAD_QUEUE q JOIN $TABLE_TRACKS t " + + "ON t.$COL_TRACK_ID = q.$COL_DOWNLOAD_TRACK_ID " + + "WHERE q.$COL_DOWNLOAD_STATUS IN (?, ?) ORDER BY q.$COL_DOWNLOAD_ENQUEUED_AT, q.rowid LIMIT 1", + arrayOf(STATUS_PENDING, STATUS_RUNNING) + ).use { cursor -> + if (!cursor.moveToFirst()) return null + cursor.toTrackCard(false)?.let { return it } + cursor.getLong(COL_TRACK_ID) } + markOfflineDownloadFailed(unreadable, "Audio: unreadable track metadata") } - - for (trackId in trackIds) { - getTrack(trackId, preferLocalMedia = false)?.let { return it } - markOfflineDownloadCompleted(trackId) - } - return null } - fun markOfflineDownloadRunning(trackId: Long): OfflineDownloadQueueState { - return updateOfflineDownloadStatus(trackId, STATUS_RUNNING, error = null) + fun nextOfflineDownloadCover(): TrackCard? = dbHelper.readableDatabase.rawQuery( + "SELECT t.* FROM $TABLE_DOWNLOAD_QUEUE q JOIN $TABLE_TRACKS t ON t.$COL_TRACK_ID = q.$COL_DOWNLOAD_TRACK_ID " + + "WHERE q.$COL_DOWNLOAD_STATUS = ? AND t.$COL_AUDIO_STATUS = ? AND t.$COL_COVER_STATUS = ? " + + "AND t.$COL_REMOTE_COVER_URL IS NOT NULL AND t.$COL_REMOTE_COVER_URL <> '' ORDER BY q.rowid LIMIT 1", + arrayOf(STATUS_READY, STATUS_READY, STATUS_NONE) + ).useCursor { cursor -> if (cursor.moveToFirst()) cursor.toTrackCard(false) else null } + + fun markOfflineCoverFailed(trackId: Long) { + dbHelper.writableDatabase.update(TABLE_TRACKS, ContentValues().apply { put(COL_COVER_STATUS, STATUS_FAILED) }, + "$COL_TRACK_ID = ? AND $COL_COVER_STATUS = ?", arrayOf(trackId.toString(), STATUS_NONE)) } - fun markOfflineDownloadCompleted(trackId: Long): OfflineDownloadQueueState { - dbHelper.writableDatabase.delete( - TABLE_DOWNLOAD_QUEUE, - "$COL_DOWNLOAD_TRACK_ID = ?", - arrayOf(trackId.toString()) - ) - return offlineDownloadQueueState() - } + fun markOfflineDownloadRunning(trackId: Long) = updateOfflineDownloadStatus(trackId, STATUS_RUNNING, null) - fun markOfflineDownloadFailed(trackId: Long, error: String?): OfflineDownloadQueueState { - return updateOfflineDownloadStatus(trackId, STATUS_FAILED, error) - } + fun markOfflineDownloadCompleted(trackId: Long) = updateOfflineDownloadStatus(trackId, STATUS_READY, null) + + fun markOfflineDownloadFailed(trackId: Long, error: String?) = updateOfflineDownloadStatus(trackId, STATUS_FAILED, error) fun offlineDownloadQueueState(): OfflineDownloadQueueState { - return dbHelper.readableDatabase.query( - TABLE_DOWNLOAD_QUEUE, - arrayOf(COL_DOWNLOAD_TRACK_ID, COL_DOWNLOAD_STATUS, COL_DOWNLOAD_ERROR), - null, - null, - null, - null, - "$COL_DOWNLOAD_UPDATED_AT DESC" + val db = dbHelper.readableDatabase + val cached = db.query( + TABLE_TRACKS, arrayOf(COL_TRACK_ID), "$COL_AUDIO_STATUS = ?", arrayOf(STATUS_READY), null, null, null + ).useCursor { cursor -> buildSet { while (cursor.moveToNext()) add(cursor.getLong(0)) } } + val active = mutableSetOf() + val completed = mutableSetOf() + val errors = mutableMapOf() + val titles = mutableMapOf() + val batchIds = mutableSetOf() + var running: Long? = null + var batch: Long? = null + db.rawQuery( + "SELECT q.$COL_DOWNLOAD_TRACK_ID, q.$COL_DOWNLOAD_STATUS, q.$COL_DOWNLOAD_ERROR, t.$COL_TITLE, " + + "q.$COL_DOWNLOAD_ENQUEUED_AT FROM $TABLE_DOWNLOAD_QUEUE q JOIN $TABLE_TRACKS t " + + "ON t.$COL_TRACK_ID = q.$COL_DOWNLOAD_TRACK_ID ORDER BY q.$COL_DOWNLOAD_ENQUEUED_AT DESC, q.rowid", + null ).useCursor { cursor -> - val activeTrackIds = mutableSetOf() - val failedTrackIds = mutableSetOf() - var lastError: String? = null while (cursor.moveToNext()) { - val trackId = cursor.getLong(COL_DOWNLOAD_TRACK_ID) - when (cursor.getString(COL_DOWNLOAD_STATUS)) { - STATUS_PENDING, - STATUS_RUNNING -> activeTrackIds.add(trackId) + val id = cursor.getLong(0) + val status = cursor.getString(1) + if (status == STATUS_READY && id !in cached) continue + val enqueued = cursor.getLong(4) + if (batch == null) batch = enqueued + if (batch == enqueued) batchIds.add(id) + titles[id] = cursor.getString(3) ?: id.toString() + when (status) { + STATUS_RUNNING -> { running = id; active.add(id) } + STATUS_PENDING -> active.add(id) + STATUS_READY -> completed.add(id) STATUS_FAILED -> { - failedTrackIds.add(trackId) - if (lastError == null) { - lastError = cursor.getStringOrNull(COL_DOWNLOAD_ERROR) + val reason = cursor.getString(2) ?: "Download failed" + val legacy = reason.removePrefix("Audio: ") + errors[id] = when { + legacy.equals("timeout", ignoreCase = true) -> DOWNLOAD_TIMEOUT_MESSAGE + legacy.startsWith("HTTP ") -> legacy.removePrefix("HTTP ").toIntOrNull() + ?.let { offlineHttpFailureMessage(it) } ?: reason + else -> reason } } } } - OfflineDownloadQueueState( - activeTrackIds = activeTrackIds, - failedTrackIds = failedTrackIds, - lastError = lastError - ) } + return OfflineDownloadQueueState( + activeTrackIds = active, failedTrackIds = errors.keys, completedTrackIds = completed, + runningTrackId = running, trackTitles = titles, errors = errors, cachedTrackIds = cached, + batchStartedAt = batch, batchTrackIds = batchIds + ) } private fun updateOfflineDownloadStatus( trackId: Long, status: String, error: String? - ): OfflineDownloadQueueState { + ) { dbHelper.writableDatabase.update( TABLE_DOWNLOAD_QUEUE, ContentValues().apply { @@ -621,21 +814,20 @@ class OfflineLibraryStore @Inject constructor( "$COL_DOWNLOAD_TRACK_ID = ?", arrayOf(trackId.toString()) ) - return offlineDownloadQueueState() } - private fun getAllTracks(preferLocalMedia: Boolean): List { + private fun queryCatalogTracks(selection: String, id: Long): List { return dbHelper.readableDatabase.query( TABLE_TRACKS, null, - "$COL_TRACK_JSON IS NOT NULL", - null, + "in_catalog = 1 AND ($selection)", + arrayOf(id.toString()), null, null, "$COL_TITLE_SORT" ).useCursor { cursor -> buildList { - while (cursor.moveToNext()) cursor.toTrackCard(preferLocalMedia)?.let(::add) + while (cursor.moveToNext()) cursor.toTrackCard(preferLocalMedia = true)?.let(::add) } } } @@ -663,14 +855,14 @@ class OfflineLibraryStore @Inject constructor( put(COL_STREAM_URL, track.remoteStreamUrl.ifBlank { track.streamUrl }) put(COL_REMOTE_STREAM_URL, track.remoteStreamUrl.ifBlank { track.streamUrl }) put(COL_TRACK_JSON, trackAdapter.toJson(storedTrack)) - put(COL_UPDATED_AT, track.metadataUpdatedAt) - put(COL_AUDIO_HASH, track.audioHash) - put(COL_AUDIO_SIZE_BYTES, track.audioSizeBytes) - put(COL_AUDIO_MIME_TYPE, track.audioMimeType) - put(COL_AUDIO_UPDATED_AT, track.audioUpdatedAt) - put(COL_COVER_HASH, track.coverHash) - put(COL_COVER_UPDATED_AT, track.coverUpdatedAt) if (existing == null) { + put(COL_UPDATED_AT, track.metadataUpdatedAt) + put(COL_AUDIO_HASH, track.audioHash) + put(COL_AUDIO_SIZE_BYTES, track.audioSizeBytes) + put(COL_AUDIO_MIME_TYPE, track.audioMimeType) + put(COL_AUDIO_UPDATED_AT, track.audioUpdatedAt) + put(COL_COVER_HASH, track.coverHash) + put(COL_COVER_UPDATED_AT, track.coverUpdatedAt) put(COL_AUDIO_STATUS, STATUS_NONE) put(COL_COVER_STATUS, STATUS_NONE) put(COL_CACHED_AUDIO_BYTES, 0L) @@ -681,30 +873,30 @@ class OfflineLibraryStore @Inject constructor( } } db.insertOrUpdate(TABLE_TRACKS, COL_TRACK_ID, track.id, values) + indexTrackArtists(db, track) } - private fun getTrackRecordLocked(db: SQLiteDatabase, trackId: Long): OfflineTrackRecord? { - return db.query( - TABLE_TRACKS, - arrayOf(COL_AUDIO_HASH, COL_COVER_HASH), - "$COL_TRACK_ID = ?", - arrayOf(trackId.toString()), - null, - null, - null, - "1" - ).useCursor { cursor -> - if (cursor.moveToFirst()) { - OfflineTrackRecord( - audioHash = cursor.getStringOrNull(COL_AUDIO_HASH), - coverHash = cursor.getStringOrNull(COL_COVER_HASH) - ) - } else { - null - } + private fun indexTrackArtists(db: SQLiteDatabase, track: TrackCard) { + db.delete("offline_track_artists", "track_id = ?", arrayOf(track.id.toString())) + val artists = (track.artistRefs + track.featuredArtistRefs).map { ArtistSeed(it) } + .ifEmpty { track.artists.map { ArtistSeed(it) } } + artists.distinctBy { it.artistId }.forEach { artist -> + db.execSQL( + "INSERT INTO offline_track_artists(track_id, artist_id, artist_name, release_id) VALUES (?, ?, ?, ?)", + arrayOf(track.id, artist.artistId, artist.artistName, track.releaseId ?: track.releaseTitle?.hashCode()?.toLong()) + ) } } + private fun getTrackRecordLocked(db: SQLiteDatabase, trackId: Long): OfflineCatalogVersion? = + db.query(TABLE_TRACKS, VERSION_COLUMNS, "$COL_TRACK_ID = ?", arrayOf(trackId.toString()), + null, null, null, "1").use { if (it.moveToFirst()) it.catalogVersion() else null } + + private fun Cursor.catalogVersion() = OfflineCatalogVersion( + getStringOrNull(COL_UPDATED_AT), getStringOrNull(COL_AUDIO_HASH), getStringOrNull(COL_COVER_HASH), + getStringOrNull(COL_AUDIO_UPDATED_AT), getStringOrNull(COL_COVER_UPDATED_AT), getLongOrNull(COL_AUDIO_SIZE_BYTES) + ) + private fun updateMediaColumns( trackId: Long, localPathColumn: String, @@ -775,9 +967,9 @@ class OfflineLibraryStore @Inject constructor( ) } - private class OfflineDbHelper(context: Context) : SQLiteOpenHelper( + private inner class OfflineDbHelper(context: Context, name: String) : SQLiteOpenHelper( context, - DB_NAME, + name, null, DB_VERSION ) { @@ -845,6 +1037,27 @@ class OfflineLibraryStore @Inject constructor( """.trimIndent() ) createDownloadQueueTable(db) + createCatalogIndex(db) + } + + private fun createCatalogIndex(db: SQLiteDatabase) { + db.execSQL("ALTER TABLE $TABLE_PLAYLISTS ADD COLUMN track_count INTEGER NOT NULL DEFAULT 0") + db.execSQL("CREATE TABLE offline_playlist_previews(playlist_id INTEGER, position INTEGER, track_id INTEGER, PRIMARY KEY(playlist_id, position))") + db.execSQL("ALTER TABLE $TABLE_TRACKS ADD COLUMN in_catalog INTEGER NOT NULL DEFAULT 1") + db.execSQL(""" + CREATE TABLE offline_track_artists ( + track_id INTEGER NOT NULL, artist_id INTEGER NOT NULL, artist_name TEXT NOT NULL, + release_id INTEGER, PRIMARY KEY(track_id, artist_id) + ) + """.trimIndent()) + db.execSQL("CREATE INDEX idx_offline_track_artist ON offline_track_artists(artist_id, release_id, track_id)") + db.execSQL(""" + CREATE TABLE offline_my_artists ( + artist_id INTEGER PRIMARY KEY, artist_name TEXT NOT NULL, image_url TEXT, + release_count INTEGER NOT NULL, track_count INTEGER NOT NULL, sort_order INTEGER NOT NULL + ) + """.trimIndent()) + db.execSQL("CREATE INDEX idx_offline_my_artists_order ON offline_my_artists(sort_order)") } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { @@ -855,6 +1068,25 @@ class OfflineLibraryStore @Inject constructor( if (oldVersion < 3) { createDownloadQueueTable(db) } + if (oldVersion < 4) { + createCatalogIndex(db) + val covers = trackCoverUrls(db) + db.rawQuery("SELECT $COL_PLAYLIST_ID, $COL_PLAYLIST_TRACK_IDS FROM $TABLE_PLAYLISTS", null).use { cursor -> + while (cursor.moveToNext()) { + val playlistId = cursor.getLong(0) + val ids = cursor.getString(1).longListFromJson() + db.execSQL("UPDATE $TABLE_PLAYLISTS SET track_count = ? WHERE $COL_PLAYLIST_ID = ?", arrayOf(ids.size.toLong(), playlistId)) + savePreviewTracks(db, playlistId, ids.asSequence().map { it to covers[it] }) + } + } + // Earlier syncs could publish new timestamps before fetching the corresponding cards. + db.execSQL("UPDATE $TABLE_TRACKS SET $COL_UPDATED_AT = NULL") + db.rawQuery("SELECT $COL_TRACK_JSON FROM $TABLE_TRACKS WHERE $COL_TRACK_JSON IS NOT NULL", null).use { cursor -> + while (cursor.moveToNext()) { + trackAdapter.fromJson(cursor.getString(0))?.let { indexTrackArtists(db, it) } + } + } + } } private fun createDownloadQueueTable(db: SQLiteDatabase) { @@ -874,8 +1106,7 @@ class OfflineLibraryStore @Inject constructor( } private companion object { - const val DB_NAME = "furumi_offline.db" - const val DB_VERSION = 3 + const val DB_VERSION = 4 const val TABLE_TRACKS = "offline_tracks" const val TABLE_PLAYLISTS = "offline_playlists" @@ -931,6 +1162,9 @@ class OfflineLibraryStore @Inject constructor( const val COL_DOWNLOAD_ENQUEUED_AT = "enqueued_at" const val COL_DOWNLOAD_UPDATED_AT = "updated_at" + val VERSION_COLUMNS = arrayOf(COL_UPDATED_AT, COL_AUDIO_HASH, COL_COVER_HASH, COL_AUDIO_UPDATED_AT, + COL_COVER_UPDATED_AT, COL_AUDIO_SIZE_BYTES) + const val STATUS_NONE = "none" const val STATUS_READY = "ready" const val STATUS_STALE = "stale" @@ -945,7 +1179,9 @@ data class OfflineCachedMediaEntry( val path: String, val sizeBytes: Long, val lastAccessedAtMs: Long, - val playCount: Int + val playCount: Int, + val coverPath: String?, + val coverBytes: Long ) data class OfflineStaleMediaPath( @@ -959,10 +1195,29 @@ data class OfflineStorageStats( val cachedTrackCount: Int ) -private data class OfflineTrackRecord( +internal data class OfflineCatalogVersion( + val updatedAt: String?, val audioHash: String?, - val coverHash: String? -) + val coverHash: String?, + val audioUpdatedAt: String?, + val coverUpdatedAt: String?, + val audioBytes: Long? +) { + fun matches(remote: OfflineManifestTrackResponse): Boolean = + updatedAt != null && updatedAt == remote.updatedAt && + audioHash == remote.audioHash && coverHash == remote.coverHash && + audioUpdatedAt == remote.audioUpdatedAt && coverUpdatedAt == remote.coverUpdatedAt && + audioBytes == remote.audioSizeBytes + + fun audioChanged(remote: OfflineManifestTrackResponse): Boolean = + if (audioHash != null && remote.audioHash != null) audioHash != remote.audioHash + else (audioUpdatedAt != null && audioUpdatedAt != remote.audioUpdatedAt) || + (audioBytes != null && remote.audioSizeBytes != null && audioBytes != remote.audioSizeBytes) + + fun coverChanged(remote: OfflineManifestTrackResponse): Boolean = + if (coverHash != null) coverHash != remote.coverHash + else coverUpdatedAt != null && coverUpdatedAt != remote.coverUpdatedAt +} private data class ArtistSeed( val artistName: String, diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineMediaStore.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineMediaStore.kt index 99b614f..3c47806 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/OfflineMediaStore.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineMediaStore.kt @@ -1,166 +1,200 @@ package cy.hexor.furumi.data.local -import android.content.Context +import android.net.Uri +import android.system.ErrnoException +import android.system.OsConstants +import android.util.Log import cy.hexor.furumi.domain.model.TrackCard -import dagger.hilt.android.qualifiers.ApplicationContext +import cy.hexor.furumi.domain.model.OfflineProgressReporter +import cy.hexor.furumi.domain.model.OfflineTransferStage +import cy.hexor.furumi.data.remote.FederatedAudioResolver import java.io.File import java.io.IOException import javax.inject.Inject import javax.inject.Singleton -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.withContext -import okhttp3.OkHttpClient -import okhttp3.Request +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.delay +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock @Singleton class OfflineMediaStore @Inject constructor( - @ApplicationContext context: Context, - private val okHttpClient: OkHttpClient, + private val accounts: OfflineAccountScope, + private val downloader: OfflineFileDownloader, + private val federatedAudio: FederatedAudioResolver, + private val queue: OfflineDownloadQueueStore, private val libraryStore: OfflineLibraryStore, private val settingsStorage: OfflineSettingsStorage ) { - private val rootDir = File(context.filesDir, "offline") - private val audioDir = File(rootDir, "audio") - private val coversDir = File(rootDir, "covers") + private val rootDir: File get() = accounts.mediaDirectory + private val audioDir: File get() = File(rootDir, "audio") + private val coversDir: File get() = File(rootDir, "covers") + private val mediaLock = Mutex() - suspend fun cacheTrackAfterListening(trackId: Long) = withContext(Dispatchers.IO) { + suspend fun cacheTrackAfterListening(trackId: Long) = accounts.withAccount(accounts.storageKey) { if (!settingsStorage.state.value.settings.saveListenedTracksEnabled) { libraryStore.markTrackAccessed(trackId) - publishStorageStats() - return@withContext + return@withAccount } - - val track = libraryStore.getTrack(trackId, preferLocalMedia = false) - ?: return@withContext + val track = libraryStore.getTrack(trackId, preferLocalMedia = false) ?: return@withAccount cacheTrackMedia(track) } - suspend fun cacheTrackMedia(track: TrackCard) = withContext(Dispatchers.IO) { - cacheTrackMediaBlocking(track = track, pinAudio = false, requireAudio = false) - } - - suspend fun downloadTrackForOffline(track: TrackCard) = withContext(Dispatchers.IO) { - ensureManualDownloadsCanFit(listOf(track)) - cacheTrackMediaBlocking(track = track, pinAudio = true, requireAudio = true) - } - - suspend fun downloadTracksForOffline(tracks: List) = withContext(Dispatchers.IO) { - val uniqueTracks = tracks.distinctBy { it.id } - ensureManualDownloadsCanFit(uniqueTracks) - uniqueTracks.forEach { track -> - cacheTrackMediaBlocking(track = track, pinAudio = true, requireAudio = true) + suspend fun cacheTrackMedia(track: TrackCard) = accounts.withAccount(accounts.storageKey) { + mediaLock.withLock { + storeAudio(track, pin = false) + saveOptionalCover(track) + publishStorageStats() + queue.refresh() } } - suspend fun validateManualDownloadSize(tracks: List) = withContext(Dispatchers.IO) { - ensureManualDownloadsCanFit(tracks.distinctBy { it.id }) + suspend fun downloadTrackForOffline(track: TrackCard) = accounts.withAccount(accounts.storageKey) { + mediaLock.withLock { + if (!libraryStore.hasPendingOfflineDownload(track.id)) return@withLock + storeAudio(track, pin = true) + publishStorageStats() + // Serialize completion with clearing files and with changes to the storage limit. + queue.markCompleted(track.id) + } } - private suspend fun cacheTrackMediaBlocking(track: TrackCard, pinAudio: Boolean, requireAudio: Boolean) { - libraryStore.upsertTracks(listOf(track)) + suspend fun cacheDownloadedCover(track: TrackCard) = accounts.withAccount(accounts.storageKey) { + mediaLock.withLock { + saveOptionalCover(track) + publishStorageStats() + } + } + + suspend fun validateManualDownloadSize(tracks: List) = accounts.withAccount(accounts.storageKey) { + availableDownloadBytes(tracks.distinctBy { it.id }) + Unit + } + + private suspend fun storeAudio(track: TrackCard, pin: Boolean) { + val stored = libraryStore.getTrack(track.id, preferLocalMedia = false) + ?: track.also { libraryStore.upsertTracks(listOf(it)) } libraryStore.markTrackAccessed(track.id) - pruneStaleMedia() - - val storedTrack = libraryStore.getTrack(track.id, preferLocalMedia = false) ?: track - val audioPath = storedTrack.localAudioPath - val hadCachedAudio = !audioPath.isNullOrBlank() && File(audioPath).exists() - val hasAudio = if (!hadCachedAudio) { - downloadAudio(storedTrack) - } else { - true - } - if (requireAudio && !hasAudio) { - throw IOException("Track has no downloadable audio source") - } - if (pinAudio && hasAudio) { - libraryStore.markAudioPinned(storedTrack.id, pinned = true) - } - - val coverPath = storedTrack.localCoverPath - if ((coverPath.isNullOrBlank() || !File(coverPath).exists()) && - !storedTrack.remoteCoverUrl.isNullOrBlank() - ) { - downloadCover(storedTrack) - } - - enforceStorageLimit() - if (pinAudio) { - enforceManualStorageLimit(storedTrack.id, canRemoveAudio = !hadCachedAudio) - } - publishStorageStats() - } - - suspend fun clearCachedMedia() = withContext(Dispatchers.IO) { - rootDir.deleteRecursively() - libraryStore.clearCachedMedia() - publishStorageStats() - } - - suspend fun pruneStaleMedia() = withContext(Dispatchers.IO) { - libraryStore.staleMediaPaths().forEach { stale -> - File(stale.path).delete() - if (stale.isAudio) { - libraryStore.markAudioRemoved(stale.trackId) - } else { - libraryStore.markCoverRemoved(stale.trackId) + val alreadyCached = stored.isAudioCached + if (!alreadyCached) { + val remote = stored.remoteStreamUrl.ifBlank { stored.streamUrl } + if (remote.isBlank()) { + if (pin) throw IOException("Track has no downloadable audio") + return } + val extension = extensionForMime(stored.audioMimeType) ?: extensionFromUrl(remote) ?: "audio" + val version = safeVersion(stored.audioHash ?: stored.audioUpdatedAt) + val file = File(audioDir, "${track.id}-$version.$extension") + val bytes = try { + val remainingBytes = availableDownloadBytes(listOf(stored)) + val progress = if (pin) OfflineProgressReporter(stored.id, queue::updateTransfer) else null + downloadAudio(stored, remote, file, remainingBytes, progress) + } catch (e: OfflineStorageLimitException) { + if (pin) throw e + return + } + libraryStore.markAudioCached(stored.id, file.absolutePath, bytes) + } + if (pin) libraryStore.markAudioPinned(stored.id, true) + enforceStorageLimit() + if (pin) enforceManualStorageLimit(stored.id, canRemoveAudio = !alreadyCached) + } + + private suspend fun downloadAudio( + track: TrackCard, remote: String, file: File, maxBytes: Long, progress: OfflineProgressReporter? + ): Long { + var attempt = 1 + while (true) { + currentCoroutineContext().ensureActive() + if (!accounts.matches(accounts.storageKey)) throw CancellationException("Offline account changed") + try { + val url = federatedAudio.resolve(Uri.parse(remote), progress) + progress?.update(OfflineTransferStage.DOWNLOADING) + return downloader.download(url, file, resume = true, account = accounts.storageKey, maxBytes = maxBytes, + onProgress = progress?.let { reporter -> + { received, total -> reporter.update(OfflineTransferStage.DOWNLOADING, received, total) } + }) + } catch (e: IOException) { + currentCoroutineContext().ensureActive() + if (e.isDeviceFull()) throw IOException("Phone storage is full. Free up space on the phone and retry.", e) + Log.w("OfflineDownloads", "Audio ${track.id} '${track.title}' file=${file.name} attempt=$attempt: ${e.message}") + if (attempt >= 3 || (e is OfflineTransferException && !e.retryable)) throw e + progress?.update(OfflineTransferStage.RETRYING) + delay(1_000L * attempt++) + } + } + } + + private suspend fun saveOptionalCover(track: TrackCard) { + val stored = libraryStore.getTrack(track.id, preferLocalMedia = false) ?: return + if (!stored.isAudioCached) { + libraryStore.markAudioRemoved(stored.id) + queue.refresh() + return + } + if (stored.localCoverPath != null) return + val url = stored.remoteCoverUrl?.takeIf { it.isNotBlank() } ?: return + val ext = extensionFromUrl(url) ?: "jpg" + val version = safeVersion(stored.coverHash ?: stored.coverUpdatedAt) + val file = File(coversDir, "${stored.id}-$version.$ext") + try { + val remaining = settingsStorage.state.value.settings.storageLimitBytes - libraryStore.storageStats().usedBytes + if (remaining <= 0L) { + libraryStore.markOfflineCoverFailed(stored.id) + return + } + val bytes = downloader.download(url, file, resume = false, account = accounts.storageKey, maxBytes = remaining) + if (libraryStore.storageStats().usedBytes + bytes > settingsStorage.state.value.settings.storageLimitBytes) { + file.delete() + libraryStore.markOfflineCoverFailed(stored.id) + } else { + libraryStore.markCoverCached(stored.id, file.absolutePath, bytes) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + currentCoroutineContext().ensureActive() + libraryStore.markOfflineCoverFailed(stored.id) + Log.w("OfflineDownloads", "Cover ${stored.id} '${stored.title}' file=${file.name}: ${e.message}") + } + } + + private fun safeVersion(version: String?): String = + version.orEmpty().filter { it.isLetterOrDigit() || it in "-_." }.take(96).ifEmpty { "media" } + + suspend fun clearCachedMedia() = accounts.withAccount(accounts.storageKey) { + mediaLock.withLock { + rootDir.deleteRecursively() + libraryStore.clearCachedMedia() + queue.refresh() + publishStorageStats() + } + } + + suspend fun publishCatalog(commit: () -> Unit) = accounts.withAccount(accounts.storageKey) { + mediaLock.withLock { + commit() + libraryStore.staleMediaPaths().forEach { stale -> + File(stale.path).delete() + if (stale.isAudio) libraryStore.markAudioRemoved(stale.trackId) + else libraryStore.markCoverRemoved(stale.trackId) + } + queue.refresh() + } + } + + suspend fun applyStorageLimit() { + mediaLock.withLock { + enforceStorageLimit() + publishStorageStats() } } fun publishStorageStats() { val stats = libraryStore.storageStats() - settingsStorage.setStorageStats(stats.usedBytes, stats.cachedTrackCount) - } - - private fun downloadAudio(track: TrackCard): Boolean { - val sourceUrl = track.remoteStreamUrl.ifBlank { track.streamUrl } - if (sourceUrl.isBlank()) return false - - val extension = extensionForMime(track.audioMimeType) - ?: extensionFromUrl(sourceUrl) - ?: "audio" - val target = File(audioDir, "${track.id}-${track.audioHash ?: track.audioUpdatedAt ?: "audio"}.$extension") - val bytes = downloadToFile(sourceUrl, target) - libraryStore.markAudioCached(track.id, target.absolutePath, bytes) - return true - } - - private fun downloadCover(track: TrackCard) { - val sourceUrl = track.remoteCoverUrl ?: track.coverUrl ?: return - if (sourceUrl.isBlank()) return - - val extension = extensionFromUrl(sourceUrl) ?: "jpg" - val target = File(coversDir, "${track.id}-${track.coverHash ?: track.coverUpdatedAt ?: "cover"}.$extension") - val bytes = downloadToFile(sourceUrl, target) - libraryStore.markCoverCached(track.id, target.absolutePath, bytes) - } - - private fun downloadToFile(url: String, target: File): Long { - target.parentFile?.mkdirs() - val temp = File(target.parentFile, "${target.name}.tmp") - temp.delete() - - val request = Request.Builder() - .url(url) - .build() - - okHttpClient.newCall(request).execute().use { response -> - if (!response.isSuccessful) { - throw IOException("Offline download failed with HTTP ${response.code}") - } - val body = response.body ?: throw IOException("Offline download response is empty") - temp.outputStream().use { output -> - body.byteStream().use { input -> - input.copyTo(output) - } - } - } - - if (!temp.renameTo(target)) { - temp.copyTo(target, overwrite = true) - temp.delete() - } - return target.length() + if (accounts.matches(accounts.storageKey)) settingsStorage.setStorageStats(stats.usedBytes, stats.cachedTrackCount) } private fun enforceStorageLimit() { @@ -170,43 +204,52 @@ class OfflineMediaStore @Inject constructor( for (entry in libraryStore.cachedAudioEntriesForEviction()) { if (usedBytes <= limitBytes) break - File(entry.path).delete() + val audio = File(entry.path) + if (audio.exists() && !audio.delete()) continue libraryStore.markAudioRemoved(entry.trackId) usedBytes -= entry.sizeBytes - } - } - - private fun ensureManualDownloadsCanFit(tracks: List) { - val limitBytes = settingsStorage.state.value.settings.storageLimitBytes - val stats = libraryStore.storageStats() - val evictableBytes = libraryStore.cachedAudioEntriesForEviction().sumOf { it.sizeBytes } - val protectedUsedBytes = (stats.usedBytes - evictableBytes).coerceAtLeast(0L) - val estimatedNeededBytes = tracks.sumOf { track -> - val storedTrack = libraryStore.getTrack(track.id, preferLocalMedia = false) - if (storedTrack?.isAudioCached == true) { - 0L - } else { - track.audioSizeBytes ?: storedTrack?.audioSizeBytes ?: 0L + val cover = entry.coverPath?.let(::File) + if (cover != null && (!cover.exists() || cover.delete())) { + libraryStore.markCoverRemoved(entry.trackId) + usedBytes -= entry.coverBytes } } + queue.refresh() + } - if (estimatedNeededBytes > 0 && protectedUsedBytes + estimatedNeededBytes > limitBytes) { - throw IOException("Not enough offline storage limit for this download") + private fun availableDownloadBytes(tracks: List): Long { + val limitBytes = settingsStorage.state.value.settings.storageLimitBytes + val stats = libraryStore.storageStats() + val requestedIds = tracks.mapTo(mutableSetOf()) { it.id } + val evictableBytes = libraryStore.cachedAudioEntriesForEviction() + .filterNot { it.trackId in requestedIds }.sumOf { it.sizeBytes + it.coverBytes } + val protectedUsedBytes = (stats.usedBytes - evictableBytes).coerceAtLeast(0L) + val stored = libraryStore.getTracksByIds(tracks.map { it.id }, preferLocalMedia = false).associateBy { it.id } + val newTracks = tracks.filterNot { stored[it.id]?.isAudioCached == true } + val remaining = (limitBytes - protectedUsedBytes).coerceAtLeast(0L) + if (newTracks.isEmpty()) return remaining + val estimatedNeededBytes = newTracks.sumOf { track -> + (track.audioSizeBytes ?: stored[track.id]?.audioSizeBytes ?: 0L).coerceAtLeast(0L) } + if (remaining == 0L || estimatedNeededBytes > remaining) throw OfflineStorageLimitException() + return remaining } private fun enforceManualStorageLimit(trackId: Long, canRemoveAudio: Boolean) { val limitBytes = settingsStorage.state.value.settings.storageLimitBytes enforceStorageLimit() - if (libraryStore.storageStats().usedBytes <= limitBytes) return + if (!canRemoveAudio || libraryStore.storageStats().usedBytes <= limitBytes) return - if (canRemoveAudio) { - libraryStore.getTrack(trackId, preferLocalMedia = false) - ?.localAudioPath - ?.let { path -> File(path).delete() } - libraryStore.markAudioRemoved(trackId) - } - throw IOException("Not enough offline storage limit for this download") + val audio = libraryStore.getTrack(trackId, preferLocalMedia = false)?.localAudioPath?.let(::File) + if (audio == null || !audio.exists() || audio.delete()) libraryStore.markAudioRemoved(trackId) + publishStorageStats() + throw OfflineStorageLimitException() + } + + private fun IOException.isDeviceFull(): Boolean = generateSequence(this) { it.cause }.any { + (it is ErrnoException && it.errno == OsConstants.ENOSPC) || + it.message?.contains("ENOSPC", ignoreCase = true) == true || + it.message?.contains("No space left on device", ignoreCase = true) == true } private fun extensionForMime(mimeType: String?): String? { diff --git a/app/src/main/java/cy/hexor/furumi/data/local/OfflineSettingsStorage.kt b/app/src/main/java/cy/hexor/furumi/data/local/OfflineSettingsStorage.kt index 453bcb1..10277ed 100644 --- a/app/src/main/java/cy/hexor/furumi/data/local/OfflineSettingsStorage.kt +++ b/app/src/main/java/cy/hexor/furumi/data/local/OfflineSettingsStorage.kt @@ -3,22 +3,45 @@ package cy.hexor.furumi.data.local import android.content.Context import cy.hexor.furumi.domain.model.OfflineSettings import cy.hexor.furumi.domain.model.OfflineState +import cy.hexor.furumi.domain.model.OfflineStorageLimit import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update import javax.inject.Inject import javax.inject.Singleton @Singleton class OfflineSettingsStorage @Inject constructor( - @ApplicationContext context: Context + @ApplicationContext private val context: Context, + private val accountScope: OfflineAccountScope ) { - private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + private val prefs get() = context.getSharedPreferences( + if (accountScope.isLegacyOwner) PREFS_NAME else "${PREFS_NAME}_${accountScope.storageKey}", + Context.MODE_PRIVATE + ) + private var displayedKey = accountScope.key private val _state = MutableStateFlow(loadState()) val state: StateFlow = _state.asStateFlow() + @Synchronized + fun reloadAccount() { + val active = accountScope.key + if (displayedKey != active) { + displayedKey = active + _state.value = loadState() + } + } + + @Synchronized + private fun updateState(transform: (OfflineState) -> OfflineState) { + if (!accountScope.matches(accountScope.storageKey)) return + reloadAccount() + _state.update(transform) + } + fun setOfflineModeEnabled(enabled: Boolean) { prefs.edit().putBoolean(KEY_OFFLINE_MODE, enabled).apply() updateSettings { it.copy(offlineModeEnabled = enabled) } @@ -30,51 +53,46 @@ class OfflineSettingsStorage @Inject constructor( } fun setStorageLimitBytes(limitBytes: Long) { - val safeLimit = limitBytes.coerceAtLeast(MIN_STORAGE_LIMIT_BYTES) + val safeLimit = OfflineStorageLimit.clamp(limitBytes) prefs.edit().putLong(KEY_STORAGE_LIMIT_BYTES, safeLimit).apply() updateSettings { it.copy(storageLimitBytes = safeLimit) } } fun setSyncing(syncing: Boolean) { - _state.value = _state.value.copy(isSyncing = syncing) + updateState { it.copy(isSyncing = syncing) } } fun setLastSyncedAt(timestampMs: Long) { prefs.edit().putLong(KEY_LAST_SYNCED_AT_MS, timestampMs).apply() - _state.value = _state.value.copy(lastSyncedAtMs = timestampMs, lastError = null) + updateState { it.copy(lastSyncedAtMs = timestampMs, lastError = null) } } fun setStorageStats(usedBytes: Long, cachedTrackCount: Int) { - _state.value = _state.value.copy( - storageUsedBytes = usedBytes.coerceAtLeast(0L), - cachedTrackCount = cachedTrackCount.coerceAtLeast(0) - ) + updateState { it.copy(storageUsedBytes = usedBytes.coerceAtLeast(0L), cachedTrackCount = cachedTrackCount.coerceAtLeast(0)) } } fun setNetworkFallback(active: Boolean, errorMessage: String? = null) { - _state.value = _state.value.copy( - isUsingNetworkFallback = active, - lastError = errorMessage ?: _state.value.lastError - ) + updateState { it.copy(isUsingNetworkFallback = active, lastError = errorMessage ?: it.lastError) } } fun setLastError(message: String?) { - _state.value = _state.value.copy(lastError = message) + updateState { it.copy(lastError = message) } } private fun updateSettings(block: (OfflineSettings) -> OfflineSettings) { - _state.value = _state.value.copy(settings = block(_state.value.settings)) + updateState { it.copy(settings = block(it.settings)) } } private fun loadState(): OfflineState { + val prefs = this.prefs + val previousLimit = prefs.getLong(KEY_STORAGE_LIMIT_BYTES, OfflineSettings.DEFAULT_STORAGE_LIMIT_BYTES) + val limit = OfflineStorageLimit.clamp(previousLimit) + if (previousLimit != limit) prefs.edit().putLong(KEY_STORAGE_LIMIT_BYTES, limit).apply() return OfflineState( settings = OfflineSettings( offlineModeEnabled = prefs.getBoolean(KEY_OFFLINE_MODE, false), saveListenedTracksEnabled = prefs.getBoolean(KEY_SAVE_LISTENED, false), - storageLimitBytes = prefs.getLong( - KEY_STORAGE_LIMIT_BYTES, - OfflineSettings.DEFAULT_STORAGE_LIMIT_BYTES - ) + storageLimitBytes = limit ), lastSyncedAtMs = prefs.getLong(KEY_LAST_SYNCED_AT_MS, 0L) ) @@ -86,6 +104,5 @@ class OfflineSettingsStorage @Inject constructor( const val KEY_SAVE_LISTENED = "save_listened" const val KEY_STORAGE_LIMIT_BYTES = "storage_limit_bytes" const val KEY_LAST_SYNCED_AT_MS = "last_synced_at_ms" - const val MIN_STORAGE_LIMIT_BYTES = 256L * 1024L * 1024L } } diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/AccessTokenInterceptor.kt b/app/src/main/java/cy/hexor/furumi/data/remote/AccessTokenInterceptor.kt index f19a217..dff0c47 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/AccessTokenInterceptor.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/AccessTokenInterceptor.kt @@ -1,6 +1,9 @@ package cy.hexor.furumi.data.remote import cy.hexor.furumi.data.local.AuthSessionStorage +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import java.io.IOException import okhttp3.Interceptor import okhttp3.Response import javax.inject.Inject @@ -23,14 +26,31 @@ class AccessTokenInterceptor @Inject constructor( return chain.proceed(baseRequest) } - val tokens = sessionStorage.getTokens() ?: return chain.proceed(baseRequest) - val authorizedRequest = baseRequest.newBuilder() - .header(HEADER_AUTHORIZATION, tokens.authorizationHeader) - .build() + val authorizedRequest = synchronized(sessionStorage) { + val account = sessionStorage.accountKeys.value + val expected = request.tag(AuthenticatedAccount::class.java)?.key + if (expected != null && expected != account) throw IOException("Offline account changed") + val server = sessionStorage.getBaseUrl()?.toHttpUrlOrNull() + val tokens = sessionStorage.getTokens() + if (account != null && server != null && tokens != null && baseRequest.url.belongsTo(server)) { + baseRequest.newBuilder() + .tag(AuthenticatedAccount::class.java, AuthenticatedAccount(account)) + .header(HEADER_AUTHORIZATION, tokens.authorizationHeader) + .build() + } else baseRequest + } return chain.proceed(authorizedRequest) } + internal data class AuthenticatedAccount(val key: String) + + private fun HttpUrl.belongsTo(server: HttpUrl): Boolean { + val prefix = server.encodedPath.trimEnd('/') + return scheme == server.scheme && host == server.host && port == server.port && + (encodedPath == prefix || encodedPath.startsWith("$prefix/")) + } + companion object { const val HEADER_AUTHORIZATION = "Authorization" const val HEADER_USER_AGENT = "User-Agent" diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/AuthAuthenticator.kt b/app/src/main/java/cy/hexor/furumi/data/remote/AuthAuthenticator.kt index a92e471..0d165e2 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/AuthAuthenticator.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/AuthAuthenticator.kt @@ -1,6 +1,7 @@ package cy.hexor.furumi.data.remote import cy.hexor.furumi.data.local.AuthSessionStorage +import cy.hexor.furumi.data.remote.AccessTokenInterceptor.AuthenticatedAccount import cy.hexor.furumi.data.remote.AccessTokenInterceptor.Companion.HEADER_AUTHORIZATION import cy.hexor.furumi.data.remote.api.AuthApi import cy.hexor.furumi.data.remote.model.RefreshRequest @@ -28,48 +29,39 @@ class AuthAuthenticator @Inject constructor( return null } + val account = response.request.tag(AuthenticatedAccount::class.java)?.key ?: return null val requestAuthorization = response.request.header(HEADER_AUTHORIZATION) ?: return null return synchronized(refreshLock) { - val currentTokens = sessionStorage.getTokens() ?: return@synchronized null - if (requestAuthorization != currentTokens.authorizationHeader) { - return@synchronized response.withAuthorization(currentTokens.authorizationHeader) + val session = synchronized(sessionStorage) { + sessionStorage.getSession()?.takeIf { sessionStorage.accountKeys.value == account } + } ?: return@synchronized null + val tokens = session.tokens + if (requestAuthorization != tokens.authorizationHeader) { + return@synchronized response.withAuthorization(tokens.authorizationHeader) } - val baseUrl = sessionStorage.getBaseUrl() ?: return@synchronized null - val refreshedTokens = runBlocking { - refreshTokens(baseUrl, currentTokens.refreshToken) + val refreshed = try { + runBlocking { + authApiLazy.get().refresh(authEndpoints.refresh(session.serverBaseUrl), RefreshRequest(tokens.refreshToken)) + } + } catch (_: java.io.IOException) { + return@synchronized null } - if (refreshedTokens == null) { - sessionStorage.clearSession() - null - } else { - sessionStorage.saveTokens(refreshedTokens) - response.withAuthorization(refreshedTokens.authorizationHeader) + synchronized(sessionStorage) update@{ + if (sessionStorage.accountKeys.value != account || sessionStorage.getTokens() != tokens) { + return@update null + } + if (refreshed.code() == 401 || refreshed.code() == 403) sessionStorage.clearSession() + val body = refreshed.body()?.takeIf { refreshed.isSuccessful } ?: return@update null + val newTokens = body.toDomain(nowEpochSeconds()) + sessionStorage.saveTokens(newTokens) + response.withAuthorization(newTokens.authorizationHeader) } } } - private suspend fun refreshTokens( - baseUrl: String, - refreshToken: String - ): cy.hexor.furumi.domain.model.AuthTokens? { - val refreshResponse = runCatching { - authApiLazy.get().refresh( - url = authEndpoints.refresh(baseUrl), - request = RefreshRequest(refreshToken) - ) - }.getOrNull() - - if (refreshResponse?.isSuccessful != true) { - return null - } - - val body = refreshResponse.body() ?: return null - return body.toDomain(nowEpochSeconds()) - } - private fun Response.withAuthorization(authorizationHeader: String): Request { return request.newBuilder() .header(HEADER_AUTHORIZATION, authorizationHeader) diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/FederatedAudioResolver.kt b/app/src/main/java/cy/hexor/furumi/data/remote/FederatedAudioResolver.kt new file mode 100644 index 0000000..1bf6efc --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/remote/FederatedAudioResolver.kt @@ -0,0 +1,96 @@ +package cy.hexor.furumi.data.remote + +import android.net.Uri +import cy.hexor.furumi.domain.model.OfflineProgressReporter +import cy.hexor.furumi.domain.model.OfflineTransferStage +import cy.hexor.furumi.data.local.AuthSessionStorage +import cy.hexor.furumi.data.local.OfflineAccountScope +import cy.hexor.furumi.data.local.OfflineFileDownloader +import cy.hexor.furumi.data.local.OfflineHttpException +import cy.hexor.furumi.data.local.OfflineTransferException +import java.io.EOFException +import java.io.IOException +import javax.inject.Inject +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONObject + +class FederatedAudioResolver @Inject constructor( + private val sessions: AuthSessionStorage, + private val accounts: OfflineAccountScope, + private val transfers: OfflineFileDownloader +) { + suspend fun resolve(uri: Uri): String = resolve(uri, null) + + internal suspend fun resolve(uri: Uri, progress: OfflineProgressReporter?): String { + if (uri.scheme != "furumi-fed") return uri.toString() + val account = uri.getQueryParameter("account") ?: throw IOException("Missing track account") + return accounts.withAccount(account) { + val base = sessions.getBaseUrl()?.trimEnd('/') ?: throw IOException("Missing server address") + val content = uri.getQueryParameter("content")?.takeIf(String::isNotBlank) + ?: throw OfflineTransferException("The track has no remote content ID") + val owner = uri.getQueryParameter("owner") + val item = uri.getQueryParameter("item") + if (!owner.isNullOrBlank() && !item.isNullOrBlank()) { + try { + return@withAccount prepare(base, account, content, owner, item, progress) + } catch (_: PeerFailure) { + // The playlist may name an old peer. Ask the server for a current source by content ID. + } + } + prepare(base, account, content, null, null, progress) + } + } + + private suspend fun prepare( + base: String, account: String, content: String, owner: String?, item: String?, progress: OfflineProgressReporter? + ): String { + progress?.update(OfflineTransferStage.PREPARING) + val payload = JSONObject().put("content_id", content).put("owner", owner).put("item_id", item) + // Cot's JSON extractor compares Content-Type exactly. A String body adds "; charset=utf-8". + val body = payload.toString().toByteArray(Charsets.UTF_8).toRequestBody("application/json".toMediaType()) + val request = Request.Builder().url("$base/api/player/federation/tracks/prepare") + .tag(AccessTokenInterceptor.AuthenticatedAccount::class.java, AccessTokenInterceptor.AuthenticatedAccount(account)) + .header("Accept", "application/x-ndjson").post(body).build() + return transfers.transfer(request, preparingRemoteTrack = true) { response -> + if (!response.isSuccessful) throw OfflineHttpException(response.code, "Preparing remote track") + val input = response.body?.source() ?: throw IOException("Empty response while preparing remote track") + var url: String? = null + while (url == null) { + val line = input.readUtf8Line() ?: throw EOFException("Remote track preparation was interrupted") + if (line.isBlank()) continue + val event = try { + JSONObject(line) + } catch (_: org.json.JSONException) { + throw OfflineTransferException("Invalid response while preparing the remote track") + } + when (event.optString("kind")) { + "progress" -> when (event.optString("phase")) { + "downloading" -> progress?.update( + OfflineTransferStage.FETCHING, event.optLong("received").coerceAtLeast(0), + event.optLong("total").takeIf { it > 0 } + ) + "verifying", "saving" -> progress?.update(OfflineTransferStage.VERIFYING) + } + "failed" -> throw PeerFailure(event.optString("error")) + "completed" -> url = event.optString("stream_url").takeIf { it.isNotBlank() } + ?: throw OfflineTransferException("The server did not return an audio address") + } + } + val origin = base.toHttpUrl() + val stream = origin.resolve(url) ?: throw OfflineTransferException("Invalid remote audio address") + if (stream.scheme != origin.scheme || stream.host != origin.host || stream.port != origin.port) { + throw OfflineTransferException("The music server returned an unexpected audio address") + } + stream.toString() + } + } + + private class PeerFailure(reason: String) : OfflineTransferException( + if (reason.contains("no peer currently advertises", ignoreCase = true)) + "No online source offers this track right now. Retry later." + else "The server could not prepare this track from its remote source. Retry later." + ) +} diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/PlayerEndpoints.kt b/app/src/main/java/cy/hexor/furumi/data/remote/PlayerEndpoints.kt index a832f2c..e5a8237 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/PlayerEndpoints.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/PlayerEndpoints.kt @@ -11,12 +11,20 @@ class PlayerEndpoints @Inject constructor() { fun search(baseUrl: String): String = "$baseUrl$SEARCH_PATH" + fun lyrics(baseUrl: String, trackId: Long): String = "$baseUrl/api/player/lyrics/$trackId" + + fun federatedLyrics(baseUrl: String): String = "$baseUrl/api/player/federation/tracks/lyrics" + fun history(baseUrl: String): String = "$baseUrl$HISTORY_PATH" fun likesToggle(baseUrl: String, trackId: Long): String = "$baseUrl$LIKES_TOGGLE_PATH/$trackId" fun likes(baseUrl: String): String = "$baseUrl$LIKES_PATH" + fun contentLikes(baseUrl: String): String = "$baseUrl/api/player/tracks/content/like" + + fun contentPlaylist(baseUrl: String): String = "$baseUrl/api/player/tracks/content/playlist" + fun recordHistory(baseUrl: String): String = "$baseUrl$HISTORY_PATH" fun playlists(baseUrl: String): String = "$baseUrl$PLAYLISTS_PATH" @@ -29,9 +37,7 @@ class PlayerEndpoints @Inject constructor() { fun addPlaylistTracks(baseUrl: String, playlistId: Long): String = "$baseUrl$PLAYLISTS_PATH/$playlistId/tracks" - fun sharePlaylist(baseUrl: String): String = "$baseUrl$SHARE_PLAYLIST_PATH" - - fun shareTrack(baseUrl: String, trackId: Long): String = "${baseUrl.trimEnd('/')}$SHARE_TRACK_PATH/$trackId" + fun shares(baseUrl: String): String = "$baseUrl/api/player/shares" fun devicesPoll(baseUrl: String): String = "$baseUrl$DEVICES_POLL_PATH" @@ -59,9 +65,8 @@ class PlayerEndpoints @Inject constructor() { private const val PLAYLISTS_PATH = "/api/player/playlists" private const val OFFLINE_MANIFEST_PATH = "/api/player/offline/manifest" private const val TRACKS_BY_IDS_PATH = "/api/player/tracks-by-ids" - private const val SHARE_PLAYLIST_PATH = "/api/player/share-playlist" - private const val SHARE_TRACK_PATH = "/share/track" private const val DEVICES_POLL_PATH = "/api/player/devices/poll" + private const val DEVICES_ACTIVE_PATH = "/api/player/devices/active" private const val DEVICES_COMMAND_PATH = "/api/player/devices/command" private const val JAMS_PATH = "/api/player/jams" diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/api/PlayerApi.kt b/app/src/main/java/cy/hexor/furumi/data/remote/api/PlayerApi.kt index 6ceb139..e0aa66d 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/api/PlayerApi.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/api/PlayerApi.kt @@ -6,6 +6,7 @@ import cy.hexor.furumi.data.remote.model.PlayHistoryPageResponse import cy.hexor.furumi.data.remote.model.ReleaseDetailResponse import cy.hexor.furumi.data.remote.model.AddPlaylistTracksRequest import cy.hexor.furumi.data.remote.model.CreatePlaylistRequest +import cy.hexor.furumi.data.remote.model.ContentTrackMutation import cy.hexor.furumi.data.remote.model.DeviceActiveRequest import cy.hexor.furumi.data.remote.model.DeviceCommandRequest import cy.hexor.furumi.data.remote.model.DevicePollRequest @@ -24,6 +25,7 @@ import cy.hexor.furumi.data.remote.model.SearchResponse import cy.hexor.furumi.data.remote.model.SharePlaylistRequest import cy.hexor.furumi.data.remote.model.SharePlaylistResponse import cy.hexor.furumi.data.remote.model.TrackItemResponse +import cy.hexor.furumi.data.remote.model.TrackLyricsResponse import cy.hexor.furumi.data.remote.model.TracksByIdsRequest import retrofit2.Response import retrofit2.http.Body @@ -64,6 +66,14 @@ interface PlayerApi { @Query("limit") limit: Int ): Response + @Headers("Accept: application/json") + @GET + suspend fun lyrics( + @Url url: String, + @Query("content_id") contentId: String? = null, + @Query("owner") owner: String? = null + ): Response + @Headers("Accept: application/json") @GET suspend fun history( @@ -84,6 +94,15 @@ interface PlayerApi { @Url url: String ): Response + @GET + suspend fun contentLikes(@Url url: String): Response> + + @POST + suspend fun setContentLike(@Url url: String, @Body body: ContentTrackMutation): Response + + @POST + suspend fun addContentTrack(@Url url: String, @Body body: ContentTrackMutation): Response + @Headers("Accept: application/json", "Content-Type: application/json") @POST suspend fun recordHistory( @@ -116,6 +135,9 @@ interface PlayerApi { @Url url: String ): Response + @GET + suspend fun federatedPlaylistTracks(@Url url: String): Response> + @Headers("Accept: application/json", "Content-Type: application/json") @POST suspend fun createPlaylist( diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedDeviceModels.kt b/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedDeviceModels.kt index cf07561..84c12cd 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedDeviceModels.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedDeviceModels.kt @@ -171,14 +171,14 @@ fun ConnectedPlaybackState.toCommandPayloadBody(): ConnectedCommandPayloadBody { ) } -fun DevicePollResponse.toDomain(baseUrl: String): ConnectedDevicesState { +fun DevicePollResponse.toDomain(baseUrl: String, account: String): ConnectedDevicesState { return ConnectedDevicesState( deviceId = deviceId, activeDeviceId = activeDeviceId, devices = devices.map { it.toDomain() }, jams = jams.map { it.toDomain() }, currentJamId = currentJamId, - remotePlaybackState = playbackState?.toDomain(baseUrl) + remotePlaybackState = playbackState?.toDomain(baseUrl, account) ) } @@ -218,11 +218,11 @@ fun JamUserResponse.toDomain(): ConnectedJamUser { ) } -fun ConnectedCommandResponse.toDomain(baseUrl: String): ConnectedCommand { +fun ConnectedCommandResponse.toDomain(baseUrl: String, account: String): ConnectedCommand { return ConnectedCommand( id = id, command = command, - payload = payload.toDomain(baseUrl) + payload = payload.toDomain(baseUrl, account) ) } @@ -237,11 +237,11 @@ private fun ConnectedDeviceResponse.toDomain(): ConnectedDevice { ) } -private fun ConnectedCommandPayloadResponse.toDomain(baseUrl: String): ConnectedCommandPayload { - val playbackState = toPlaybackState(baseUrl) +private fun ConnectedCommandPayloadResponse.toDomain(baseUrl: String, account: String): ConnectedCommandPayload { + val playbackState = toPlaybackState(baseUrl, account) return ConnectedCommandPayload( playbackState = playbackState, - tracks = tracks.map { it.toDomain(baseUrl) }, + tracks = tracks.map { it.toConnectedTrack(baseUrl, account) }, index = index, time = time, volume = volume, @@ -252,9 +252,9 @@ private fun ConnectedCommandPayloadResponse.toDomain(baseUrl: String): Connected ) } -private fun ConnectedCommandPayloadResponse.toPlaybackState(baseUrl: String): ConnectedPlaybackState? { - val playbackTracks = tracks.map { it.toDomain(baseUrl) } - val playbackTrack = track?.toDomain(baseUrl) ?: playbackTracks.getOrNull(index ?: 0) +private fun ConnectedCommandPayloadResponse.toPlaybackState(baseUrl: String, account: String): ConnectedPlaybackState? { + val playbackTracks = tracks.map { it.toConnectedTrack(baseUrl, account) } + val playbackTrack = track?.toConnectedTrack(baseUrl, account) ?: playbackTracks.getOrNull(index ?: 0) if (playbackTrack == null && playbackTracks.isEmpty()) return null return ConnectedPlaybackState( @@ -270,10 +270,10 @@ private fun ConnectedCommandPayloadResponse.toPlaybackState(baseUrl: String): Co ) } -private fun ConnectedPlaybackStateBody.toDomain(baseUrl: String): ConnectedPlaybackState { - val mappedTracks = tracks.map { it.toDomain(baseUrl) } +private fun ConnectedPlaybackStateBody.toDomain(baseUrl: String, account: String): ConnectedPlaybackState { + val mappedTracks = tracks.map { it.toConnectedTrack(baseUrl, account) } return ConnectedPlaybackState( - track = track?.toDomain(baseUrl) ?: mappedTracks.getOrNull(index), + track = track?.toConnectedTrack(baseUrl, account) ?: mappedTracks.getOrNull(index), tracks = mappedTracks, index = index, positionSeconds = positionSeconds, diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedFederationTrack.kt b/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedFederationTrack.kt new file mode 100644 index 0000000..240fae8 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/remote/model/ConnectedFederationTrack.kt @@ -0,0 +1,63 @@ +package cy.hexor.furumi.data.remote.model + +import com.squareup.moshi.FromJson +import com.squareup.moshi.Json +import com.squareup.moshi.JsonQualifier +import com.squareup.moshi.JsonReader +import com.squareup.moshi.JsonWriter +import com.squareup.moshi.ToJson +import cy.hexor.furumi.domain.model.TrackCard + +/** The player uses JSON integers for local tracks and "fed:" strings for remote tracks. */ +@Retention(AnnotationRetention.RUNTIME) +@JsonQualifier +annotation class PlayerTrackId + +object PlayerTrackIdAdapter { + @FromJson + @PlayerTrackId + fun read(reader: JsonReader): String? = + if (reader.peek() == JsonReader.Token.NULL) reader.nextNull() else reader.nextString() + + @ToJson + fun write(writer: JsonWriter, @PlayerTrackId id: String?) { + if (id == null) { + writer.nullValue() + return + } + val localId = id.toLongOrNull() + if (localId == null) writer.value(id) else writer.value(localId) + } +} + +data class DeviceFederationSource(val owner: String, @param:Json(name = "item_id") val itemId: String) +data class DeviceFederationKey(@param:Json(name = "content_id") val contentId: String) +data class DeviceFederationAvailability( + val federation: List = emptyList(), + val state: String = "federated" +) + +data class DeviceFederationTrack( + val key: DeviceFederationKey, + val availability: DeviceFederationAvailability, + val metadata: TrackItemResponse? = null +) + +data class PreparedDeviceFederation(val sources: List = emptyList()) + +internal fun TrackItemResponse.toConnectedTrack(baseUrl: String, account: String): TrackCard { + val contentId = wireId?.takeIf { it.startsWith("fed:") }?.removePrefix("fed:") + ?: return toDomain(baseUrl) + val track = toDomain(baseUrl).copy(id = federationTrackId(contentId), preparedContentId = contentId) + val source = federationTrack?.availability?.federation?.firstOrNull() ?: federation?.sources?.firstOrNull() + ?: return track + val remote = FederatedTrackWire( + contentId = contentId, owner = source.owner, itemId = source.itemId, title = title, + artists = artists.map { it.name }, featuredArtists = featuredArtists.map { it.name }, + releaseTitle = releaseTitle, duration = durationSeconds?.toInt(), disc = discNumber, number = trackNumber, year = releaseYear + ).toDomain(baseUrl, account) ?: return track + return remote.copy( + coverUrl = track.coverUrl ?: remote.coverUrl, + remoteCoverUrl = track.remoteCoverUrl ?: remote.remoteCoverUrl + ) +} diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/model/FederatedPlaylistTrack.kt b/app/src/main/java/cy/hexor/furumi/data/remote/model/FederatedPlaylistTrack.kt new file mode 100644 index 0000000..ff28a3b --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/remote/model/FederatedPlaylistTrack.kt @@ -0,0 +1,64 @@ +package cy.hexor.furumi.data.remote.model + +import android.net.Uri +import com.squareup.moshi.Json +import cy.hexor.furumi.domain.model.FederatedTrackSource +import cy.hexor.furumi.domain.model.TrackCard +import java.nio.ByteBuffer +import java.security.MessageDigest +import okhttp3.HttpUrl.Companion.toHttpUrl + +fun federationTrackId(contentId: String): Long = + ByteBuffer.wrap(MessageDigest.getInstance("SHA-256").digest(contentId.toByteArray())).long or Long.MIN_VALUE + +data class FederatedPlaylistTrack(val position: Long = 0, val federation: FederatedTrackWire?) + +data class ContentTrackMutation( + @param:Json(name = "content_id") val contentId: String, + val federation: FederatedTrackWire?, + val liked: Boolean? = null, + @param:Json(name = "playlist_id") val playlistId: Long? = null +) + +fun TrackCard.contentMutation(liked: Boolean? = null, playlistId: Long? = null): ContentTrackMutation { + val source = federation + val contentId = source?.contentId ?: preparedContentId ?: error("Missing federated track identity") + require(source != null || liked == false) { "Track source is unavailable" } + val reference = source?.let { + FederatedTrackWire(contentId, it.owner, it.itemId, title, it.artistNames ?: artists, it.featuredArtistNames, + releaseTitle, durationSeconds, discNumber, trackNumber, releaseYear) + } + return ContentTrackMutation(contentId, reference, liked, playlistId) +} + +data class FederatedTrackWire( + @param:Json(name = "content_id") val contentId: String?, + val owner: String?, + @param:Json(name = "item_id") val itemId: String?, + val title: String?, + @param:Json(name = "artist_names") val artists: List = emptyList(), + @param:Json(name = "featured_artist_names") val featuredArtists: List = emptyList(), + @param:Json(name = "release_title") val releaseTitle: String?, + @param:Json(name = "duration_seconds") val duration: Int?, + @param:Json(name = "disc_number") val disc: Int?, + @param:Json(name = "track_number") val number: Int?, + val year: Int? +) { + fun toDomain(baseUrl: String, account: String): TrackCard? { + if (contentId.isNullOrBlank() || owner.isNullOrBlank() || itemId.isNullOrBlank()) return null + val source = FederatedTrackSource(contentId, owner, itemId, artists, featuredArtists) + // Server-side local IDs are positive integers. Keep federation's string identity on the wire. + val id = federationTrackId(contentId) + val cover = (baseUrl.trimEnd('/') + "/api/player/federation/tracks/artwork").toHttpUrl().newBuilder() + .addQueryParameter("owner", owner).addQueryParameter("item_id", itemId).build().toString() + val uri = Uri.Builder().scheme("furumi-fed").authority("track") + .appendQueryParameter("account", account).appendQueryParameter("content", contentId) + .appendQueryParameter("owner", owner).appendQueryParameter("item", itemId).build() + return TrackCard( + id = id, title = title ?: "Unknown track", trackNumber = number, discNumber = disc, + durationSeconds = duration, artists = artists.ifEmpty { featuredArtists }, + releaseYear = year, releaseTitle = releaseTitle, coverUrl = cover, streamUrl = uri.toString(), + federation = source + ) + } +} diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/model/PlayerResponses.kt b/app/src/main/java/cy/hexor/furumi/data/remote/model/PlayerResponses.kt index 7bebfd5..de7b6e4 100644 --- a/app/src/main/java/cy/hexor/furumi/data/remote/model/PlayerResponses.kt +++ b/app/src/main/java/cy/hexor/furumi/data/remote/model/PlayerResponses.kt @@ -20,7 +20,7 @@ data class ArtistRefResponse( ) data class TrackItemResponse( - @param:Json(name = "id") val id: Long? = null, + @param:Json(name = "id") @param:PlayerTrackId val wireId: String? = null, @param:Json(name = "title") val title: String, @param:Json(name = "track_number") val trackNumber: Int? = null, @param:Json(name = "disc_number") val discNumber: Int? = null, @@ -31,8 +31,15 @@ data class TrackItemResponse( @param:Json(name = "release_title") val releaseTitle: String? = null, @param:Json(name = "release_year") val releaseYear: Int? = null, @param:Json(name = "cover_url") val coverUrl: String? = null, - @param:Json(name = "stream_url") val streamUrl: String? = null -) + @param:Json(name = "stream_url") val streamUrl: String? = null, + @param:Json(name = "sort_key") val sortKey: Long? = null, + @param:Json(name = "content_id") val contentId: String? = null, + @param:Json(name = "federation_pending") val federationPending: Boolean? = null, + @param:Json(name = "_federationTrack") val federationTrack: DeviceFederationTrack? = null, + val federation: PreparedDeviceFederation? = null +) { + val id: Long? get() = wireId?.toLongOrNull() +} data class TracksByIdsRequest( @param:Json(name = "ids") val ids: List @@ -74,12 +81,23 @@ data class OfflineManifestPlaylistResponse( @param:Json(name = "track_ids") val trackIds: List = emptyList() ) +data class HistoryTrackResponse( + @param:Json(name = "content_id") val contentId: String? = null, + @param:Json(name = "duration_seconds") val durationSeconds: Double? = null, + val title: String? = null, + val artists: List = emptyList(), + @param:Json(name = "featured_artists") val featuredArtists: List = emptyList(), + @param:Json(name = "release_title") val releaseTitle: String? = null +) + +data class HistoryArtistResponse(val name: String) + data class PlayHistoryItemResponse( - @param:Json(name = "id") val id: Long, - @param:Json(name = "track_id") val trackId: Long, + @param:Json(name = "id") val id: String, + @param:Json(name = "track_id") val trackId: Long? = null, @param:Json(name = "track_title") val trackTitle: String, @param:Json(name = "release_title") val releaseTitle: String? = null, - @param:Json(name = "track") val track: TrackItemResponse, + @param:Json(name = "track") val track: HistoryTrackResponse, @param:Json(name = "played_at") val playedAt: String, @param:Json(name = "duration_listened") val durationListened: Double? = null, @param:Json(name = "completed") val completed: Boolean @@ -163,11 +181,9 @@ data class PlaylistCardResponse( @param:Json(name = "owner_name") val ownerName: String? = null, @param:Json(name = "is_public") val isPublic: Boolean = false, @param:Json(name = "is_saved") val isSaved: Boolean = false, - @param:Json(name = "kind") val kind: String? = null -) - -data class PlaylistListResponse( - @param:Json(name = "playlists") val playlists: List + @param:Json(name = "kind") val kind: String? = null, + @param:Json(name = "cover_url") val coverUrl: String? = null, + @param:Json(name = "cover_urls") val coverUrls: List = emptyList() ) data class CreatePlaylistRequest( @@ -211,7 +227,9 @@ data class PlaylistDetailResponse( @param:Json(name = "is_public") val isPublic: Boolean? = null, @param:Json(name = "is_saved") val isSaved: Boolean? = null, @param:Json(name = "kind") val kind: String? = null, - @param:Json(name = "tracks") val tracks: List = emptyList() + @param:Json(name = "tracks") val tracks: List = emptyList(), + @param:Json(name = "cover_url") val coverUrl: String? = null, + @param:Json(name = "cover_urls") val coverUrls: List = emptyList() ) fun PlayHistoryPageResponse.toDomain(): ListeningHistoryPage { @@ -228,17 +246,29 @@ private fun PlayHistoryItemResponse.toDomain(): ListeningHistoryItem { .ifEmpty { track.featuredArtists } .map { it.name } + val title = trackTitle.ifBlank { track.title.orEmpty() } + val album = releaseTitle ?: track.releaseTitle + val localId = trackId?.takeIf { it > 0L } + val contentId = track.contentId?.takeIf { it.isNotBlank() } + val lyricsId = localId ?: contentId?.let(::federationTrackId) return ListeningHistoryItem( id = id, trackId = trackId, - title = trackTitle.ifBlank { track.title }, + title = title, artists = artistNames, - releaseTitle = releaseTitle ?: track.releaseTitle, + releaseTitle = album, playedAt = playedAt, durationListenedSeconds = durationListened?.toInt(), - completed = completed + completed = completed, + lyricsTrack = lyricsId?.let { + TrackCard( + id = it, title = title, trackNumber = null, discNumber = null, + durationSeconds = track.durationSeconds?.toInt(), artists = artistNames, + releaseTitle = album, coverUrl = null, streamUrl = "", + preparedContentId = if (localId == null) contentId else null + ) + } ) - } fun ArtistPageResponse.toDomain(baseUrl: String): ArtistPage { @@ -306,7 +336,8 @@ fun SearchResponse.toDomain(baseUrl: String): SearchResults { return SearchResults( artistMatches = artists.map { it.toDomain(baseUrl) }, trackArtists = trackArtists, - tracks = tracks.map { it.toDomain(baseUrl) } + tracks = tracks.map { it.toDomain(baseUrl) }, + releases = releases.map { it.toDomain(baseUrl) } ) } @@ -361,28 +392,38 @@ fun TrackItemResponse.toDomain(baseUrl: String): TrackCard { } fun TrackCard.toTrackItemResponse(): TrackItemResponse { - val primaryArtists = artistRefs.ifEmpty { - artists.mapIndexed { index, name -> - ArtistRef(id = -(index + 1L), name = name) - } - } - - return TrackItemResponse( - id = id, + val source = federation + val contentId = source?.contentId ?: preparedContentId + val item = TrackItemResponse( + wireId = contentId?.let { "fed:$it" } ?: id.toString(), title = title, trackNumber = trackNumber, discNumber = discNumber, durationSeconds = durationSeconds?.toDouble() ?: 0.0, - artists = primaryArtists.map { it.toResponse() }, + artists = if (artistRefs.isEmpty()) artists.map { ArtistRefResponse(name = it) } else artistRefs.map { it.toResponse() }, featuredArtists = featuredArtistRefs.map { it.toResponse() }, releaseId = releaseId, releaseTitle = releaseTitle, releaseYear = releaseYear, - coverUrl = remoteCoverUrl ?: coverUrl, - streamUrl = remoteStreamUrl.ifBlank { streamUrl } + coverUrl = remoteCoverUrl?.httpMediaUrl(), + streamUrl = if (source == null) remoteStreamUrl.httpMediaUrl() else "" + ) + if (source == null) return item + val availability = DeviceFederationAvailability(listOf(DeviceFederationSource(source.owner, source.itemId))) + return item.copy( + contentId = source.contentId, + federationPending = true, + federationTrack = DeviceFederationTrack( + key = DeviceFederationKey(source.contentId), + availability = availability, + metadata = item.copy(wireId = null) + ) ) } +private fun String.httpMediaUrl(): String? = + takeIf { startsWith("/") || startsWith("https://", true) || startsWith("http://", true) } + fun OfflineManifestTrackResponse.withAbsoluteUrls(baseUrl: String): OfflineManifestTrackResponse { return copy( streamUrl = streamUrl.toAbsoluteMediaUrl(baseUrl).orEmpty(), @@ -420,28 +461,11 @@ private fun ArtistRef.toResponse(): ArtistRefResponse { ) } -fun PlaylistListResponse.toDomain(): List { - return playlists.map { - PlaylistCard( - id = it.id, - title = it.title, - trackCount = it.trackCount, - isPublic = it.isPublic, - isOwn = it.isOwn, - ownerName = it.ownerName, - isSaved = it.isSaved, - kind = it.kind - ) - } -} - -fun List.toDomain(): List { - return map { it.toDomain() } -} +fun List.toDomain(baseUrl: String): List = map { it.toDomain(baseUrl) } fun PlaylistDetailResponse.toDomain(baseUrl: String): PlaylistDetail { val mappedTracks = tracks.map { it.toDomain(baseUrl) } - val mappedPlaylist = playlist?.toDomain() ?: PlaylistCard( + val mappedPlaylist = (playlist ?: PlaylistCardResponse( id = id ?: 0L, title = title ?: "Untitled playlist", trackCount = trackCount ?: mappedTracks.size, @@ -449,8 +473,10 @@ fun PlaylistDetailResponse.toDomain(baseUrl: String): PlaylistDetail { isOwn = isOwn ?: false, ownerName = ownerName, isSaved = isSaved ?: false, - kind = kind - ) + kind = kind, + coverUrl = coverUrl, + coverUrls = coverUrls + )).toDomain(baseUrl) return PlaylistDetail( playlist = mappedPlaylist, @@ -459,7 +485,7 @@ fun PlaylistDetailResponse.toDomain(baseUrl: String): PlaylistDetail { ) } -fun PlaylistCardResponse.toDomain(): PlaylistCard { +fun PlaylistCardResponse.toDomain(baseUrl: String): PlaylistCard { return PlaylistCard( id = id, title = title, @@ -468,7 +494,8 @@ fun PlaylistCardResponse.toDomain(): PlaylistCard { isOwn = isOwn, ownerName = ownerName, isSaved = isSaved, - kind = kind + kind = kind, + coverUrls = (coverUrls + listOfNotNull(coverUrl)).mapNotNull { it.toAbsoluteMediaUrl(baseUrl) }.distinct().take(4) ) } diff --git a/app/src/main/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponse.kt b/app/src/main/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponse.kt new file mode 100644 index 0000000..1670c0c --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponse.kt @@ -0,0 +1,59 @@ +package cy.hexor.furumi.data.remote.model + +import com.squareup.moshi.Json +import cy.hexor.furumi.domain.model.LyricsLine +import cy.hexor.furumi.domain.model.LyricsVersion + +data class TrackLyricsResponse( + @param:Json(name = "content_id") val contentId: String? = null, + val versions: List +) + +data class LyricsVersionResponse( + val id: String, + val label: String = "", + val source: String = "", + val language: String? = null, + @param:Json(name = "plain_text") val plainText: String? = null, + @param:Json(name = "synced_lrc") val syncedLrc: String? = null, + val instrumental: Boolean = false +) + +fun TrackLyricsResponse.toDomain(): List = versions.mapNotNull { version -> + val parsed = version.syncedLrc?.let(::parseLrc).orEmpty() + val lines = parsed.takeIf { cues -> cues.any { it.text.isNotBlank() } }.orEmpty() + val plain = version.plainText?.trim()?.takeIf(String::isNotEmpty) + if (lines.isEmpty() && plain == null && !version.instrumental) return@mapNotNull null + LyricsVersion(version.id, version.label, version.source, version.language, plain, lines, version.instrumental) +}.sortedByDescending { it.lines.isNotEmpty() } + +private val timestamp = Regex("""\[(\d{1,4}):(\d{1,2})(?:\.(\d+))?]""") +private val fileOffset = Regex("""\[offset:\s*([+-]?\d+)\s*]""", RegexOption.IGNORE_CASE) + +private fun parseLrc(lrc: String): List { + val input = lrc.removePrefix("\uFEFF") + val offset = input.lineSequence().firstNotNullOfOrNull { line -> + fileOffset.matchEntire(line.trim())?.groupValues?.get(1)?.toLongOrNull() + }?.coerceIn(-3_600_000L, 3_600_000L) ?: 0L + + return buildList { + for (raw in input.lineSequence()) { + val line = raw.trim() + val times = mutableListOf() + var index = 0 + while (true) { + val match = timestamp.matchAt(line, index) ?: break + val (_, minutes, seconds, fraction) = match.groupValues + val min = minutes.toLong() + val sec = seconds.toLong() + if (min > 1440 || sec >= 60) break + // A fraction may be tenths, hundredths, milliseconds or finer. + val millis = (fraction.take(4).padEnd(4, '0').toInt() + 5) / 10 + times.add(((min * 60 + sec) * 1000 + millis + offset).coerceAtLeast(0)) + index = match.range.last + 1 + } + val text = line.substring(index).trim() + times.forEach { add(LyricsLine(it, text)) } + } + }.sortedBy { it.startMs } +} diff --git a/app/src/main/java/cy/hexor/furumi/data/repository/MediaImageLoader.kt b/app/src/main/java/cy/hexor/furumi/data/repository/MediaImageLoader.kt index 60a0e53..97a3bbc 100644 --- a/app/src/main/java/cy/hexor/furumi/data/repository/MediaImageLoader.kt +++ b/app/src/main/java/cy/hexor/furumi/data/repository/MediaImageLoader.kt @@ -16,17 +16,19 @@ import okhttp3.Request class MediaImageLoader @Inject constructor( private val okHttpClient: OkHttpClient ) { + private val dispatcher = Dispatchers.IO.limitedParallelism(4) + suspend fun load(url: String): Result { - return withContext(Dispatchers.IO) { + return withContext(dispatcher) { runCatching { if (url.startsWith("file://", ignoreCase = true)) { val path = Uri.parse(url).path ?: throw IOException("Image file path is empty") - return@runCatching BitmapFactory.decodeFile(path) + return@runCatching decode { options -> BitmapFactory.decodeFile(path, options) } ?: throw IOException("Image file is not a supported bitmap") } if (url.startsWith("/", ignoreCase = false)) { - return@runCatching BitmapFactory.decodeFile(File(url).absolutePath) + return@runCatching decode { options -> BitmapFactory.decodeFile(File(url).absolutePath, options) } ?: throw IOException("Image file is not a supported bitmap") } @@ -42,10 +44,23 @@ class MediaImageLoader @Inject constructor( val bytes = response.body?.bytes() ?: throw IOException("Image response is empty") - BitmapFactory.decodeByteArray(bytes, 0, bytes.size) + decode { options -> BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) } ?: throw IOException("Image response is not a supported bitmap") } } } } + + private fun decode(read: (BitmapFactory.Options) -> Bitmap?): Bitmap? { + val options = BitmapFactory.Options().apply { + inJustDecodeBounds = true + inSampleSize = 1 + } + read(options) + while (maxOf(options.outWidth, options.outHeight) / options.inSampleSize > 768) { + options.inSampleSize = options.inSampleSize.coerceAtLeast(1) * 2 + } + options.inJustDecodeBounds = false + return read(options) + } } diff --git a/app/src/main/java/cy/hexor/furumi/data/repository/PlayerRepositoryImpl.kt b/app/src/main/java/cy/hexor/furumi/data/repository/PlayerRepositoryImpl.kt index bb5d839..e4cb73b 100644 --- a/app/src/main/java/cy/hexor/furumi/data/repository/PlayerRepositoryImpl.kt +++ b/app/src/main/java/cy/hexor/furumi/data/repository/PlayerRepositoryImpl.kt @@ -1,6 +1,8 @@ package cy.hexor.furumi.data.repository +import android.util.Log import cy.hexor.furumi.data.local.AuthSessionStorage +import cy.hexor.furumi.data.local.OfflineAccountScope import cy.hexor.furumi.data.local.ConnectedDeviceStorage import cy.hexor.furumi.data.local.OfflineDownloadJobScheduler import cy.hexor.furumi.data.local.OfflineDownloadQueueStore @@ -21,13 +23,18 @@ import cy.hexor.furumi.data.remote.model.JamCreateRequest import cy.hexor.furumi.data.remote.model.JamInviteRequest import cy.hexor.furumi.data.remote.model.JamJoinRequest import cy.hexor.furumi.data.remote.model.RecordHistoryRequest +import cy.hexor.furumi.data.remote.model.SharePlaylistRequest +import cy.hexor.furumi.data.remote.model.TrackLyricsResponse import cy.hexor.furumi.data.remote.model.TracksByIdsRequest +import cy.hexor.furumi.data.remote.model.contentMutation +import cy.hexor.furumi.data.remote.model.federationTrackId import cy.hexor.furumi.data.remote.model.toDomain import cy.hexor.furumi.data.remote.model.toBody import cy.hexor.furumi.data.remote.model.toCommandPayloadBody import cy.hexor.furumi.data.remote.model.toTrackItemResponse import cy.hexor.furumi.data.remote.model.withAbsoluteUrls import cy.hexor.furumi.data.remote.model.withOfflineManifest +import cy.hexor.furumi.domain.model.ArtistCard import cy.hexor.furumi.domain.model.ArtistDetail import cy.hexor.furumi.domain.model.ArtistPage import cy.hexor.furumi.domain.model.AuthException @@ -36,6 +43,7 @@ import cy.hexor.furumi.domain.model.ConnectedDevicesState import cy.hexor.furumi.domain.model.ConnectedJamUser import cy.hexor.furumi.domain.model.ConnectedPlaybackState import cy.hexor.furumi.domain.model.ListeningHistoryPage +import cy.hexor.furumi.domain.model.LyricsVersion import cy.hexor.furumi.domain.model.OfflineDownloadQueueState import cy.hexor.furumi.domain.model.OfflineState import cy.hexor.furumi.domain.model.OfflineSyncSummary @@ -46,11 +54,24 @@ import cy.hexor.furumi.domain.model.SearchResults import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.repository.PlayerRepository import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.collectLatest +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import javax.inject.Inject +import retrofit2.Response class PlayerRepositoryImpl @Inject constructor( private val playerApi: PlayerApi, + private val accountScope: OfflineAccountScope, private val sessionStorage: AuthSessionStorage, private val connectedDeviceStorage: ConnectedDeviceStorage, private val offlineSettingsStorage: OfflineSettingsStorage, @@ -65,9 +86,27 @@ class PlayerRepositoryImpl @Inject constructor( override val offlineState: StateFlow = offlineSettingsStorage.state override val offlineDownloadQueueState: StateFlow = offlineDownloadQueueStore.state + private val catalogSyncMutex = Mutex() + init { - offlineMediaStore.publishStorageStats() - offlineDownloadQueueStore.refresh() + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + accountScope.keys.collectLatest { account -> + offlineSettingsStorage.reloadAccount() + if (account != null) { + accountScope.withAccount(account) { + offlineSettingsStorage.state + .map { it.settings.storageLimitBytes } + .distinctUntilChanged() + .collect { offlineMediaStore.applyStorageLimit() } + } + } + } + } + } + + private suspend fun inOfflineAccount(block: suspend () -> T): T { + val account = accountScope.key ?: throw CancellationException("No signed-in account") + return accountScope.withAccount(account, block) } override fun setOfflineModeEnabled(enabled: Boolean) { @@ -85,8 +124,11 @@ class PlayerRepositoryImpl @Inject constructor( offlineSettingsStorage.setStorageLimitBytes(limitBytes) } - override suspend fun clearOfflineCache(): Result { - return try { + override suspend fun getDownloadedTracks(ids: Set?): List = + inOfflineAccount { offlineLibraryStore.getDownloadedTracks(ids) } + + override suspend fun clearOfflineCache(): Result = inOfflineAccount { + try { offlineMediaStore.clearCachedMedia() Result.success(Unit) } catch (e: CancellationException) { @@ -96,56 +138,54 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun syncOfflineLibrary(): Result { + override suspend fun syncOfflineLibrary(): Result = inOfflineAccount { + catalogSyncMutex.withLock { refreshCatalog() } + } + + private suspend fun refreshCatalog(): Result { offlineSettingsStorage.setSyncing(true) return try { - val baseUrl = sessionStorage.getBaseUrl() - ?: throw AuthException("Server URL is missing") - val manifestResponse = playerApi.offlineManifest(playerEndpoints.offlineManifest(baseUrl)) - - if (!manifestResponse.isSuccessful) { - throw AuthException(errorParser.messageFrom(manifestResponse)) + val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") + val response = playerApi.offlineManifest(playerEndpoints.offlineManifest(baseUrl)) + if (!response.isSuccessful) throw AuthException(errorParser.messageFrom(response)) + val manifest = response.body() ?: throw AuthException("Offline manifest response is empty") + val versions = offlineLibraryStore.catalogVersions() + val manifestTracks = manifest.tracks.associateBy { it.id } + val changed = manifest.tracks.filter { versions[it.id]?.matches(it) != true } + .map { it.withAbsoluteUrls(baseUrl) } + val cards = changed.chunked(TRACKS_BY_IDS_CHUNK_SIZE).flatMap { batch -> + val versionsById = batch.associateBy { it.id } + val details = playerApi.tracksByIds( + playerEndpoints.tracksByIds(baseUrl), TracksByIdsRequest(batch.map { it.id }) + ) + if (!details.isSuccessful) throw AuthException(errorParser.messageFrom(details)) + val items = details.body().orEmpty() + items.map { item -> + item.toDomain(baseUrl).withOfflineManifest(versionsById.getValue(requireNotNull(item.id))) + } } - val manifest = manifestResponse.body() - ?: throw AuthException("Offline manifest response is empty") - val manifestTracks = manifest.tracks.map { it.withAbsoluteUrls(baseUrl) } - val manifestById = manifestTracks.associateBy { it.id } - - offlineLibraryStore.upsertManifestTracks(manifestTracks) - offlineLibraryStore.replacePlaylists(manifest.playlists) - offlineLibraryStore.replaceLikedTrackIds(manifest.likedTrackIds.toSet()) - - val trackCards = manifestTracks - .map { it.id } - .chunked(TRACKS_BY_IDS_CHUNK_SIZE) - .flatMap { ids -> - val tracksResponse = playerApi.tracksByIds( - url = playerEndpoints.tracksByIds(baseUrl), - body = TracksByIdsRequest(ids) - ) - if (!tracksResponse.isSuccessful) { - throw AuthException(errorParser.messageFrom(tracksResponse)) - } - tracksResponse.body().orEmpty().map { track -> - val domainTrack = track.toDomain(baseUrl) - manifestById[domainTrack.id]?.let(domainTrack::withOfflineManifest) ?: domainTrack - } - } - - offlineLibraryStore.upsertTracks(trackCards) - offlineMediaStore.pruneStaleMedia() + // The manifest lists followed artists. Upload ownership comes from the personal artists API. + val mine = mutableListOf() + var page = 1 + do { + val artists = playerApi.artists(playerEndpoints.artists(baseUrl), page, 200, mine = true) + if (!artists.isSuccessful) throw AuthException(errorParser.messageFrom(artists)) + val result = artists.body()?.toDomain(baseUrl) ?: throw AuthException("Missing personal artists page") + check(result.page == page && (!result.hasMore || result.items.isNotEmpty())) { "Invalid artists page" } + mine += result.items + page++ + } while (result.hasMore) + currentCoroutineContext().ensureActive() + offlineMediaStore.publishCatalog { + offlineLibraryStore.publishCatalog( + changed, cards, versions.keys - manifestTracks.keys, manifest.playlists, manifest.likedTrackIds.toSet(), mine + ) + } offlineMediaStore.publishStorageStats() val syncedAtMs = System.currentTimeMillis() offlineSettingsStorage.setLastSyncedAt(syncedAtMs) - offlineSettingsStorage.setNetworkFallback(false) - Result.success( - OfflineSyncSummary( - trackCount = manifestTracks.size, - playlistCount = manifest.playlists.size, - syncedAtMs = syncedAtMs - ) - ) + Result.success(OfflineSyncSummary(manifest.tracks.size, manifest.playlists.size, syncedAtMs)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -156,41 +196,49 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun downloadTrackForOffline(track: TrackCard): Result { - return try { - offlineMediaStore.validateManualDownloadSize(listOf(track)) - offlineDownloadQueueStore.enqueueDownloads(listOf(track)) - offlineDownloadJobScheduler.schedule(estimatedDownloadBytes(listOf(track))) - Result.success(track) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - offlineSettingsStorage.setLastError(e.message ?: "Unable to download track") - Result.failure(e) - } - } + override suspend fun downloadTrackForOffline(track: TrackCard): Result = + downloadTracksForOffline(listOf(track)).map { track } override suspend fun downloadTracksForOffline(tracks: List): Result> { + val key = accountScope.key ?: return Result.failure(AuthException("Sign in to download tracks")) return try { - val uniqueTracks = tracks.distinctBy { it.id } - offlineMediaStore.validateManualDownloadSize(uniqueTracks) - offlineDownloadQueueStore.enqueueDownloads(uniqueTracks) - offlineDownloadJobScheduler.schedule(estimatedDownloadBytes(uniqueTracks)) - Result.success(uniqueTracks) + accountScope.withAccount(key) { + val unique = tracks.distinctBy { it.id } + offlineMediaStore.validateManualDownloadSize(unique) + val queued = offlineDownloadQueueStore.enqueueDownloads(unique) + if (queued.activeTrackIds.isNotEmpty()) { + try { + offlineDownloadJobScheduler.schedule(estimatedDownloadBytes(unique), key) + } catch (error: Exception) { + unique.filter { it.id in queued.activeTrackIds }.forEach { + offlineDownloadQueueStore.markFailed(it.id, error.message) + } + throw error + } + } + Result.success(unique) + } } catch (e: CancellationException) { throw e } catch (e: Exception) { - offlineSettingsStorage.setLastError(e.message ?: "Unable to download tracks") Result.failure(e) } } - override suspend fun getArtists(page: Int, limit: Int, mine: Boolean): Result { - if (isOfflineModeEnabled()) { - return Result.success(offlineLibraryStore.getArtists(page, limit)) + override suspend fun retryFailedDownloads(trackIds: Set): Result { + val key = accountScope.key ?: return Result.failure(AuthException("Sign in to retry downloads")) + return accountScope.withAccount(key) { + val failed = trackIds.intersect(offlineDownloadQueueStore.state.value.failedTrackIds) + downloadTracksForOffline(offlineLibraryStore.getTracksByIds(failed.toList(), preferLocalMedia = false)).map {} + } + } + + override suspend fun getArtists(page: Int, limit: Int, mine: Boolean): Result = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount Result.success(offlineLibraryStore.getArtists(page, limit, mine)) } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.artists( @@ -210,19 +258,19 @@ class PlayerRepositoryImpl @Inject constructor( } catch (e: CancellationException) { throw e } catch (e: Exception) { - fallbackToOffline(e) { offlineLibraryStore.getArtists(page, limit) } + fallbackToOffline(e) { offlineLibraryStore.getArtists(page, limit, mine) } } } - override suspend fun getArtistDetail(artistId: Long): Result { - if (isOfflineModeEnabled()) { - return offlineLibraryStore.getArtistDetail(artistId) + override suspend fun getArtistDetail(artistId: Long): Result = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount offlineLibraryStore.getArtistDetail(artistId) ?.withOnlyCachedPlayback() ?.let { Result.success(it) } ?: offlineUnavailable("Artist is not available offline") } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.artistDetail( @@ -247,15 +295,15 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun getReleaseDetail(releaseId: Long): Result { - if (isOfflineModeEnabled()) { - return offlineLibraryStore.getReleaseDetail(releaseId) + override suspend fun getReleaseDetail(releaseId: Long): Result = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount offlineLibraryStore.getReleaseDetail(releaseId) ?.withOnlyCachedPlayback() ?.let { Result.success(it) } ?: offlineUnavailable("Release is not available offline") } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.releaseDetail( @@ -280,12 +328,12 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun search(query: String, limit: Int): Result { - if (isOfflineModeEnabled()) { - return Result.success(offlineLibraryStore.search(query, limit).withOnlyCachedPlayback()) + override suspend fun search(query: String, limit: Int): Result = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount Result.success(offlineLibraryStore.search(query, limit).withOnlyCachedPlayback()) } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.search( @@ -310,6 +358,45 @@ class PlayerRepositoryImpl @Inject constructor( } } + override suspend fun getLyrics(track: TrackCard): Result> = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount offlineUnavailable("Connect to the server to load lyrics") + } + try { + val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") + val source = if (track.id < 0 && track.federation == null && track.preparedContentId == null) { + offlineLibraryStore.getTrack(track.id, preferLocalMedia = false) ?: track + } else track + val knownContentId = source.federation?.contentId ?: source.preparedContentId + val local = if (track.id > 0) { + val response = playerApi.lyrics(playerEndpoints.lyrics(baseUrl, track.id)) + if (response.code() == 404 && knownContentId != null) null else response.lyricsBody() + } else null + val localVersions = local?.toDomain().orEmpty() + if (localVersions.isNotEmpty()) return@inOfflineAccount Result.success(localVersions) + + val contentId = local?.contentId ?: knownContentId + if (contentId == null || !FEDERATION_CONTENT_ID.matches(contentId)) { + if (local != null) return@inOfflineAccount Result.success(emptyList()) + throw AuthException("This track has no valid lyrics identifier") + } + val peer = playerApi.lyrics( + playerEndpoints.federatedLyrics(baseUrl), contentId, source.federation?.owner?.takeIf(String::isNotBlank) + ).lyricsBody() + if (peer.contentId != contentId) throw AuthException("The server returned lyrics for a different track") + Result.success(peer.toDomain()) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Result.failure(e) + } + } + + private fun Response.lyricsBody(): TrackLyricsResponse { + if (!isSuccessful) throw AuthException(errorParser.messageFrom(this)) + return body() ?: throw AuthException("Lyrics response is empty") + } + override suspend fun getListeningHistory(page: Int, limit: Int): Result { if (isOfflineModeEnabled()) { return offlineUnavailable("Listening history is not available offline") @@ -338,27 +425,27 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun toggleLike(trackId: Long): Result { + override suspend fun toggleLike(trackId: Long, desired: Boolean, knownTrack: TrackCard?): Result = inOfflineAccount { if (isOfflineModeEnabled()) { - return offlineUnavailable("Likes cannot be changed offline") + return@inOfflineAccount offlineUnavailable("Likes cannot be changed offline") } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") - val response = playerApi.toggleLike( - url = playerEndpoints.likesToggle(baseUrl, trackId) - ) + val track = if (trackId < 0) federatedTrack(trackId, knownTrack) else null + val response = if (track == null) { + playerApi.toggleLike(playerEndpoints.likesToggle(baseUrl, trackId)) + } else { + playerApi.setContentLike(playerEndpoints.contentLikes(baseUrl), track.contentMutation(liked = desired)) + } if (!response.isSuccessful) { throw AuthException(errorParser.messageFrom(response)) } val body = response.body() ?: throw AuthException("Like toggle response is empty") - val likedIds = offlineLibraryStore.getLikedTrackIds() - offlineLibraryStore.replaceLikedTrackIds( - if (body.liked) likedIds + trackId else likedIds - trackId - ) + offlineLibraryStore.setTrackLiked(trackId, body.liked, track) markOnlineSuccess() Result.success(body.liked) } catch (e: CancellationException) { @@ -368,12 +455,12 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun getLikedTrackIds(): Result> { - if (isOfflineModeEnabled()) { - return Result.success(offlineLibraryStore.getLikedTrackIds()) + override suspend fun getLikedTrackIds(): Result> = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount Result.success(offlineLibraryStore.getLikedTrackIds()) } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.likes( @@ -385,7 +472,15 @@ class PlayerRepositoryImpl @Inject constructor( } val body = response.body() ?: throw AuthException("Likes response is empty") - val likedIds = body.trackIds.toSet() + val remoteLikes = try { + val response = playerApi.contentLikes(playerEndpoints.contentLikes(baseUrl)) + response.body()?.takeIf { response.isSuccessful }?.map(::federationTrackId) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } + val likedIds = body.trackIds.toSet() + (remoteLikes ?: offlineLibraryStore.getLikedTrackIds().filter { it < 0 }) offlineLibraryStore.replaceLikedTrackIds(likedIds) markOnlineSuccess() Result.success(likedIds) @@ -401,9 +496,9 @@ class PlayerRepositoryImpl @Inject constructor( startedAt: Long, durationListened: Int, completed: Boolean - ): Result { + ): Result = inOfflineAccount { if (isOfflineModeEnabled()) { - return try { + return@inOfflineAccount try { offlineMediaStore.cacheTrackAfterListening(trackId) Result.success(Unit) } catch (e: CancellationException) { @@ -413,7 +508,7 @@ class PlayerRepositoryImpl @Inject constructor( } } - return try { + val result = try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.recordHistory( @@ -430,24 +525,30 @@ class PlayerRepositoryImpl @Inject constructor( throw AuthException(errorParser.messageFrom(response)) } - offlineMediaStore.cacheTrackAfterListening(trackId) markOnlineSuccess() Result.success(Unit) } catch (e: CancellationException) { throw e } catch (e: Exception) { - runCatching { offlineMediaStore.cacheTrackAfterListening(trackId) } offlineSettingsStorage.setNetworkFallback(true, e.message) Result.failure(e) } + try { + offlineMediaStore.cacheTrackAfterListening(trackId) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w("OfflineDownloads", "Could not cache listened track $trackId", e) + } + result } - override suspend fun getPlaylists(): Result> { - if (isOfflineModeEnabled()) { - return Result.success(offlineLibraryStore.getPlaylists()) + override suspend fun getPlaylists(): Result> = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount Result.success(offlineLibraryStore.getPlaylists()) } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.playlists( @@ -460,7 +561,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Playlists response is empty") markOnlineSuccess() - Result.success(body.toDomain()) + Result.success(body.toDomain(baseUrl)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -468,15 +569,15 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun getPlaylistDetail(playlistId: Long): Result { - if (isOfflineModeEnabled()) { - return offlineLibraryStore.getPlaylistDetail(playlistId) + override suspend fun getPlaylistDetail(playlistId: Long): Result = inOfflineAccount { + if (offlineState.value.isOfflineActive) { + return@inOfflineAccount offlineLibraryStore.getPlaylistDetail(playlistId) ?.withOnlyCachedPlayback() ?.let { Result.success(it) } ?: offlineUnavailable("Playlist is not available offline") } - return try { + try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.playlistDetail( @@ -488,8 +589,33 @@ class PlayerRepositoryImpl @Inject constructor( } val body = response.body() ?: throw AuthException("Playlist response is empty") - val detail = body.toDomain(baseUrl).withCachedMedia() - offlineLibraryStore.upsertPlaylistDetail(detail) + val local = body.toDomain(baseUrl) + val key = accountScope.storageKey + val remote = try { + val refs = playerApi.federatedPlaylistTracks(playerEndpoints.playlistDetail(baseUrl, playlistId) + "/federation-tracks") + refs.body()?.takeIf { refs.isSuccessful }?.map { row -> + row.position to (row.federation?.toDomain(baseUrl, key) ?: throw AuthException("Invalid remote track")) + } + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + null + } + val ordered = when { + remote == null -> local.tracks + offlineLibraryStore.getPlaylistDetail(playlistId)?.tracks.orEmpty().filter { it.id < 0 } + remote.isEmpty() -> local.tracks + else -> { + val combined = local.tracks.mapIndexed { index, track -> (body.tracks[index].sortKey ?: 0L) to track } + remote + val sorted = if (playlistId == -1L) combined.sortedByDescending { it.first } else combined + sorted.map { it.second }.distinctBy { it.id } + } + } + val detail = local.copy( + playlist = local.playlist.copy(trackCount = if (remote == null) maxOf(local.playlist.trackCount, ordered.size) else ordered.size), + tracks = ordered, isMembershipComplete = remote != null + ).withCachedMedia() + if (detail.isMembershipComplete) offlineLibraryStore.upsertPlaylistDetail(detail) + else offlineLibraryStore.upsertTracks(local.tracks) markOnlineSuccess() Result.success(detail) } catch (e: CancellationException) { @@ -520,7 +646,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Create playlist response is empty") markOnlineSuccess() - Result.success(body.toDomain()) + Result.success(body.toDomain(baseUrl)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -553,23 +679,27 @@ class PlayerRepositoryImpl @Inject constructor( } } - override suspend fun addTracksToPlaylist(playlistId: Long, trackIds: List): Result { - if (isOfflineModeEnabled()) { - return offlineUnavailable("Playlists cannot be changed offline") - } + private fun federatedTrack(id: Long, known: TrackCard?): TrackCard = + known?.takeIf { it.id == id && it.federation != null } + ?: offlineLibraryStore.getTrack(id, preferLocalMedia = false) + ?: known?.takeIf { it.id == id && it.preparedContentId != null } + ?: throw AuthException("Track source is unavailable") - return try { - val baseUrl = sessionStorage.getBaseUrl() - ?: throw AuthException("Server URL is missing") - val response = playerApi.addTracksToPlaylist( - url = playerEndpoints.addPlaylistTracks(baseUrl, playlistId), - body = AddPlaylistTracksRequest(trackIds = trackIds) - ) - - if (!response.isSuccessful) { - throw AuthException(errorParser.messageFrom(response)) + override suspend fun addTracksToPlaylist(playlistId: Long, trackIds: List, knownTrack: TrackCard?): Result = inOfflineAccount { + if (isOfflineModeEnabled()) return@inOfflineAccount offlineUnavailable("Playlists cannot be changed offline") + try { + val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") + val (localIds, remoteIds) = trackIds.distinct().partition { it >= 0 } + val references = remoteIds.map { federatedTrack(it, knownTrack).contentMutation(playlistId = playlistId) } + if (localIds.isNotEmpty()) { + val response = playerApi.addTracksToPlaylist(playerEndpoints.addPlaylistTracks(baseUrl, playlistId), + AddPlaylistTracksRequest(trackIds = localIds)) + if (!response.isSuccessful) throw AuthException(errorParser.messageFrom(response)) + } + for (reference in references) { + val response = playerApi.addContentTrack(playerEndpoints.contentPlaylist(baseUrl), reference) + if (!response.isSuccessful) throw AuthException(errorParser.messageFrom(response)) } - markOnlineSuccess() Result.success(Unit) } catch (e: CancellationException) { @@ -580,6 +710,7 @@ class PlayerRepositoryImpl @Inject constructor( } override suspend fun shareTrack(trackId: Long, title: String): Result { + if (trackId <= 0) return Result.failure(AuthException("Only tracks hosted on this server can be shared")) if (isOfflineModeEnabled()) { return offlineUnavailable("Tracks cannot be shared offline") } @@ -587,8 +718,11 @@ class PlayerRepositoryImpl @Inject constructor( return try { val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") + val response = playerApi.sharePlaylist(playerEndpoints.shares(baseUrl), SharePlaylistRequest(listOf(trackId), title)) + if (!response.isSuccessful) throw AuthException(errorParser.messageFrom(response)) + val path = response.body()?.url?.takeIf { it.isNotBlank() } ?: throw AuthException("Share URL is missing") markOnlineSuccess() - Result.success(playerEndpoints.shareTrack(baseUrl, trackId)) + Result.success(java.net.URI(baseUrl).resolve(path).toString()) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -605,6 +739,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.pollDevice( @@ -623,10 +758,11 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Device poll response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl) to body.commands.map { it.toDomain(baseUrl) }) + Result.success(body.toDomain(baseUrl, account) to body.commands.map { it.toDomain(baseUrl, account) }) } catch (e: CancellationException) { throw e } catch (e: Exception) { + if (e is java.io.IOException) offlineSettingsStorage.setNetworkFallback(true, e.message) Result.failure(e) } } @@ -637,6 +773,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.setActiveDevice( @@ -653,7 +790,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Active device response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl)) + Result.success(body.toDomain(baseUrl, account)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -721,6 +858,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.createJam( @@ -734,7 +872,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Jam response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl)) + Result.success(body.toDomain(baseUrl, account)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -748,6 +886,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.joinJam( @@ -764,7 +903,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Jam response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl)) + Result.success(body.toDomain(baseUrl, account)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -778,6 +917,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.leaveJam( @@ -794,7 +934,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Jam response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl)) + Result.success(body.toDomain(baseUrl, account)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -836,6 +976,7 @@ class PlayerRepositoryImpl @Inject constructor( } return try { + val account = accountScope.key ?: throw AuthException("Signed out") val baseUrl = sessionStorage.getBaseUrl() ?: throw AuthException("Server URL is missing") val response = playerApi.inviteToJam( @@ -853,7 +994,7 @@ class PlayerRepositoryImpl @Inject constructor( val body = response.body() ?: throw AuthException("Jam response is empty") markOnlineSuccess() - Result.success(body.toDomain(baseUrl)) + Result.success(body.toDomain(baseUrl, account)) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -884,34 +1025,30 @@ class PlayerRepositoryImpl @Inject constructor( return Result.failure(AuthException(message)) } - private fun ArtistDetail.withCachedMedia(): ArtistDetail { - return copy( - topTracks = topTracks.map { it.withCachedMedia() }, - featuredTracks = featuredTracks.map { it.withCachedMedia() } - ) - } + private fun ArtistDetail.withCachedMedia(): ArtistDetail = copy( + topTracks = topTracks.withCachedMedia(), + featuredTracks = featuredTracks.withCachedMedia() + ) - private fun ReleaseDetail.withCachedMedia(): ReleaseDetail { - return copy(tracks = tracks.map { it.withCachedMedia() }) - } + private fun ReleaseDetail.withCachedMedia(): ReleaseDetail = copy(tracks = tracks.withCachedMedia()) - private fun PlaylistDetail.withCachedMedia(): PlaylistDetail { - return copy(tracks = tracks.map { it.withCachedMedia() }) - } + private fun PlaylistDetail.withCachedMedia(): PlaylistDetail = copy(tracks = tracks.withCachedMedia()) - private fun SearchResults.withCachedMedia(): SearchResults { - return copy(tracks = tracks.map { it.withCachedMedia() }) - } + private fun SearchResults.withCachedMedia(): SearchResults = copy(tracks = tracks.withCachedMedia()) - private fun TrackCard.withCachedMedia(): TrackCard { - val cached = offlineLibraryStore.getTrack(id, preferLocalMedia = true) ?: return this - return copy( - streamUrl = if (cached.isAudioCached) cached.streamUrl else streamUrl, - coverUrl = if (cached.localCoverPath != null) cached.coverUrl else coverUrl, - localAudioPath = cached.localAudioPath, - localCoverPath = cached.localCoverPath, - isAudioCached = cached.isAudioCached - ) + private fun List.withCachedMedia(): List { + val cachedById = offlineLibraryStore.getTracksByIds(map { it.id }).associateBy { it.id } + return map { track -> + val cached = cachedById[track.id] ?: return@map track + track.copy( + streamUrl = if (cached.isAudioCached) cached.streamUrl else track.streamUrl, + coverUrl = if (cached.localCoverPath != null) cached.coverUrl else track.coverUrl, + localAudioPath = cached.localAudioPath, + localCoverPath = cached.localCoverPath, + audioSizeBytes = cached.audioSizeBytes ?: track.audioSizeBytes, + isAudioCached = cached.isAudioCached + ) + } } private fun ArtistDetail.withOnlyCachedPlayback(): ArtistDetail { @@ -953,5 +1090,6 @@ class PlayerRepositoryImpl @Inject constructor( private companion object { const val TRACKS_BY_IDS_CHUNK_SIZE = 500 + val FEDERATION_CONTENT_ID = Regex("b3:[0-9a-f]{64}") } } diff --git a/app/src/main/java/cy/hexor/furumi/di/StorageModule.kt b/app/src/main/java/cy/hexor/furumi/di/StorageModule.kt index 093efae..5b595ac 100644 --- a/app/src/main/java/cy/hexor/furumi/di/StorageModule.kt +++ b/app/src/main/java/cy/hexor/furumi/di/StorageModule.kt @@ -2,6 +2,7 @@ package cy.hexor.furumi.di import android.content.Context import cy.hexor.furumi.data.local.AuthSessionStorage +import cy.hexor.furumi.data.remote.model.PlayerTrackIdAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module @@ -19,7 +20,8 @@ object StorageModule { @Singleton fun provideMoshi(): Moshi { return Moshi.Builder() - .add(KotlinJsonAdapterFactory()) + .add(PlayerTrackIdAdapter) + .addLast(KotlinJsonAdapterFactory()) .build() } diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/Artist.kt b/app/src/main/java/cy/hexor/furumi/domain/model/Artist.kt index a355e76..51bcd6a 100644 --- a/app/src/main/java/cy/hexor/furumi/domain/model/Artist.kt +++ b/app/src/main/java/cy/hexor/furumi/domain/model/Artist.kt @@ -55,7 +55,15 @@ data class TrackCard( val coverUpdatedAt: String? = null, val localAudioPath: String? = null, val localCoverPath: String? = null, - val isAudioCached: Boolean = false + val isAudioCached: Boolean = false, + val federation: FederatedTrackSource? = null, + val preparedContentId: String? = null +) + +data class FederatedTrackSource( + val contentId: String, val owner: String, val itemId: String, + val artistNames: List? = null, + val featuredArtistNames: List = emptyList() ) data class ArtistDetail( @@ -79,17 +87,20 @@ data class PlaylistCard( val isOwn: Boolean = false, val ownerName: String? = null, val isSaved: Boolean = false, - val kind: String? = null + val kind: String? = null, + val coverUrls: List = emptyList() ) data class PlaylistDetail( val playlist: PlaylistCard, val description: String?, - val tracks: List + val tracks: List, + val isMembershipComplete: Boolean = true ) data class SearchResults( val artistMatches: List, val trackArtists: List, - val tracks: List + val tracks: List, + val releases: List = emptyList() ) diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/ConnectedDevice.kt b/app/src/main/java/cy/hexor/furumi/domain/model/ConnectedDevice.kt index 59274ba..8b5d56e 100644 --- a/app/src/main/java/cy/hexor/furumi/domain/model/ConnectedDevice.kt +++ b/app/src/main/java/cy/hexor/furumi/domain/model/ConnectedDevice.kt @@ -19,6 +19,13 @@ data class ConnectedDevicesState( ) { val isCurrentDeviceActive: Boolean get() = activeDeviceId == deviceId + + val remoteControlTargetId: String? + get() { + val jam = jams.firstOrNull { it.id == currentJamId } ?: jams.firstOrNull { it.isActive } + if (jam != null && jam.isMember && !jam.isOwner) return activeDeviceId ?: deviceId + return activeDeviceId?.takeIf { it != deviceId } + } } data class ConnectedJam( diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/ListeningHistory.kt b/app/src/main/java/cy/hexor/furumi/domain/model/ListeningHistory.kt index 5fd69cc..ee0b2f2 100644 --- a/app/src/main/java/cy/hexor/furumi/domain/model/ListeningHistory.kt +++ b/app/src/main/java/cy/hexor/furumi/domain/model/ListeningHistory.kt @@ -8,12 +8,13 @@ data class ListeningHistoryPage( ) data class ListeningHistoryItem( - val id: Long, - val trackId: Long, + val id: String, + val trackId: Long?, val title: String, val artists: List, val releaseTitle: String?, val playedAt: String, val durationListenedSeconds: Int?, - val completed: Boolean + val completed: Boolean, + val lyricsTrack: TrackCard? = null ) diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/LyricsVersion.kt b/app/src/main/java/cy/hexor/furumi/domain/model/LyricsVersion.kt new file mode 100644 index 0000000..e2e9510 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/domain/model/LyricsVersion.kt @@ -0,0 +1,13 @@ +package cy.hexor.furumi.domain.model + +data class LyricsLine(val startMs: Long, val text: String) + +data class LyricsVersion( + val id: String, + val label: String, + val source: String, + val language: String?, + val plainText: String?, + val lines: List, + val instrumental: Boolean +) diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/OfflineMode.kt b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineMode.kt index 9403e49..1c75bd1 100644 --- a/app/src/main/java/cy/hexor/furumi/domain/model/OfflineMode.kt +++ b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineMode.kt @@ -32,7 +32,14 @@ data class OfflineSyncSummary( data class OfflineDownloadQueueState( val activeTrackIds: Set = emptySet(), val failedTrackIds: Set = emptySet(), - val lastError: String? = null + val completedTrackIds: Set = emptySet(), + val runningTrackId: Long? = null, + val trackTitles: Map = emptyMap(), + val errors: Map = emptyMap(), + val cachedTrackIds: Set = emptySet(), + val batchStartedAt: Long? = null, + val batchTrackIds: Set = emptySet(), + val transferProgress: OfflineTransferProgress? = null ) { val isDownloading: Boolean get() = activeTrackIds.isNotEmpty() diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/OfflineStorageLimit.kt b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineStorageLimit.kt new file mode 100644 index 0000000..91fc743 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineStorageLimit.kt @@ -0,0 +1,19 @@ +package cy.hexor.furumi.domain.model + +import kotlin.math.log2 +import kotlin.math.pow +import kotlin.math.roundToInt + +internal object OfflineStorageLimit { + const val GIB = 1024L * 1024 * 1024 + const val MAX_GIB = 512 + private const val OCTAVES = 9 + + fun clamp(bytes: Long): Long = bytes.coerceIn(GIB, MAX_GIB * GIB) + + fun position(bytes: Long): Float = + (log2(clamp(bytes).toDouble() / GIB) / OCTAVES).toFloat() + + fun bytesAt(position: Float): Long = + 2.0.pow(position.coerceIn(0f, 1f).toDouble() * OCTAVES).roundToInt() * GIB +} diff --git a/app/src/main/java/cy/hexor/furumi/domain/model/OfflineTransferProgress.kt b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineTransferProgress.kt new file mode 100644 index 0000000..03f5f93 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/domain/model/OfflineTransferProgress.kt @@ -0,0 +1,66 @@ +package cy.hexor.furumi.domain.model + +import java.util.Locale + +enum class OfflineTransferStage(val label: String) { + PREPARING("Finding a remote source"), + FETCHING("Receiving on server"), + VERIFYING("Verifying on server"), + DOWNLOADING("Saving to phone"), + RETRYING("Retrying download") +} + +data class OfflineTransferProgress( + val trackId: Long, + val stage: OfflineTransferStage, + val receivedBytes: Long = 0, + val totalBytes: Long? = null +) { + fun displayText(): String { + val amount = when { + totalBytes != null && totalBytes > 0 -> "${formatSize(receivedBytes)} / ${formatSize(totalBytes)}" + receivedBytes > 0 -> formatSize(receivedBytes) + else -> return stage.label + } + return "${stage.label} · $amount" + } + + private fun formatSize(bytes: Long): String { + val divisor = when { + bytes >= 1L shl 30 -> 1L shl 30 + bytes >= 1L shl 20 -> 1L shl 20 + bytes >= 1L shl 10 -> 1L shl 10 + else -> return "$bytes B" + } + val unit = when (divisor) { + 1L shl 30 -> "GiB" + 1L shl 20 -> "MiB" + else -> "KiB" + } + val amount = if (bytes % divisor == 0L) (bytes / divisor).toString() + else String.format(Locale.getDefault(), "%.1f", bytes.toDouble() / divisor) + return "$amount $unit" + } +} + +/** One reporter per transfer, including its retries. Byte callbacks run on its worker. */ +internal class OfflineProgressReporter( + private val trackId: Long, + private val publish: (OfflineTransferProgress) -> Unit, + private val nowMs: () -> Long = { System.nanoTime() / 1_000_000 } +) { + private var last: OfflineTransferProgress? = null + private var lastTime = 0L + + fun update(stage: OfflineTransferStage, received: Long = 0, total: Long? = null) { + val previous = last + if (previous?.stage == stage && previous.totalBytes == total) { + if (previous.receivedBytes == received) return + if (received != total && nowMs() - lastTime < 1000) return + } + val progress = OfflineTransferProgress(trackId, stage, received, total) + last = progress + lastTime = nowMs() + publish(progress) + } +} diff --git a/app/src/main/java/cy/hexor/furumi/domain/repository/PlayerRepository.kt b/app/src/main/java/cy/hexor/furumi/domain/repository/PlayerRepository.kt index da5d3ed..fe398e0 100644 --- a/app/src/main/java/cy/hexor/furumi/domain/repository/PlayerRepository.kt +++ b/app/src/main/java/cy/hexor/furumi/domain/repository/PlayerRepository.kt @@ -7,6 +7,7 @@ import cy.hexor.furumi.domain.model.ConnectedDevicesState import cy.hexor.furumi.domain.model.ConnectedJamUser import cy.hexor.furumi.domain.model.ConnectedPlaybackState import cy.hexor.furumi.domain.model.ListeningHistoryPage +import cy.hexor.furumi.domain.model.LyricsVersion import cy.hexor.furumi.domain.model.OfflineDownloadQueueState import cy.hexor.furumi.domain.model.OfflineState import cy.hexor.furumi.domain.model.OfflineSyncSummary @@ -31,11 +32,13 @@ interface PlayerRepository { suspend fun getReleaseDetail(releaseId: Long): Result + suspend fun getLyrics(track: TrackCard): Result> + suspend fun search(query: String, limit: Int = 20): Result suspend fun getListeningHistory(page: Int = 1, limit: Int = 20): Result - suspend fun toggleLike(trackId: Long): Result + suspend fun toggleLike(trackId: Long, desired: Boolean, knownTrack: TrackCard? = null): Result suspend fun getLikedTrackIds(): Result> @@ -54,7 +57,7 @@ interface PlayerRepository { suspend fun deletePlaylist(playlistId: Long): Result - suspend fun addTracksToPlaylist(playlistId: Long, trackIds: List): Result + suspend fun addTracksToPlaylist(playlistId: Long, trackIds: List, knownTrack: TrackCard? = null): Result suspend fun shareTrack(trackId: Long, title: String): Result @@ -102,5 +105,9 @@ interface PlayerRepository { suspend fun downloadTracksForOffline(tracks: List): Result> + suspend fun retryFailedDownloads(trackIds: Set): Result + + suspend fun getDownloadedTracks(ids: Set? = null): List + suspend fun clearOfflineCache(): Result } diff --git a/app/src/main/java/cy/hexor/furumi/offline/OfflineDownloadJobService.kt b/app/src/main/java/cy/hexor/furumi/offline/OfflineDownloadJobService.kt index 4e8004e..b472ee3 100644 --- a/app/src/main/java/cy/hexor/furumi/offline/OfflineDownloadJobService.kt +++ b/app/src/main/java/cy/hexor/furumi/offline/OfflineDownloadJobService.kt @@ -8,6 +8,22 @@ import android.app.job.JobService import android.content.Context import android.content.Intent import android.os.Build +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import java.net.ConnectException +import java.net.SocketException +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import android.util.Log +import cy.hexor.furumi.data.local.OfflineAccountScope +import cy.hexor.furumi.data.local.OfflineDownloadJobScheduler +import cy.hexor.furumi.data.local.DOWNLOAD_TIMEOUT_MESSAGE +import cy.hexor.furumi.domain.model.OfflineDownloadQueueState +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.coroutineScope import androidx.core.app.NotificationCompat import cy.hexor.furumi.MainActivity import cy.hexor.furumi.data.local.OfflineDownloadQueueStore @@ -20,32 +36,68 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel -import kotlinx.coroutines.isActive import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext @AndroidEntryPoint class OfflineDownloadJobService : JobService() { @Inject lateinit var downloadQueueStore: OfflineDownloadQueueStore @Inject lateinit var offlineMediaStore: OfflineMediaStore - private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + @Inject lateinit var accounts: OfflineAccountScope + @Inject lateinit var scheduler: OfflineDownloadJobScheduler + + private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private var activeJob: Job? = null - @Volatile private var stoppedBySystem = false + private var activeParams: JobParameters? = null override fun onStartJob(params: JobParameters): Boolean { - stoppedBySystem = false - publishUserInitiatedJobNotification(params) + // Satisfy the UIDT deadline even on a cold process with an unopened catalog. + publishProgress(params, OfflineDownloadQueueState()) + val account = params.extras.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY) + if (!accounts.matches(account) || account == null) { + removeNotification() + return false + } activeJob?.cancel() + downloadQueueStore.pauseTransfer(account) + activeParams = params activeJob = serviceScope.launch { + var reschedule = false try { - runDownloadQueue() - if (!stoppedBySystem) { - jobFinished(params, false) + accounts.withAccount(account) { + coroutineScope { + val notifications = launch(Dispatchers.Main.immediate) { + downloadQueueStore.state.collect { state -> + if (activeParams === params && accounts.matches(account)) publishProgress(params, state) + } + } + val worker = launch { reschedule = runDownloadQueue(account) } + val watch = launch { + accounts.keys.first { it != account } + worker.cancel() + } + try { + worker.join() + } finally { + notifications.cancel() + watch.cancel() + } + } } } catch (_: CancellationException) { - if (!stoppedBySystem) { - jobFinished(params, true) + reschedule = accounts.matches(account) + } catch (error: Exception) { + Log.w("OfflineDownloads", "Download job interrupted", error) + reschedule = accounts.matches(account) + } finally { + if (activeParams === params) { + activeParams = null + downloadQueueStore.pauseTransfer(account) + removeNotification() + scheduler.finished { + val pending = accounts.matches(account) && downloadQueueStore.state.value.isDownloading + jobFinished(params, reschedule || pending) + } } } } @@ -53,71 +105,101 @@ class OfflineDownloadJobService : JobService() { } override fun onStopJob(params: JobParameters): Boolean { - stoppedBySystem = true - activeJob?.cancel() - return true + if (activeParams?.extras?.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY) == + params.extras.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY)) { + activeParams = null + activeJob?.cancel() + downloadQueueStore.pauseTransfer(params.extras.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY)) + removeNotification() + } + return accounts.matches(params.extras.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY)) } override fun onDestroy() { - activeJob?.cancel() + downloadQueueStore.pauseTransfer(activeParams?.extras?.getString(OfflineDownloadJobScheduler.ACCOUNT_KEY)) + activeParams = null serviceScope.cancel() super.onDestroy() } - private suspend fun runDownloadQueue() = withContext(Dispatchers.IO) { + private suspend fun runDownloadQueue(account: String): Boolean { downloadQueueStore.refresh() - offlineMediaStore.publishStorageStats() - - while (isActive) { - val track = downloadQueueStore.nextPendingDownloadTrack() ?: break + while (accounts.matches(account)) { + currentCoroutineContext().ensureActive() + val track = downloadQueueStore.nextPendingDownloadTrack() + if (track == null) { + val cover = downloadQueueStore.nextCover() ?: break + offlineMediaStore.cacheDownloadedCover(cover) + continue + } downloadQueueStore.markRunning(track.id) try { offlineMediaStore.downloadTrackForOffline(track) - downloadQueueStore.markCompleted(track.id) } catch (e: CancellationException) { throw e } catch (e: Exception) { - downloadQueueStore.markFailed(track.id, e.message ?: "Unable to download track") + currentCoroutineContext().ensureActive() + val isConnectionError = e is SocketTimeoutException || e is UnknownHostException || + e is SocketException || e is java.io.EOFException || e is java.net.ProtocolException + val connectivity = getSystemService(ConnectivityManager::class.java) + val network = connectivity.getNetworkCapabilities(connectivity.activeNetwork) + if (isConnectionError && network?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) != true) { + return true // Keep the interrupted file queued for the next network. + } + val message = when (e) { + is SocketTimeoutException -> DOWNLOAD_TIMEOUT_MESSAGE + is UnknownHostException, is ConnectException -> "Could not connect to the music server. Check the connection and retry." + is SocketException -> "The connection was interrupted. Retry to resume." + else -> e.message ?: "Could not download this track" + } + Log.w("OfflineDownloads", "Audio ${track.id} '${track.title}' failed: ${e.message}") + downloadQueueStore.markFailed(track.id, message) } - offlineMediaStore.publishStorageStats() } - - offlineMediaStore.publishStorageStats() + return false } - private fun publishUserInitiatedJobNotification(params: JobParameters) { - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE || !params.isUserInitiatedJob) { - return - } - + private fun publishProgress(params: JobParameters, state: OfflineDownloadQueueState) { createNotificationChannel() - setNotification( - params, - NOTIFICATION_ID, - buildNotification(), - JOB_END_NOTIFICATION_POLICY_REMOVE - ) - } - - private fun buildNotification() = - NotificationCompat.Builder(this, CHANNEL_ID) + val batch = state.batchTrackIds + val completed = batch.count { it in state.completedTrackIds } + val errors = batch.count { it in state.failedTrackIds } + val track = state.runningTrackId?.let(state.trackTitles::get) + val batchSummary = buildList { + if (batch.isNotEmpty()) add("$completed of ${batch.size} downloaded") + if (errors > 0) add("$errors failed") + }.joinToString(" · ") + val transfer = state.transferProgress?.displayText() + val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(android.R.drawable.stat_sys_download) - .setContentTitle("Downloading offline music") - .setContentText("Saving tracks for offline playback") + .setContentTitle(track ?: "Offline music") + .setContentText(transfer ?: batchSummary.ifEmpty { "Preparing downloads" }) + .setSubText(batchSummary.takeIf { transfer != null && it.isNotEmpty() }) .setContentIntent(contentIntent()) .setCategory(NotificationCompat.CATEGORY_PROGRESS) .setPriority(NotificationCompat.PRIORITY_LOW) - .setProgress(0, 0, true) + .setProgress(batch.size, completed, batch.isEmpty()) .setOnlyAlertOnce(true) .setSilent(true) .setOngoing(true) .build() + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE && params.isUserInitiatedJob) { + setNotification(params, NOTIFICATION_ID, notification, JOB_END_NOTIFICATION_POLICY_REMOVE) + } else { + val manager = getSystemService(NotificationManager::class.java) + if (manager.areNotificationsEnabled()) manager.notify(NOTIFICATION_ID, notification) + } + } + + private fun removeNotification() { + getSystemService(NotificationManager::class.java).cancel(NOTIFICATION_ID) + } private fun contentIntent(): PendingIntent = PendingIntent.getActivity( this, 0, - Intent(this, MainActivity::class.java), + Intent(this, MainActivity::class.java).setAction(MainActivity.ACTION_OPEN_DOWNLOADS), PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) diff --git a/app/src/main/java/cy/hexor/furumi/playback/PlaybackController.kt b/app/src/main/java/cy/hexor/furumi/playback/PlaybackController.kt index 8b683cc..346562f 100644 --- a/app/src/main/java/cy/hexor/furumi/playback/PlaybackController.kt +++ b/app/src/main/java/cy/hexor/furumi/playback/PlaybackController.kt @@ -30,6 +30,7 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlin.math.roundToLong import okhttp3.OkHttpClient import javax.inject.Inject import javax.inject.Singleton @@ -72,7 +73,8 @@ data class AudioPlaybackState( @Singleton class PlaybackController @Inject constructor( @param:ApplicationContext private val context: Context, - okHttpClient: OkHttpClient + okHttpClient: OkHttpClient, + federatedAudio: cy.hexor.furumi.data.remote.FederatedAudioResolver ) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val _state = MutableStateFlow(AudioPlaybackState()) @@ -92,7 +94,12 @@ class PlaybackController @Inject constructor( context, OkHttpDataSource.Factory(okHttpClient) ) - val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory) + val resolved = androidx.media3.datasource.ResolvingDataSource.Factory(dataSourceFactory) { data -> + if (data.uri.scheme == "furumi-fed") { + data.withUri(Uri.parse(kotlinx.coroutines.runBlocking { federatedAudio.resolve(data.uri) })) + } else data + } + val mediaSourceFactory = DefaultMediaSourceFactory(resolved) player = ExoPlayer.Builder(context) .setMediaSourceFactory(mediaSourceFactory) @@ -245,12 +252,15 @@ class PlaybackController @Inject constructor( fun seekToProgress(progress: Float) { val duration = player.duration.takeIf { it > 0L } ?: return - player.seekTo((duration * progress.coerceIn(0f, 1f)).toLong()) - publishState() + seekToPositionMs((duration * progress.coerceIn(0f, 1f)).toLong()) } fun seekToSeconds(seconds: Double) { - player.seekTo((seconds.coerceAtLeast(0.0) * 1_000.0).toLong()) + if (seconds.isFinite()) seekToPositionMs((seconds * 1_000.0).roundToLong()) + } + + fun seekToPositionMs(positionMs: Long) { + player.seekTo(positionMs.coerceAtLeast(0L)) publishState() } diff --git a/app/src/main/java/cy/hexor/furumi/ui/login/LoginScreen.kt b/app/src/main/java/cy/hexor/furumi/ui/login/LoginScreen.kt index 97c0207..b0d9dd8 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/login/LoginScreen.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/login/LoginScreen.kt @@ -30,12 +30,12 @@ import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiInk import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -129,7 +129,7 @@ private fun BrandHeader() { modifier = Modifier .size(34.dp) .clip(CircleShape) - .background(FurumiNeonPink), + .background(FurumiAccent), contentAlignment = Alignment.Center ) { Text( @@ -158,15 +158,15 @@ private fun AlbumTileStrip() { ) { AlbumTile( modifier = Modifier.weight(1f), - brush = Brush.linearGradient(listOf(FurumiNeonPink, FurumiSurfaceHigh)) + brush = Brush.linearGradient(listOf(FurumiAccent, FurumiSurfaceHigh)) ) AlbumTile( modifier = Modifier.weight(1f), - brush = Brush.linearGradient(listOf(FurumiElectricCyan, FurumiInk)) + brush = Brush.linearGradient(listOf(FurumiAccentBright, FurumiInk)) ) AlbumTile( modifier = Modifier.weight(1f), - brush = Brush.linearGradient(listOf(FurumiNeonViolet, FurumiHotOrange, FurumiSurface)) + brush = Brush.linearGradient(listOf(FurumiAccentMuted, FurumiAccentMuted, FurumiSurface)) ) } } @@ -234,7 +234,7 @@ private fun LoginControls( enabled = !uiState.isLoading, shape = CircleShape, colors = ButtonDefaults.buttonColors( - containerColor = FurumiNeonPink, + containerColor = FurumiAccent, contentColor = MaterialTheme.colorScheme.onPrimary, disabledContainerColor = FurumiSurfaceHigh, disabledContentColor = FurumiTextMuted @@ -365,10 +365,10 @@ private fun LoginTextField( focusedContainerColor = FurumiSurface, unfocusedContainerColor = FurumiSurface, disabledContainerColor = FurumiSurface, - focusedBorderColor = FurumiNeonPink, + focusedBorderColor = FurumiAccent, unfocusedBorderColor = FurumiLine, disabledBorderColor = FurumiLine, - focusedLabelColor = FurumiNeonPink, + focusedLabelColor = FurumiAccent, unfocusedLabelColor = FurumiTextMuted, disabledLabelColor = FurumiTextMuted, focusedPlaceholderColor = FurumiTextMuted, diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/DeviceDownloadsContent.kt b/app/src/main/java/cy/hexor/furumi/ui/player/DeviceDownloadsContent.kt new file mode 100644 index 0000000..8c93295 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/ui/player/DeviceDownloadsContent.kt @@ -0,0 +1,170 @@ +package cy.hexor.furumi.ui.player + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import cy.hexor.furumi.domain.model.TrackCard +import kotlinx.coroutines.CancellationException + +@Composable +internal fun DeviceDownloadsContent( + uiState: PlayerUiState, + getDownloadedTracks: suspend (Set?) -> List, + onMediaImageNeeded: (String?) -> Unit, + onPlay: (TrackCard, List) -> Unit, + onLyrics: (TrackCard) -> Unit, + onRetry: (Set) -> Unit, + onStorageLimitChange: (Long) -> Unit, + onClear: () -> Unit, + onBack: () -> Unit +) { + val queue = uiState.offlineQueue + var tracks by remember { mutableStateOf?>(null) } + var loadError by remember { mutableStateOf(null) } + var reload by remember { mutableIntStateOf(0) } + val count = uiState.offlineState.cachedTrackCount + LaunchedEffect(queue.cachedTrackIds, reload) { + try { + val previous = tracks + tracks = if (previous == null) { + getDownloadedTracks(null) + } else { + val kept = previous.filter { it.id in queue.cachedTrackIds } + val missing = queue.cachedTrackIds - kept.map { it.id }.toSet() + if (missing.isEmpty()) kept else (kept + getDownloadedTracks(missing)).sortedBy { it.title.lowercase() } + } + loadError = null + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + loadError = e.message ?: "Could not read downloads" + } + } + + var showFailures by rememberSaveable { mutableStateOf(false) } + var menuOpen by remember { mutableStateOf(false) } + val colors = MaterialTheme.colorScheme + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + item(key = "header") { + Column { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + TextButton(onClick = onBack, contentPadding = PaddingValues(end = 12.dp)) { + BackGlyph(Modifier.size(18.dp), colors.onSurfaceVariant) + Spacer(Modifier.width(6.dp)) + Text("Library", color = colors.onSurfaceVariant) + } + Spacer(Modifier.weight(1f)) + if (count > 0 || queue.activeTrackIds.isNotEmpty() || queue.failedTrackIds.isNotEmpty()) { + Box { + IconButton(onClick = { menuOpen = true }, + modifier = Modifier.semantics { contentDescription = "Manage downloads" }) { + MoreDotsGlyph(Modifier.size(24.dp), colors.onSurfaceVariant) + } + DropdownMenu(menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem(text = { Text("Clear downloads", color = colors.error) }, + onClick = { menuOpen = false; onClear() }) + } + } + } + } + Text("On device", style = MaterialTheme.typography.headlineMedium) + } + } + if (queue.activeTrackIds.isNotEmpty() || queue.failedTrackIds.isNotEmpty()) { + item(key = "download-status") { + Surface(shape = RoundedCornerShape(16.dp), color = colors.surfaceContainer) { + Column(Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { + val current = queue.runningTrackId + val waiting = queue.activeTrackIds.size - if (current in queue.activeTrackIds) 1 else 0 + val status = when { + current != null -> "Downloading" + waiting > 0 && uiState.offlineState.isUsingNetworkFallback -> "Waiting for connection" + waiting > 0 -> "In queue" + else -> "Downloads" + } + Text(status, style = MaterialTheme.typography.titleMedium) + if (current != null) { + Text(queue.trackTitles[current].orEmpty().ifBlank { "Untitled track" }, + style = MaterialTheme.typography.bodyMedium, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + queue.transferProgress?.takeIf { it.trackId == current }?.let { transfer -> + Text(transfer.displayText(), style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant) + } + if (waiting > 0) Text("$waiting queued", color = colors.onSurfaceVariant, + style = MaterialTheme.typography.bodyMedium) + if (queue.failedTrackIds.isNotEmpty()) { + TextButton(onClick = { showFailures = !showFailures }, contentPadding = PaddingValues(horizontal = 4.dp)) { + Text(if (showFailures) "Hide failed downloads" else "${queue.failedTrackIds.size} failed · View details", + color = colors.error) + } + } + } + } + } + if (showFailures && queue.failedTrackIds.isNotEmpty()) { + items(queue.failedTrackIds.toList(), key = { "failed-$it" }, contentType = { "failure" }) { id -> + Column(Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp)) { + Text(queue.trackTitles[id].orEmpty().ifBlank { "Untitled track" }, style = MaterialTheme.typography.titleSmall) + Text(queue.errors[id] ?: "Download interrupted", style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant) + } + } + item(key = "retry") { + OutlinedButton(onClick = { onRetry(queue.failedTrackIds) }, enabled = uiState.canStartOfflineDownload()) { + Text("Retry failed downloads") + } + } + } + } + item(key = "limit") { + Surface(shape = RoundedCornerShape(16.dp), color = colors.surfaceContainer) { + Box(Modifier.fillMaxWidth().padding(16.dp)) { + OfflineStorageSlider(uiState.offlineState, onStorageLimitChange) + } + } + } + item(key = "saved") { + Row(Modifier.fillMaxWidth().padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) { + Text("Available offline", modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleLarge) + Text(pluralCount(count, "track"), color = colors.onSurfaceVariant, style = MaterialTheme.typography.labelLarge) + } + } + val available = tracks + when { + loadError != null -> item(key = "error") { + TextButton(onClick = { reload++ }) { Text("${loadError.orEmpty()} · Retry") } + } + available == null -> item(key = "loading") { LoadingTrackRows() } + available.isEmpty() -> item(key = "empty") { Text("No downloaded tracks yet", color = colors.onSurfaceVariant) } + else -> items(available, key = { it.id }, contentType = { "track" }) { track -> + LaunchedEffect(track.coverUrl) { onMediaImageNeeded(track.coverUrl) } + Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClickLabel = "Play") { onPlay(track, available) } + .padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { + MediaArtwork(title = track.title, seedId = track.id, bitmap = mediaImageFor(uiState.mediaImages, track.coverUrl), + modifier = Modifier.size(44.dp), cornerRadius = 6) + Column(Modifier.weight(1f).padding(start = 12.dp)) { + Text(track.title, style = MaterialTheme.typography.titleSmall, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(trackSubtitle(track), color = colors.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium, + maxLines = 1, overflow = TextOverflow.Ellipsis) + } + LyricsIconButton(track.title) { onLyrics(track) } + } + } + } + } +} diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/DevicePollingSession.kt b/app/src/main/java/cy/hexor/furumi/ui/player/DevicePollingSession.kt new file mode 100644 index 0000000..fc15bb6 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/ui/player/DevicePollingSession.kt @@ -0,0 +1,30 @@ +package cy.hexor.furumi.ui.player + +import cy.hexor.furumi.domain.model.ConnectedCommand +import cy.hexor.furumi.domain.model.ConnectedDevicesState +import cy.hexor.furumi.domain.model.ConnectedPlaybackState + +/** Only an uninterrupted, server-confirmed local owner can publish its queue. */ +internal class DevicePollingSession { + var generation = 0L + private set + private var canPublishPlayback = false + + fun invalidate() { + generation++ + canPublishPlayback = false + } + + suspend fun poll( + playback: () -> ConnectedPlaybackState?, + request: suspend (ConnectedPlaybackState?) -> Result>> + ): Result>>? { + val started = generation + val result = request(if (canPublishPlayback) playback() else null) + if (started != generation) return null + + val devices = result.getOrNull()?.first + canPublishPlayback = devices?.isCurrentDeviceActive == true && devices.remoteControlTargetId == null + return result + } +} diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/LyricsScreen.kt b/app/src/main/java/cy/hexor/furumi/ui/player/LyricsScreen.kt new file mode 100644 index 0000000..abf3610 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/ui/player/LyricsScreen.kt @@ -0,0 +1,305 @@ +package cy.hexor.furumi.ui.player + +import android.graphics.Bitmap +import android.os.SystemClock +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import cy.hexor.furumi.domain.model.LyricsLine +import cy.hexor.furumi.domain.model.LyricsVersion +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.playback.AudioPlaybackState +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import kotlinx.coroutines.delay +import kotlin.math.abs + +sealed interface LyricsUiState { + data object Loading : LyricsUiState + data class Content(val versions: List) : LyricsUiState + data class Error(val message: String) : LyricsUiState +} + +private val LyricsBackground = Brush.verticalGradient(listOf(Color(0xFF204A3B), Color(0xFF142E26), Color(0xFF101B17))) +private val LyricsSecondary = Color(0xFFD0DED6) +private val UpcomingLine = Color(0xFFB0C6B8) + +@Composable +internal fun LyricsScreen( + track: TrackCard, + state: LyricsUiState, + playback: AudioPlaybackState, + onClose: () -> Unit, + onRetry: () -> Unit, + onPlayPause: () -> Unit, + onSeekToLine: (Long) -> Unit, + coverBitmap: Bitmap? = null +) { + val versions = (state as? LyricsUiState.Content)?.versions.orEmpty() + var selectedId by rememberSaveable(track.id) { mutableStateOf(null) } + val version = remember(versions, selectedId) { + versions.firstOrNull { it.id == selectedId } ?: versions.firstOrNull { it.lines.isNotEmpty() } ?: versions.firstOrNull() + } + val isCurrent = playback.currentTrack?.id == track.id + + Dialog( + onDismissRequest = onClose, + properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false) + ) { + Box( + Modifier.fillMaxSize().background(LyricsBackground).windowInsetsPadding(WindowInsets.safeDrawing), + contentAlignment = Alignment.TopCenter + ) { + Column(Modifier.widthIn(max = 720.dp).fillMaxSize()) { + Row(Modifier.fillMaxWidth().padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = onClose, modifier = Modifier.semantics { contentDescription = "Close lyrics" }) { + BackGlyph(Modifier.size(20.dp), Color.White) + } + Text("Lyrics", modifier = Modifier.weight(1f).padding(start = 4.dp), + color = Color.White, style = MaterialTheme.typography.titleMedium) + if (versions.size > 1 && version != null) { + LyricsVersions(versions, version, onSelect = { selectedId = it.id }) + } + } + Row(Modifier.fillMaxWidth().padding(start = 20.dp, end = 20.dp, top = 4.dp, bottom = 16.dp), + verticalAlignment = Alignment.CenterVertically) { + MediaArtwork(track.title, track.id, coverBitmap, Modifier.size(48.dp), cornerRadius = 8) + Column(Modifier.weight(1f).padding(start = 12.dp)) { + Text(track.title, style = MaterialTheme.typography.titleLarge, color = Color.White, + fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis) + val artist = track.artists.joinToString(", ") + if (artist.isNotBlank()) Text(artist, style = MaterialTheme.typography.bodyMedium, + color = LyricsSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + HorizontalDivider(color = Color.White.copy(alpha = 0.13f)) + key(track.id, version?.id) { + var follow by rememberSaveable { mutableStateOf(true) } + val timed = version?.lines?.isNotEmpty() == true + Box(Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.Center) { + when { + state is LyricsUiState.Loading -> + CircularProgressIndicator(Modifier.semantics { contentDescription = "Loading lyrics" }, color = FurumiAccentBright) + state is LyricsUiState.Error -> Column( + Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally + ) { + Text(state.message, color = LyricsSecondary, style = MaterialTheme.typography.bodyLarge) + TextButton(onClick = onRetry) { Text("Retry", color = Color.White) } + } + version == null -> Text("Lyrics are unavailable for this track", color = LyricsSecondary) + version.instrumental -> Text("Instrumental", color = LyricsSecondary, style = MaterialTheme.typography.titleLarge) + timed -> TimedLyrics( + lines = version.lines, + positionMs = playback.positionMs.takeIf { isCurrent }, + advancing = playback.isPlaying && !playback.isBuffering, + follow = follow, + onBrowse = { follow = false }, + onSeekToLine = { positionMs -> + onSeekToLine(positionMs) + follow = true + } + ) + !version.plainText.isNullOrBlank() -> PlainLyrics(version.plainText) + else -> Text("Lyrics are unavailable for this track", color = LyricsSecondary) + } + } + + if (isCurrent || !version?.source.isNullOrBlank()) { + HorizontalDivider(color = Color.White.copy(alpha = 0.13f)) + Row(Modifier.fillMaxWidth().heightIn(min = 60.dp).padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically) { + if (isCurrent) { + FilledIconButton( + onClick = onPlayPause, + modifier = Modifier.semantics { contentDescription = if (playback.isPlaying) "Pause" else "Play" }, + colors = IconButtonDefaults.filledIconButtonColors(containerColor = FurumiAccentBright) + ) { PlaybackGlyph(playback, playSize = 19, pauseSize = 19) } + Text(formatPlaybackTime(playback.positionMs), color = Color.White, + modifier = Modifier.padding(start = 8.dp), + style = MaterialTheme.typography.labelLarge) + } + Spacer(Modifier.weight(1f)) + if (isCurrent && timed && !follow) { + TextButton(onClick = { follow = true }) { Text("Back to current line", color = FurumiAccentBright) } + } else if (version != null) { + Text(version.source, style = MaterialTheme.typography.labelMedium, + color = LyricsSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis) + } + } + } + } + } + } + } +} + +@Composable +private fun LyricsVersions(versions: List, selected: LyricsVersion, onSelect: (LyricsVersion) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + TextButton(onClick = { open = true }, modifier = Modifier.widthIn(max = 200.dp)) { + Text(selected.displayLabel(versions.indexOf(selected)), Modifier.weight(1f, fill = false), + color = Color.White, maxLines = 1, overflow = TextOverflow.Ellipsis) + Spacer(Modifier.width(8.dp)) + BackGlyph(Modifier.size(12.dp).rotate(-90f), LyricsSecondary) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }) { + versions.forEachIndexed { index, version -> + DropdownMenuItem(text = { + Column { + Text(version.displayLabel(index), color = if (selected.id == version.id) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface) + val details = listOfNotNull(version.source.takeIf { it.isNotBlank() }, version.language?.takeIf { it.isNotBlank() }).distinct() + if (details.isNotEmpty()) Text(details.joinToString(" · "), style = MaterialTheme.typography.bodySmall) + } + }, onClick = { open = false; onSelect(version) }) + } + } + } +} + +private fun LyricsVersion.displayLabel(index: Int): String = + label.ifBlank { language?.takeIf(String::isNotBlank) ?: source.ifBlank { "Version ${index + 1}" } } + +@Composable +private fun TimedLyrics( + lines: List, + positionMs: Long?, + advancing: Boolean, + follow: Boolean, + onBrowse: () -> Unit, + onSeekToLine: (Long) -> Unit +) { + val isCurrent = positionMs != null + val active by produceState(initialValue = -1, lines, positionMs, advancing) { + if (positionMs == null) { + value = -1 + return@produceState + } + // Remote playheads arrive in polls. Wake at the next cue, then re-anchor on each real update. + val anchor = SystemClock.elapsedRealtime() + while (true) { + val elapsed = if (advancing) SystemClock.elapsedRealtime() - anchor else 0L + val position = positionMs + elapsed + value = activeLyricsLine(lines, position) + val next = lines.getOrNull(value + 1) ?: break + if (!advancing) break + delay((next.startMs - position).coerceAtLeast(1)) + } + } + val list = rememberLazyListState() + var activeBeforeSeek by remember { mutableStateOf(null) } + val browse by rememberUpdatedState(onBrowse) + val scroll = remember { + object : NestedScrollConnection { + override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset { + if (available.y != 0f && source == NestedScrollSource.UserInput) browse() + return Offset.Zero + } + } + } + BoxWithConstraints(Modifier.fillMaxSize()) { + val anchor = maxHeight * 0.30f + val anchorPx = with(LocalDensity.current) { anchor.roundToPx() } + LaunchedEffect(active, follow, anchorPx, isCurrent) { + if (!follow || !isCurrent) return@LaunchedEffect + // A remote player can still report its old position when a tap resumes following. + val waitingForSeek = activeBeforeSeek == active + activeBeforeSeek = null + if (waitingForSeek) return@LaunchedEffect + val target = active.coerceAtLeast(0) + val offset = if (target == 0) 0 else -anchorPx + if (abs(target - list.firstVisibleItemIndex) > 8) list.scrollToItem(target, offset) + else list.animateScrollToItem(target, offset) + } + LazyColumn( + state = list, + modifier = Modifier.fillMaxSize().nestedScroll(scroll), + contentPadding = PaddingValues(top = 18.dp, bottom = maxHeight * 0.60f) + ) { + itemsIndexed(lines) { index, line -> + val current = index == active + val color = when { + !isCurrent -> Color.White + current -> Color.White + index < active -> LyricsSecondary + else -> UpcomingLine + } + val seekAction = if (isCurrent) { + Modifier.clickable( + role = Role.Button, + onClickLabel = "Seek to ${formatPlaybackTime(line.startMs)}" + ) { + if (!follow && index != active) activeBeforeSeek = active + onSeekToLine(line.startMs) + } + } else Modifier + Row( + modifier = Modifier.fillMaxWidth().then(seekAction) + .semantics(mergeDescendants = true) { selected = current } + .heightIn(min = 48.dp) + .padding(start = 12.dp, top = 7.dp, end = 24.dp, bottom = 7.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Box(Modifier.size(width = 3.dp, height = 26.dp).clip(CircleShape) + .background(if (current) FurumiAccentBright else Color.Transparent)) + Spacer(Modifier.width(12.dp)) + val isBreak = line.text.isBlank() + Text(if (isBreak) "♪" else line.text, modifier = if (isBreak) Modifier.semantics { + contentDescription = "Instrumental break" + } else Modifier, color = color, fontWeight = FontWeight.Bold, fontSize = 28.sp, lineHeight = 36.sp) + } + } + } + } +} + +@Composable +private fun PlainLyrics(text: String) { + val lines = remember(text) { text.trim().lines() } + LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(horizontal = 24.dp, vertical = 20.dp)) { + items(lines.size) { index -> + val line = lines[index] + if (line.isBlank()) Spacer(Modifier.height(16.dp)) + else Text(line, modifier = Modifier.padding(vertical = 4.dp), color = Color.White, + fontWeight = FontWeight.SemiBold, fontSize = 24.sp, lineHeight = 32.sp) + } + } +} + +/** Index of the last line whose start time has been reached, or -1 during the intro. */ +internal fun activeLyricsLine(lines: List, positionMs: Long): Int { + var from = 0 + var until = lines.size + while (from < until) { + val middle = from + (until - from) / 2 + if (lines[middle].startMs <= positionMs) from = middle + 1 else until = middle + } + return from - 1 +} diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/OfflineStorageSlider.kt b/app/src/main/java/cy/hexor/furumi/ui/player/OfflineStorageSlider.kt new file mode 100644 index 0000000..8c024e7 --- /dev/null +++ b/app/src/main/java/cy/hexor/furumi/ui/player/OfflineStorageSlider.kt @@ -0,0 +1,85 @@ +package cy.hexor.furumi.ui.player + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.semantics.setProgress +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.unit.dp +import cy.hexor.furumi.domain.model.OfflineState +import cy.hexor.furumi.domain.model.OfflineStorageLimit +import kotlin.math.roundToInt + +@Composable +internal fun OfflineStorageSlider(offlineState: OfflineState, onLimitChange: (Long) -> Unit) { + val limit = offlineState.settings.storageLimitBytes + var position by remember(limit) { mutableFloatStateOf(OfflineStorageLimit.position(limit)) } + val selected = OfflineStorageLimit.bytesAt(position) + val gib = (selected / OfflineStorageLimit.GIB).toInt() + val label = "$gib GB" + val colors = MaterialTheme.colorScheme + + Column(modifier = Modifier.fillMaxWidth()) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Offline storage limit", modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleSmall) + Text(label, style = MaterialTheme.typography.titleSmall, color = colors.primary) + } + Text( + "${formatStorageBytes(offlineState.storageUsedBytes)} used", + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant + ) + Box( + modifier = Modifier.fillMaxWidth().clearAndSetSemantics { + contentDescription = "Offline storage limit" + stateDescription = label + progressBarRangeInfo = ProgressBarRangeInfo(gib.toFloat(), 1f..512f, 510) + setProgress { target -> + val next = target.roundToInt().coerceIn(1, OfflineStorageLimit.MAX_GIB) + if (next == gib) return@setProgress false + val bytes = next * OfflineStorageLimit.GIB + position = OfflineStorageLimit.position(bytes) + onLimitChange(bytes) + true + } + } + ) { + Slider( + value = position, + onValueChange = { position = it }, + onValueChangeFinished = { + val bytes = OfflineStorageLimit.bytesAt(position) + if (bytes != limit) onLimitChange(bytes) + } + ) + } + Row(modifier = Modifier.fillMaxWidth()) { + Text("1 GB", modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelSmall, color = colors.onSurfaceVariant) + Text("512 GB", style = MaterialTheme.typography.labelSmall, color = colors.onSurfaceVariant) + } + if (offlineState.storageUsedBytes > selected) { + Text( + "Downloaded tracks are kept. Raise the limit or clear downloads to make room.", + modifier = Modifier.padding(top = 6.dp), + style = MaterialTheme.typography.bodySmall, + color = colors.onSurfaceVariant + ) + } + } +} diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerArtwork.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerArtwork.kt index 2585325..cbad15c 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerArtwork.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerArtwork.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerChrome.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerChrome.kt index 49322c9..18b39c5 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerChrome.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerChrome.kt @@ -25,7 +25,8 @@ import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.IconButton +import androidx.compose.material3.TextButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Slider @@ -44,6 +45,8 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset @@ -63,17 +66,18 @@ import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import cy.hexor.furumi.domain.model.ArtistCard import cy.hexor.furumi.domain.model.ConnectedDevice +import cy.hexor.furumi.domain.model.ConnectedDevicesState import cy.hexor.furumi.domain.model.PlaylistCard import cy.hexor.furumi.domain.model.ReleaseCard import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -120,7 +124,7 @@ internal fun PlayerHeader( modifier = Modifier .size(28.dp) .clip(CircleShape) - .background(FurumiNeonPink), + .background(FurumiAccent), contentAlignment = Alignment.Center ) { Text( @@ -204,7 +208,7 @@ internal fun ProfileMenu( enabled = !uiState.isLoggingOut, shape = CircleShape, colors = ButtonDefaults.buttonColors( - containerColor = FurumiNeonPink, + containerColor = FurumiAccent, contentColor = FurumiBlack, disabledContainerColor = FurumiSurface, disabledContentColor = FurumiTextMuted @@ -240,7 +244,7 @@ private fun ProfileSummary(uiState: PlayerUiState) { modifier = Modifier .size(34.dp) .clip(CircleShape) - .background(FurumiNeonPink), + .background(FurumiAccent), contentAlignment = Alignment.Center ) { Text( @@ -294,12 +298,6 @@ private fun OfflineControlsSection( ) { val offlineState = uiState.offlineState val settings = offlineState.settings - val storageProgress = if (settings.storageLimitBytes > 0L) { - (offlineState.storageUsedBytes.toFloat() / settings.storageLimitBytes.toFloat()).coerceIn(0f, 1f) - } else { - 0f - } - Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { Text( text = "Offline", @@ -318,42 +316,7 @@ private fun OfflineControlsSection( checked = settings.saveListenedTracksEnabled, onCheckedChange = onSaveListenedChange ) - Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = "Storage", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onBackground, - modifier = Modifier.weight(1f) - ) - Text( - text = "${formatStorageBytes(offlineState.storageUsedBytes)} / ${formatStorageBytes(settings.storageLimitBytes)}", - style = MaterialTheme.typography.labelSmall, - color = FurumiTextMuted - ) - } - LinearProgressIndicator( - progress = { storageProgress }, - modifier = Modifier - .fillMaxWidth() - .height(4.dp) - .clip(CircleShape), - color = FurumiNeonPink, - trackColor = FurumiLine - ) - Row( - modifier = Modifier.horizontalScroll(rememberScrollState()), - horizontalArrangement = Arrangement.spacedBy(8.dp) - ) { - offlineStorageLimitOptions.forEach { limit -> - OfflineLimitChip( - label = formatStorageBytes(limit), - selected = settings.storageLimitBytes == limit, - onClick = { onStorageLimitChange(limit) } - ) - } - } - } + OfflineStorageSlider(offlineState = offlineState, onLimitChange = onStorageLimitChange) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedButton( onClick = onSyncOffline, @@ -401,7 +364,7 @@ private fun OfflineControlsSection( Text( text = error, style = MaterialTheme.typography.bodySmall, - color = FurumiHotOrange, + color = FurumiError, maxLines = 2, overflow = TextOverflow.Ellipsis ) @@ -439,7 +402,7 @@ private fun ProfileSwitchRow( onCheckedChange = onCheckedChange, colors = SwitchDefaults.colors( checkedThumbColor = FurumiBlack, - checkedTrackColor = FurumiNeonPink, + checkedTrackColor = FurumiAccent, uncheckedThumbColor = FurumiTextMuted, uncheckedTrackColor = FurumiSurface, uncheckedBorderColor = FurumiLine @@ -448,33 +411,6 @@ private fun ProfileSwitchRow( } } -@Composable -private fun OfflineLimitChip( - label: String, - selected: Boolean, - onClick: () -> Unit -) { - Surface( - modifier = Modifier - .height(32.dp) - .clip(CircleShape) - .clickable(onClick = onClick), - shape = CircleShape, - color = if (selected) FurumiNeonPink else FurumiSurface, - border = if (selected) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine) - ) { - Box( - modifier = Modifier.padding(horizontal = 12.dp), - contentAlignment = Alignment.Center - ) { - Text( - text = label, - style = MaterialTheme.typography.labelSmall, - color = if (selected) FurumiBlack else MaterialTheme.colorScheme.onBackground - ) - } - } -} @Composable internal fun OfflineStatusBadge( @@ -484,7 +420,7 @@ internal fun OfflineStatusBadge( Surface( modifier = modifier, shape = CircleShape, - color = if (offlineState.settings.offlineModeEnabled) FurumiNeonPink else FurumiHotOrange, + color = if (offlineState.settings.offlineModeEnabled) FurumiAccent else FurumiError, shadowElevation = 4.dp ) { Text( @@ -521,7 +457,7 @@ private fun ConnectedDevicesSection( Text( text = status, style = MaterialTheme.typography.bodySmall, - color = if (uiState.connectedDevicesError != null) FurumiHotOrange else FurumiTextMuted, + color = if (uiState.connectedDevicesError != null) FurumiError else FurumiTextMuted, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -547,7 +483,7 @@ private fun ConnectedDeviceRow( .clickable(onClick = onClick), shape = RoundedCornerShape(6.dp), color = if (device.isActive) FurumiSurface else Color.Transparent, - border = if (device.isActive) androidx.compose.foundation.BorderStroke(1.dp, FurumiNeonPink) else null + border = if (device.isActive) androidx.compose.foundation.BorderStroke(1.dp, FurumiAccent) else null ) { Row( modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp), @@ -557,7 +493,7 @@ private fun ConnectedDeviceRow( modifier = Modifier .size(8.dp) .clip(CircleShape) - .background(if (device.isActive) FurumiNeonPink else FurumiLine) + .background(if (device.isActive) FurumiAccent else FurumiLine) ) Spacer(modifier = Modifier.width(10.dp)) Text( @@ -597,7 +533,7 @@ internal fun FilterChips(filters: List) { filters.forEachIndexed { index, filter -> Surface( shape = CircleShape, - color = if (index == 0) FurumiNeonPink else FurumiSurface, + color = if (index == 0) FurumiAccent else FurumiSurface, border = if (index == 0) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine) ) { Text( @@ -624,7 +560,7 @@ internal fun PillAction( .clip(CircleShape) .clickable(onClick = onClick), shape = CircleShape, - color = if (selected) FurumiNeonPink else FurumiSurface, + color = if (selected) FurumiAccent else FurumiSurface, border = if (selected) null else androidx.compose.foundation.BorderStroke(1.dp, FurumiLine) ) { Box(contentAlignment = Alignment.Center) { @@ -641,115 +577,117 @@ internal fun PillAction( internal fun NowPlayingBar( playback: AudioPlaybackState, coverBitmap: Bitmap?, - isLiked: Boolean, + devices: ConnectedDevicesState?, onMediaImageNeeded: (String?) -> Unit, onClick: () -> Unit, onPlayPause: () -> Unit, - onPrevious: () -> Unit, onNext: () -> Unit, - onToggleShuffle: () -> Unit, - onCycleRepeatMode: () -> Unit, - onToggleLike: () -> Unit + onSelectDevice: (String) -> Unit ) { - val track = playback.currentTrack ?: return - - LaunchedEffect(track.coverUrl) { - onMediaImageNeeded(track.coverUrl) - } + val track = playback.currentTrack + val remoteId = devices?.remoteControlTargetId + val activeName = devices?.devices?.firstOrNull { it.id == remoteId }?.name + var devicesOpen by remember { mutableStateOf(false) } + LaunchedEffect(track?.coverUrl) { onMediaImageNeeded(track?.coverUrl) } Surface( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 10.dp, vertical = 6.dp) - .clip(RoundedCornerShape(8.dp)) - .clickable(onClick = onClick), + modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 6.dp), shape = RoundedCornerShape(8.dp), color = FurumiSurfaceHigh, border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine) ) { Column { Row( - modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp), + modifier = Modifier.padding(start = 10.dp, end = 4.dp), verticalAlignment = Alignment.CenterVertically ) { - MediaArtwork( - title = track.title, - seedId = track.id, - bitmap = coverBitmap, - modifier = Modifier.size(42.dp), - cornerRadius = 6 - ) - Spacer(modifier = Modifier.width(10.dp)) - Column(modifier = Modifier.weight(1f)) { - Text( - text = track.title, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onBackground, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - Text( - text = playback.errorMessage ?: trackSubtitle(track), - style = MaterialTheme.typography.bodyMedium, - color = if (playback.errorMessage == null) FurumiTextMuted else FurumiHotOrange, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - } - Spacer(modifier = Modifier.width(6.dp)) - MiniPlayerIconButton(size = 30, onClick = onToggleShuffle) { - ShuffleGlyph( - modifier = Modifier.size(16.dp), - color = if (playback.shuffle) FurumiNeonPink else MaterialTheme.colorScheme.onBackground - ) - } - MiniPlayerIconButton(onClick = onPrevious) { - PreviousGlyph(Modifier.size(16.dp), MaterialTheme.colorScheme.onBackground) + Row( + modifier = Modifier.weight(1f).clickable( + enabled = track != null, onClickLabel = "Open full player", onClick = onClick + ).padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + if (track != null) { + MediaArtwork( + title = track.title, seedId = track.id, bitmap = coverBitmap, + modifier = Modifier.size(42.dp), cornerRadius = 6 + ) + Spacer(Modifier.width(10.dp)) + } + Column { + Text( + text = track?.title ?: "No track selected", + style = MaterialTheme.typography.labelLarge, + maxLines = 1, overflow = TextOverflow.Ellipsis + ) + if (track != null) { + Text( + text = playback.errorMessage ?: trackSubtitle(track), + style = MaterialTheme.typography.bodyMedium, + color = if (playback.errorMessage == null) FurumiTextMuted else FurumiError, + maxLines = 1, overflow = TextOverflow.Ellipsis + ) + } + } } MiniPlayerIconButton( - size = 38, - background = FurumiNeonPink, + label = if (playback.isPlaying) "Pause" else "Play", + enabled = track != null, onClick = onPlayPause ) { - PlaybackGlyph( - playback = playback, - playSize = 16, - pauseSize = 16 - ) + Box( + modifier = Modifier.size(36.dp).background(MaterialTheme.colorScheme.primary, CircleShape), + contentAlignment = Alignment.Center + ) { + PlaybackGlyph(playback = playback, playSize = 18, pauseSize = 18) + } } - MiniPlayerIconButton(onClick = onNext) { - NextGlyph(Modifier.size(16.dp), MaterialTheme.colorScheme.onBackground) + MiniPlayerIconButton(label = "Next track", enabled = track != null, onClick = onNext) { + NextGlyph(Modifier.size(20.dp), MaterialTheme.colorScheme.onBackground) } - MiniPlayerIconButton(size = 30, onClick = onCycleRepeatMode) { - RepeatGlyph( - modifier = Modifier.size(18.dp), - color = if (playback.repeatMode.equals("off", ignoreCase = true)) { - MaterialTheme.colorScheme.onBackground - } else { - FurumiNeonPink - }, - repeatMode = playback.repeatMode - ) - } - MiniPlayerIconButton(onClick = onToggleLike) { - HeartGlyph( - isLiked = isLiked, - modifier = Modifier.size(18.dp) - ) + if (devices != null) { + Box { + MiniPlayerIconButton(label = "Choose playback device", onClick = { devicesOpen = true }) { + DevicesGlyph( + Modifier.size(22.dp), + if (remoteId != null) MaterialTheme.colorScheme.primary else FurumiTextMuted + ) + } + DropdownMenu(expanded = devicesOpen, onDismissRequest = { devicesOpen = false }) { + devices.devices.forEach { device -> + DropdownMenuItem( + text = { Text(if (device.isCurrent) "Play on this phone" else device.name) }, + enabled = !device.isActive, + onClick = { + devicesOpen = false + onSelectDevice(device.id) + } + ) + } + } + } } } - Box( - modifier = Modifier - .fillMaxWidth() - .height(3.dp) - .background(FurumiLine) - ) { - Box( - modifier = Modifier - .fillMaxWidth(playback.progress) - .fillMaxHeight() - .background(FurumiNeonPink) - ) + if (remoteId != null) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + val name = activeName ?: "another device" + Text( + text = if (playback.isPlaying) "Playing on $name" else "Playback on $name", + modifier = Modifier.weight(1f), + color = MaterialTheme.colorScheme.primary, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, overflow = TextOverflow.Ellipsis + ) + if (!devices.isCurrentDeviceActive) { + TextButton(onClick = { onSelectDevice(devices.deviceId) }) { Text("Play on this phone") } + } + } + } + Box(Modifier.fillMaxWidth().height(3.dp).background(FurumiLine)) { + Box(Modifier.fillMaxWidth(playback.progress).fillMaxHeight().background(MaterialTheme.colorScheme.primary)) } } } @@ -757,18 +695,15 @@ internal fun NowPlayingBar( @Composable private fun MiniPlayerIconButton( - size: Int = 34, - background: Color = Color.Transparent, + label: String, + enabled: Boolean = true, onClick: () -> Unit, - content: @Composable BoxScope.() -> Unit + content: @Composable () -> Unit ) { - Box( - modifier = Modifier - .size(size.dp) - .clip(CircleShape) - .background(background) - .clickable(onClick = onClick), - contentAlignment = Alignment.Center, + IconButton( + onClick = onClick, + enabled = enabled, + modifier = Modifier.size(48.dp).semantics { contentDescription = label }, content = content ) } @@ -806,7 +741,7 @@ internal fun BottomNavItem( selected: Boolean, onClick: () -> Unit ) { - val color = if (selected) FurumiNeonPink else FurumiTextMuted + val color = if (selected) FurumiAccent else FurumiTextMuted Column( modifier = Modifier .width(86.dp) @@ -829,15 +764,7 @@ internal fun BottomNavItem( } } -private val offlineStorageLimitOptions = listOf( - 512L * 1024L * 1024L, - 1L * 1024L * 1024L * 1024L, - 2L * 1024L * 1024L * 1024L, - 5L * 1024L * 1024L * 1024L, - 10L * 1024L * 1024L * 1024L -) - -private fun formatStorageBytes(bytes: Long): String { +internal fun formatStorageBytes(bytes: Long): String { val safeBytes = bytes.coerceAtLeast(0L) val megabytes = safeBytes / (1024.0 * 1024.0) return if (megabytes >= 1024.0) { diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerGlobalContent.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerGlobalContent.kt index bb170f0..821a03b 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerGlobalContent.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerGlobalContent.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -101,7 +101,7 @@ internal fun GlobalContent( when { uiState.isGlobalArtistsLoading && uiState.globalArtists.isEmpty() -> { - item(span = { GridItemSpan(maxLineSpan) }) { GlobalArtistsLoading() } + items(4, contentType = { "loading artist" }) { LoadingMusicCard() } } uiState.globalArtistsError != null && uiState.globalArtists.isEmpty() -> { @@ -220,6 +220,7 @@ internal fun ArtistDetailContent( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -267,7 +268,7 @@ internal fun ArtistDetailContent( Spacer(modifier = Modifier.height(28.dp)) when { - uiState.isArtistDetailLoading && uiState.artistDetail == null -> ArtistDetailLoading() + uiState.isArtistDetailLoading && uiState.artistDetail == null -> LoadingTrackRows() uiState.artistDetailError != null && uiState.artistDetail == null -> ArtistDetailError( message = uiState.artistDetailError, onRetry = onRetry @@ -285,6 +286,7 @@ internal fun ArtistDetailContent( onToggleLike = onToggleLike, onPlayNext = onPlayNext, onPlayLast = onPlayLast, + onLyrics = onLyrics, onShare = onShare, onAddToPlaylist = onAddToPlaylist, onDownloadForOffline = onDownloadForOffline @@ -358,21 +360,6 @@ internal fun ArtistDetailHero( } } -@Composable -internal fun ArtistDetailLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(180.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) - } -} - @Composable internal fun ArtistDetailError( message: String, @@ -417,6 +404,7 @@ internal fun PopularTracksSection( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -438,6 +426,7 @@ internal fun PopularTracksSection( onToggleLike = { onToggleLike(track.id) }, onPlayNext = { onPlayNext(track) }, onPlayLast = { onPlayLast(track) }, + onLyrics = { onLyrics(track) }, onShare = { onShare(track) }, onAddToPlaylist = { onAddToPlaylist(track) }, onDownloadForOffline = { onDownloadForOffline(track) } @@ -641,7 +630,7 @@ internal fun GlobalArtistsFooter( contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier.size(24.dp) ) @@ -674,7 +663,7 @@ internal fun GlobalArtistsFooter( .clickable(onClick = onLoadMore) .padding(horizontal = 10.dp, vertical = 8.dp), style = MaterialTheme.typography.labelLarge, - color = FurumiNeonPink + color = FurumiAccent ) } } @@ -692,7 +681,7 @@ internal fun GlobalArtistsFooter( contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier.size(24.dp) ) @@ -712,21 +701,6 @@ internal fun GlobalArtistsFooter( } } -@Composable -internal fun GlobalArtistsLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(240.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) - } -} - @Composable internal fun GlobalArtistsError( message: String, diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerHistoryContent.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerHistoryContent.kt index 7b0d3a9..1d1d6b9 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerHistoryContent.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerHistoryContent.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -79,6 +79,7 @@ import kotlin.math.roundToInt internal fun ListeningHistoryPanel( uiState: PlayerUiState, onDismiss: () -> Unit, + onLyrics: (TrackCard) -> Unit, onRetry: () -> Unit ) { Surface( @@ -135,7 +136,7 @@ internal fun ListeningHistoryPanel( onRetry = onRetry ) uiState.listeningHistory.isEmpty() -> ListeningHistoryEmpty() - else -> ListeningHistoryList(uiState.listeningHistory) + else -> ListeningHistoryList(uiState.listeningHistory, onLyrics) } } } @@ -150,7 +151,7 @@ internal fun ListeningHistoryLoading() { contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp ) } @@ -214,16 +215,16 @@ internal fun ListeningHistoryEmpty() { } @Composable -internal fun ListeningHistoryList(items: List) { +internal fun ListeningHistoryList(items: List, onLyrics: (TrackCard) -> Unit) { Column(verticalArrangement = Arrangement.spacedBy(14.dp)) { items.forEach { item -> - ListeningHistoryRow(item) + ListeningHistoryRow(item, onLyrics) } } } @Composable -internal fun ListeningHistoryRow(item: ListeningHistoryItem) { +internal fun ListeningHistoryRow(item: ListeningHistoryItem, onLyrics: (TrackCard) -> Unit) { Surface( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(10.dp), @@ -235,7 +236,7 @@ internal fun ListeningHistoryRow(item: ListeningHistoryItem) { verticalAlignment = Alignment.CenterVertically ) { AlbumArtwork( - colors = historyArtworkColors(item.trackId), + colors = historyArtworkColors(item.trackId ?: item.id.hashCode().toLong()), modifier = Modifier.size(54.dp), cornerRadius = 8 ) @@ -273,9 +274,12 @@ internal fun ListeningHistoryRow(item: ListeningHistoryItem) { Text( text = if (item.completed) "Completed" else "Partial", style = MaterialTheme.typography.labelSmall, - color = if (item.completed) FurumiNeonPink else FurumiTextMuted + color = if (item.completed) FurumiAccent else FurumiTextMuted ) } + item.lyricsTrack?.let { track -> + LyricsIconButton(item.title) { onLyrics(track) } + } } } } diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerIcons.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerIcons.kt index a1135ee..6d708be 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerIcons.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerIcons.kt @@ -41,6 +41,8 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset @@ -66,11 +68,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -463,6 +465,37 @@ internal fun LibraryGlyph( } } +@Composable +internal fun LyricsGlyph(modifier: Modifier, color: Color) { + Canvas(modifier) { + val unit = size.minDimension / 24f + val stroke = Stroke(width = 1.8f * unit, cap = StrokeCap.Round) + drawRoundRect( + color = color, topLeft = Offset(8.5f * unit, 2.5f * unit), + size = androidx.compose.ui.geometry.Size(7f * unit, 12f * unit), + cornerRadius = androidx.compose.ui.geometry.CornerRadius(3.5f * unit), + style = stroke + ) + drawArc( + color = color, startAngle = 0f, sweepAngle = 180f, useCenter = false, + topLeft = Offset(5f * unit, 5f * unit), + size = androidx.compose.ui.geometry.Size(14f * unit, 13f * unit), style = stroke + ) + drawLine(color, Offset(12f * unit, 18f * unit), Offset(12f * unit, 21.5f * unit), stroke.width) + drawLine(color, Offset(8.5f * unit, 21.5f * unit), Offset(15.5f * unit, 21.5f * unit), stroke.width, StrokeCap.Round) + } +} + +@Composable +internal fun LyricsIconButton(title: String, onClick: () -> Unit) { + androidx.compose.material3.IconButton( + onClick = onClick, + modifier = Modifier.semantics { contentDescription = "Lyrics for $title" } + ) { + LyricsGlyph(Modifier.size(22.dp), MaterialTheme.colorScheme.onSurfaceVariant) + } +} + @Composable internal fun ShareGlyph( modifier: Modifier, @@ -564,11 +597,11 @@ internal fun HeartGlyph( } if (isLiked) { - drawPath(path, color = Color(0xFFFF3EA5).copy(alpha = alpha), style = Fill) + drawPath(path, color = FurumiAccent.copy(alpha = alpha), style = Fill) } drawPath( path, - color = if (isLiked) Color(0xFFFF3EA5).copy(alpha = alpha) else Color(0xFFC9B8D6).copy(alpha = alpha), + color = if (isLiked) FurumiAccent.copy(alpha = alpha) else FurumiTextMuted.copy(alpha = alpha), style = Stroke(width = size.minDimension * 0.08f) ) } @@ -602,7 +635,7 @@ internal fun AudioWaveGlyph( @Composable internal fun MoreDotsGlyph( modifier: Modifier, - color: Color = Color(0xFFC9B8D6) + color: Color = FurumiTextMuted ) { Canvas(modifier = modifier) { val dotRadius = size.minDimension * 0.07f diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerLibraryContent.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerLibraryContent.kt index 6885135..d97196b 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerLibraryContent.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerLibraryContent.kt @@ -12,14 +12,23 @@ import androidx.compose.foundation.clickable import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.progressSemantics +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator @@ -27,10 +36,12 @@ import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect @@ -44,8 +55,10 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color @@ -55,7 +68,10 @@ import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel @@ -66,11 +82,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -82,12 +98,14 @@ internal fun SearchContent( onProfileClick: () -> Unit, onQueryChange: (String) -> Unit, onRetry: () -> Unit, + onReleaseClick: (ReleaseCard) -> Unit, onArtistClick: (ArtistCard) -> Unit, onMediaImageNeeded: (String?) -> Unit, onTrackClick: (TrackCard) -> Unit, onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -95,6 +113,7 @@ internal fun SearchContent( val query = uiState.searchQuery val results = uiState.searchResults val artists = searchArtists(uiState) + val releases = results?.releases.orEmpty() val tracks = results?.tracks.orEmpty() Column( @@ -114,7 +133,7 @@ internal fun SearchContent( singleLine = true, placeholder = { Text( - text = "Artists and tracks", + text = "Artists, albums and tracks", style = MaterialTheme.typography.bodyLarge ) }, @@ -130,12 +149,12 @@ internal fun SearchContent( when { query.isBlank() -> SearchEmptyPrompt() - uiState.isSearchLoading && results == null -> SearchLoading() + uiState.isSearchLoading && results == null -> LoadingTrackRows() uiState.searchError != null && results == null -> SearchError( message = uiState.searchError, onRetry = onRetry ) - artists.isEmpty() && tracks.isEmpty() && !uiState.isSearchLoading -> SearchNoResults() + artists.isEmpty() && releases.isEmpty() && tracks.isEmpty() && !uiState.isSearchLoading -> SearchNoResults() else -> { if (artists.isNotEmpty()) { SearchArtistsSection( @@ -147,6 +166,17 @@ internal fun SearchContent( Spacer(modifier = Modifier.height(26.dp)) } + if (releases.isNotEmpty()) { + SectionTitle("Albums") + Spacer(Modifier.height(12.dp)) + LazyRow(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + items(releases, key = { it.id }, contentType = { "album" }) { release -> + ReleaseTile(release, mediaImageFor(uiState.mediaImages, release.coverUrl), + onMediaImageNeeded, { onReleaseClick(release) }, Modifier.width(144.dp)) + } + } + Spacer(Modifier.height(26.dp)) + } if (tracks.isNotEmpty()) { SearchTracksSection( uiState = uiState, @@ -158,6 +188,7 @@ internal fun SearchContent( onToggleLike = onToggleLike, onPlayNext = onPlayNext, onPlayLast = onPlayLast, + onLyrics = onLyrics, onShare = onShare, onAddToPlaylist = onAddToPlaylist, onDownloadForOffline = onDownloadForOffline @@ -167,7 +198,7 @@ internal fun SearchContent( if (uiState.isSearchLoading) { Spacer(modifier = Modifier.height(20.dp)) CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier .size(24.dp) @@ -249,6 +280,7 @@ private fun SearchTracksSection( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -270,6 +302,7 @@ private fun SearchTracksSection( onToggleLike = { onToggleLike(track.id) }, onPlayNext = { onPlayNext(track) }, onPlayLast = { onPlayLast(track) }, + onLyrics = { onLyrics(track) }, onShare = { onShare(track) }, onAddToPlaylist = { onAddToPlaylist(track) }, onDownloadForOffline = { onDownloadForOffline(track) } @@ -281,27 +314,12 @@ private fun SearchTracksSection( @Composable private fun SearchEmptyPrompt() { Text( - text = "Start typing to search artists and tracks.", + text = "Start typing to search artists, albums and tracks.", style = MaterialTheme.typography.bodyMedium, color = FurumiTextMuted ) } -@Composable -private fun SearchLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(180.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) - } -} - @Composable private fun SearchError( message: String, @@ -349,25 +367,79 @@ private fun searchArtists(uiState: PlayerUiState): List { return (results.artistMatches + results.trackArtists).distinctBy { it.id } } +@Composable +private fun PlaylistSearchField( + query: String, + onQueryChange: (String) -> Unit, + hint: String +) { + val focusManager = LocalFocusManager.current + OutlinedTextField( + value = query, + onValueChange = onQueryChange, + modifier = Modifier.fillMaxWidth().semantics { contentDescription = hint }, + placeholder = { Text(hint) }, + leadingIcon = { SearchGlyph(Modifier.size(20.dp), FurumiTextMuted) }, + trailingIcon = if (query.isNotEmpty()) { + { + IconButton( + onClick = { onQueryChange("") }, + modifier = Modifier.semantics { contentDescription = "Clear search" } + ) { + PlusGlyph(Modifier.size(18.dp).rotate(45f), FurumiTextMuted) + } + } + } else null, + singleLine = true, + shape = RoundedCornerShape(12.dp), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions(onSearch = { focusManager.clearFocus() }) + ) +} + @Composable internal fun LibraryContent( uiState: PlayerUiState, + showDownloads: Boolean, + onShowDownloadsChange: (Boolean) -> Unit, onProfileClick: () -> Unit, onLoadLibrary: () -> Unit, onRetryPlaylists: () -> Unit, onRetryArtists: () -> Unit, onLoadMoreArtists: () -> Unit, onCreatePlaylistClick: () -> Unit, - onPlaylistPreviewNeeded: (PlaylistCard) -> Unit, + getDownloadedTracks: suspend (Set?) -> List, + onLyrics: (TrackCard) -> Unit, + onPlayDownloaded: (TrackCard, List) -> Unit, + onStorageLimitChange: (Long) -> Unit, + onClearDownloads: () -> Unit, + onRetryFailed: (Set) -> Unit, onPlaylistClick: (PlaylistCard) -> Unit, onArtistImageNeeded: (String?) -> Unit, onArtistClick: (ArtistCard) -> Unit ) { - LaunchedEffect(Unit) { - onLoadLibrary() + var playlistQuery by rememberSaveable { mutableStateOf("") } + if (showDownloads) { + BackHandler { onShowDownloadsChange(false) } + DeviceDownloadsContent( + uiState = uiState, + getDownloadedTracks = getDownloadedTracks, + onMediaImageNeeded = onArtistImageNeeded, + onLyrics = onLyrics, + onPlay = onPlayDownloaded, + onRetry = onRetryFailed, + onStorageLimitChange = onStorageLimitChange, + onClear = onClearDownloads, + onBack = { onShowDownloadsChange(false) } + ) + return + } + LaunchedEffect(Unit) { onLoadLibrary() } + val playlists = remember(uiState.playlists) { orderedLibraryPlaylists(uiState.playlists) } + val playlistTerm = playlistQuery.trim() + val visiblePlaylists = remember(playlists, playlistTerm) { + if (playlistTerm.isEmpty()) playlists else playlists.filter { it.title.contains(playlistTerm, ignoreCase = true) } } - - val playlists = orderedLibraryPlaylists(uiState.playlists) LazyVerticalGrid( columns = GridCells.Adaptive(minSize = 148.dp), @@ -385,6 +457,11 @@ internal fun LibraryContent( ) } + item(key = "on-device", span = { GridItemSpan(maxLineSpan) }, contentType = "navigation") { + OutlinedButton(onClick = { onShowDownloadsChange(true) }, modifier = Modifier.fillMaxWidth()) { + Text("On device · ${uiState.offlineState.cachedTrackCount} downloaded") + } + } item(span = { GridItemSpan(maxLineSpan) }) { Row( modifier = Modifier.fillMaxWidth(), @@ -398,7 +475,7 @@ internal fun LibraryContent( .clip(CircleShape) .clickable(onClick = onCreatePlaylistClick), shape = CircleShape, - color = FurumiNeonPink + color = FurumiAccent ) { Box(contentAlignment = Alignment.Center) { PlusGlyph(Modifier.size(16.dp), FurumiBlack) @@ -407,11 +484,12 @@ internal fun LibraryContent( } } + item(key = "playlist-search", span = { GridItemSpan(maxLineSpan) }) { + PlaylistSearchField(playlistQuery, { playlistQuery = it }, "Search playlists") + } when { uiState.isPlaylistsLoading && playlists.isEmpty() -> { - item(span = { GridItemSpan(maxLineSpan) }) { - LibraryLoading() - } + items(2, contentType = { "loading card" }) { LoadingMusicCard() } } uiState.playlistsError != null && playlists.isEmpty() -> { @@ -429,16 +507,22 @@ internal fun LibraryContent( } } + visiblePlaylists.isEmpty() -> { + item(span = { GridItemSpan(maxLineSpan) }) { + Text("No matching playlists", color = FurumiTextMuted) + } + } + else -> { items( - items = playlists, - key = { playlist -> "playlist-${playlist.id}-${playlist.title}" } + items = visiblePlaylists, + key = { playlist -> "playlist-${playlist.id}" }, + contentType = { "playlist" } ) { playlist -> PlaylistTile( playlist = playlist, - coverUrls = uiState.playlistPreviewCoverUrls[playlist.id].orEmpty(), mediaImages = uiState.mediaImages, - onPlaylistPreviewNeeded = onPlaylistPreviewNeeded, + onMediaImageNeeded = onArtistImageNeeded, onClick = { onPlaylistClick(playlist) } ) } @@ -456,9 +540,7 @@ internal fun LibraryContent( when { uiState.isLibraryArtistsLoading && uiState.libraryArtists.isEmpty() -> { - item(span = { GridItemSpan(maxLineSpan) }) { - LibraryLoading() - } + items(2, contentType = { "loading card" }) { LoadingMusicCard() } } uiState.libraryArtistsError != null && uiState.libraryArtists.isEmpty() -> { @@ -503,17 +585,10 @@ internal fun LibraryContent( @Composable private fun PlaylistTile( playlist: PlaylistCard, - coverUrls: List, mediaImages: Map, - onPlaylistPreviewNeeded: (PlaylistCard) -> Unit, + onMediaImageNeeded: (String?) -> Unit, onClick: () -> Unit ) { - LaunchedEffect(playlist.id) { - if (!playlist.isLikesPlaylist()) { - onPlaylistPreviewNeeded(playlist) - } - } - Column( modifier = Modifier .fillMaxWidth() @@ -522,8 +597,8 @@ private fun PlaylistTile( ) { PlaylistArtwork( playlist = playlist, - coverUrls = coverUrls, mediaImages = mediaImages, + onMediaImageNeeded = onMediaImageNeeded, modifier = Modifier .fillMaxWidth() .aspectRatio(1f), @@ -551,8 +626,8 @@ private fun PlaylistTile( @Composable private fun PlaylistArtwork( playlist: PlaylistCard, - coverUrls: List, mediaImages: Map, + onMediaImageNeeded: (String?) -> Unit, modifier: Modifier, cornerRadius: Int ) { @@ -563,7 +638,7 @@ private fun PlaylistArtwork( Box( modifier = modifier .clip(artworkShape) - .background(Brush.linearGradient(listOf(FurumiSurfaceHigh, FurumiNeonViolet, FurumiBlack))), + .background(Brush.linearGradient(listOf(FurumiSurfaceHigh, FurumiAccentMuted, FurumiBlack))), contentAlignment = Alignment.Center ) { HeartGlyph( @@ -574,7 +649,14 @@ private fun PlaylistArtwork( return } - val previewCoverUrls = coverUrls.take(4) + val previewCoverUrls = playlist.coverUrls.take(4) + LaunchedEffect(playlist.id, previewCoverUrls) { + previewCoverUrls.forEach(onMediaImageNeeded) + } + if (previewCoverUrls.size == 1) { + MediaArtwork(playlist.title, playlist.id, mediaImageFor(mediaImages, previewCoverUrls.single()), modifier, cornerRadius) + return + } if (previewCoverUrls.isEmpty()) { AlbumArtwork( colors = playlistArtworkColors(playlist), @@ -627,6 +709,7 @@ private fun PlaylistArtwork( } } +@OptIn(ExperimentalLayoutApi::class) @Composable internal fun PlaylistDetailContent( uiState: PlayerUiState, @@ -639,218 +722,302 @@ internal fun PlaylistDetailContent( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit, onDownloadPlaylistClick: () -> Unit, + onRetryFailed: (Set) -> Unit, onDeletePlaylistClick: (PlaylistCard) -> Unit ) { val playlist = uiState.playlistDetail?.playlist ?: uiState.selectedPlaylist ?: return val tracks = uiState.playlistDetail?.tracks.orEmpty() - val isPlaylistDownloading = uiState.offlineDownloadingPlaylistIds.contains(playlist.id) - val isPlaylistDownloaded = tracks.isNotEmpty() && tracks.all(uiState::isDownloadedForOffline) - val heroTrack = tracks.firstOrNull { !it.coverUrl.isNullOrBlank() } - val heroImage = mediaImageFor(uiState.mediaImages, heroTrack?.coverUrl) + var trackQuery by rememberSaveable(playlist.id) { mutableStateOf("") } + val trackTerm = trackQuery.trim() + val matchingIndices = remember(tracks, trackTerm) { + if (trackTerm.isEmpty()) null else tracks.indices.filter { tracks[it].matchesPlaylistSearch(trackTerm) } + } + val queue = uiState.offlineQueue + val trackIds = remember(tracks) { tracks.mapTo(linkedSetOf()) { it.id } } + val total = trackIds.size + val ready = remember(tracks, queue.cachedTrackIds, uiState.offlineDownloadedTrackIds) { + tracks.asSequence().filter(uiState::isDownloadedForOffline).map { it.id }.distinct().count() + } + val isPreparing = playlist.id in uiState.preparingDownloadPlaylistIds + val activeCount = remember(trackIds, queue.activeTrackIds) { queue.activeTrackIds.count(trackIds::contains) } + val incomplete = uiState.playlistDetail?.isMembershipComplete == false + val isPlaylistDownloaded = !incomplete && total > 0 && ready == total + val currentId = queue.runningTrackId?.takeIf(trackIds::contains) + val failed = remember(trackIds, queue.failedTrackIds) { queue.failedTrackIds.intersect(trackIds) } + var menuOpen by remember(playlist.id) { mutableStateOf(false) } + var showFailures by rememberSaveable(playlist.id) { mutableStateOf(false) } - LaunchedEffect(heroTrack?.coverUrl) { - onMediaImageNeeded(heroTrack?.coverUrl) + if (showFailures && failed.isNotEmpty()) { + val failedTracks = remember(tracks, failed) { tracks.filter { it.id in failed }.distinctBy { it.id } } + AlertDialog( + onDismissRequest = { showFailures = false }, + title = { Text("Failed downloads") }, + text = { + LazyColumn( + modifier = Modifier.heightIn(max = 320.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + items(failedTracks, key = { it.id }) { track -> + Column { + Text(track.title, style = MaterialTheme.typography.titleSmall) + Text( + queue.errors[track.id].orEmpty().ifBlank { "The file could not be saved." }, + style = MaterialTheme.typography.bodyMedium + ) + } + } + } + }, + confirmButton = { + TextButton( + onClick = { + showFailures = false + onRetryFailed(failed) + }, + enabled = uiState.canStartOfflineDownload() + ) { Text("Retry failed downloads") } + }, + dismissButton = { TextButton(onClick = { showFailures = false }) { Text("Close") } } + ) } - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 20.dp) + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) ) { - Row( - modifier = Modifier - .clip(RoundedCornerShape(8.dp)) - .clickable(onClick = onBack) - .padding(vertical = 8.dp, horizontal = 2.dp), - verticalAlignment = Alignment.CenterVertically - ) { - BackGlyph( - modifier = Modifier.size(20.dp), - color = MaterialTheme.colorScheme.onBackground - ) - Spacer(modifier = Modifier.width(8.dp)) - Text( - text = "Playlist", - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onBackground - ) - } - - Spacer(modifier = Modifier.height(20.dp)) - - MediaArtwork( - title = playlist.title, - seedId = playlist.id, - bitmap = heroImage, - modifier = Modifier - .size(190.dp) - .align(Alignment.CenterHorizontally), - cornerRadius = 10 - ) - - Spacer(modifier = Modifier.height(22.dp)) - - Text( - text = playlist.title, - style = MaterialTheme.typography.headlineMedium, - color = MaterialTheme.colorScheme.onBackground - ) - Spacer(modifier = Modifier.height(6.dp)) - uiState.playlistDetail?.description - ?.takeIf { it.isNotBlank() } - ?.let { description -> - Text( - text = description, - style = MaterialTheme.typography.bodyMedium, - color = FurumiTextMuted - ) - Spacer(modifier = Modifier.height(6.dp)) - } - Spacer(modifier = Modifier.height(10.dp)) - Text( - text = playlistMeta(playlist), - style = MaterialTheme.typography.labelSmall, - color = FurumiTextMuted - ) - - Spacer(modifier = Modifier.height(18.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - PillAction( - label = "Play", - selected = true, - modifier = Modifier.weight(1f), - onClick = onPlayClick - ) - Spacer(modifier = Modifier.width(12.dp)) - PillAction( - label = "Shuffle", - selected = false, - modifier = Modifier.weight(1f), - onClick = onShuffleClick - ) - } - - Spacer(modifier = Modifier.height(12.dp)) - OutlinedButton( - onClick = onDownloadPlaylistClick, - enabled = tracks.isNotEmpty() && - !isPlaylistDownloaded && - !isPlaylistDownloading && - uiState.canStartOfflineDownload(), - modifier = Modifier - .fillMaxWidth() - .height(44.dp), - shape = CircleShape, - border = androidx.compose.foundation.BorderStroke(1.dp, FurumiNeonPink.copy(alpha = 0.72f)), - colors = ButtonDefaults.outlinedButtonColors( - contentColor = FurumiNeonPink, - disabledContentColor = FurumiTextMuted - ) - ) { - Text( - when { - isPlaylistDownloaded -> "Downloaded" - isPlaylistDownloading -> "Downloading..." - else -> "Download offline" + item(key = "header", contentType = "header") { + Column(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + TextButton(onClick = onBack, contentPadding = PaddingValues(end = 12.dp)) { + BackGlyph(Modifier.size(20.dp), FurumiTextMuted) + Spacer(Modifier.width(6.dp)) + Text("Library", color = FurumiTextMuted) + } + if (playlist.canDeleteFromDetail()) { + Box { + IconButton( + onClick = { menuOpen = true }, + modifier = Modifier.semantics { contentDescription = "Playlist options" } + ) { + MoreDotsGlyph(Modifier.size(24.dp), FurumiTextMuted) + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem( + text = { Text("Delete playlist", color = MaterialTheme.colorScheme.error) }, + onClick = { + menuOpen = false + onDeletePlaylistClick(playlist) + } + ) + } + } + } } - ) - } - uiState.offlineDownloadError?.let { error -> - Spacer(modifier = Modifier.height(8.dp)) - Text( - text = error, - style = MaterialTheme.typography.bodySmall, - color = FurumiHotOrange - ) - } - - if (playlist.canDeleteFromDetail()) { - Spacer(modifier = Modifier.height(12.dp)) - OutlinedButton( - onClick = { onDeletePlaylistClick(playlist) }, - modifier = Modifier - .fillMaxWidth() - .height(44.dp), - shape = CircleShape, - border = androidx.compose.foundation.BorderStroke(1.dp, FurumiHotOrange.copy(alpha = 0.72f)), - colors = ButtonDefaults.outlinedButtonColors( - contentColor = FurumiHotOrange, - disabledContentColor = FurumiTextMuted - ) - ) { - Text("Delete playlist") - } - } - - Spacer(modifier = Modifier.height(24.dp)) - - when { - uiState.isPlaylistDetailLoading && uiState.playlistDetail == null -> PlaylistDetailLoading() - uiState.playlistDetailError != null && uiState.playlistDetail == null -> PlaylistDetailError( - message = uiState.playlistDetailError, - onRetry = onRetry - ) - uiState.playlistDetail != null -> { - SectionTitle("Tracks") - Spacer(modifier = Modifier.height(12.dp)) - if (tracks.isEmpty()) { - Text( - text = "No tracks yet", - style = MaterialTheme.typography.bodyMedium, - color = FurumiTextMuted + Spacer(Modifier.height(12.dp)) + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + verticalAlignment = Alignment.CenterVertically + ) { + PlaylistArtwork( + playlist = uiState.selectedPlaylist ?: playlist, + mediaImages = uiState.mediaImages, + onMediaImageNeeded = onMediaImageNeeded, + modifier = Modifier.size(96.dp), + cornerRadius = 12 ) - } else { - tracks.forEachIndexed { index, track -> - PlaylistTrackRow( - index = index + 1, - track = track, - bitmap = mediaImageFor(uiState.mediaImages, track.coverUrl), - isLiked = uiState.likedTrackIds.contains(track.id), - isDownloadedForOffline = uiState.isDownloadedForOffline(track), - isDownloadingForOffline = uiState.isDownloadingForOffline(track), - canDownloadForOffline = uiState.canStartOfflineDownload(), - onMediaImageNeeded = onMediaImageNeeded, - onTrackClick = onTrackClick, - onToggleLike = { onToggleLike(track.id) }, - onPlayNext = { onPlayNext(track) }, - onPlayLast = { onPlayLast(track) }, - onShare = { onShare(track) }, - onAddToPlaylist = { onAddToPlaylist(track) }, - onDownloadForOffline = { onDownloadForOffline(track) } + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text( + playlist.title, + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onBackground ) - if (index < tracks.lastIndex) { - Spacer(modifier = Modifier.height(12.dp)) + Text(playlistMeta(playlist), style = MaterialTheme.typography.bodyMedium, color = FurumiTextMuted) + } + } + uiState.playlistDetail?.description?.takeIf { it.isNotBlank() }?.let { description -> + Spacer(Modifier.height(10.dp)) + Text(description, style = MaterialTheme.typography.bodyMedium, color = FurumiTextMuted) + } + + if (tracks.isNotEmpty()) { + Spacer(Modifier.height(16.dp)) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + Button( + onClick = onPlayClick, + modifier = Modifier.heightIn(min = 48.dp), + colors = ButtonDefaults.buttonColors(containerColor = FurumiAccent, contentColor = FurumiBlack) + ) { + PlayGlyph(Modifier.size(16.dp), FurumiBlack) + Spacer(Modifier.width(8.dp)) + Text("Play") + } + IconButton( + onClick = onShuffleClick, + modifier = Modifier.size(48.dp).semantics { contentDescription = "Shuffle playlist" } + ) { + ShuffleGlyph(Modifier.size(24.dp), MaterialTheme.colorScheme.onBackground) + } + if (!incomplete && !isPlaylistDownloaded && !isPreparing && activeCount == 0 && + ready + failed.size < total && uiState.canStartOfflineDownload()) { + OutlinedButton( + onClick = onDownloadPlaylistClick, + modifier = Modifier.heightIn(min = 48.dp), + enabled = !uiState.isPlaylistDetailLoading + ) { Text("Download", color = MaterialTheme.colorScheme.onBackground) } + } + } + } + if (isPreparing || activeCount > 0 || ready > 0 || failed.isNotEmpty() || incomplete) { + Spacer(Modifier.height(14.dp)) + Surface( + shape = RoundedCornerShape(14.dp), + color = FurumiSurfaceHigh, + contentColor = MaterialTheme.colorScheme.onSurface + ) { + Column( + Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text( + if (incomplete) "$ready of $total listed tracks downloaded" else "$ready of $total downloaded", + style = MaterialTheme.typography.titleSmall + ) + if (total > 0 && !isPlaylistDownloaded) { + LinearProgressIndicator( + progress = { ready.toFloat() / total }, + modifier = Modifier.fillMaxWidth(), + color = FurumiAccent, + trackColor = FurumiLine + ) + } + val status = when { + currentId != null -> "Downloading " + queue.trackTitles[currentId] + .orEmpty().ifBlank { tracks.first { it.id == currentId }.title } + isPreparing -> "Preparing downloads…" + activeCount > 0 && uiState.offlineState.isUsingNetworkFallback -> "Waiting for connection · $activeCount queued" + activeCount > 0 -> "$activeCount queued" + isPlaylistDownloaded -> "Available offline" + else -> null + } + status?.let { Text(it, style = MaterialTheme.typography.bodyMedium, color = FurumiTextMuted) } + queue.transferProgress?.takeIf { it.trackId == currentId }?.let { progress -> + Text(progress.displayText(), style = MaterialTheme.typography.bodySmall, color = FurumiTextMuted) + } + if (incomplete) { + Text("Some remote tracks could not be loaded.", style = MaterialTheme.typography.bodyMedium) + TextButton(onClick = onRetry, enabled = !uiState.isPlaylistDetailLoading) { Text("Reload full playlist") } + } + if (failed.isNotEmpty()) { + TextButton( + onClick = { showFailures = true }, + contentPadding = PaddingValues(horizontal = 4.dp) + ) { Text("${failed.size} failed · View details", color = MaterialTheme.colorScheme.error) } + } } } } } } + when { + uiState.isPlaylistDetailLoading && uiState.playlistDetail == null -> + item(key = "loading", contentType = "status") { LoadingTrackRows() } + uiState.playlistDetailError != null && uiState.playlistDetail == null -> + item(key = "error", contentType = "status") { PlaylistDetailError(uiState.playlistDetailError, onRetry) } + uiState.playlistDetail != null -> { + item(key = "tracks", contentType = "heading") { SectionTitle("Tracks") } + item(key = "track-search", contentType = "search") { + PlaylistSearchField(trackQuery, { trackQuery = it }, "Search tracks") + } + if (tracks.isEmpty() || matchingIndices?.isEmpty() == true) { + item(key = "empty", contentType = "status") { + Text(if (tracks.isEmpty()) "No tracks yet" else "No matching tracks", color = FurumiTextMuted) + } + } + items( + count = matchingIndices?.size ?: tracks.size, + key = { row -> + val index = matchingIndices?.get(row) ?: row + "${tracks[index].id}:$index" + }, + contentType = { "track" } + ) { row -> + val index = matchingIndices?.get(row) ?: row + val track = tracks[index] + PlaylistTrackRow( + index = index + 1, + track = track, + bitmap = mediaImageFor(uiState.mediaImages, track.coverUrl), + isLiked = uiState.likedTrackIds.contains(track.id), + isDownloadedForOffline = uiState.isDownloadedForOffline(track), + isDownloadingForOffline = uiState.isDownloadingForOffline(track), + downloadStatus = when { + track.id in failed -> "Download failed" + track.id == currentId -> "Downloading" + track.id in queue.activeTrackIds -> "Queued" + else -> null + }, + canDownloadForOffline = uiState.canStartOfflineDownload(), + onMediaImageNeeded = onMediaImageNeeded, + onTrackClick = onTrackClick, + onToggleLike = { onToggleLike(track.id) }, + onPlayNext = { onPlayNext(track) }, + onPlayLast = { onPlayLast(track) }, + onLyrics = { onLyrics(track) }, + onShare = { onShare(track) }, + onAddToPlaylist = { onAddToPlaylist(track) }, + onDownloadForOffline = { onDownloadForOffline(track) } + ) + } + } + } + } +} - Spacer(modifier = Modifier.height(24.dp)) +private fun TrackCard.matchesPlaylistSearch(term: String): Boolean = + title.contains(term, ignoreCase = true) || + releaseTitle?.contains(term, ignoreCase = true) == true || + artists.any { it.contains(term, ignoreCase = true) } || + artistRefs.any { it.name.contains(term, ignoreCase = true) } || + featuredArtistRefs.any { it.name.contains(term, ignoreCase = true) } || + federation?.featuredArtistNames.orEmpty().any { it.contains(term, ignoreCase = true) } + +@Composable +internal fun LoadingMusicCard() { + val color = MaterialTheme.colorScheme.surfaceVariant + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Spacer(Modifier.fillMaxWidth().aspectRatio(1f).background(color, RoundedCornerShape(8.dp))) + Spacer(Modifier.fillMaxWidth(0.65f).height(14.dp).background(color, CircleShape)) } } @Composable -internal fun LibraryLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(180.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) +internal fun LoadingTrackRows() { + val color = MaterialTheme.colorScheme.surfaceVariant + Column(Modifier.fillMaxWidth().progressSemantics(), verticalArrangement = Arrangement.spacedBy(12.dp)) { + repeat(4) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Spacer(Modifier.size(48.dp).background(color, RoundedCornerShape(6.dp))) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Spacer(Modifier.fillMaxWidth(0.66f).height(14.dp).background(color, CircleShape)) + Spacer(Modifier.fillMaxWidth(0.42f).height(10.dp).background(color, CircleShape)) + } + } + } } } @@ -975,7 +1142,7 @@ private fun LibraryArtistsFooter( contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier.size(24.dp) ) @@ -1008,7 +1175,7 @@ private fun LibraryArtistsFooter( .clickable(onClick = onLoadMore) .padding(horizontal = 10.dp, vertical = 8.dp), style = MaterialTheme.typography.labelLarge, - color = FurumiNeonPink + color = FurumiAccent ) } } @@ -1026,7 +1193,7 @@ private fun LibraryArtistsFooter( contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier.size(24.dp) ) @@ -1061,27 +1228,12 @@ private fun PlaylistCard.canDeleteFromDetail(): Boolean { private fun playlistArtworkColors(playlist: PlaylistCard): List { return if (playlist.isLikesPlaylist()) { - listOf(FurumiNeonPink, FurumiHotOrange, FurumiBlack) + listOf(FurumiAccent, FurumiAccentMuted, FurumiBlack) } else { artistArtworkColors(playlist.id) } } -@Composable -internal fun PlaylistDetailLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(180.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) - } -} - @Composable internal fun PlaylistDetailError( message: String, @@ -1118,10 +1270,10 @@ internal fun PlaylistDetailError( @Composable internal fun GenreGrid() { val genres = listOf( - "Synthwave" to listOf(FurumiNeonPink, FurumiNeonViolet), - "Electronic" to listOf(FurumiElectricCyan, FurumiSurfaceHigh), - "Indie" to listOf(FurumiHotOrange, FurumiNeonPink), - "Focus" to listOf(FurumiNeonViolet, FurumiSurface) + "Synthwave" to listOf(FurumiAccent, FurumiAccentMuted), + "Electronic" to listOf(FurumiAccentBright, FurumiSurfaceHigh), + "Indie" to listOf(FurumiAccentMuted, FurumiAccent), + "Focus" to listOf(FurumiAccentMuted, FurumiSurface) ) Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerMenus.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerMenus.kt index 0485c86..bc165b6 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerMenus.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerMenus.kt @@ -69,11 +69,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -87,6 +87,7 @@ internal fun TrackContextMenu( onToggleLike: () -> Unit, onPlayNext: () -> Unit, onPlayLast: () -> Unit, + onLyrics: () -> Unit, onShare: () -> Unit, onAddToPlaylist: () -> Unit, isDownloadedForOffline: Boolean, @@ -102,6 +103,7 @@ internal fun TrackContextMenu( text = { Text(if (isLiked) "Unlike" else "Like") }, onClick = onToggleLike ) + DropdownMenuItem(text = { Text("Lyrics") }, onClick = onLyrics) DropdownMenuItem( text = { Text("Play next") }, onClick = onPlayNext @@ -179,7 +181,7 @@ internal fun AddToPlaylistDialog( .clip(RoundedCornerShape(8.dp)) .clickable(onClick = onCreatePlaylist), shape = RoundedCornerShape(8.dp), - color = FurumiNeonPink, + color = FurumiAccent, ) { Row( modifier = Modifier.padding(horizontal = 12.dp, vertical = 12.dp), @@ -206,7 +208,7 @@ internal fun AddToPlaylistDialog( contentAlignment = Alignment.Center ) { CircularProgressIndicator( - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp, modifier = Modifier.size(24.dp) ) @@ -324,7 +326,7 @@ internal fun CreatePlaylistDialog( Text( text = message, style = MaterialTheme.typography.bodyMedium, - color = FurumiHotOrange + color = FurumiError ) } Spacer(modifier = Modifier.height(18.dp)) @@ -350,7 +352,7 @@ internal fun CreatePlaylistDialog( enabled = canSubmit, shape = CircleShape, colors = ButtonDefaults.buttonColors( - containerColor = FurumiNeonPink, + containerColor = FurumiAccent, contentColor = FurumiBlack, disabledContainerColor = FurumiSurface, disabledContentColor = FurumiTextMuted @@ -424,7 +426,7 @@ internal fun DeletePlaylistDialog( Text( text = message, style = MaterialTheme.typography.bodyMedium, - color = FurumiHotOrange + color = FurumiError ) } Spacer(modifier = Modifier.height(18.dp)) @@ -450,7 +452,7 @@ internal fun DeletePlaylistDialog( enabled = !isDeleting, shape = CircleShape, colors = ButtonDefaults.buttonColors( - containerColor = FurumiHotOrange, + containerColor = FurumiError, contentColor = FurumiBlack, disabledContainerColor = FurumiSurface, disabledContentColor = FurumiTextMuted diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerModels.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerModels.kt index 075d5d2..a0b8c1c 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerModels.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerModels.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerOverlay.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerOverlay.kt index 65d973d..dd0c509 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerOverlay.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerOverlay.kt @@ -12,6 +12,9 @@ import androidx.compose.foundation.clickable import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid @@ -46,6 +49,10 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color @@ -70,11 +77,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -96,10 +103,12 @@ internal fun FullPlayerOverlay( onToggleShuffle: () -> Unit, onCycleRepeatMode: () -> Unit, onSeekToProgress: (Float) -> Unit, + onNowPlayingLyrics: (TrackCard) -> Unit, onQueueTrackClick: (TrackCard, Int) -> Unit, onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, offlineDownloadedTrackIds: Set, @@ -136,7 +145,7 @@ internal fun FullPlayerOverlay( val density = LocalDensity.current val dismissThresholdPx = with(density) { 150.dp.toPx() } val flingVelocityThresholdPx = with(density) { 800.dp.toPx() } - val scrollState = rememberScrollState() + val scrollState = rememberLazyListState() val currentOnDismiss by androidx.compose.runtime.rememberUpdatedState(onDismiss) val nestedScrollConnection = remember(dragOffsetY) { @@ -162,7 +171,7 @@ internal fun FullPlayerOverlay( val dy = available.y // Only allow drag-to-dismiss when content is scrolled to top // and user is actively dragging (not fling inertia from scrolling up) - if (dy > 0 && scrollState.value == 0 + if (dy > 0 && !scrollState.canScrollBackward && source == androidx.compose.ui.input.nestedscroll.NestedScrollSource.Drag) { onDragOffsetChange(dragOffsetY + dy) return androidx.compose.ui.geometry.Offset(0f, dy) @@ -211,7 +220,7 @@ internal fun FullPlayerOverlay( } } - Box( + BoxWithConstraints( modifier = Modifier .fillMaxSize() .offset { IntOffset(0, dragOffsetY.roundToInt().coerceAtLeast(0)) } @@ -219,232 +228,154 @@ internal fun FullPlayerOverlay( .background(MaterialTheme.colorScheme.background) .windowInsetsPadding(WindowInsets.safeDrawing) ) { - Column( - modifier = Modifier - .fillMaxSize() - .verticalScroll(scrollState) - .padding(horizontal = 24.dp, vertical = 18.dp) + val artworkMaxSize = (maxHeight * 0.43f).coerceIn(132.dp, 400.dp) + val remoteName = connectedDevicesState?.let { state -> + state.devices.firstOrNull { it.id == state.remoteControlTargetId }?.name + } + LazyColumn( + state = scrollState, + modifier = Modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + contentPadding = PaddingValues(horizontal = 20.dp, vertical = 8.dp) ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Text( - text = "Now playing", - style = MaterialTheme.typography.labelLarge, - color = FurumiTextMuted - ) - Row(verticalAlignment = Alignment.CenterVertically) { - RoundControlButton( - size = 42, - background = FurumiSurface, - onClick = { onShare(track) } - ) { - ShareGlyph( - modifier = Modifier.size(20.dp), - color = MaterialTheme.colorScheme.onBackground - ) - } - Spacer(modifier = Modifier.width(12.dp)) - Box { - RoundControlButton( - size = 42, - background = FurumiSurface, - onClick = { currentTrackMenuExpanded = true } - ) { - MoreDotsGlyph( - modifier = Modifier.size(22.dp), - color = MaterialTheme.colorScheme.onBackground - ) + item(key = "player-controls") { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + RoundControlButton(label = "Close player", onClick = onDismiss) { + BackGlyph(Modifier.size(18.dp).rotate(-90f), MaterialTheme.colorScheme.onSurface) } - TrackContextMenu( - expanded = currentTrackMenuExpanded, - isLiked = likedTrackIds.contains(track.id), - onDismiss = { currentTrackMenuExpanded = false }, - onToggleLike = { - currentTrackMenuExpanded = false - onToggleLike(track.id) - }, - onPlayNext = { - currentTrackMenuExpanded = false - onPlayNext(track) - }, - onPlayLast = { - currentTrackMenuExpanded = false - onPlayLast(track) - }, - onShare = { - currentTrackMenuExpanded = false - onShare(track) - }, - onAddToPlaylist = { - currentTrackMenuExpanded = false - onAddToPlaylist(track) - }, - isDownloadedForOffline = track.isAudioCached || offlineDownloadedTrackIds.contains(track.id), - isDownloadingForOffline = offlineDownloadingTrackIds.contains(track.id), - canDownloadForOffline = canDownloadForOffline, - onDownloadForOffline = { - currentTrackMenuExpanded = false - onDownloadForOffline(track) + Column(Modifier.weight(1f), horizontalAlignment = Alignment.CenterHorizontally) { + Text("Now playing", style = MaterialTheme.typography.titleMedium) + if (remoteName != null) { + Text(remoteName, style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, maxLines = 1, overflow = TextOverflow.Ellipsis) } - ) - } - Spacer(modifier = Modifier.width(12.dp)) - RoundControlButton( - size = 42, - background = if (connectedDevicesState?.currentJamId != null) FurumiNeonPink else FurumiSurface, - onClick = { isDevicesMenuOpen = true } - ) { - DevicesGlyph( - modifier = Modifier.size(22.dp), - color = if (connectedDevicesState?.currentJamId != null) FurumiBlack else MaterialTheme.colorScheme.onBackground - ) - } - } - } - - Spacer(modifier = Modifier.height(36.dp)) - - MediaArtwork( - title = track.title, - seedId = track.id, - bitmap = coverBitmap, - modifier = Modifier - .fillMaxWidth() - .aspectRatio(1f), - cornerRadius = 12 - ) - - Spacer(modifier = Modifier.height(28.dp)) - - Text( - text = track.title, - style = MaterialTheme.typography.headlineMedium, - color = MaterialTheme.colorScheme.onBackground, - maxLines = 1, - overflow = TextOverflow.Ellipsis - ) - - val artists = track.artistRefs.ifEmpty { - track.artists.mapIndexed { i, name -> cy.hexor.furumi.domain.model.ArtistRef(id = -(i + 1L), name = name) } - } - - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically - ) { - artists.forEachIndexed { index, artistRef -> - Text( - text = artistRef.name, - style = MaterialTheme.typography.bodyLarge, - color = if (artistRef.id > 0) FurumiNeonPink else FurumiTextMuted, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.clickable(enabled = artistRef.id > 0) { - onArtistClick( - cy.hexor.furumi.domain.model.ArtistCard( - id = artistRef.id, - name = artistRef.name, - imageUrl = null, - releaseCount = 0, - trackCount = 0 - ) + } + Box { + RoundControlButton(label = "More track options", onClick = { currentTrackMenuExpanded = true }) { + MoreDotsGlyph(Modifier.size(22.dp), MaterialTheme.colorScheme.onSurface) + } + TrackContextMenu( + expanded = currentTrackMenuExpanded, + isLiked = likedTrackIds.contains(track.id), + onDismiss = { currentTrackMenuExpanded = false }, + onToggleLike = { + currentTrackMenuExpanded = false + onToggleLike(track.id) + }, + onPlayNext = { + currentTrackMenuExpanded = false + onPlayNext(track) + }, + onPlayLast = { + currentTrackMenuExpanded = false + onPlayLast(track) + }, + onLyrics = { + currentTrackMenuExpanded = false + onLyrics(track) + }, + onShare = { + currentTrackMenuExpanded = false + onShare(track) + }, + onAddToPlaylist = { + currentTrackMenuExpanded = false + onAddToPlaylist(track) + }, + isDownloadedForOffline = track.isAudioCached || offlineDownloadedTrackIds.contains(track.id), + isDownloadingForOffline = offlineDownloadingTrackIds.contains(track.id), + canDownloadForOffline = canDownloadForOffline, + onDownloadForOffline = { + currentTrackMenuExpanded = false + onDownloadForOffline(track) + } ) } - ) - if (index < artists.lastIndex) { - Text( - text = ", ", - style = MaterialTheme.typography.bodyLarge, - color = FurumiTextMuted - ) } - } - - if (playback.errorMessage != null) { - Text( - text = " • ${playback.errorMessage}", - style = MaterialTheme.typography.bodyLarge, - color = FurumiHotOrange, - maxLines = 1, - overflow = TextOverflow.Ellipsis + Spacer(Modifier.height(12.dp)) + MediaArtwork( + title = track.title, seedId = track.id, bitmap = coverBitmap, + modifier = Modifier.widthIn(max = artworkMaxSize).fillMaxWidth().aspectRatio(1f), + cornerRadius = 16 ) + Spacer(Modifier.height(20.dp)) + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Column(Modifier.weight(1f)) { + Text(track.title, style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis) + val artistColor = MaterialTheme.colorScheme.onSurfaceVariant + if (track.artistRefs.none { it.id > 0 }) { + Text(track.artists.joinToString(", "), color = artistColor, + style = MaterialTheme.typography.bodyLarge, maxLines = 1, overflow = TextOverflow.Ellipsis) + } else { + Row(Modifier.horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.CenterVertically) { + track.artistRefs.forEachIndexed { index, artist -> + if (index > 0) Text(", ", color = artistColor) + Text(artist.name, color = artistColor, style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.clickable(enabled = artist.id > 0, onClickLabel = "Open artist") { + onArtistClick(ArtistCard(artist.id, artist.name, null, 0, 0)) + }.padding(vertical = 4.dp)) + } + } + } + } + val liked = track.id in likedTrackIds + RoundControlButton(label = if (liked) "Remove from favorites" else "Add to favorites", + onClick = { onToggleLike(track.id) }) { + HeartGlyph(liked, Modifier.size(28.dp)) + } + } + playback.errorMessage?.let { message -> + Text(message, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall, + modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) + } + PlayerProgress(playback, onSeekToProgress) + Spacer(Modifier.height(8.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically) { + RoundControlButton(label = if (playback.shuffle) "Turn shuffle off" else "Turn shuffle on", + onClick = onToggleShuffle) { + ShuffleGlyph(Modifier.size(22.dp), if (playback.shuffle) FurumiAccent else FurumiTextMuted) + } + RoundControlButton(label = "Previous track", onClick = onPrevious) { + PreviousGlyph(Modifier.size(28.dp), MaterialTheme.colorScheme.onSurface) + } + RoundControlButton(label = if (playback.isPlaying) "Pause" else "Play", + size = 64, background = FurumiAccent, onClick = onPlayPause) { + PlaybackGlyph(playback, playSize = 28, pauseSize = 28) + } + RoundControlButton(label = "Next track", onClick = onNext) { + NextGlyph(Modifier.size(28.dp), MaterialTheme.colorScheme.onSurface) + } + RoundControlButton(label = "Change repeat mode, currently ${playback.repeatMode}", + onClick = onCycleRepeatMode) { + RepeatGlyph(Modifier.size(22.dp), if (playback.repeatMode.equals("off", true)) FurumiTextMuted else FurumiAccent, + repeatMode = playback.repeatMode) + } + } + Row(Modifier.fillMaxWidth().padding(top = 12.dp), verticalAlignment = Alignment.CenterVertically) { + OutlinedButton( + onClick = { onNowPlayingLyrics(track) }, + modifier = Modifier.heightIn(min = 48.dp) + ) { + LyricsGlyph(Modifier.size(18.dp), MaterialTheme.colorScheme.primary) + Spacer(Modifier.width(8.dp)) + Text("Lyrics") + } + Spacer(Modifier.weight(1f)) + RoundControlButton(label = "Choose playback device", onClick = { isDevicesMenuOpen = true }) { + DevicesGlyph(Modifier.size(22.dp), if (remoteName != null) FurumiAccent else MaterialTheme.colorScheme.onSurfaceVariant) + } + RoundControlButton(label = "Share track", onClick = { onShare(track) }) { + ShareGlyph(Modifier.size(21.dp), MaterialTheme.colorScheme.onSurfaceVariant) + } + } + Text("Queue", style = MaterialTheme.typography.titleLarge, + modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp)) } } - - Spacer(modifier = Modifier.height(26.dp)) - - PlayerProgress( - playback = playback, - onSeekToProgress = onSeekToProgress - ) - - Spacer(modifier = Modifier.height(24.dp)) - - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.SpaceEvenly, - verticalAlignment = Alignment.CenterVertically - ) { - RoundControlButton( - size = 48, - background = FurumiSurface, - onClick = onToggleShuffle - ) { - ShuffleGlyph( - modifier = Modifier.size(20.dp), - color = if (playback.shuffle) FurumiNeonPink else MaterialTheme.colorScheme.onBackground - ) - } - RoundControlButton( - size = 48, - background = FurumiSurface, - onClick = onPrevious - ) { - PreviousGlyph(Modifier.size(20.dp), MaterialTheme.colorScheme.onBackground) - } - RoundControlButton( - size = 72, - background = FurumiNeonPink, - onClick = onPlayPause - ) { - PlaybackGlyph( - playback = playback, - playSize = 24, - pauseSize = 24 - ) - } - RoundControlButton( - size = 48, - background = FurumiSurface, - onClick = onNext - ) { - NextGlyph(Modifier.size(20.dp), MaterialTheme.colorScheme.onBackground) - } - RoundControlButton( - size = 48, - background = FurumiSurface, - onClick = onCycleRepeatMode - ) { - RepeatGlyph( - modifier = Modifier.size(22.dp), - color = if (playback.repeatMode.equals("off", ignoreCase = true)) { - MaterialTheme.colorScheme.onBackground - } else { - FurumiNeonPink - }, - repeatMode = playback.repeatMode - ) - } - } - - Spacer(modifier = Modifier.height(34.dp)) - - SectionTitle("Queue") - Spacer(modifier = Modifier.height(12.dp)) - FullPlayerQueue( + fullPlayerQueue( queue = queue, playback = playback, mediaImages = mediaImages, @@ -456,6 +387,7 @@ internal fun FullPlayerOverlay( onToggleLike = onToggleLike, onPlayNext = onPlayNext, onPlayLast = onPlayLast, + onLyrics = onLyrics, onShare = onShare, onAddToPlaylist = onAddToPlaylist, offlineDownloadedTrackIds = offlineDownloadedTrackIds, @@ -484,8 +416,7 @@ internal fun FullPlayerOverlay( } } -@Composable -private fun FullPlayerQueue( +private fun LazyListScope.fullPlayerQueue( queue: List, playback: AudioPlaybackState, mediaImages: Map, @@ -497,6 +428,7 @@ private fun FullPlayerQueue( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, offlineDownloadedTrackIds: Set, @@ -505,11 +437,9 @@ private fun FullPlayerQueue( onDownloadForOffline: (TrackCard) -> Unit ) { if (queue.isEmpty()) { - Text( - text = "Queue is empty", - style = MaterialTheme.typography.bodyMedium, - color = FurumiTextMuted - ) + item(key = "empty-queue") { + Text("Queue is empty", style = MaterialTheme.typography.bodyMedium, color = FurumiTextMuted) + } return } @@ -519,40 +449,15 @@ private fun FullPlayerQueue( .takeIf { it >= 0 } ?: 0 val firstVisibleIndex = if (showPreviousQueue) 0 else currentIndex - val visibleQueue = queue - .mapIndexed { index, queueTrack -> index to queueTrack } - .drop(firstVisibleIndex) - if (!showPreviousQueue && currentIndex > 0) { - Box( - modifier = Modifier.fillMaxWidth(), - contentAlignment = Alignment.Center - ) { - Surface( - modifier = Modifier - .height(30.dp) - .clip(CircleShape) - .clickable(onClick = onShowPrevious), - shape = CircleShape, - color = FurumiSurface, - border = androidx.compose.foundation.BorderStroke(1.dp, FurumiLine) - ) { - Box( - modifier = Modifier.padding(horizontal = 14.dp), - contentAlignment = Alignment.Center - ) { - Text( - text = "Show previous", - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onBackground - ) - } - } + item(key = "show-previous") { + androidx.compose.material3.TextButton(onClick = onShowPrevious) { Text("Show previous") } } - Spacer(modifier = Modifier.height(12.dp)) } - visibleQueue.forEachIndexed { visibleIndex, (index, queueTrack) -> + items(count = queue.size - firstVisibleIndex, key = { "queue-${firstVisibleIndex + it}" }, contentType = { "queue-track" }) { offset -> + val index = firstVisibleIndex + offset + val queueTrack = queue[index] val isPlayed = index < currentIndex val isCurrent = index == currentIndex @@ -570,13 +475,12 @@ private fun FullPlayerQueue( onToggleLike = { onToggleLike(queueTrack.id) }, onPlayNext = { onPlayNext(queueTrack) }, onPlayLast = { onPlayLast(queueTrack) }, + onLyrics = { onLyrics(queueTrack) }, onShare = { onShare(queueTrack) }, onAddToPlaylist = { onAddToPlaylist(queueTrack) }, onDownloadForOffline = { onDownloadForOffline(queueTrack) } ) - if (visibleIndex < visibleQueue.lastIndex) { - Spacer(modifier = Modifier.height(12.dp)) - } + Spacer(Modifier.height(8.dp)) } } @@ -585,14 +489,21 @@ internal fun PlayerProgress( playback: AudioPlaybackState, onSeekToProgress: (Float) -> Unit ) { + var scrubPosition by remember(playback.currentTrack?.id) { mutableStateOf(null) } + val fraction = scrubPosition ?: playback.progress.coerceIn(0f, 1f) Column { Slider( - value = playback.progress, - onValueChange = onSeekToProgress, + modifier = Modifier.semantics { contentDescription = "Playback position" }, + value = fraction, + onValueChange = { scrubPosition = it }, + onValueChangeFinished = { + scrubPosition?.let(onSeekToProgress) + scrubPosition = null + }, enabled = playback.durationMs > 0L, colors = SliderDefaults.colors( - thumbColor = FurumiNeonPink, - activeTrackColor = FurumiNeonPink, + thumbColor = FurumiAccent, + activeTrackColor = FurumiAccent, inactiveTrackColor = FurumiLine, disabledThumbColor = FurumiTextMuted, disabledActiveTrackColor = FurumiLine, @@ -604,7 +515,7 @@ internal fun PlayerProgress( horizontalArrangement = Arrangement.SpaceBetween ) { Text( - text = formatPlaybackTime(playback.positionMs), + text = formatPlaybackTime(scrubPosition?.let { (it * playback.durationMs).toLong() } ?: playback.positionMs), style = MaterialTheme.typography.labelSmall, color = FurumiTextMuted ) @@ -683,7 +594,7 @@ private fun DevicesJamMenu( Text( text = error, style = MaterialTheme.typography.bodyMedium, - color = FurumiHotOrange, + color = FurumiError, maxLines = 2, overflow = TextOverflow.Ellipsis ) @@ -749,7 +660,7 @@ private fun DeviceMenuRow( .clickable(onClick = onClick), shape = RoundedCornerShape(8.dp), color = if (device.isActive) FurumiSurface else Color.Transparent, - border = if (device.isActive) androidx.compose.foundation.BorderStroke(1.dp, FurumiNeonPink) else null + border = if (device.isActive) androidx.compose.foundation.BorderStroke(1.dp, FurumiAccent) else null ) { Row( modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp), @@ -759,7 +670,7 @@ private fun DeviceMenuRow( modifier = Modifier .size(10.dp) .clip(CircleShape) - .background(if (device.isActive) FurumiNeonPink else FurumiLine) + .background(if (device.isActive) FurumiAccent else FurumiLine) ) Spacer(modifier = Modifier.width(14.dp)) Column(modifier = Modifier.weight(1f)) { @@ -774,7 +685,7 @@ private fun DeviceMenuRow( Text( text = if (device.isCurrent) "Current device" else "Playing", style = MaterialTheme.typography.bodySmall, - color = if (device.isActive) FurumiNeonPink else FurumiTextMuted, + color = if (device.isActive) FurumiAccent else FurumiTextMuted, maxLines = 1 ) } @@ -782,7 +693,7 @@ private fun DeviceMenuRow( if (device.isActive) { DevicesGlyph( modifier = Modifier.size(20.dp), - color = FurumiNeonPink + color = FurumiAccent ) } } @@ -856,10 +767,10 @@ private fun JamCard( modifier = Modifier .size(32.dp) .clip(CircleShape) - .background(FurumiNeonViolet.copy(alpha = 0.2f)), + .background(FurumiAccentMuted.copy(alpha = 0.2f)), contentAlignment = Alignment.Center ) { - Text("J", color = FurumiNeonViolet, fontWeight = FontWeight.Bold) + Text("J", color = FurumiAccentMuted, fontWeight = FontWeight.Bold) } Spacer(modifier = Modifier.width(12.dp)) Column(modifier = Modifier.weight(1f)) { @@ -988,7 +899,7 @@ private fun JamInviteSearch( ) { CircularProgressIndicator( modifier = Modifier.size(20.dp), - color = FurumiNeonPink, + color = FurumiAccent, strokeWidth = 2.dp ) } @@ -1095,9 +1006,10 @@ private fun JamInviteRow( } @Composable -internal fun RoundControlButton( - size: Int, - background: Color, +private fun RoundControlButton( + label: String, + size: Int = 48, + background: Color = Color.Transparent, onClick: () -> Unit, content: @Composable BoxScope.() -> Unit ) { @@ -1106,7 +1018,8 @@ internal fun RoundControlButton( .size(size.dp) .clip(CircleShape) .background(background) - .clickable(onClick = onClick), + .semantics { contentDescription = label } + .clickable(role = Role.Button, onClick = onClick), contentAlignment = Alignment.Center, content = content ) diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerReleaseContent.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerReleaseContent.kt index 9f444bb..7f5cbde 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerReleaseContent.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerReleaseContent.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -87,6 +87,7 @@ internal fun ReleaseDetailContent( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -136,7 +137,7 @@ internal fun ReleaseDetailContent( Spacer(modifier = Modifier.height(28.dp)) when { - uiState.isReleaseDetailLoading && uiState.releaseDetail == null -> ReleaseDetailLoading() + uiState.isReleaseDetailLoading && uiState.releaseDetail == null -> LoadingTrackRows() uiState.releaseDetailError != null && uiState.releaseDetail == null -> ReleaseDetailError( message = uiState.releaseDetailError, onRetry = onRetry @@ -149,6 +150,7 @@ internal fun ReleaseDetailContent( onToggleLike = onToggleLike, onPlayNext = onPlayNext, onPlayLast = onPlayLast, + onLyrics = onLyrics, onShare = onShare, onAddToPlaylist = onAddToPlaylist, onDownloadForOffline = onDownloadForOffline @@ -223,21 +225,6 @@ internal fun ReleaseDetailHero( } } -@Composable -internal fun ReleaseDetailLoading() { - Box( - modifier = Modifier - .fillMaxWidth() - .height(180.dp), - contentAlignment = Alignment.Center - ) { - CircularProgressIndicator( - color = FurumiNeonPink, - strokeWidth = 2.dp - ) - } -} - @Composable internal fun ReleaseDetailError( message: String, @@ -280,6 +267,7 @@ internal fun ReleaseTracksSection( onToggleLike: (Long) -> Unit, onPlayNext: (TrackCard) -> Unit, onPlayLast: (TrackCard) -> Unit, + onLyrics: (TrackCard) -> Unit, onShare: (TrackCard) -> Unit, onAddToPlaylist: (TrackCard) -> Unit, onDownloadForOffline: (TrackCard) -> Unit @@ -328,6 +316,7 @@ internal fun ReleaseTracksSection( onToggleLike = { onToggleLike(track.id) }, onPlayNext = { onPlayNext(track) }, onPlayLast = { onPlayLast(track) }, + onLyrics = { onLyrics(track) }, onShare = { onShare(track) }, onAddToPlaylist = { onAddToPlaylist(track) }, onDownloadForOffline = { onDownloadForOffline(track) } diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerRows.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerRows.kt index d85945a..dd52636 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerRows.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerRows.kt @@ -25,6 +25,7 @@ import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Slider @@ -57,6 +58,8 @@ import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.drawscope.Fill import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -68,11 +71,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -92,6 +95,7 @@ internal fun ArtistDetailTrackRow( onToggleLike: () -> Unit, onPlayNext: () -> Unit, onPlayLast: () -> Unit, + onLyrics: () -> Unit, onShare: () -> Unit, onAddToPlaylist: () -> Unit, onDownloadForOffline: () -> Unit @@ -162,14 +166,7 @@ internal fun ArtistDetailTrackRow( alpha = contentAlpha ) Box { - MoreDotsGlyph( - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable { menuExpanded = true } - .padding(4.dp), - color = FurumiTextMuted.copy(alpha = contentAlpha) - ) + TrackOptionsButton(track.title, FurumiTextMuted.copy(alpha = contentAlpha)) { menuExpanded = true } TrackContextMenu( expanded = menuExpanded, isLiked = isLiked, @@ -177,6 +174,7 @@ internal fun ArtistDetailTrackRow( onToggleLike = { menuExpanded = false; onToggleLike() }, onPlayNext = { menuExpanded = false; onPlayNext() }, onPlayLast = { menuExpanded = false; onPlayLast() }, + onLyrics = { menuExpanded = false; onLyrics() }, onShare = { menuExpanded = false; onShare() }, onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }, isDownloadedForOffline = isDownloadedForOffline, @@ -206,6 +204,7 @@ internal fun ReleaseTrackRow( onToggleLike: () -> Unit, onPlayNext: () -> Unit, onPlayLast: () -> Unit, + onLyrics: () -> Unit, onShare: () -> Unit, onAddToPlaylist: () -> Unit, onDownloadForOffline: () -> Unit @@ -260,14 +259,7 @@ internal fun ReleaseTrackRow( alpha = contentAlpha ) Box { - MoreDotsGlyph( - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable { menuExpanded = true } - .padding(4.dp), - color = FurumiTextMuted.copy(alpha = contentAlpha) - ) + TrackOptionsButton(track.title, FurumiTextMuted.copy(alpha = contentAlpha)) { menuExpanded = true } TrackContextMenu( expanded = menuExpanded, isLiked = isLiked, @@ -275,6 +267,7 @@ internal fun ReleaseTrackRow( onToggleLike = { menuExpanded = false; onToggleLike() }, onPlayNext = { menuExpanded = false; onPlayNext() }, onPlayLast = { menuExpanded = false; onPlayLast() }, + onLyrics = { menuExpanded = false; onLyrics() }, onShare = { menuExpanded = false; onShare() }, onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }, isDownloadedForOffline = isDownloadedForOffline, @@ -306,9 +299,11 @@ internal fun PlaylistTrackRow( onToggleLike: () -> Unit, onPlayNext: () -> Unit, onPlayLast: () -> Unit, + onLyrics: () -> Unit, onShare: () -> Unit, onAddToPlaylist: () -> Unit, - onDownloadForOffline: () -> Unit + onDownloadForOffline: () -> Unit, + downloadStatus: String? = null ) { var menuExpanded by remember { mutableStateOf(false) } val isUnavailable = track.isUnavailableForPlayback() @@ -328,60 +323,46 @@ internal fun PlaylistTrackRow( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(8.dp)) - .clickable(enabled = !isUnavailable) { onTrackClick(track) } - .padding(vertical = 4.dp), + .clickable(enabled = !isUnavailable, onClickLabel = "Play track $index") { onTrackClick(track) } + .padding(vertical = 3.dp), verticalAlignment = Alignment.CenterVertically ) { - Text( - text = index.toString(), - modifier = Modifier.width(28.dp), - style = MaterialTheme.typography.bodyMedium, - color = secondaryColor - ) MediaArtwork( title = track.title, seedId = track.id, bitmap = bitmap, - modifier = Modifier - .size(48.dp) - .unavailableTrackArtworkOverlay(isUnavailable), + modifier = Modifier.size(48.dp).unavailableTrackArtworkOverlay(isUnavailable), cornerRadius = 6 ) - Spacer(modifier = Modifier.width(12.dp)) - Column(modifier = Modifier.weight(1f)) { + Spacer(Modifier.width(12.dp)) + Column(Modifier.weight(1f).padding(vertical = 4.dp)) { Text( - text = track.title, - style = MaterialTheme.typography.labelLarge, + track.title, + style = MaterialTheme.typography.titleSmall, color = primaryColor, - maxLines = 1, + maxLines = 2, overflow = TextOverflow.Ellipsis ) Text( - text = trackSubtitle(track), - style = MaterialTheme.typography.bodyMedium, + trackSubtitle(track), + style = MaterialTheme.typography.bodySmall, color = secondaryColor, maxLines = 1, overflow = TextOverflow.Ellipsis ) + val status = downloadStatus ?: if (isDownloadedForOffline) "Downloaded" else null + if (status != null) { + Text( + status, + style = MaterialTheme.typography.labelSmall, + color = if (isDownloadedForOffline) FurumiAccent else secondaryColor + ) + } } - HeartGlyph( - isLiked = isLiked, - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable(onClick = onToggleLike) - .padding(4.dp), - alpha = contentAlpha - ) + Spacer(Modifier.width(8.dp)) + Text(formatDuration(track.durationSeconds), style = MaterialTheme.typography.labelSmall, color = secondaryColor) Box { - MoreDotsGlyph( - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable { menuExpanded = true } - .padding(4.dp), - color = FurumiTextMuted.copy(alpha = contentAlpha) - ) + TrackOptionsButton(track.title) { menuExpanded = true } TrackContextMenu( expanded = menuExpanded, isLiked = isLiked, @@ -389,6 +370,7 @@ internal fun PlaylistTrackRow( onToggleLike = { menuExpanded = false; onToggleLike() }, onPlayNext = { menuExpanded = false; onPlayNext() }, onPlayLast = { menuExpanded = false; onPlayLast() }, + onLyrics = { menuExpanded = false; onLyrics() }, onShare = { menuExpanded = false; onShare() }, onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }, isDownloadedForOffline = isDownloadedForOffline, @@ -397,12 +379,6 @@ internal fun PlaylistTrackRow( onDownloadForOffline = { menuExpanded = false; onDownloadForOffline() } ) } - Spacer(modifier = Modifier.width(4.dp)) - Text( - text = formatDuration(track.durationSeconds), - style = MaterialTheme.typography.bodyMedium, - color = secondaryColor - ) } } @@ -458,6 +434,7 @@ internal fun QueueTrackRow( onToggleLike: () -> Unit, onPlayNext: () -> Unit, onPlayLast: () -> Unit, + onLyrics: () -> Unit, onShare: () -> Unit, onAddToPlaylist: () -> Unit, onDownloadForOffline: () -> Unit @@ -501,7 +478,7 @@ internal fun QueueTrackRow( .background(Color.Black.copy(alpha = 0.4f)), contentAlignment = Alignment.Center ) { - AudioWaveGlyph(modifier = Modifier.size(20.dp), color = FurumiNeonPink) + AudioWaveGlyph(modifier = Modifier.size(20.dp), color = FurumiAccent) } } } @@ -510,7 +487,7 @@ internal fun QueueTrackRow( Text( text = track.title, style = if (isCurrent) MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Bold) else MaterialTheme.typography.labelLarge, - color = if (isCurrent) FurumiNeonPink else MaterialTheme.colorScheme.onBackground.copy(alpha = contentAlpha), + color = if (isCurrent) FurumiAccent else MaterialTheme.colorScheme.onBackground.copy(alpha = contentAlpha), maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -532,13 +509,7 @@ internal fun QueueTrackRow( alpha = contentAlpha ) Box { - MoreDotsGlyph( - modifier = Modifier - .size(32.dp) - .clip(CircleShape) - .clickable { menuExpanded = true } - .padding(4.dp) - ) + TrackOptionsButton(track.title) { menuExpanded = true } TrackContextMenu( expanded = menuExpanded, isLiked = isLiked, @@ -546,6 +517,7 @@ internal fun QueueTrackRow( onToggleLike = { menuExpanded = false; onToggleLike() }, onPlayNext = { menuExpanded = false; onPlayNext() }, onPlayLast = { menuExpanded = false; onPlayLast() }, + onLyrics = { menuExpanded = false; onLyrics() }, onShare = { menuExpanded = false; onShare() }, onAddToPlaylist = { menuExpanded = false; onAddToPlaylist() }, isDownloadedForOffline = isDownloadedForOffline, @@ -563,6 +535,14 @@ internal fun QueueTrackRow( } } +@Composable +private fun TrackOptionsButton(title: String, tint: Color = FurumiTextMuted, onClick: () -> Unit) { + IconButton(onClick = onClick, + modifier = Modifier.size(48.dp).semantics { contentDescription = "More options for $title" }) { + MoreDotsGlyph(Modifier.size(22.dp), tint) + } +} + private fun TrackCard.isUnavailableForPlayback(): Boolean { return streamUrl.isBlank() } diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerScreen.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerScreen.kt index 5b2cb93..47721dd 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerScreen.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerScreen.kt @@ -39,6 +39,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -60,7 +61,6 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import cy.hexor.furumi.domain.model.ArtistCard -import cy.hexor.furumi.domain.model.ConnectedDevicesState import cy.hexor.furumi.domain.model.ConnectedPlaybackState import cy.hexor.furumi.domain.model.PlaylistCard import cy.hexor.furumi.domain.model.ReleaseCard @@ -68,26 +68,32 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted import kotlin.math.roundToInt +import kotlin.math.roundToLong @Composable fun PlayerScreen( viewModel: PlayerViewModel = hiltViewModel(), + openDownloads: Boolean = false, + onDownloadsOpened: () -> Unit = {}, onLoggedOut: () -> Unit ) { val uiState by viewModel.uiState.collectAsState() val displayedPlayback = uiState.displayedPlayback() var selectedTabName by rememberSaveable { mutableStateOf(PlayerTab.Global.name) } val selectedTab = PlayerTab.entries.firstOrNull { it.name == selectedTabName } ?: PlayerTab.Global + var showDownloads by rememberSaveable { mutableStateOf(false) } + val libraryState = rememberSaveableStateHolder() var isProfileMenuOpen by rememberSaveable { mutableStateOf(false) } + var confirmClearDownloads by rememberSaveable { mutableStateOf(false) } var isFullPlayerOpen by rememberSaveable { mutableStateOf(false) } var fullPlayerDragOffset by remember { androidx.compose.runtime.mutableFloatStateOf(0f) } var addToPlaylistTrack by remember { mutableStateOf(null) } @@ -95,6 +101,29 @@ fun PlayerScreen( var createPlaylistTrack by remember { mutableStateOf(null) } var deletePlaylistCandidate by remember { mutableStateOf(null) } + LaunchedEffect(displayedPlayback.currentTrack?.id, uiState.followPlayingLyrics) { + if (uiState.followPlayingLyrics) displayedPlayback.currentTrack?.let(viewModel::openNowPlayingLyrics) + } + + LaunchedEffect(openDownloads) { + if (openDownloads && !uiState.isLoggedOut) { + selectedTabName = PlayerTab.Library.name + showDownloads = true + isProfileMenuOpen = false + confirmClearDownloads = false + isFullPlayerOpen = false + addToPlaylistTrack = null + isCreatePlaylistDialogOpen = false + createPlaylistTrack = null + deletePlaylistCandidate = null + viewModel.closePlaylistDetail() + viewModel.closeArtistDetail() + viewModel.closeLyrics() + viewModel.closeListeningHistory() + onDownloadsOpened() + } + } + val openCreatePlaylistDialog: (TrackCard?) -> Unit = { track -> viewModel.clearPlaylistCreateError() createPlaylistTrack = track @@ -173,38 +202,34 @@ fun PlayerScreen( val onProfileClick = { isProfileMenuOpen = !isProfileMenuOpen } val artistScrollState = rememberScrollState() if (uiState.selectedPlaylist != null) { - Box( - modifier = Modifier - .fillMaxSize() - .verticalScroll(rememberScrollState()) - ) { - PlaylistDetailContent( - uiState = uiState, - onBack = viewModel::closePlaylistDetail, - onRetry = viewModel::retryPlaylistDetail, - onMediaImageNeeded = viewModel::loadMediaImage, - onPlayClick = { - viewModel.playPlaylistTracks(shuffle = false) - }, - onShuffleClick = { - viewModel.playPlaylistTracks(shuffle = true) - }, - onTrackClick = { track -> - viewModel.playTrack(track, uiState.playlistDetail?.tracks.orEmpty()) - }, - onToggleLike = viewModel::toggleLike, - onPlayNext = viewModel::addToPlayNext, - onPlayLast = viewModel::addToQueueEnd, - onShare = viewModel::shareTrack, - onAddToPlaylist = { track -> addToPlaylistTrack = track }, - onDownloadForOffline = viewModel::downloadTrackForOffline, - onDownloadPlaylistClick = viewModel::downloadPlaylistForOffline, - onDeletePlaylistClick = { playlist -> - viewModel.clearPlaylistDeleteError() - deletePlaylistCandidate = playlist - } - ) - } + PlaylistDetailContent( + uiState = uiState, + onBack = viewModel::closePlaylistDetail, + onRetry = viewModel::retryPlaylistDetail, + onMediaImageNeeded = viewModel::loadMediaImage, + onPlayClick = { + viewModel.playPlaylistTracks(shuffle = false) + }, + onShuffleClick = { + viewModel.playPlaylistTracks(shuffle = true) + }, + onTrackClick = { track -> + viewModel.playTrack(track, uiState.playlistDetail?.tracks.orEmpty()) + }, + onToggleLike = viewModel::toggleLike, + onPlayNext = viewModel::addToPlayNext, + onPlayLast = viewModel::addToQueueEnd, + onLyrics = viewModel::openLyrics, + onShare = viewModel::shareTrack, + onAddToPlaylist = { track -> addToPlaylistTrack = track }, + onDownloadForOffline = viewModel::downloadTrackForOffline, + onDownloadPlaylistClick = viewModel::downloadPlaylistForOffline, + onRetryFailed = viewModel::retryFailedDownloads, + onDeletePlaylistClick = { playlist -> + viewModel.clearPlaylistDeleteError() + deletePlaylistCandidate = playlist + } + ) } else if (uiState.selectedRelease != null) { Box( modifier = Modifier @@ -228,6 +253,7 @@ fun PlayerScreen( onToggleLike = viewModel::toggleLike, onPlayNext = viewModel::addToPlayNext, onPlayLast = viewModel::addToQueueEnd, + onLyrics = viewModel::openLyrics, onShare = viewModel::shareTrack, onAddToPlaylist = { track -> addToPlaylistTrack = track }, onDownloadForOffline = viewModel::downloadTrackForOffline @@ -257,6 +283,7 @@ fun PlayerScreen( onToggleLike = viewModel::toggleLike, onPlayNext = viewModel::addToPlayNext, onPlayLast = viewModel::addToQueueEnd, + onLyrics = viewModel::openLyrics, onShare = viewModel::shareTrack, onAddToPlaylist = { track -> addToPlaylistTrack = track }, onDownloadForOffline = viewModel::downloadTrackForOffline @@ -281,6 +308,7 @@ fun PlayerScreen( uiState = uiState, onProfileClick = onProfileClick, onQueryChange = viewModel::onSearchQueryChange, + onReleaseClick = viewModel::openRelease, onRetry = viewModel::retrySearch, onArtistClick = viewModel::openArtist, onMediaImageNeeded = viewModel::loadMediaImage, @@ -290,23 +318,29 @@ fun PlayerScreen( onToggleLike = viewModel::toggleLike, onPlayNext = viewModel::addToPlayNext, onPlayLast = viewModel::addToQueueEnd, + onLyrics = viewModel::openLyrics, onShare = viewModel::shareTrack, onAddToPlaylist = { track -> addToPlaylistTrack = track }, onDownloadForOffline = viewModel::downloadTrackForOffline ) } - PlayerTab.Library -> Box( - modifier = Modifier.fillMaxSize() - ) { + PlayerTab.Library -> libraryState.SaveableStateProvider("library") { LibraryContent( uiState = uiState, + showDownloads = showDownloads, + onShowDownloadsChange = { showDownloads = it }, onProfileClick = onProfileClick, onLoadLibrary = viewModel::loadLibraryIfNeeded, onRetryPlaylists = viewModel::loadPlaylists, onRetryArtists = viewModel::retryLibraryArtists, onLoadMoreArtists = viewModel::loadMoreLibraryArtists, onCreatePlaylistClick = { openCreatePlaylistDialog(null) }, - onPlaylistPreviewNeeded = viewModel::loadPlaylistPreview, + getDownloadedTracks = viewModel::getDownloadedTracks, + onLyrics = viewModel::openLyrics, + onPlayDownloaded = { track, tracks -> viewModel.playTrack(track, tracks) }, + onStorageLimitChange = viewModel::setOfflineStorageLimit, + onClearDownloads = { confirmClearDownloads = true }, + onRetryFailed = viewModel::retryFailedDownloads, onPlaylistClick = viewModel::openPlaylist, onArtistImageNeeded = viewModel::loadMediaImage, onArtistClick = viewModel::openArtist @@ -316,28 +350,27 @@ fun PlayerScreen( } } - displayedPlayback.currentTrack?.let { track -> + val devices = uiState.connectedDevicesState?.takeUnless { uiState.offlineState.isOfflineActive } + if (displayedPlayback.currentTrack != null || devices?.remoteControlTargetId != null) { NowPlayingBar( playback = displayedPlayback, - coverBitmap = mediaImageFor(uiState.mediaImages, track.coverUrl), - isLiked = uiState.likedTrackIds.contains(track.id), + coverBitmap = mediaImageFor(uiState.mediaImages, displayedPlayback.currentTrack?.coverUrl), + devices = devices, onMediaImageNeeded = viewModel::loadMediaImage, onClick = { isFullPlayerOpen = true fullPlayerDragOffset = 0f }, onPlayPause = viewModel::togglePlayPause, - onPrevious = viewModel::previousTrack, onNext = viewModel::nextTrack, - onToggleShuffle = viewModel::toggleShuffle, - onCycleRepeatMode = viewModel::cycleRepeatMode, - onToggleLike = { viewModel.toggleLike(track.id) } + onSelectDevice = viewModel::setActiveDevice ) } BottomPlayerNav( selectedTab = selectedTab, onTabSelected = { selectedTabName = it.name + showDownloads = false viewModel.closePlaylistDetail() viewModel.closeArtistDetail() } @@ -356,7 +389,7 @@ fun PlayerScreen( onSaveListenedChange = viewModel::setSaveListenedTracksEnabled, onStorageLimitChange = viewModel::setOfflineStorageLimit, onSyncOffline = viewModel::syncOfflineLibrary, - onClearOfflineCache = viewModel::clearOfflineCache, + onClearOfflineCache = { confirmClearDownloads = true }, onLogout = viewModel::logout, modifier = Modifier .align(Alignment.TopCenter) @@ -364,6 +397,24 @@ fun PlayerScreen( ) } + if (confirmClearDownloads) { + androidx.compose.material3.AlertDialog( + onDismissRequest = { confirmClearDownloads = false }, + title = { Text("Clear downloads?") }, + text = { + Text("Remove ${pluralCount(uiState.offlineState.cachedTrackCount, "track")} and free ${formatStorageBytes(uiState.offlineState.storageUsedBytes)} on this device?") + }, + confirmButton = { + androidx.compose.material3.TextButton(onClick = { + confirmClearDownloads = false + viewModel.clearOfflineCache() + }) { Text("Clear downloads") } + }, + dismissButton = { + androidx.compose.material3.TextButton(onClick = { confirmClearDownloads = false }) { Text("Cancel") } + } + ) + } if (uiState.offlineState.isOfflineActive && !isProfileMenuOpen) { OfflineStatusBadge( offlineState = uiState.offlineState, @@ -391,6 +442,7 @@ fun PlayerScreen( onNext = viewModel::nextTrack, onToggleShuffle = viewModel::toggleShuffle, onCycleRepeatMode = viewModel::cycleRepeatMode, + onNowPlayingLyrics = viewModel::openNowPlayingLyrics, onSeekToProgress = viewModel::seekToPlaybackProgress, onQueueTrackClick = { track, index -> viewModel.playTrack(track, displayedPlayback.queue, index) @@ -398,6 +450,7 @@ fun PlayerScreen( onToggleLike = viewModel::toggleLike, onPlayNext = viewModel::addToPlayNext, onPlayLast = viewModel::addToQueueEnd, + onLyrics = viewModel::openLyrics, onShare = viewModel::shareTrack, onAddToPlaylist = { track -> addToPlaylistTrack = track }, offlineDownloadedTrackIds = uiState.offlineDownloadedTrackIds, @@ -426,6 +479,7 @@ fun PlayerScreen( ListeningHistoryPanel( uiState = uiState, onDismiss = viewModel::closeListeningHistory, + onLyrics = viewModel::openLyrics, onRetry = viewModel::retryListeningHistory ) } @@ -486,37 +540,37 @@ fun PlayerScreen( } ) } + uiState.lyricsTrack?.let { track -> + LyricsScreen( + track = track, + state = uiState.lyricsState, + playback = displayedPlayback, + onClose = viewModel::closeLyrics, + onRetry = viewModel::retryLyrics, + onSeekToLine = { positionMs -> viewModel.seekToLyricsLine(track, positionMs) }, + onPlayPause = viewModel::togglePlayPause, + coverBitmap = mediaImageFor(uiState.mediaImages, track.coverUrl) + ) + } } } -private fun PlayerUiState.displayedPlayback(): AudioPlaybackState { - if (offlineState.isOfflineActive) return playback - val connectedState = connectedDevicesState - val remotePlayback = connectedState?.remotePlaybackState - return if (connectedState != null && - (!connectedState.isCurrentDeviceActive || connectedState.isControllingRemoteJam()) && - remotePlayback != null - ) { - remotePlayback.toAudioPlaybackState() - } else { - playback - } -} - -private fun ConnectedDevicesState.isControllingRemoteJam(): Boolean { - val currentJam = jams.firstOrNull { it.id == currentJamId } - ?: jams.firstOrNull { it.isActive } - return currentJam != null && currentJam.isMember && !currentJam.isOwner +internal fun PlayerUiState.displayedPlayback(): AudioPlaybackState { + val devices = connectedDevicesState + if (offlineState.isOfflineActive || devices?.remoteControlTargetId == null) return playback + return devices.remotePlaybackState?.toAudioPlaybackState() ?: AudioPlaybackState() } private fun ConnectedPlaybackState.toAudioPlaybackState(): AudioPlaybackState { + val queue = tracks.ifEmpty { listOfNotNull(track) } + val currentIndex = index.takeIf { it in queue.indices } ?: queue.indexOfFirst { it.id == track?.id } return AudioPlaybackState( - queue = tracks, - currentIndex = index, + queue = queue, + currentIndex = currentIndex, isPlaying = !paused, isBuffering = false, - positionMs = (positionSeconds * 1_000.0).toLong().coerceAtLeast(0L), - durationMs = (durationSeconds * 1_000.0).toLong().coerceAtLeast(0L), + positionMs = (positionSeconds * 1_000.0).roundToLong().coerceAtLeast(0L), + durationMs = (durationSeconds * 1_000.0).roundToLong().coerceAtLeast(0L), shuffle = shuffle, repeatMode = repeatMode, volume = volume.toFloat() diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerUiUtils.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerUiUtils.kt index 774657e..31fb716 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerUiUtils.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerUiUtils.kt @@ -65,11 +65,11 @@ import cy.hexor.furumi.domain.model.TrackCard import cy.hexor.furumi.domain.model.ListeningHistoryItem import cy.hexor.furumi.playback.AudioPlaybackState import cy.hexor.furumi.ui.theme.FurumiBlack -import cy.hexor.furumi.ui.theme.FurumiElectricCyan -import cy.hexor.furumi.ui.theme.FurumiHotOrange +import cy.hexor.furumi.ui.theme.FurumiAccentBright +import cy.hexor.furumi.ui.theme.FurumiError import cy.hexor.furumi.ui.theme.FurumiLine -import cy.hexor.furumi.ui.theme.FurumiNeonPink -import cy.hexor.furumi.ui.theme.FurumiNeonViolet +import cy.hexor.furumi.ui.theme.FurumiAccent +import cy.hexor.furumi.ui.theme.FurumiAccentMuted import cy.hexor.furumi.ui.theme.FurumiSurface import cy.hexor.furumi.ui.theme.FurumiSurfaceHigh import cy.hexor.furumi.ui.theme.FurumiTextMuted @@ -157,16 +157,13 @@ internal fun playlistMeta(playlist: PlaylistCard): String { } internal fun mediaImageFor(mediaImages: Map, url: String?): Bitmap? { - val imageUrl = url?.takeIf { it.isNotBlank() } ?: return null - mediaImages[imageUrl]?.let { return it } - val requestedResource = canonicalMediaImageResource(imageUrl) - return mediaImages.entries.firstOrNull { (cachedUrl, _) -> - canonicalMediaImageResource(cachedUrl) == requestedResource - }?.value + return url?.let { mediaImages[canonicalMediaImageResource(it)] } } internal fun canonicalMediaImageResource(url: String): String { - val cleanUrl = url.substringBefore('?').trimEnd('/') + // Federation artwork identifies the track in its query string. + if ('?' in url) return url + val cleanUrl = url.trimEnd('/') val lastSlash = cleanUrl.lastIndexOf('/') if (lastSlash < 0) return cleanUrl @@ -180,21 +177,21 @@ internal fun canonicalMediaImageResource(url: String): String { internal fun artistArtworkColors(artistId: Long): List { val palettes = listOf( - listOf(FurumiNeonPink, FurumiNeonViolet, FurumiBlack), - listOf(FurumiElectricCyan, FurumiSurfaceHigh), - listOf(FurumiHotOrange, FurumiNeonPink), - listOf(FurumiNeonViolet, FurumiSurface), - listOf(FurumiSurfaceHigh, FurumiNeonPink) + listOf(FurumiAccent, FurumiAccentMuted, FurumiBlack), + listOf(FurumiAccentBright, FurumiSurfaceHigh), + listOf(FurumiAccentMuted, FurumiAccent), + listOf(FurumiAccentMuted, FurumiSurface), + listOf(FurumiSurfaceHigh, FurumiAccent) ) return palettes[paletteIndex(artistId, palettes.size)] } internal fun historyArtworkColors(trackId: Long): List { val palettes = listOf( - listOf(FurumiNeonPink, FurumiNeonViolet, FurumiBlack), - listOf(FurumiElectricCyan, FurumiSurfaceHigh), - listOf(FurumiHotOrange, FurumiNeonPink), - listOf(FurumiNeonViolet, FurumiSurface) + listOf(FurumiAccent, FurumiAccentMuted, FurumiBlack), + listOf(FurumiAccentBright, FurumiSurfaceHigh), + listOf(FurumiAccentMuted, FurumiAccent), + listOf(FurumiAccentMuted, FurumiSurface) ) return palettes[paletteIndex(trackId, palettes.size)] } diff --git a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerViewModel.kt b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerViewModel.kt index 93986ef..42239a7 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/player/PlayerViewModel.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/player/PlayerViewModel.kt @@ -2,6 +2,7 @@ package cy.hexor.furumi.ui.player import android.graphics.Bitmap import android.util.Log +import android.util.LruCache import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import cy.hexor.furumi.data.repository.MediaImageLoader @@ -12,6 +13,8 @@ import cy.hexor.furumi.domain.model.ConnectedDevicesState import cy.hexor.furumi.domain.model.ConnectedJamUser import cy.hexor.furumi.domain.model.ConnectedPlaybackState import cy.hexor.furumi.domain.model.ListeningHistoryItem +import cy.hexor.furumi.domain.model.LyricsVersion +import cy.hexor.furumi.domain.model.OfflineDownloadQueueState import cy.hexor.furumi.domain.model.OfflineState import cy.hexor.furumi.domain.model.PlaylistCard import cy.hexor.furumi.domain.model.PlaylistDetail @@ -31,8 +34,11 @@ import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.Job +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import javax.inject.Inject data class PlayerUiState( @@ -46,6 +52,9 @@ data class PlayerUiState( val listeningHistory: List = emptyList(), val listeningHistoryTotal: Long = 0, val listeningHistoryError: String? = null, + val lyricsTrack: TrackCard? = null, + val lyricsState: LyricsUiState = LyricsUiState.Loading, + val followPlayingLyrics: Boolean = false, val globalArtists: List = emptyList(), val globalArtistsTotal: Long = 0, val globalArtistsPage: Int = 0, @@ -79,16 +88,14 @@ data class PlayerUiState( val playlists: List = emptyList(), val isPlaylistsLoading: Boolean = false, val playlistsError: String? = null, - val playlistPreviewCoverUrls: Map> = emptyMap(), - val loadingPlaylistPreviewIds: Set = emptySet(), val isCreatingPlaylist: Boolean = false, val playlistCreateError: String? = null, val isDeletingPlaylist: Boolean = false, val playlistDeleteError: String? = null, val offlineDownloadedTrackIds: Set = emptySet(), val offlineDownloadingTrackIds: Set = emptySet(), - val offlineDownloadingPlaylistIds: Set = emptySet(), - val offlineDownloadError: String? = null, + val offlineQueue: OfflineDownloadQueueState = OfflineDownloadQueueState(), + val preparingDownloadPlaylistIds: Set = emptySet(), val selectedPlaylist: PlaylistCard? = null, val playlistDetail: PlaylistDetail? = null, val isPlaylistDetailLoading: Boolean = false, @@ -113,16 +120,22 @@ class PlayerViewModel @Inject constructor( private val artistDetailCache = mutableMapOf() private val releaseDetailCache = mutableMapOf() private val playlistDetailCache = mutableMapOf() + private val lyricsCache = LruCache>(32) + private var lyricsJob: Job? = null private var searchJob: Job? = null private var jamInviteSearchJob: Job? = null - private var offlineModeRefreshJob: Job? = null - private var offlineDownloadRefreshJob: Job? = null + private var globalArtistsJob: Job? = null + private var libraryArtistsJob: Job? = null + private var playlistsJob: Job? = null + private var playlistDetailJob: Job? = null + private var libraryOpened = false + private var catalogSyncJob: Job? = null private val handledConnectedCommandIds = ArrayDeque() private val handledConnectedCommandIdSet = mutableSetOf() - private var wasCurrentDeviceActive = false - private var wasControllingRemoteJam = false - private var hasResolvedStartupActiveDevice = false - private var shouldClaimActiveDeviceOnReconnect = false + private val deviceSession = DevicePollingSession() + private val deviceRequestMutex = Mutex() + private val likeMutex = Mutex() + private var catalogSyncPending = true private val _shareEvent = MutableSharedFlow(extraBufferCapacity = 1) val shareEvent: SharedFlow = _shareEvent.asSharedFlow() private val _messageEvent = MutableSharedFlow(extraBufferCapacity = 1) @@ -211,6 +224,7 @@ class PlayerViewModel @Inject constructor( } fun loadLibraryIfNeeded() { + libraryOpened = true loadPlaylistsIfNeeded() loadLibraryArtistsIfNeeded() } @@ -309,7 +323,7 @@ class PlayerViewModel @Inject constructor( val cachedDetail = playlistDetailCache[playlist.id] _uiState.value = _uiState.value.copy( - selectedPlaylist = cachedDetail?.playlist ?: playlist, + selectedPlaylist = playlist, playlistDetail = cachedDetail, isPlaylistDetailLoading = cachedDetail == null, playlistDetailError = null @@ -321,6 +335,7 @@ class PlayerViewModel @Inject constructor( } fun closePlaylistDetail() { + playlistDetailJob?.cancel() _uiState.value = _uiState.value.copy( selectedPlaylist = null, playlistDetail = null, @@ -494,31 +509,32 @@ class PlayerViewModel @Inject constructor( } fun setActiveDevice(deviceId: String) { - if (_uiState.value.offlineState.isOfflineActive) return + if (playerRepository.offlineState.value.isOfflineActive) return + val generation = deviceSession.generation viewModelScope.launch { - playerRepository.setActiveDevice(deviceId) - .onSuccess { devicesState -> - applyConnectedDevicesState(devicesState) - } - .onFailure { error -> + deviceRequestMutex.withLock { + if (generation != deviceSession.generation || playerRepository.offlineState.value.isOfflineActive) return@withLock + deviceSession.invalidate() + val selection = deviceSession.generation + val result = playerRepository.setActiveDevice(deviceId) + if (selection != deviceSession.generation || playerRepository.offlineState.value.isOfflineActive) return@withLock + result.onSuccess { devices -> + applyConnectedDevicesState(devices) + // Fetch the transfer command before publishing this phone's previous queue. + pollConnectedDevices() + }.onFailure { error -> _uiState.value = _uiState.value.copy( connectedDevicesError = error.message ?: "Unable to switch active device" ) } + } } } fun setOfflineModeEnabled(enabled: Boolean) { + deviceSession.invalidate() playerRepository.setOfflineModeEnabled(enabled) - if (enabled) { - _uiState.value = _uiState.value.copy( - connectedDevicesState = null, - connectedDevicesError = null - ) - syncOfflineLibrary() - } else { - shouldClaimActiveDeviceOnReconnect = true - } + _uiState.value = _uiState.value.copy(connectedDevicesState = null, connectedDevicesError = null) } fun setSaveListenedTracksEnabled(enabled: Boolean) { @@ -533,12 +549,11 @@ class PlayerViewModel @Inject constructor( } fun syncOfflineLibrary() { - if (_uiState.value.offlineState.isSyncing) return - viewModelScope.launch { - playerRepository.syncOfflineLibrary() - .onSuccess { - refreshAfterOfflineLibraryChange() - } + if (catalogSyncJob?.isActive == true) return + catalogSyncJob = viewModelScope.launch { + playerRepository.syncOfflineLibrary().onSuccess { + if (_uiState.value.offlineState.isOfflineActive) refreshVisibleContentForOfflineMode() + } } } @@ -628,6 +643,23 @@ class PlayerViewModel @Inject constructor( } } + fun seekToLyricsLine(track: TrackCard, positionMs: Long) { + val state = _uiState.value + if (state.lyricsTrack?.id != track.id) return + + val targetDeviceId = activeRemoteDeviceId() + val playback = if (targetDeviceId == null) playbackController.state.value else state.displayedPlayback() + if (playback.currentTrack?.id != track.id) return + + val endMs = playback.durationMs.takeIf { it > 0L } ?: Long.MAX_VALUE + val targetMs = positionMs.coerceIn(0L, endMs) + if (targetDeviceId == null) { + playbackController.seekToPositionMs(targetMs) + } else { + sendConnectedCommand(targetDeviceId, command = "seek", time = targetMs / 1_000.0) + } + } + fun seekToPlaybackProgress(progress: Float) { activeRemoteDeviceId()?.let { targetDeviceId -> val durationSeconds = _uiState.value.connectedDevicesState @@ -646,41 +678,83 @@ class PlayerViewModel @Inject constructor( playbackController.seekToProgress(progress) } + private val imageCache = object : android.util.LruCache(24 * 1024 * 1024) { + override fun sizeOf(key: String, value: Bitmap): Int = value.allocationByteCount + } + fun loadMediaImage(url: String?) { val imageUrl = url?.takeIf { it.isNotBlank() } ?: return + val key = canonicalMediaImageResource(imageUrl) val state = _uiState.value - - if (state.mediaImages.containsKey(imageUrl) || - state.loadingMediaImageUrls.contains(imageUrl) - ) { - return - } - - val equivalentBitmap = state.mediaImages.findEquivalentMediaImage(imageUrl) - if (equivalentBitmap != null) { - _uiState.value = state.copy( - mediaImages = state.mediaImages + (imageUrl to equivalentBitmap) - ) - return - } - - _uiState.value = state.copy( - loadingMediaImageUrls = state.loadingMediaImageUrls + imageUrl - ) + if (imageCache.get(key) != null || key in state.loadingMediaImageUrls) return + _uiState.value = state.copy(loadingMediaImageUrls = state.loadingMediaImageUrls + key) viewModelScope.launch { - mediaImageLoader.load(imageUrl) - .onSuccess { bitmap -> - val currentState = _uiState.value - _uiState.value = currentState.copy( - mediaImages = currentState.mediaImages + (imageUrl to bitmap) - ) + try { + mediaImageLoader.load(imageUrl).onSuccess { bitmap -> + imageCache.put(key, bitmap) + _uiState.value = _uiState.value.copy(mediaImages = imageCache.snapshot()) } + } finally { + val current = _uiState.value + _uiState.value = current.copy(loadingMediaImageUrls = current.loadingMediaImageUrls - key) + } + } + } - val currentState = _uiState.value - _uiState.value = currentState.copy( - loadingMediaImageUrls = currentState.loadingMediaImageUrls - imageUrl + suspend fun getDownloadedTracks(ids: Set?): List = playerRepository.getDownloadedTracks(ids) + + fun openLyrics(track: TrackCard) = loadLyrics(track, followPlayback = false) + + fun openNowPlayingLyrics(track: TrackCard) = loadLyrics(track, followPlayback = true) + + fun retryLyrics() { + val state = _uiState.value + state.lyricsTrack?.let { loadLyrics(it, state.followPlayingLyrics, retry = true) } + } + + fun closeLyrics() { + lyricsJob?.cancel() + _uiState.value = _uiState.value.copy(lyricsTrack = null, lyricsState = LyricsUiState.Loading, followPlayingLyrics = false) + } + + private fun TrackCard.lyricsKey(): String = + (federation?.contentId ?: preparedContentId)?.let { "content:$it" } ?: "track:$id" + + private fun loadLyrics(track: TrackCard, followPlayback: Boolean, retry: Boolean = false) { + val state = _uiState.value + val key = track.lyricsKey() + if (!retry && state.lyricsTrack?.lyricsKey() == key) { + if (state.followPlayingLyrics != followPlayback || state.lyricsTrack != track) { + _uiState.value = state.copy(lyricsTrack = track, followPlayingLyrics = followPlayback) + } + return + } + + lyricsJob?.cancel() + val cached = lyricsCache.get(key) + val initial = when { + cached != null -> LyricsUiState.Content(cached) + state.offlineState.isOfflineActive -> LyricsUiState.Error("Connect to the server to load lyrics for this track.") + else -> LyricsUiState.Loading + } + _uiState.value = state.copy(lyricsTrack = track, lyricsState = initial, followPlayingLyrics = followPlayback) + if (initial != LyricsUiState.Loading) return + + lyricsJob = viewModelScope.launch { + val result = playerRepository.getLyrics(track) + ensureActive() + if (_uiState.value.lyricsTrack?.lyricsKey() != key) return@launch + val next = result.fold( + onSuccess = { versions -> + if (versions.isNotEmpty()) lyricsCache.put(key, versions) + LyricsUiState.Content(versions) + }, + onFailure = { error -> + LyricsUiState.Error(error.localizedMessage?.takeIf(String::isNotBlank) ?: "Could not load lyrics.") + } ) + _uiState.value = _uiState.value.copy(lyricsState = next) } } @@ -703,8 +777,12 @@ class PlayerViewModel @Inject constructor( fun logout() { if (_uiState.value.isLoggingOut) return + closeLyrics() + lyricsCache.evictAll() viewModelScope.launch { _uiState.value = _uiState.value.copy(isLoggingOut = true) + playbackController.onTrackPlayReported = null + playbackController.clearQueue() authRepository.logout() _uiState.value = _uiState.value.copy( isLoggingOut = false, @@ -713,24 +791,36 @@ class PlayerViewModel @Inject constructor( } } + private fun knownFederatedTrack(id: Long): TrackCard? { + if (id >= 0) return null + val state = _uiState.value + val remote = state.connectedDevicesState?.remotePlaybackState + return state.playlistDetail?.tracks?.firstOrNull { it.id == id } + ?: remote?.track?.takeIf { it.id == id } + ?: remote?.tracks?.firstOrNull { it.id == id } + ?: state.playback.queue.firstOrNull { it.id == id } + } + fun toggleLike(trackId: Long) { val current = _uiState.value.likedTrackIds - val optimistic = if (current.contains(trackId)) current - trackId else current + trackId - _uiState.value = _uiState.value.copy(likedTrackIds = optimistic) - + val desired = trackId !in current + val track = knownFederatedTrack(trackId) + _uiState.value = _uiState.value.copy(likedTrackIds = if (desired) current + trackId else current - trackId) viewModelScope.launch { - playerRepository.toggleLike(trackId) - .onSuccess { liked -> - val updated = if (liked) { - _uiState.value.likedTrackIds + trackId - } else { - _uiState.value.likedTrackIds - trackId + likeMutex.withLock { + playerRepository.toggleLike(trackId, desired, track) + .onSuccess { liked -> + val latest = _uiState.value + _uiState.value = latest.copy(likedTrackIds = if (liked) latest.likedTrackIds + trackId else latest.likedTrackIds - trackId) + playlistDetailCache.remove(-1L) + if (_uiState.value.selectedPlaylist?.id == -1L) loadPlaylistDetail(-1L) } - _uiState.value = _uiState.value.copy(likedTrackIds = updated) - } - .onFailure { - _uiState.value = _uiState.value.copy(likedTrackIds = current) - } + .onFailure { error -> + val latest = _uiState.value + _uiState.value = latest.copy(likedTrackIds = if (desired) latest.likedTrackIds - trackId else latest.likedTrackIds + trackId) + _messageEvent.tryEmit(error.message ?: "Could not change like") + } + } } } @@ -757,9 +847,8 @@ class PlayerViewModel @Inject constructor( fun shareTrack(track: TrackCard) { viewModelScope.launch { playerRepository.shareTrack(track.id, track.title) - .onSuccess { url -> - _shareEvent.tryEmit(url) - } + .onSuccess { url -> _shareEvent.tryEmit(url) } + .onFailure { error -> _messageEvent.tryEmit(error.message ?: "Unable to create share link") } } } @@ -781,56 +870,64 @@ class PlayerViewModel @Inject constructor( } .onFailure { error -> val message = error.message ?: "Unable to download track" - _uiState.value = _uiState.value.copy(offlineDownloadError = message) _messageEvent.tryEmit(message) } } } fun downloadPlaylistForOffline() { - val detail = _uiState.value.playlistDetail ?: return - val playlistId = detail.playlist.id - if (_uiState.value.offlineDownloadingPlaylistIds.contains(playlistId)) return + val state = _uiState.value + val detail = state.playlistDetail ?: return + val id = detail.playlist.id + val tracks = detail.tracks + if (state.isPlaylistDetailLoading || !detail.isMembershipComplete) { + _messageEvent.tryEmit("Reload the full playlist before downloading it") + return + } + if (id in state.preparingDownloadPlaylistIds || tracks.isEmpty() || tracks.all(state::isDownloadedForOffline)) return + if (state.offlineState.isOfflineActive) { + _messageEvent.tryEmit("Downloads need an online connection") + return + } + _uiState.value = state.copy(preparingDownloadPlaylistIds = state.preparingDownloadPlaylistIds + id) + viewModelScope.launch { + try { + playerRepository.downloadTracksForOffline(tracks) + .onSuccess { _messageEvent.tryEmit("Playlist download queued") } + .onFailure { _messageEvent.tryEmit(it.message ?: "Unable to download playlist") } + } finally { + val latest = _uiState.value + _uiState.value = latest.copy(preparingDownloadPlaylistIds = latest.preparingDownloadPlaylistIds - id) + } + } + } + + fun retryFailedDownloads(trackIds: Set) { if (_uiState.value.offlineState.isOfflineActive) { _messageEvent.tryEmit("Downloads need an online connection") return } - - val currentState = _uiState.value - val tracks = detail.tracks.filter { - !currentState.isDownloadedForOffline(it) && !currentState.isDownloadingForOffline(it) - } - if (tracks.isEmpty()) { - _messageEvent.tryEmit("Playlist is already downloaded") - return - } viewModelScope.launch { - playerRepository.downloadTracksForOffline(tracks) - .onSuccess { - _uiState.value = _uiState.value.copy( - offlineDownloadingPlaylistIds = _uiState.value.offlineDownloadingPlaylistIds + playlistId - ) - _messageEvent.tryEmit("Playlist download queued") - } - .onFailure { error -> - val message = error.message ?: "Unable to download playlist" - _uiState.value = _uiState.value.copy(offlineDownloadError = message) - _messageEvent.tryEmit(message) - } + playerRepository.retryFailedDownloads(trackIds) + .onFailure { _messageEvent.tryEmit(it.message ?: "Unable to retry downloads") } } } fun loadPlaylists() { - if (_uiState.value.isPlaylistsLoading) return + playlistsJob?.cancel() _uiState.value = _uiState.value.copy( isPlaylistsLoading = true, playlistsError = null ) - viewModelScope.launch { + playlistsJob = viewModelScope.launch { playerRepository.getPlaylists() .onSuccess { playlists -> - _uiState.value = _uiState.value.copy( + val state = _uiState.value + _uiState.value = state.copy( playlists = playlists, + selectedPlaylist = state.selectedPlaylist?.let { selected -> + playlists.firstOrNull { it.id == selected.id } ?: selected + }, isPlaylistsLoading = false, playlistsError = null ) @@ -850,36 +947,6 @@ class PlayerViewModel @Inject constructor( loadPlaylists() } - fun loadPlaylistPreview(playlist: PlaylistCard) { - if (playlist.isLikesPlaylistPreview()) return - - val state = _uiState.value - if (state.playlistPreviewCoverUrls.containsKey(playlist.id) || - state.loadingPlaylistPreviewIds.contains(playlist.id) - ) { - return - } - - playlistDetailCache[playlist.id]?.let { detail -> - setPlaylistPreviewCoverUrls(playlist.id, detail.previewCoverUrls()) - return - } - - _uiState.value = state.copy( - loadingPlaylistPreviewIds = state.loadingPlaylistPreviewIds + playlist.id - ) - - viewModelScope.launch { - playerRepository.getPlaylistDetail(playlist.id) - .onSuccess { detail -> - playlistDetailCache[playlist.id] = detail - setPlaylistPreviewCoverUrls(playlist.id, detail.previewCoverUrls()) - } - .onFailure { - setPlaylistPreviewCoverUrls(playlist.id, emptyList()) - } - } - } fun clearPlaylistCreateError() { if (_uiState.value.playlistCreateError == null) return @@ -921,7 +988,7 @@ class PlayerViewModel @Inject constructor( return@launch } - playerRepository.addTracksToPlaylist(playlist.id, listOf(trackIdToAdd)) + playerRepository.addTracksToPlaylist(playlist.id, listOf(trackIdToAdd), knownFederatedTrack(trackIdToAdd)) .onSuccess { addPlaylistToState(playlist.copy(trackCount = playlist.trackCount + 1)) playlistDetailCache.remove(playlist.id) @@ -967,8 +1034,6 @@ class PlayerViewModel @Inject constructor( playlistDetailCache.remove(playlist.id) _uiState.value = _uiState.value.copy( playlists = _uiState.value.playlists.filterNot { it.id == playlist.id }, - playlistPreviewCoverUrls = _uiState.value.playlistPreviewCoverUrls - playlist.id, - loadingPlaylistPreviewIds = _uiState.value.loadingPlaylistPreviewIds - playlist.id, selectedPlaylist = null, playlistDetail = null, isPlaylistDetailLoading = false, @@ -989,7 +1054,7 @@ class PlayerViewModel @Inject constructor( fun addTrackToPlaylist(trackId: Long, playlistId: Long) { viewModelScope.launch { - playerRepository.addTracksToPlaylist(playlistId, listOf(trackId)) + playerRepository.addTracksToPlaylist(playlistId, listOf(trackId), knownFederatedTrack(trackId)) .onSuccess { incrementPlaylistTrackCount(playlistId) playlistDetailCache.remove(playlistId) @@ -1021,16 +1086,6 @@ class PlayerViewModel @Inject constructor( ) } - private fun setPlaylistPreviewCoverUrls(playlistId: Long, coverUrls: List) { - val distinctCoverUrls = coverUrls.distinct().take(PLAYLIST_PREVIEW_IMAGE_LIMIT) - val state = _uiState.value - _uiState.value = state.copy( - playlistPreviewCoverUrls = state.playlistPreviewCoverUrls + (playlistId to distinctCoverUrls), - loadingPlaylistPreviewIds = state.loadingPlaylistPreviewIds - playlistId - ) - distinctCoverUrls.forEach(::loadMediaImage) - } - private fun reportListeningHistory( trackId: Long, startedAt: Long, @@ -1057,10 +1112,11 @@ class PlayerViewModel @Inject constructor( private fun loadLikedTrackIds() { viewModelScope.launch { - playerRepository.getLikedTrackIds() - .onSuccess { ids -> + likeMutex.withLock { + playerRepository.getLikedTrackIds().onSuccess { ids -> _uiState.value = _uiState.value.copy(likedTrackIds = ids) } + } } } @@ -1102,17 +1158,18 @@ class PlayerViewModel @Inject constructor( playerRepository.offlineState.collect { offlineState -> val current = _uiState.value val offlineModeChanged = current.offlineState.isOfflineActive != offlineState.isOfflineActive - if (current.offlineState.isOfflineActive && !offlineState.isOfflineActive) { - shouldClaimActiveDeviceOnReconnect = true + if (offlineModeChanged && offlineState.isOfflineActive) { + deviceSession.invalidate() + catalogSyncPending = true } _uiState.value = current.copy( offlineState = offlineState, - connectedDevicesState = if (offlineState.settings.offlineModeEnabled) { + connectedDevicesState = if (offlineState.isOfflineActive) { null } else { current.connectedDevicesState }, - connectedDevicesError = if (offlineState.settings.offlineModeEnabled) { + connectedDevicesError = if (offlineState.isOfflineActive) { null } else { current.connectedDevicesError @@ -1128,156 +1185,111 @@ class PlayerViewModel @Inject constructor( private fun observeOfflineDownloadQueue() { viewModelScope.launch { - var previousActiveTrackIds = playerRepository.offlineDownloadQueueState.value.activeTrackIds - playerRepository.offlineDownloadQueueState.collect { queueState -> - val completedTrackIds = (previousActiveTrackIds - queueState.activeTrackIds) - - queueState.failedTrackIds - val playlistDetail = _uiState.value.playlistDetail - val activePlaylistIds = if (playlistDetail != null && - playlistDetail.tracks.any { it.id in queueState.activeTrackIds } - ) { - setOf(playlistDetail.playlist.id) - } else { - emptySet() - } - + var previous: Set? = null + playerRepository.offlineDownloadQueueState.collect { queue -> + val oldIds = previous + val changed = oldIds != null && oldIds !== queue.cachedTrackIds + val added = if (changed) queue.cachedTrackIds - oldIds.orEmpty() else emptySet() + val removed = if (changed) oldIds.orEmpty() - queue.cachedTrackIds else emptySet() + previous = queue.cachedTrackIds + val state = _uiState.value + val hasDetails = state.playlistDetail != null || state.artistDetail != null || + state.releaseDetail != null || state.searchResults != null || playlistDetailCache.isNotEmpty() || + artistDetailCache.isNotEmpty() || releaseDetailCache.isNotEmpty() + val saved = if (hasDetails && added.isNotEmpty()) { + playerRepository.getDownloadedTracks(added).associateBy { it.id } + } else emptyMap() + if (saved.isNotEmpty() || removed.isNotEmpty()) updateLocalAudio(saved, removed) _uiState.value = _uiState.value.copy( - offlineDownloadedTrackIds = _uiState.value.offlineDownloadedTrackIds + completedTrackIds, - offlineDownloadingTrackIds = queueState.activeTrackIds, - offlineDownloadingPlaylistIds = activePlaylistIds, - offlineDownloadError = queueState.lastError + offlineQueue = queue, + offlineDownloadedTrackIds = queue.cachedTrackIds, + offlineDownloadingTrackIds = queue.activeTrackIds ) - if (completedTrackIds.isNotEmpty()) { - scheduleOfflineDownloadRefresh() - } - previousActiveTrackIds = queueState.activeTrackIds } } } + private fun updateLocalAudio(saved: Map, removed: Set) { + val current = _uiState.value + fun List.updated(): List { + if (none { it.id in saved || it.id in removed }) return this + return map { card -> + val local = saved[card.id] + when { + local != null -> card.copy( + streamUrl = local.streamUrl, localAudioPath = local.localAudioPath, isAudioCached = true + ) + card.id in removed -> card.copy( + streamUrl = if (current.offlineState.isOfflineActive) "" else card.remoteStreamUrl, + localAudioPath = null, isAudioCached = false + ) + else -> card + } + } + } + fun PlaylistDetail.updated() = copy(tracks = tracks.updated()) + fun ReleaseDetail.updated() = copy(tracks = tracks.updated()) + fun ArtistDetail.updated() = copy(topTracks = topTracks.updated(), featuredTracks = featuredTracks.updated()) + playlistDetailCache.replaceAll { _, detail -> detail.updated() } + releaseDetailCache.replaceAll { _, detail -> detail.updated() } + artistDetailCache.replaceAll { _, detail -> detail.updated() } + _uiState.value = current.copy( + playlistDetail = current.playlistDetail?.updated(), + artistDetail = current.artistDetail?.updated(), + releaseDetail = current.releaseDetail?.updated(), + searchResults = current.searchResults?.let { it.copy(tracks = it.tracks.updated()) } + ) + } + private fun startConnectedDevicesPolling() { viewModelScope.launch { while (true) { - pollConnectedDevices() + deviceRequestMutex.withLock { pollConnectedDevices() } delay(CONNECTED_DEVICES_POLL_MS) } } } private suspend fun pollConnectedDevices() { + val offline = playerRepository.offlineState.value + if (offline.settings.offlineModeEnabled) return val state = _uiState.value - if (state.offlineState.settings.offlineModeEnabled) return - val shouldClaimActiveDevice = shouldClaimActiveDeviceOnReconnect || - state.offlineState.isUsingNetworkFallback - val isCurrentDeviceActive = state.connectedDevicesState?.isCurrentDeviceActive == true - - // Android follows the spec: only the active device sends its playback state. - // If current device is active and not controlling a remote Jam as a member, it sends its state. - val playbackState = if (isCurrentDeviceActive && !state.connectedDevicesState.isControllingRemoteJam()) { - state.playback.toConnectedPlaybackState() - } else { - null - } - - playerRepository.pollConnectedDevice( - playbackState = playbackState, - currentJamId = state.connectedDevicesState?.currentJamId - ).onSuccess { (devicesState, commands) -> - val resolvedDevicesState = if (shouldClaimActiveDevice) { - claimCurrentDeviceActive(devicesState) - } else { - resolveStartupActiveDevice(devicesState) + val result = deviceSession.poll( + playback = { + if (offline.isOfflineActive || state.connectedDevicesState?.isCurrentDeviceActive != true || + state.connectedDevicesState.remoteControlTargetId != null + ) null else state.playback.toConnectedPlaybackState() + }, + request = { playback -> + playerRepository.pollConnectedDevice(playback, state.connectedDevicesState?.currentJamId) } - applyConnectedDevicesState( - devicesState = resolvedDevicesState, - pauseOnLostControl = !shouldClaimActiveDevice - ) + ) ?: return + if (playerRepository.offlineState.value.isOfflineActive) return - if (!shouldClaimActiveDevice) { - commands.forEach { command -> - if (shouldHandleConnectedCommand(command)) { - handleConnectedCommand(command) - } - } + result.onSuccess { (devices, commands) -> + applyConnectedDevicesState(devices) + for (command in commands) { + if (shouldHandleConnectedCommand(command)) handleConnectedCommand(command) + } + if (catalogSyncPending) { + catalogSyncPending = false + syncOfflineLibrary() } }.onFailure { error -> + catalogSyncPending = true _uiState.value = _uiState.value.copy( + connectedDevicesState = null, connectedDevicesError = error.message ?: "Unable to poll connected devices" ) } } - private suspend fun resolveStartupActiveDevice(devicesState: ConnectedDevicesState): ConnectedDevicesState { - if (hasResolvedStartupActiveDevice) return devicesState - hasResolvedStartupActiveDevice = true - if (!devicesState.shouldCurrentDeviceBecomeActiveOnStartup()) return devicesState - - return playerRepository.setActiveDevice(devicesState.deviceId) - .onFailure { error -> - _uiState.value = _uiState.value.copy( - connectedDevicesError = error.message ?: "Unable to switch active device" - ) - } - .getOrElse { devicesState } - } - - private suspend fun claimCurrentDeviceActive(devicesState: ConnectedDevicesState): ConnectedDevicesState { - val activeDevicesState = if (devicesState.isCurrentDeviceActive) { - devicesState - } else { - playerRepository.setActiveDevice(devicesState.deviceId) - .onFailure { error -> - _uiState.value = _uiState.value.copy( - connectedDevicesError = error.message ?: "Unable to switch active device" - ) - } - .getOrElse { return devicesState } - } - - val (syncedDevicesState, didSync) = pushLocalPlaybackStateAfterReconnect(activeDevicesState) - if (didSync) { - shouldClaimActiveDeviceOnReconnect = false - } - return syncedDevicesState - } - - private suspend fun pushLocalPlaybackStateAfterReconnect( - devicesState: ConnectedDevicesState - ): Pair { - val playbackState = _uiState.value.playback.toConnectedPlaybackState() - ?: return devicesState to true - - return playerRepository.pollConnectedDevice( - playbackState = playbackState, - currentJamId = devicesState.currentJamId - ) - .onFailure { error -> - _uiState.value = _uiState.value.copy( - connectedDevicesError = error.message ?: "Unable to sync playback state" - ) - } - .fold( - onSuccess = { (updatedDevicesState, _) -> updatedDevicesState to true }, - onFailure = { devicesState to false } - ) - } - - private fun applyConnectedDevicesState( - devicesState: ConnectedDevicesState, - pauseOnLostControl: Boolean = true - ) { - val becameInactive = wasCurrentDeviceActive && !devicesState.isCurrentDeviceActive - val isControllingRemoteJam = devicesState.isControllingRemoteJam() - val startedControllingRemoteJam = !wasControllingRemoteJam && isControllingRemoteJam - _uiState.value = _uiState.value.copy( - connectedDevicesState = devicesState, - connectedDevicesError = null - ) - wasCurrentDeviceActive = devicesState.isCurrentDeviceActive - wasControllingRemoteJam = isControllingRemoteJam - if (pauseOnLostControl && - (becameInactive || startedControllingRemoteJam) && - _uiState.value.playback.currentTrack != null + private fun applyConnectedDevicesState(devicesState: ConnectedDevicesState) { + if (playerRepository.offlineState.value.isOfflineActive) return + val state = _uiState.value + _uiState.value = state.copy(connectedDevicesState = devicesState, connectedDevicesError = null) + if (devicesState.remoteControlTargetId != null && state.playback.currentTrack != null && + (state.connectedDevicesState?.remoteControlTargetId == null || state.playback.isPlaying || state.playback.isBuffering) ) { playbackController.pause() } @@ -1353,14 +1365,8 @@ class PlayerViewModel @Inject constructor( } private fun activeRemoteDeviceId(): String? { - if (_uiState.value.offlineState.isOfflineActive) return null - if (shouldClaimActiveDeviceOnReconnect) return null - val devicesState = _uiState.value.connectedDevicesState ?: return null - if (devicesState.isControllingRemoteJam()) { - return devicesState.activeDeviceId ?: devicesState.deviceId - } - val activeDeviceId = devicesState.activeDeviceId ?: return null - return activeDeviceId.takeIf { it != devicesState.deviceId } + val state = _uiState.value + return if (state.offlineState.isOfflineActive) null else state.connectedDevicesState?.remoteControlTargetId } private fun playbackOptionsForActiveTarget(): Pair { @@ -1403,7 +1409,8 @@ class PlayerViewModel @Inject constructor( } private fun loadGlobalArtists(page: Int, append: Boolean) { - viewModelScope.launch { + globalArtistsJob?.cancel() + globalArtistsJob = viewModelScope.launch { val state = _uiState.value _uiState.value = if (append) { state.copy( @@ -1445,7 +1452,8 @@ class PlayerViewModel @Inject constructor( } private fun loadLibraryArtists(page: Int, append: Boolean) { - viewModelScope.launch { + libraryArtistsJob?.cancel() + libraryArtistsJob = viewModelScope.launch { val state = _uiState.value _uiState.value = if (append) { state.copy( @@ -1589,11 +1597,8 @@ class PlayerViewModel @Inject constructor( playerRepository.getReleaseDetail(releaseId) .onSuccess { detail -> val preferredRelease = _uiState.value.selectedRelease - val displayDetail = if (preferredRelease != null) { - detail.withPreferredReleaseArtwork(preferredRelease) - } else { - detail - } + if (preferredRelease?.id != releaseId) return@onSuccess + val displayDetail = detail.withPreferredReleaseArtwork(preferredRelease) releaseDetailCache[releaseId] = displayDetail _uiState.value = _uiState.value.copy( selectedRelease = displayDetail.release, @@ -1603,6 +1608,7 @@ class PlayerViewModel @Inject constructor( ) } .onFailure { error -> + if (_uiState.value.selectedRelease?.id != releaseId) return@onFailure _uiState.value = _uiState.value.copy( isReleaseDetailLoading = false, releaseDetailError = error.message ?: "Unable to load release" @@ -1612,7 +1618,8 @@ class PlayerViewModel @Inject constructor( } private fun loadPlaylistDetail(playlistId: Long) { - viewModelScope.launch { + playlistDetailJob?.cancel() + playlistDetailJob = viewModelScope.launch { _uiState.value = _uiState.value.copy( isPlaylistDetailLoading = true, playlistDetailError = null @@ -1620,16 +1627,17 @@ class PlayerViewModel @Inject constructor( playerRepository.getPlaylistDetail(playlistId) .onSuccess { detail -> - playlistDetailCache[playlistId] = detail + if (detail.isMembershipComplete) playlistDetailCache[playlistId] = detail + else playlistDetailCache.remove(playlistId) + if (_uiState.value.selectedPlaylist?.id != playlistId) return@onSuccess _uiState.value = _uiState.value.copy( - selectedPlaylist = detail.playlist, playlistDetail = detail, isPlaylistDetailLoading = false, playlistDetailError = null ) - setPlaylistPreviewCoverUrls(playlistId, detail.previewCoverUrls()) } .onFailure { error -> + if (_uiState.value.selectedPlaylist?.id != playlistId) return@onFailure _uiState.value = _uiState.value.copy( isPlaylistDetailLoading = false, playlistDetailError = error.message ?: "Unable to load playlist" @@ -1645,45 +1653,22 @@ class PlayerViewModel @Inject constructor( } private fun refreshVisibleContentForOfflineMode() { - offlineModeRefreshJob?.cancel() - offlineModeRefreshJob = viewModelScope.launch { - val state = _uiState.value - when { - state.selectedPlaylist != null -> { - loadPlaylistDetail(state.selectedPlaylist.id) - } - state.selectedRelease != null -> { - loadReleaseDetail(state.selectedRelease.id) - } - state.selectedArtist != null -> { - loadArtistDetail(state.selectedArtist.id) - } - state.searchQuery.isNotBlank() && state.searchResults != null -> { - searchJob?.cancel() - search(state.searchQuery) - } - state.playlists.isNotEmpty() -> { - loadPlaylists() - } - } + val state = _uiState.value + loadGlobalArtists(page = 1, append = false) + if (libraryOpened) { + loadLibraryArtists(page = 1, append = false) + loadPlaylists() } - } - - private fun scheduleOfflineDownloadRefresh() { - offlineDownloadRefreshJob?.cancel() - offlineDownloadRefreshJob = viewModelScope.launch { - delay(350L) - refreshAfterOfflineLibraryChange() + when { + state.selectedPlaylist != null -> loadPlaylistDetail(state.selectedPlaylist.id) + state.selectedRelease != null -> loadReleaseDetail(state.selectedRelease.id) + state.selectedArtist != null -> loadArtistDetail(state.selectedArtist.id) + state.searchQuery.isNotBlank() -> retrySearch() } } private fun refreshAfterOfflineLibraryChange() { clearModeSensitiveCaches() - _uiState.value = _uiState.value.copy( - playlists = emptyList(), - playlistPreviewCoverUrls = emptyMap(), - loadingPlaylistPreviewIds = emptySet() - ) loadLikedTrackIds() if (_uiState.value.selectedPlaylist != null) { _uiState.value.selectedPlaylist?.id?.let(::loadPlaylistDetail) @@ -1722,21 +1707,6 @@ private fun AudioPlaybackState.toConnectedPlaybackState(): ConnectedPlaybackStat ) } -private fun ConnectedDevicesState.isControllingRemoteJam(): Boolean { - val currentJam = jams.firstOrNull { it.id == currentJamId } - ?: jams.firstOrNull { it.isActive } - return currentJam != null && currentJam.isMember && !currentJam.isOwner -} - -private fun ConnectedDevicesState.shouldCurrentDeviceBecomeActiveOnStartup(): Boolean { - if (isCurrentDeviceActive || isControllingRemoteJam()) return false - return remotePlaybackState?.isActivelyPlaying() != true -} - -private fun ConnectedPlaybackState.isActivelyPlaying(): Boolean { - return !paused && (track != null || tracks.isNotEmpty()) -} - private fun PlaylistCard.isLikesPlaylistPreview(): Boolean { return id == -1L || kind.equals("likes", ignoreCase = true) } @@ -1745,12 +1715,6 @@ private fun PlaylistCard.canDeleteUserPlaylist(): Boolean { return isOwn && !isLikesPlaylistPreview() } -private fun PlaylistDetail.previewCoverUrls(): List { - return tracks.mapNotNull { track -> - track.coverUrl?.takeIf { it.isNotBlank() } - }.take(PLAYLIST_PREVIEW_IMAGE_LIMIT) -} - private fun SearchResults.withArtistCards(artistCards: Map): SearchResults { if (artistCards.isEmpty()) return this return copy( @@ -1760,7 +1724,6 @@ private fun SearchResults.withArtistCards(artistCards: Map): S } private const val ANDROID_CONNECTED_VOLUME = 1.0 -private const val PLAYLIST_PREVIEW_IMAGE_LIMIT = 4 private fun String.nextPlaybackRepeatMode(): String { return when (lowercase()) { @@ -1794,13 +1757,6 @@ private fun ReleaseDetail.withPreferredReleaseArtwork(preferred: ReleaseCard): R ) } -private fun Map.findEquivalentMediaImage(url: String): Bitmap? { - val requestedResource = canonicalMediaImageResource(url) - return entries.firstOrNull { (cachedUrl, _) -> - canonicalMediaImageResource(cachedUrl) == requestedResource - }?.value -} - private fun sameMediaImageResource(first: String?, second: String?): Boolean { if (first.isNullOrBlank() || second.isNullOrBlank()) return false return canonicalMediaImageResource(first) == canonicalMediaImageResource(second) diff --git a/app/src/main/java/cy/hexor/furumi/ui/theme/Color.kt b/app/src/main/java/cy/hexor/furumi/ui/theme/Color.kt index 00f6a49..62d5817 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/theme/Color.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/theme/Color.kt @@ -2,15 +2,15 @@ package cy.hexor.furumi.ui.theme import androidx.compose.ui.graphics.Color -val FurumiBlack = Color(0xFF080A0E) -val FurumiInk = Color(0xFF111019) -val FurumiSurface = Color(0xFF1A1524) -val FurumiSurfaceHigh = Color(0xFF2A2036) -val FurumiLine = Color(0xFF4A385D) -val FurumiText = Color(0xFFFFF7FB) -val FurumiTextMuted = Color(0xFFC9B8D6) -val FurumiNeonPink = Color(0xFFFF3EA5) -val FurumiNeonPinkPressed = Color(0xFFE12A8E) -val FurumiElectricCyan = Color(0xFF37F3FF) -val FurumiNeonViolet = Color(0xFFA855F7) -val FurumiHotOrange = Color(0xFFFF7A3D) +val FurumiBlack = Color(0xFF121212) +val FurumiInk = Color(0xFF181818) +val FurumiSurface = Color(0xFF181818) +val FurumiSurfaceHigh = Color(0xFF232323) +val FurumiLine = Color(0xFF383838) +val FurumiText = Color.White +val FurumiTextMuted = Color(0xFFB3B3B3) +val FurumiAccent = Color(0xFF1DB954) +val FurumiAccentPressed = Color(0xFF159443) +val FurumiAccentBright = Color(0xFF1ED760) +val FurumiAccentMuted = Color(0xFF36774C) +val FurumiError = Color(0xFFFF8B83) diff --git a/app/src/main/java/cy/hexor/furumi/ui/theme/Theme.kt b/app/src/main/java/cy/hexor/furumi/ui/theme/Theme.kt index 7164204..a37ed51 100644 --- a/app/src/main/java/cy/hexor/furumi/ui/theme/Theme.kt +++ b/app/src/main/java/cy/hexor/furumi/ui/theme/Theme.kt @@ -1,42 +1,53 @@ package cy.hexor.furumi.ui.theme +import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color private val DarkColorScheme = darkColorScheme( - primary = FurumiNeonPink, + primary = FurumiAccent, onPrimary = FurumiBlack, - primaryContainer = FurumiNeonPinkPressed, + primaryContainer = FurumiAccentPressed, onPrimaryContainer = FurumiBlack, - secondary = FurumiElectricCyan, + secondary = FurumiAccentBright, onSecondary = FurumiBlack, - tertiary = FurumiNeonViolet, + secondaryContainer = FurumiSurfaceHigh, + onSecondaryContainer = FurumiText, + tertiary = FurumiTextMuted, + onTertiary = FurumiBlack, background = FurumiBlack, onBackground = FurumiText, - surface = FurumiInk, + surface = FurumiSurface, onSurface = FurumiText, - surfaceVariant = FurumiSurface, + surfaceVariant = FurumiSurfaceHigh, onSurfaceVariant = FurumiTextMuted, - outline = FurumiLine, - error = FurumiHotOrange, - onError = Color.White + surfaceContainer = FurumiSurfaceHigh, + surfaceContainerHigh = FurumiSurfaceHigh, + surfaceContainerHighest = FurumiLine, + outline = FurumiTextMuted, + outlineVariant = FurumiLine, + error = FurumiError, + onError = FurumiBlack ) private val LightColorScheme = lightColorScheme( - primary = Color(0xFFB90068), + primary = Color(0xFF006C30), onPrimary = Color.White, - secondary = Color(0xFF006B73), - tertiary = Color(0xFF6D27B8), - background = Color(0xFFFFF7FB), - onBackground = Color(0xFF17101F), + primaryContainer = Color(0xFFA0F4B5), + onPrimaryContainer = Color(0xFF00210B), + secondary = Color(0xFF41654A), + tertiary = Color(0xFF4D6252), + background = Color(0xFFFAFAFA), + onBackground = FurumiBlack, surface = Color.White, - onSurface = Color(0xFF17101F), - surfaceVariant = Color(0xFFF2E6F6), - onSurfaceVariant = Color(0xFF67536F), - outline = Color(0xFFD8BFE2) + onSurface = FurumiBlack, + surfaceVariant = Color(0xFFE9ECE9), + onSurfaceVariant = Color(0xFF444B45), + outline = Color(0xFF727972) ) @Composable @@ -44,11 +55,10 @@ fun FurumiTheme( darkTheme: Boolean = true, content: @Composable () -> Unit ) { - val colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme - MaterialTheme( - colorScheme = colorScheme, - typography = Typography, - content = content - ) + colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme, + typography = Typography + ) { + CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onBackground, content = content) + } } diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index d571627..28b9ebf 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -1,5 +1,8 @@ - diff --git a/app/src/test/java/cy/hexor/furumi/data/local/OfflineFileDownloaderTest.kt b/app/src/test/java/cy/hexor/furumi/data/local/OfflineFileDownloaderTest.kt new file mode 100644 index 0000000..f792bfe --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/data/local/OfflineFileDownloaderTest.kt @@ -0,0 +1,122 @@ +package cy.hexor.furumi.data.local + +import java.io.File +import java.io.IOException +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.Response +import okhttp3.ResponseBody +import okio.Buffer +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class OfflineFileDownloaderTest { + @get:Rule val folder = TemporaryFolder() + + @Test fun interruptedTransferResumesAtPersistedOffset() = runBlocking { + val target = File(folder.root, "song") + val requests = mutableListOf() + val client = client(requests) { request, attempt -> + if (attempt == 1) response(request, 200, "abc", length = 6) + else response(request, 206, "def", range = "bytes 3-5/6") + } + val downloader = OfflineFileDownloader(client) + assertTrue(runCatching { downloader.download(URL, target, true) }.exceptionOrNull() is IOException) + assertFalse(target.exists()) + // A new worker has only the on-disk partial and its strong validator. + val progress = mutableListOf>() + assertEquals(6L, OfflineFileDownloader(client).download(URL, target, true) { received, total -> + progress.add(received to total) + }) + assertEquals(listOf(3L to 6L, 6L to 6L), progress) + assertEquals("bytes=3-", requests[1].header("Range")) + assertEquals("\"v1\"", requests[1].header("If-Range")) + assertEquals("abcdef", target.readText()) + assertFalse(File(folder.root, "song.tmp").exists()) + } + + @Test fun serverErrorsKeepFailedAudioOutOfTheCacheAndDistinguishRetryableResponses() = runBlocking { + val file = File(folder.root, "song") + for ((status, retryable) in listOf(400 to false, 404 to false, 429 to true, 503 to true)) { + val downloader = OfflineFileDownloader(client(mutableListOf()) { req, _ -> + response(req, status, "error") + }) + val failure = runCatching { downloader.download(URL, file, true) }.exceptionOrNull() + assertTrue(failure is OfflineHttpException) + assertEquals(retryable, (failure as OfflineHttpException).retryable) + assertTrue(failure.message.orEmpty().contains("HTTP $status")) + assertFalse(file.exists()) + } + } + + @Test fun changedEtagEvenOn206ForcesFreshRequest() = verifyRestart(206, "bytes 3-5/6", "\"v2\"") + + @Test fun wrongStartForcesFreshRequest() = verifyRestart(206, "bytes 2-5/6", "\"v1\"") + + @Test fun unsatisfiableRangeForcesFreshRequest() = verifyRestart(416, "bytes */2", "\"v1\"") + + private fun verifyRestart(status: Int, range: String, validator: String) = runBlocking { + val target = File(folder.root, "song") + File(folder.root, "song.tmp").writeText("old") + File(folder.root, "song.etag").writeText("\"v1\"") + val requests = mutableListOf() + val client = client(requests) { request, attempt -> + if (attempt == 1) response(request, status, "bad", range, validator) + else response(request, 200, "new contents", etag = "\"v2\"") + } + OfflineFileDownloader(client).download(URL, target, true) + assertEquals("new contents", target.readText()) + assertEquals("bytes=3-", requests[0].header("Range")) + assertNull(requests[1].header("Range")) + } + + @Test fun storageLimitStopsKnownAndChunkedAudioBeforeCommittingIt() = runBlocking { + for (declaredLength in listOf(10L, -1L)) { + val target = File(folder.root, "song") + val downloader = OfflineFileDownloader(client(mutableListOf()) { req, _ -> + response(req, 200, "0123456789", length = declaredLength) + }) + val error = runCatching { downloader.download(URL, target, true, maxBytes = 8L) }.exceptionOrNull() + assertTrue(error is OfflineStorageLimitException) + assertFalse(File(folder.root, "song.tmp").exists()) + assertFalse(File(folder.root, "song.etag").exists()) + assertFalse(target.exists()) + assertEquals(10L, downloader.download(URL, target, true, maxBytes = 10L)) + assertTrue(target.delete()) + } + } + + @Test fun fullResponseToRangeReplacesPartialInOneRequest() = runBlocking { + val target = File(folder.root, "song") + File(folder.root, "song.tmp").writeText("old") + File(folder.root, "song.etag").writeText("\"v1\"") + val requests = mutableListOf() + val client = client(requests) { request, _ -> response(request, 200, "replacement", etag = "\"v2\"") } + OfflineFileDownloader(client).download(URL, target, true) + assertEquals("replacement", target.readText()) + assertEquals(1, requests.size) + } + + private fun client(requests: MutableList, handler: (Request, Int) -> Response): OkHttpClient = + OkHttpClient.Builder().addInterceptor { chain -> + requests.add(chain.request()) + handler(chain.request(), requests.size) + }.build() + + private fun response(request: Request, status: Int, text: String, range: String? = null, + etag: String = "\"v1\"", length: Long = text.length.toLong()): Response = + Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(status).message("test") + .header("ETag", etag).apply { if (range != null) header("Content-Range", range) } + .body(object : ResponseBody() { + private val buffer = Buffer().writeUtf8(text) + override fun source() = buffer + override fun contentType() = null + override fun contentLength() = length + }).build() + + private companion object { const val URL = "https://example.test/audio" } +} diff --git a/app/src/test/java/cy/hexor/furumi/data/remote/model/ConnectedTrackWireTest.kt b/app/src/test/java/cy/hexor/furumi/data/remote/model/ConnectedTrackWireTest.kt new file mode 100644 index 0000000..0e52637 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/data/remote/model/ConnectedTrackWireTest.kt @@ -0,0 +1,47 @@ +package cy.hexor.furumi.data.remote.model + +import cy.hexor.furumi.di.StorageModule +import cy.hexor.furumi.domain.model.FederatedTrackSource +import cy.hexor.furumi.domain.model.TrackCard +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ConnectedTrackWireTest { + private val adapter = StorageModule.provideMoshi().adapter(TrackItemResponse::class.java) + + @Test + fun federatedQueueCanBePreparedByTheWebPlayerWithoutPhonePaths() { + val source = FederatedTrackSource("content-hash", "peer", "item") + val track = TrackCard( + id = -50, title = "Remote", trackNumber = 3, discNumber = 1, + durationSeconds = 215, artists = listOf("Artist"), releaseTitle = "Album", + coverUrl = "file:///cache/cover", streamUrl = "furumi-fed://track/private", + federation = source + ) + val json = adapter.toJson(track.toTrackItemResponse()) + assertTrue(json.contains("\"id\":\"fed:content-hash\"")) + assertFalse(json.contains("furumi-fed:") || json.contains("file:") || json.contains("-50")) + val result = adapter.fromJson(json)!! + assertTrue(result.federationPending == true) + assertEquals("Remote", result.federationTrack?.metadata?.title) + assertEquals("item", result.federationTrack?.availability?.federation?.single()?.itemId) + } + + @Test + fun numericIdsRemainJsonNumbersAndRetainIntegerPrecision() { + val id = 9_007_199_254_740_993L + val value = adapter.fromJson("""{"id":$id,"title":"Local"}""")!! + assertEquals(id, value.id) + assertTrue(adapter.toJson(value).contains("\"id\":$id")) + } + + @Test + fun preparedWebTrackWithoutSourceRetainsItsContentIdAndStream() { + val value = adapter.fromJson("""{"id":"fed:old","title":"Remote","stream_url":"/prepared/old"}""")!! + val track = value.toConnectedTrack("https://server", "account") + assertEquals("https://server/prepared/old", track.streamUrl) + assertEquals("fed:old", track.toTrackItemResponse().wireId) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/data/remote/model/PlayerResponseContractTest.kt b/app/src/test/java/cy/hexor/furumi/data/remote/model/PlayerResponseContractTest.kt new file mode 100644 index 0000000..c86e5d0 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/data/remote/model/PlayerResponseContractTest.kt @@ -0,0 +1,77 @@ +package cy.hexor.furumi.data.remote.model + +import cy.hexor.furumi.di.StorageModule +import org.junit.Assert.* +import org.junit.Test + +class PlayerResponseContractTest { + private val moshi = StorageModule.provideMoshi() + private val server = "https://music.example" + + @Test fun historyAcceptsFederatedSnapshotAndLocalEntriesTogether() { + val page = moshi.adapter(PlayHistoryPageResponse::class.java).fromJson( + """{"total":2,"page":1,"per_page":20,"items":[ + {"id":"listen:one","track_id":null,"track_title":"Remote","played_at":"2026-05-02","completed":true, + "track":{"id":"history:hash","content_id":"hash","duration_seconds":212.6,"artists":[{"id":null,"name":"Guest"}]}}, + {"id":"listen:two","track_id":7,"track_title":"Local","played_at":"2026-05-03","completed":false, + "track":{"id":7,"title":"Local","artists":[]}}]}""" + )!!.toDomain() + assertEquals(listOf("listen:one", "listen:two"), page.items.map { it.id }) + assertNull(page.items.first().trackId) + assertEquals(listOf("Guest"), page.items.first().artists) + assertEquals(7L, page.items.last().trackId) + val remote = requireNotNull(page.items.first().lyricsTrack) + assertEquals(federationTrackId("hash"), remote.id) + assertEquals("hash", remote.preparedContentId) + assertEquals(212, remote.durationSeconds) + assertEquals(7L, page.items.last().lyricsTrack?.id) + } + + @Test fun federatedLibraryMutationsUseContentIdentityAndPlayableSource() { + val track = cy.hexor.furumi.domain.model.TrackCard( + id = federationTrackId("content-id"), title = "Remote", trackNumber = 2, discNumber = 1, + durationSeconds = 120, artists = listOf("Artist"), releaseTitle = "Album", + coverUrl = null, streamUrl = "file:///private/song", + federation = cy.hexor.furumi.domain.model.FederatedTrackSource("content-id", "owner", "item") + ) + val adapter = moshi.adapter(ContentTrackMutation::class.java) + val json = adapter.toJson(track.contentMutation(playlistId = 42)) + assertTrue(json.contains("\"content_id\":\"content-id\"")) + assertTrue(json.contains("\"playlist_id\":42")) + assertTrue(json.contains("\"item_id\":\"item\"")) + assertTrue(json.contains("\"duration_seconds\":120,")) + assertFalse(json.contains("file:")) + assertFalse(json.contains(track.id.toString())) + assertEquals(false, adapter.fromJson(adapter.toJson(track.contentMutation(liked = false)))!!.liked) + } + + @Test fun albumOnlySearchHasNavigableRelease() { + val result = moshi.adapter(SearchResponse::class.java).fromJson( + """{"releases":[{"id":17,"title":"Blue","cover_url":"/cover/1"}]}""" + )!!.toDomain(server) + assertTrue(result.tracks.isEmpty()) + assertEquals(17L, result.releases.single().id) + assertEquals("$server/cover/1", result.releases.single().coverUrl) + } + + @Test fun flatPlaylistDetailUsesPlaylistArtworkForUploadsAndCollages() { + val adapter = moshi.adapter(PlaylistDetailResponse::class.java) + fun detail(artwork: String) = adapter.fromJson( + """{"id":2,"title":"Mix",$artwork,"tracks":[{"id":8,"title":"Intro","cover_url":"/track-art"}]}""" + )!!.toDomain(server) + + val uploaded = detail(""""cover_url":"/api/player/playlists/2/cover?hash=aa"""") + assertEquals(listOf("$server/api/player/playlists/2/cover?hash=aa"), uploaded.playlist.coverUrls) + assertEquals("$server/track-art", uploaded.tracks.single().coverUrl) + val collage = detail(""""cover_url":"/c2","cover_urls":["/c2","https://peer.example/c1"]""") + assertEquals(listOf("$server/c2", "https://peer.example/c1"), collage.playlist.coverUrls) + } + + @Test fun playlistPreviewUsesListArtworkAndSingleCoverFallback() { + val adapter = moshi.adapter(PlaylistCardResponse::class.java) + fun urls(artwork: String) = adapter.fromJson("""{"id":2,"title":"Mix",$artwork}""")!!.toDomain(server).coverUrls + assertEquals(listOf("$server/c1", "$server/c2"), + urls(""""cover_urls":["/c1","/c2"],"cover_url":"/c1"""")) + assertEquals(listOf("$server/c1"), urls(""""cover_url":"/c1"""")) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponseTest.kt b/app/src/test/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponseTest.kt new file mode 100644 index 0000000..b9068d1 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/data/remote/model/TrackLyricsResponseTest.kt @@ -0,0 +1,45 @@ +package cy.hexor.furumi.data.remote.model + +import cy.hexor.furumi.di.StorageModule +import cy.hexor.furumi.domain.model.LyricsLine +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class TrackLyricsResponseTest { + private val adapter = StorageModule.provideMoshi().adapter(TrackLyricsResponse::class.java) + + @Test + fun timedVersionsLeadAndRepeatedTimestampsUseTheFileOffset() { + val result = adapter.fromJson( + """{"content_id":null,"versions":[ + {"id":"translation","label":"Translation","language":"ru","plain_text":"Текст"}, + {"id":"original","label":"Original","source":"manual","synced_lrc":"[ar:Artist]\n[00:02.50][01:03]Chorus\n[00:00.12]Intro\n[00:03.0005]\n[00:60]invalid\n[1441:00]invalid\n[offset:-500]"} + ]}""" + )!!.toDomain() + assertEquals(listOf("original", "translation"), result.map { it.id }) + assertEquals( + listOf(LyricsLine(0, "Intro"), LyricsLine(2000, "Chorus"), LyricsLine(2501, ""), LyricsLine(62500, "Chorus")), + result.first().lines + ) + assertEquals("manual", result.first().source) + assertEquals("ru", result.last().language) + assertEquals("Текст", result.last().plainText) + } + + @Test + fun unusableTimingFallsBackToPlainTextAndInstrumentalRemainsDistinctFromMissing() { + val result = adapter.fromJson( + """{"versions":[ + {"id":"text","plain_text":"First line\nSecond line","synced_lrc":"[xx:ii]bad timing"}, + {"id":"instrumental","instrumental":true}, + {"id":"empty","plain_text":"\n","synced_lrc":"[ar:Band]\n[00:01]"} + ]}""" + )!!.toDomain() + assertEquals(listOf("text", "instrumental"), result.map { it.id }) + assertEquals("First line\nSecond line", result.first().plainText) + assertTrue(result.first().lines.isEmpty()) + assertTrue(result.last().instrumental) + assertTrue(adapter.fromJson("""{"versions":[]}""")!!.toDomain().isEmpty()) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/domain/model/OfflineStorageLimitTest.kt b/app/src/test/java/cy/hexor/furumi/domain/model/OfflineStorageLimitTest.kt new file mode 100644 index 0000000..0eaa9c6 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/domain/model/OfflineStorageLimitTest.kt @@ -0,0 +1,36 @@ +package cy.hexor.furumi.domain.model + +import org.junit.Assert.assertEquals +import org.junit.Test + +class OfflineStorageLimitTest { + private val gib = OfflineStorageLimit.GIB + + @Test + fun legacyAndInvalidLimitsAreClampedWithoutChangingValidPreferences() { + assertEquals(gib, OfflineStorageLimit.clamp(512 * 1024L * 1024L)) + assertEquals(gib, OfflineStorageLimit.clamp(Long.MIN_VALUE)) + assertEquals(512 * gib, OfflineStorageLimit.clamp(Long.MAX_VALUE)) + for (previous in listOf(gib, 2 * gib, 5 * gib, 10 * gib, 512 * gib)) { + assertEquals(previous, OfflineStorageLimit.clamp(previous)) + } + } + + @Test + fun everyDoublingOccupiesTheSameSliderDistance() { + for (octave in 0..9) { + val bytes = (1L shl octave) * gib + assertEquals(octave / 9f, OfflineStorageLimit.position(bytes), 0.00001f) + assertEquals(bytes, OfflineStorageLimit.bytesAt(octave / 9f)) + } + } + + @Test + fun allWholeGigabytesCanBeSelectedAndRestored() { + for (size in 1..512) { + assertEquals(size * gib, OfflineStorageLimit.bytesAt(OfflineStorageLimit.position(size * gib))) + } + assertEquals(gib, OfflineStorageLimit.bytesAt(-1f)) + assertEquals(512 * gib, OfflineStorageLimit.bytesAt(2f)) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/domain/model/OfflineTransferProgressTest.kt b/app/src/test/java/cy/hexor/furumi/domain/model/OfflineTransferProgressTest.kt new file mode 100644 index 0000000..79761a3 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/domain/model/OfflineTransferProgressTest.kt @@ -0,0 +1,28 @@ +package cy.hexor.furumi.domain.model + +import org.junit.Assert.assertEquals +import org.junit.Test + +class OfflineTransferProgressTest { + @Test fun reportsStageChangesImmediatelyAndLimitsByteTicks() { + var time = 0L + val updates = mutableListOf() + val reporter = OfflineProgressReporter(42L, { updates.add(it) }, { time }) + reporter.update(OfflineTransferStage.PREPARING) + reporter.update(OfflineTransferStage.FETCHING, 0, 60) + time = 400 + reporter.update(OfflineTransferStage.FETCHING, 25, 60) + time = 1000 + reporter.update(OfflineTransferStage.FETCHING, 50, 60) + reporter.update(OfflineTransferStage.FETCHING, 60, 60) + reporter.update(OfflineTransferStage.FETCHING, 60, 60) + reporter.update(OfflineTransferStage.DOWNLOADING, 524288, null) + reporter.update(OfflineTransferStage.DOWNLOADING, 524288, 1048576) + assertEquals(listOf( + "Finding a remote source", "Receiving on server · 0 B / 60 B", + "Receiving on server · 50 B / 60 B", "Receiving on server · 60 B / 60 B", + "Saving to phone · 512 KiB", "Saving to phone · 512 KiB / 1 MiB" + ), updates.map { it.displayText() }) + assertEquals(setOf(42L), updates.map { it.trackId }.toSet()) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/ui/player/DevicePollingSessionTest.kt b/app/src/test/java/cy/hexor/furumi/ui/player/DevicePollingSessionTest.kt new file mode 100644 index 0000000..598727e --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/ui/player/DevicePollingSessionTest.kt @@ -0,0 +1,83 @@ +package cy.hexor.furumi.ui.player + +import cy.hexor.furumi.domain.model.ConnectedCommand +import cy.hexor.furumi.domain.model.ConnectedDevicesState +import cy.hexor.furumi.domain.model.ConnectedPlaybackState +import cy.hexor.furumi.domain.model.TrackCard +import cy.hexor.furumi.playback.AudioPlaybackState +import java.io.IOException +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class DevicePollingSessionTest { + private fun playback(id: Long, paused: Boolean): ConnectedPlaybackState { + val track = TrackCard( + id = id, title = "Track $id", trackNumber = null, discNumber = null, + durationSeconds = 100, artists = emptyList(), releaseTitle = null, coverUrl = null, + streamUrl = "/stream/$id" + ) + return ConnectedPlaybackState(track, listOf(track), 0, 37.5, 100.0, paused, false, "off", 1.0) + } + + private fun devices(owner: String, remote: ConnectedPlaybackState? = null) = ConnectedDevicesState( + deviceId = "phone", activeDeviceId = owner, devices = emptyList(), jams = emptyList(), + currentJamId = null, remotePlaybackState = remote + ) + + @Test + fun reconnectLeavesTheBrowserQueueAndPositionAloneWhetherPlayingOrPaused() = runBlocking { + val local = playback(10, paused = false) + for (paused in listOf(false, true)) { + val browser = playback(25, paused) + val session = DevicePollingSession() + val sent = mutableListOf() + suspend fun poll(owner: String) = session.poll({ local }) { published -> + sent.add(published) + Result.success(devices(owner, browser) to emptyList()) + } + + poll("phone") + poll("phone") + session.invalidate() + val returned = poll("browser")!!.getOrThrow().first + poll("browser") + assertEquals(listOf(null, local, null, null), sent) + val shown = PlayerUiState( + connectedDevicesState = returned, + playback = AudioPlaybackState(local.tracks, currentIndex = 0, positionMs = 1_000) + ).displayedPlayback() + assertEquals(browser.tracks, shown.queue) + assertEquals(37_500L, shown.positionMs) + assertEquals(!paused, shown.isPlaying) + assertEquals("browser", returned.remoteControlTargetId) + } + } + + @Test + fun failedPollRequiresFreshOwnershipAndLateRepliesCannotRestoreIt() = runBlocking { + val local = playback(10, paused = false) + val session = DevicePollingSession() + val localResponse = Result.success(devices("phone") to emptyList()) + session.poll({ local }) { localResponse } + assertTrue(session.poll({ local }) { Result.failure(IOException()) }!!.isFailure) + assertNull(session.poll({ local }) { payload -> + assertNull(payload) + session.invalidate() + localResponse + }) + val browser = session.poll({ local }) { payload -> + assertNull(payload) + Result.success(devices("browser") to emptyList()) + }!!.getOrThrow().first + val shown = PlayerUiState( + connectedDevicesState = browser, + playback = AudioPlaybackState(local.tracks, currentIndex = 0, isPlaying = true) + ).displayedPlayback() + assertNull(shown.currentTrack) + assertFalse(shown.isPlaying) + } +} diff --git a/app/src/test/java/cy/hexor/furumi/ui/player/LyricsPositionTest.kt b/app/src/test/java/cy/hexor/furumi/ui/player/LyricsPositionTest.kt new file mode 100644 index 0000000..6142461 --- /dev/null +++ b/app/src/test/java/cy/hexor/furumi/ui/player/LyricsPositionTest.kt @@ -0,0 +1,21 @@ +package cy.hexor.furumi.ui.player + +import cy.hexor.furumi.domain.model.LyricsLine +import org.junit.Assert.assertEquals +import org.junit.Test + +class LyricsPositionTest { + @Test + fun activeLineChangesAtTheCueAndHandlesIntrosBreaksAndSeeks() { + val lines = listOf(LyricsLine(1000, "First"), LyricsLine(2000, "Second"), + LyricsLine(2000, "Same time"), LyricsLine(3000, ""), LyricsLine(4000, "Last")) + + assertEquals(-1, activeLyricsLine(emptyList(), 5000)) + assertEquals(-1, activeLyricsLine(lines, 999)) + assertEquals(0, activeLyricsLine(lines, 1000)) + assertEquals(2, activeLyricsLine(lines, 2000)) + assertEquals(3, activeLyricsLine(lines, 3999)) + assertEquals(4, activeLyricsLine(lines, 5000)) + assertEquals(0, activeLyricsLine(lines, 1500)) + } +} diff --git a/ci/publish-release.sh b/ci/publish-release.sh new file mode 100644 index 0000000..f7421d7 --- /dev/null +++ b/ci/publish-release.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +die() { printf '%s\n' "$*" >&2; exit 1; } +[[ $# == 1 ]] || die 'Usage: bash ci/publish-release.sh ' +apk=$1 +tag=${GITHUB_REF_NAME:?Missing release tag} +[[ $tag =~ ^v[0-9]+(\.[0-9]+)+(-[0-9A-Za-z.-]+)?$ ]] || die "Invalid release tag: $tag" +name="furumi-android-${tag#v}.apk" +[[ -f $apk && -s $apk && ${apk##*/} == "$name" ]] || die "Expected a nonempty $name" + +base=${GITHUB_API_URL:-${GITHUB_SERVER_URL:?Missing Gitea server URL}/api/v1} +base=${base%/} +server=${GITHUB_SERVER_URL:-${base%/api/v1}} +releases="$base/repos/${GITHUB_REPOSITORY:?Missing repository}/releases" +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +request=(curl --silent --show-error --header "Authorization: token ${RELEASE_TOKEN:?Missing release token}") +release="$tmp/release.json" +status=$("${request[@]}" --output "$release" --write-out '%{http_code}' "$releases/tags/$tag") +case "$status" in + 200) ;; + 404) + payload=$(jq -nc --arg tag "$tag" '{tag_name: $tag, name: ("Furumi " + $tag), prerelease: ($tag | contains("-"))}') + status=$("${request[@]}" --header 'Content-Type: application/json' --data "$payload" \ + --output "$release" --write-out '%{http_code}' "$releases") + case "$status" in + 201) ;; + 409|422) "${request[@]}" --fail --output "$release" "$releases/tags/$tag" ;; + *) die "Creating release $tag failed (HTTP $status)" ;; + esac + ;; + *) die "Looking up release $tag failed (HTTP $status)" ;; +esac +id=$(jq -er --arg tag "$tag" 'select(.tag_name == $tag) | .id | numbers' "$release") + +asset_url() { + jq -r --arg name "$name" '[.assets[]? | select(.name == $name)] | + if length > 1 then error("Duplicate release assets") else .[0].browser_download_url // empty end' "$release" +} + +verify_existing() { + local url=$1 + [[ $url == "${server%/}/"* ]] || die 'Unexpected asset download host' + "${request[@]}" --fail --location --output "$tmp/existing.apk" "$url" + cmp -s "$apk" "$tmp/existing.apk" || die "$tag already has a different $name" + printf 'Release %s already contains the identical %s\n' "$tag" "$name" +} + +url=$(asset_url) +if [[ -n $url ]]; then + verify_existing "$url" + exit 0 +fi + +if status=$("${request[@]}" --output /dev/null --write-out '%{http_code}' \ + --form "attachment=@-;filename=$name;type=application/vnd.android.package-archive" \ + "$releases/$id/assets?name=$name" < "$apk") && [[ $status == 201 ]]; then + printf 'Published %s on release %s\n' "$name" "$tag" +else + # The server may have stored the upload even when its response was lost. + "${request[@]}" --fail --output "$release" "$releases/tags/$tag" + url=$(asset_url) + [[ -n $url ]] || die "Uploading $name to release $tag failed" + verify_existing "$url" +fi diff --git a/ci/sign-release.sh b/ci/sign-release.sh new file mode 100644 index 0000000..df02429 --- /dev/null +++ b/ci/sign-release.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +tag=${GITHUB_REF_NAME:?Missing release tag} +[[ $tag =~ ^v[0-9]+(\.[0-9]+)+(-[0-9A-Za-z.-]+)?$ ]] || { echo "Invalid version tag: $tag" >&2; exit 1; } +version=${tag#v} +unsigned=app/build/outputs/apk/release/app-release-unsigned.apk +tools="${ANDROID_HOME:?}/build-tools/36.0.0" +apk="${RUNNER_TEMP:?}/furumi-android-$version.apk" + +# Check the built manifest before using the signing key. +code=$(awk -F= '$1 == "furumi.versionCode" {print $2}' gradle.properties) +[[ $code =~ ^[1-9][0-9]*$ ]] || { echo "Invalid furumi.versionCode" >&2; exit 1; } +badging=$("$tools/aapt" dump badging "$unsigned") +expected="package: name='cy.hexor.furumi' versionCode='$code' versionName='$version'" +case "${badging%%$'\n'*} " in + "$expected "*) ;; + *) echo "APK manifest does not match $expected" >&2; exit 1 ;; +esac +if [[ $'\n'$badging$'\n' == *$'\napplication-debuggable\n'* ]]; then + echo "Refusing to publish a debuggable APK" >&2 + exit 1 +fi +"$tools/zipalign" -c -P 16 4 "$unsigned" + +: "${ANDROID_KEYSTORE_BASE64:?Missing signing keystore}" +: "${ANDROID_KEYSTORE_PASSWORD:?Missing keystore password}" +umask 077 +keystore=$(mktemp "$RUNNER_TEMP/furumi-keystore.XXXXXXXX") +trap 'rm -f "$keystore"' EXIT +printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$keystore" +unset ANDROID_KEYSTORE_BASE64 +"$tools/apksigner" sign --ks "$keystore" --ks-pass env:ANDROID_KEYSTORE_PASSWORD \ + --key-pass env:ANDROID_KEYSTORE_PASSWORD --v4-signing-enabled false --out "$apk" "$unsigned" +"$tools/apksigner" verify --verbose --print-certs "$apk" +printf 'apk=%s\n' "$apk" >> "${GITHUB_OUTPUT:?}" diff --git a/cy.hexor.furumi.yml b/cy.hexor.furumi.yml index 6dff263..769c4f2 100644 --- a/cy.hexor.furumi.yml +++ b/cy.hexor.furumi.yml @@ -35,7 +35,14 @@ Builds: gradle: - yes + - versionName: '1.4' + versionCode: 4 + commit: v1.4 + subdir: app + gradle: + - yes + AutoUpdateMode: Version v%v UpdateCheckMode: Tags -CurrentVersion: '1.3' -CurrentVersionCode: 3 +CurrentVersion: '1.4' +CurrentVersionCode: 4 diff --git a/fastlane/metadata/android/en-US/changelogs/4.txt b/fastlane/metadata/android/en-US/changelogs/4.txt new file mode 100644 index 0000000..ae12258 --- /dev/null +++ b/fastlane/metadata/android/en-US/changelogs/4.txt @@ -0,0 +1 @@ +Search your playlists and the tracks in each one. Follow synced lyrics and tap a line to seek. Offline downloads resume after interruptions, show progress and support a configurable storage limit. Reconnecting your phone keeps playback on your chosen device. diff --git a/gradle.properties b/gradle.properties index 420b43b..a7b9b5c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,5 +20,5 @@ kotlin.code.style=official android.disallowKotlinSourceSets=false # App version used by Gradle for the APK/AAB manifest and BuildConfig. -furumi.versionCode=3 -furumi.versionName=1.3 +furumi.versionCode=4 +furumi.versionName=1.4 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index de496f1..4bcb1d1 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,7 +3,7 @@ agp = "9.2.1" coreKtx = "1.10.1" junit = "4.13.2" junitVersion = "1.1.5" -espressoCore = "3.5.1" +espressoCore = "3.7.0" lifecycleRuntimeKtx = "2.6.1" lifecycleViewmodelCompose = "2.6.1" activityCompose = "1.8.0"