diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 0000000..4466c76
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,60 @@
+name: Android
+
+# 只在 PR 上跑;合并到 main 的内容已经测过,不再重跑。需要时可以手动运行。
+on:
+ pull_request:
+ paths: [android/**, ios/scripts/**, ios/testplugin/**, .github/workflows/android.yml]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: android-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ test:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: 21
+ cache: gradle
+ - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0
+ with:
+ go-version-file: server/go.mod
+ cache-dependency-path: server/go.sum
+ - name: 单元测试、静态检查和编译
+ working-directory: android
+ run: ./gradlew --console=plain :app:testDebugUnitTest :app:lintDebug :app:assembleDebug :app:assembleDebugAndroidTest :app:assembleRelease
+ - name: 允许模拟器使用 KVM
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+ - name: 界面测试
+ uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0
+ with:
+ api-level: 34
+ target: google_apis
+ arch: x86_64
+ profile: pixel_7
+ script: android/scripts/ui-test.sh "$RUNNER_TEMP/screenshots"
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: always()
+ with:
+ name: android-screenshots
+ path: ${{ runner.temp }}/screenshots
+ if-no-files-found: ignore
+ retention-days: 14
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: android-apk
+ path: android/app/build/outputs/apk/release/app-release.apk
+ retention-days: 14
diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml
index f3c4399..c6d021a 100644
--- a/.github/workflows/ios.yml
+++ b/.github/workflows/ios.yml
@@ -1,9 +1,7 @@
name: iOS
+# 只在 PR 上跑;合并到 main 的内容已经测过,不再重跑。需要时可以手动运行。
on:
- push:
- branches: [main]
- paths: [ios/**, .github/workflows/ios.yml]
pull_request:
paths: [ios/**, .github/workflows/ios.yml]
workflow_dispatch:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..5ec271b
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,127 @@
+name: Release
+
+# 推送 v1.2.3 这样的 tag:编译 iOS(不签名的 ipa)和 Android(正式签名的 APK),发布到 GitHub Release。
+# 手动运行只编译、上传产物,不发布,用来在合并前试一遍。
+on:
+ push:
+ tags: ['v*']
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: release-${{ github.ref }}
+
+jobs:
+ version:
+ runs-on: ubuntu-24.04
+ outputs:
+ name: ${{ steps.v.outputs.name }}
+ code: ${{ steps.v.outputs.code }}
+ steps:
+ - id: v
+ env:
+ REF_TYPE: ${{ github.ref_type }}
+ REF_NAME: ${{ github.ref_name }}
+ run: |
+ if [ "$REF_TYPE" = tag ]; then name="${REF_NAME#v}"; else name=0.0.0; fi
+ if ! [[ "$name" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
+ echo "tag 要写成 v1.2.3:$REF_NAME" >&2; exit 1
+ fi
+ # Android 的 versionCode 必须递增:1.2.3 → 10203。
+ code=$(( BASH_REMATCH[1] * 10000 + BASH_REMATCH[2] * 100 + BASH_REMATCH[3] ))
+ echo "name=$name" >> "$GITHUB_OUTPUT"
+ echo "code=$(( code > 0 ? code : 1 ))" >> "$GITHUB_OUTPUT"
+
+ android:
+ needs: version
+ runs-on: ubuntu-24.04
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
+ with:
+ distribution: temurin
+ java-version: 21
+ - name: 编译并签名
+ working-directory: android
+ env:
+ KEYSTORE_BASE64: ${{ secrets.MUSICGO_KEYSTORE_BASE64 }}
+ MUSICGO_KEYSTORE_PASSWORD: ${{ secrets.MUSICGO_KEYSTORE_PASSWORD }}
+ MUSICGO_KEY_ALIAS: ${{ secrets.MUSICGO_KEY_ALIAS }}
+ MUSICGO_KEY_PASSWORD: ${{ secrets.MUSICGO_KEY_PASSWORD }}
+ VERSION_NAME: ${{ needs.version.outputs.name }}
+ VERSION_CODE: ${{ needs.version.outputs.code }}
+ run: |
+ # 每个版本必须用同一把密钥签名,否则装不上更新。
+ test -n "$KEYSTORE_BASE64" || { echo "缺少仓库密钥 MUSICGO_KEYSTORE_BASE64" >&2; exit 1; }
+ export MUSICGO_KEYSTORE="$RUNNER_TEMP/release.jks"
+ base64 -d <<<"$KEYSTORE_BASE64" > "$MUSICGO_KEYSTORE"
+ ./gradlew --console=plain :app:assembleRelease \
+ -Pmusicgo.versionName="$VERSION_NAME" -Pmusicgo.versionCode="$VERSION_CODE"
+ rm "$MUSICGO_KEYSTORE"
+ mkdir -p "$RUNNER_TEMP/out"
+ cp app/build/outputs/apk/release/app-release.apk "$RUNNER_TEMP/out/MusicGo-$VERSION_NAME.apk"
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: android
+ path: ${{ runner.temp }}/out
+ if-no-files-found: error
+
+ ios:
+ needs: version
+ runs-on: ${{ vars.IOS_RUNNER || 'macos-26' }}
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: 编译不签名的 ipa
+ env:
+ VERSION_NAME: ${{ needs.version.outputs.name }}
+ VERSION_CODE: ${{ needs.version.outputs.code }}
+ run: |
+ set -o pipefail
+ command -v xcodegen >/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install xcodegen
+ (cd ios && xcodegen)
+ xcodebuild build -quiet -project ios/MusicGo.xcodeproj -scheme MusicGo -configuration Release \
+ -destination 'generic/platform=iOS' -derivedDataPath "$RUNNER_TEMP/build" \
+ MARKETING_VERSION="$VERSION_NAME" CURRENT_PROJECT_VERSION="$VERSION_CODE" \
+ CODE_SIGNING_ALLOWED=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY=""
+ mkdir -p "$RUNNER_TEMP/ipa/Payload" "$RUNNER_TEMP/out"
+ cp -R "$RUNNER_TEMP/build/Build/Products/Release-iphoneos/MusicGo.app" "$RUNNER_TEMP/ipa/Payload/"
+ (cd "$RUNNER_TEMP/ipa" && zip -qry "$RUNNER_TEMP/out/MusicGo-$VERSION_NAME-unsigned.ipa" Payload)
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: ios
+ path: ${{ runner.temp }}/out
+ if-no-files-found: error
+
+ publish:
+ if: github.ref_type == 'tag'
+ needs: [version, android, ios]
+ runs-on: ubuntu-24.04
+ permissions:
+ contents: write
+ steps:
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+ with:
+ path: out
+ merge-multiple: true
+ - name: 发布
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ github.ref_name }}
+ run: |
+ cat > notes.md <<'NOTES'
+ ## 安装
+
+ - **Android**:下载 `.apk` 直接安装。以后的版本可以覆盖安装。
+ - **iOS**:`-unsigned.ipa` 没有签名,要用 AltStore、Sideloadly 或 xtool 等工具用自己的 Apple ID 签名后安装。免费 Apple ID 签的 App 7 天后要重装。
+
+ NOTES
+ gh release create "$TAG" out/* --repo "$GITHUB_REPOSITORY" --verify-tag --title "$TAG" \
+ --notes-file notes.md --generate-notes
diff --git a/.gitignore b/.gitignore
index d964ef6..fb3ff26 100644
--- a/.gitignore
+++ b/.gitignore
@@ -41,3 +41,12 @@ filter-allow.txt
/ios/App/Info.plist
.build/
/ios/build/
+
+# Android
+/android/.gradle/
+/android/.kotlin/
+/android/build/
+/android/app/build/
+/android/local.properties
+*.jks
+*.keystore
diff --git a/README.md b/README.md
index b5230fd..0719e29 100644
--- a/README.md
+++ b/README.md
@@ -61,6 +61,7 @@ http://127.0.0.1:8870/rooms/<房间 ID>#token=<令牌>
| `server/` | Go 服务端和命令行:房间、队列、播放、音源、歌词、飞书 |
| `web/` | 网页大屏:React、TypeScript、Vite |
| `ios/` | iOS 客户端(SwiftUI),见 [ios/README.md](ios/README.md) |
+| `android/` | Android 客户端(Kotlin、Compose),见 [android/README.md](android/README.md) |
| `mcp/` | 给 AI Agent 用的 MCP 工具:服务端自带的 `/mcp` 远程入口,以及本地程序 |
| `deploy/` | systemd、Caddy 配置,以及发布、备份、升级脚本 |
| `docs/` | 文档 |
@@ -78,9 +79,11 @@ make release VERSION=v1.0.0
所有 Go 代码都以 `CGO_ENABLED=0` 编译。
+推送 `v1.2.3` 这样的 tag,`.github/workflows/release.yml` 会编译 iOS 和 Android 客户端,发布到 GitHub Release:不签名的 ipa,以及能直接安装的 APK。两个 App 的版本号都取自 tag。
+
## 目前的限制
-- 锁屏播放还没有实现。
+- 网页版不支持锁屏播放,锁屏听歌请用 iOS 或 Android 客户端。
- 歌词来自公开的歌词源,找不到就不显示。
- 插件音源的音频由你的服务器转发给房间成员,请只播放你有权播放的内容。
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 6ee4aaf..5ac972d 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -10,6 +10,9 @@ MusicGo 以 [GNU AGPL-3.0](LICENSE) 发布。它包含或改写了下面这些
| [metadata-filter](https://github.com/web-scrobbler/metadata-filter) | MIT | 标题清理规则 |
| [AppleMusicStylePlayer](https://github.com/f728743/AppleMusicStylePlayer) | MIT | iOS 播放页,[`ios/App/Player`](ios/App/Player/NOTICE.md) |
| [MelismaKit for iOS](https://github.com/kmgcc/melismakit-ios) | AGPL-3.0 | iOS 歌词的滚动和逐字高亮,作为依赖使用,见 [`ios/project.yml`](ios/project.yml) |
+| [accompanist-lyrics-ui](https://github.com/6xingyv/accompanist-lyrics-ui) | Apache-2.0 | Android 歌词的滚动和逐字高亮,作为依赖使用,见 [`libs.versions.toml`](android/gradle/libs.versions.toml) |
+| [Reorderable](https://github.com/Calvin-LL/Reorderable) | Apache-2.0 | Android 拖动调整队列,作为依赖使用 |
+| [Material Symbols](https://github.com/google/material-design-icons) | Apache-2.0 | Android 的图标,`android/app/src/main/res/drawable` |
所用的提交、改动和许可全文见各目录的 `NOTICE.md`。
diff --git a/android/README.md b/android/README.md
new file mode 100644
index 0000000..3722840
--- /dev/null
+++ b/android/README.md
@@ -0,0 +1,36 @@
+# MusicGo Android 客户端
+
+功能与网页版相同:一起听、点歌、调整队列、逐字歌词、投票切歌、管理成员和房间设置。需要 Android 8.0 或更高版本。
+
+## 使用
+
+粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在 App 的私有目录,不参与系统备份。还不是成员时,链接里可以带 `invite=<邀请码>`。公网服务器必须用 `https`。
+
+- 静音,以及通知和耳机上的播放、暂停只管本机;通知里的「下一首」和进度条会影响整个房间。房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。
+- YouTube 用官方的内嵌播放器,只在播放页打开时播放,不能在后台听。
+- 歌放完后,App 会在后台等 30 分钟,有人点歌就接着放。
+- 点待播歌曲右边的 ✕ 撤回;房主和管理员拖动把手可以调整顺序。
+- 歌词的时间偏移和手动选的歌词只存在本机。
+
+## 开发
+
+需要 JDK 21 和 Android SDK(设好 `ANDROID_HOME`)。
+
+```sh
+cd android
+./gradlew :app:installDebug # 装到已连接的设备
+./gradlew :app:testDebugUnitTest :app:lintDebug # 单元测试和静态检查
+scripts/ui-test.sh # 界面测试,需要开着模拟器,还需要 Go
+./gradlew :app:assembleRelease # 发布版
+```
+
+正式版本由 GitHub Release 发布(见根目录 README),用仓库密钥 `MUSICGO_KEYSTORE_BASE64` 等签名,每个版本必须用同一把密钥,否则无法覆盖安装。本地编译发布版时,签名读取环境变量 `MUSICGO_KEYSTORE`、`MUSICGO_KEYSTORE_PASSWORD`、`MUSICGO_KEY_ALIAS` 和 `MUSICGO_KEY_PASSWORD`;没设 `MUSICGO_KEYSTORE` 时用调试密钥,只适合自己安装。
+
+| 目录(`app/src/main/java/dev/luckybot/musicgo/`) | 内容 |
+|---|---|
+| `api/` | 接口、数据结构、链接解析、进度推算、歌词解析 |
+| `player/` | 跟着房间播放,以及通知和锁屏控制(Media3) |
+| `ui/` | Compose 界面 |
+| `RoomSession.kt` | 实时连接和房间操作 |
+
+界面测试在 `app/src/androidTest`,对着 `ios/scripts/test-server.sh` 启动的真实服务端走完整流程。改动推到 PR 后,`.github/workflows/android.yml` 会编译、测试并上传截图(产物 `android-screenshots`)和 APK。
diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 0000000..6ecf9a9
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,79 @@
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
+}
+
+android {
+ namespace = "dev.luckybot.musicgo"
+ compileSdk {
+ version = release(37) { minorApiLevel = 1 }
+ }
+
+ defaultConfig {
+ applicationId = "dev.luckybot.musicgo"
+ minSdk = 26
+ targetSdk = 37
+ // 发布时由 tag 决定,见 .github/workflows/release.yml。
+ versionCode = providers.gradleProperty("musicgo.versionCode").orNull?.toInt() ?: 1
+ versionName = providers.gradleProperty("musicgo.versionName").orNull ?: "0.1.0"
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ }
+
+ // 正式签名从环境变量读取;没有时用调试签名,只适合自己安装。
+ val keystore = System.getenv("MUSICGO_KEYSTORE")
+ if (keystore != null) {
+ signingConfigs.create("release") {
+ storeFile = file(keystore)
+ storePassword = System.getenv("MUSICGO_KEYSTORE_PASSWORD")
+ keyAlias = System.getenv("MUSICGO_KEY_ALIAS")
+ keyPassword = System.getenv("MUSICGO_KEY_PASSWORD")
+ }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"))
+ signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug")
+ }
+ }
+
+ buildFeatures.compose = true
+ // Media3 的 SimpleBasePlayer 等还标着不稳定,没有替代
+ lint.disable += "UnsafeOptInUsageError"
+}
+
+kotlin {
+ compilerOptions {
+ optIn.addAll(
+ "androidx.compose.material3.ExperimentalMaterial3Api",
+ "androidx.compose.ui.ExperimentalComposeUiApi",
+ "kotlinx.serialization.ExperimentalSerializationApi",
+ )
+ }
+}
+
+dependencies {
+ implementation(platform(libs.compose.bom))
+ implementation(libs.compose.material3)
+ implementation(libs.activity.compose)
+ implementation(libs.lifecycle.compose)
+ implementation(libs.media3.exoplayer)
+ implementation(libs.media3.session)
+ implementation(libs.okhttp)
+ implementation(libs.okhttp.coroutines)
+ implementation(libs.coil.compose)
+ implementation(libs.coil.okhttp)
+ implementation(libs.serialization.json)
+ implementation(libs.coroutines.android)
+ implementation(libs.lyrics.ui)
+ implementation(libs.lyrics.core)
+ implementation(libs.reorderable)
+
+ testImplementation(libs.junit)
+ androidTestImplementation(libs.androidx.junit)
+ androidTestImplementation(libs.androidx.runner)
+ androidTestImplementation(libs.uiautomator)
+}
diff --git a/android/app/src/androidTest/java/dev/luckybot/musicgo/ListenTogetherTest.kt b/android/app/src/androidTest/java/dev/luckybot/musicgo/ListenTogetherTest.kt
new file mode 100644
index 0000000..6719008
--- /dev/null
+++ b/android/app/src/androidTest/java/dev/luckybot/musicgo/ListenTogetherTest.kt
@@ -0,0 +1,186 @@
+package dev.luckybot.musicgo
+
+import android.content.Intent
+import android.os.ParcelFileDescriptor
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.uiautomator.By
+import androidx.test.uiautomator.BySelector
+import androidx.test.uiautomator.UiDevice
+import androidx.test.uiautomator.UiObject2
+import androidx.test.uiautomator.Until
+import java.util.regex.Pattern
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * 对着真实的服务端走一遍:登录、点歌、出声、歌词、暂停、切歌、后台播放、房间设置。
+ * 服务端由 ios/scripts/test-server.sh 启动,用 scripts/ui-test.sh 运行。
+ */
+@RunWith(AndroidJUnit4::class)
+class ListenTogetherTest {
+ private val instrumentation = InstrumentationRegistry.getInstrumentation()
+ private val device = UiDevice.getInstance(instrumentation)
+ private val context = instrumentation.targetContext
+
+ @Test
+ fun listenTogether() {
+ val link = InstrumentationRegistry.getArguments().getString("link")
+ assertNotNull("缺少参数 link", link)
+ launch()
+
+ find(id("entry-link")).text = "not a link"
+ find(id("enter-room")).click()
+ find(By.textContains("这不是网页链接"))
+ find(id("entry-link")).text = link
+ capture("1-login")
+ find(id("enter-room")).click()
+ find(By.text("现在没有在放歌"))
+
+ order("first", capture = true)
+ find(By.desc("正在放 first 1"))
+ order("second")
+ find(By.text("second 1"))
+ order("third")
+ find(By.text("待播 2 首"))
+ capture("3-room")
+
+ // 撤回,再拖动换顺序。
+ find(By.desc("撤回 second 1")).click()
+ gone(By.text("second 1"))
+ order("second")
+ find(By.text("second 1"))
+ assertEquals(listOf("third 1", "second 1"), queue())
+ val handle = find(By.desc("拖动调整 second 1 的顺序")).visibleCenter
+ val target = find(By.desc("拖动调整 third 1 的顺序")).visibleCenter
+ device.drag(handle.x, handle.y, target.x, target.y - 40, 60)
+ waitUntil("顺序没有变") { queue() == listOf("second 1", "third 1") }
+
+ find(id("mini-player")).click()
+ find(id("now-playing-title").text("first 1"))
+ find(id("player-state").text("正在本机播放"))
+ capture("4-player")
+
+ find(id("show-lyrics")).click()
+ find(id("lyrics"))
+ Thread.sleep(3000)
+ capture("5-lyrics")
+ find(id("lyrics-options")).click()
+ find(By.text("歌词时间:原样"))
+ find(By.text("+0.5")).click()
+ find(By.text("歌词提前 0.5 秒"))
+ capture("6-lyrics-options")
+ device.pressBack()
+ gone(By.text("歌词提前 0.5 秒"))
+ find(id("show-queue")).click()
+ find(By.text("待播 2 首"))
+ capture("7-queue")
+
+ find(id("toggle-pause")).click()
+ find(id("player-state").text("已暂停"))
+ find(id("toggle-pause")).click()
+ find(id("player-state").text("正在本机播放"))
+ // 房主也能举手投票;只有一个人在听,一票就切。
+ find(id("skip"))
+ find(id("vote-skip")).click()
+ find(id("now-playing-title").text("second 1"))
+ find(id("player-state").text("正在本机播放"))
+
+ // 后台继续播放,通知里能暂停和切歌。
+ device.pressHome()
+ Thread.sleep(3000)
+ assertTrue("后台没有继续播放", mediaSession().contains("state=PLAYING"))
+ device.openNotification()
+ find(By.text("second 1"))
+ capture("8-notification")
+ find(By.desc(Pattern.compile("(?i).*next.*|.*下一.*"))).click()
+ find(By.text("third 1"))
+ waitUntil("切歌后没有接着放") { mediaSession().contains("state=PLAYING") }
+ device.pressBack()
+ launch()
+ find(id("now-playing-title").text("third 1"))
+ find(id("player-state").text("正在本机播放"))
+ find(id("close-player")).click()
+
+ find(id("open-room-info")).click()
+ find(By.text("邀请码"))
+ capture("9-room-info")
+ find(id("open-settings")).click()
+ find(id("room-name")).text = "周六音乐房"
+ capture("10-settings")
+ find(id("save-settings")).click()
+ find(By.text("周六音乐房"))
+ find(id("open-history")).click()
+ find(By.text("first 1"))
+ }
+
+ private fun launch() {
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)!!
+ context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ device.wait(Until.hasObject(By.pkg(context.packageName)), TIMEOUT)
+ }
+
+ private fun order(query: String, capture: Boolean = false) {
+ find(id("open-search")).click()
+ find(id("search-field")).text = query
+ device.pressEnter()
+ find(By.text("$query 1")).click()
+ find(By.desc("已点"))
+ if (capture) capture("2-search")
+ find(id("back")).click()
+ gone(id("search-field"))
+ }
+
+ private fun queue() = device.findObjects(By.desc(Pattern.compile("拖动调整 .* 的顺序")))
+ .sortedBy { it.visibleCenter.y }
+ .map { it.contentDescription.removePrefix("拖动调整 ").removeSuffix(" 的顺序") }
+
+ private fun id(tag: String): BySelector = By.res(tag)
+
+ private fun find(selector: BySelector): UiObject2 {
+ var found = device.wait(Until.findObject(selector), TIMEOUT)
+ if (found == null && dismissNotResponding()) found = device.wait(Until.findObject(selector), TIMEOUT)
+ if (found == null) capture("failure")
+ assertNotNull("找不到 $selector", found)
+ return found
+ }
+
+ /** CI 的模拟器很慢,系统应用会弹「没有响应」,挡住界面。点「等待」关掉。 */
+ private fun dismissNotResponding(): Boolean {
+ if (!device.hasObject(By.textContains("isn't responding"))) return false
+ device.findObject(By.text("Wait"))?.click()
+ return device.wait(Until.gone(By.textContains("isn't responding")), TIMEOUT)
+ }
+
+ private fun gone(selector: BySelector) = assertTrue("还在 $selector", device.wait(Until.gone(selector), TIMEOUT))
+
+ private fun waitUntil(message: String, condition: () -> Boolean) {
+ val end = System.currentTimeMillis() + TIMEOUT
+ while (!condition()) {
+ if (System.currentTimeMillis() > end) capture("failure")
+ assertTrue(message, System.currentTimeMillis() <= end)
+ Thread.sleep(200)
+ }
+ }
+
+ /** 系统看到的本 App 的播放状态。 */
+ private fun mediaSession() = shell("dumpsys media_session").substringAfter("package=${context.packageName}", "")
+ .lineSequence().take(12).joinToString("\n")
+
+ private fun capture(name: String) {
+ shell("mkdir -p $SHOTS")
+ shell("screencap -p $SHOTS/$name.png")
+ }
+
+ private fun shell(command: String): String =
+ ParcelFileDescriptor.AutoCloseInputStream(instrumentation.uiAutomation.executeShellCommand(command))
+ .bufferedReader().use { it.readText() }
+
+ private companion object {
+ const val TIMEOUT = 15_000L
+ const val SHOTS = "/sdcard/Download/musicgo-shots"
+ }
+}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..9f8771d
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/app/src/main/java/dev/luckybot/musicgo/MainActivity.kt b/android/app/src/main/java/dev/luckybot/musicgo/MainActivity.kt
new file mode 100644
index 0000000..1b362f9
--- /dev/null
+++ b/android/app/src/main/java/dev/luckybot/musicgo/MainActivity.kt
@@ -0,0 +1,46 @@
+package dev.luckybot.musicgo
+
+import android.content.ComponentName
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.runtime.key
+import androidx.lifecycle.compose.LifecycleStartEffect
+import androidx.media3.session.MediaController
+import androidx.media3.session.SessionToken
+import dev.luckybot.musicgo.player.PlaybackService
+import dev.luckybot.musicgo.ui.LoginScreen
+import dev.luckybot.musicgo.ui.MusicGoTheme
+import dev.luckybot.musicgo.ui.RoomNavigation
+
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ val app = application as MusicGoApp
+ setContent {
+ MusicGoTheme {
+ val session = app.session
+ if (session == null) {
+ LoginScreen(onLogin = app::login)
+ } else {
+ key(session) {
+ LifecycleStartEffect(session) {
+ session.player.isVisible = true
+ session.wake()
+ // 连着控制器,播放服务才会启动;开始出声后它自己转入前台。
+ val token = SessionToken(this@MainActivity, ComponentName(this@MainActivity, PlaybackService::class.java))
+ val controller = MediaController.Builder(this@MainActivity, token).buildAsync()
+ onStopOrDispose {
+ session.player.isVisible = false
+ MediaController.releaseFuture(controller)
+ }
+ }
+ RoomNavigation(session, onLeave = app::logout)
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/android/app/src/main/java/dev/luckybot/musicgo/MusicGoApp.kt b/android/app/src/main/java/dev/luckybot/musicgo/MusicGoApp.kt
new file mode 100644
index 0000000..2b77d53
--- /dev/null
+++ b/android/app/src/main/java/dev/luckybot/musicgo/MusicGoApp.kt
@@ -0,0 +1,44 @@
+package dev.luckybot.musicgo
+
+import android.app.Application
+import android.content.Context
+import android.content.Intent
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import androidx.core.content.edit
+import dev.luckybot.musicgo.api.EntryLink
+import dev.luckybot.musicgo.player.PlaybackService
+import kotlinx.serialization.json.Json
+
+/** 房间连接归整个进程所有,界面关掉后还能在后台播放。 */
+class MusicGoApp : Application() {
+ var session by mutableStateOf(null)
+ private set
+
+ // 存在 App 的私有目录,系统备份已关闭(见 AndroidManifest.xml)。
+ private val credentials by lazy { getSharedPreferences("credentials", Context.MODE_PRIVATE) }
+
+ override fun onCreate() {
+ super.onCreate()
+ credentials.getString(LINK, null)
+ ?.let { runCatching { Json.decodeFromString(it) }.getOrNull() }
+ ?.let { session = RoomSession(this, it) }
+ }
+
+ fun login(link: EntryLink) {
+ credentials.edit { putString(LINK, Json.encodeToString(link)) }
+ session = RoomSession(this, link)
+ }
+
+ fun logout() {
+ credentials.edit { clear() }
+ stopService(Intent(this, PlaybackService::class.java))
+ session?.close()
+ session = null
+ }
+
+ private companion object {
+ const val LINK = "link"
+ }
+}
diff --git a/android/app/src/main/java/dev/luckybot/musicgo/RoomSession.kt b/android/app/src/main/java/dev/luckybot/musicgo/RoomSession.kt
new file mode 100644
index 0000000..6561770
--- /dev/null
+++ b/android/app/src/main/java/dev/luckybot/musicgo/RoomSession.kt
@@ -0,0 +1,268 @@
+package dev.luckybot.musicgo
+
+import android.content.Context
+import android.os.SystemClock
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import dev.luckybot.musicgo.api.ApiClient
+import dev.luckybot.musicgo.api.ApiException
+import dev.luckybot.musicgo.api.EntryLink
+import dev.luckybot.musicgo.api.Playback
+import dev.luckybot.musicgo.api.PlaybackClock
+import dev.luckybot.musicgo.api.QueueEntry
+import dev.luckybot.musicgo.api.Room
+import dev.luckybot.musicgo.api.RoomMessage
+import dev.luckybot.musicgo.api.User
+import dev.luckybot.musicgo.api.userMessage
+import dev.luckybot.musicgo.player.RoomPlayer
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import okhttp3.Response
+import okhttp3.WebSocket
+import okhttp3.WebSocketListener
+
+/** 一个房间的连接和状态。服务端是唯一事实来源,这里只保留它最近一次给的快照。 */
+class RoomSession(val context: Context, link: EntryLink) {
+ val scope: CoroutineScope = MainScope()
+ val client = ApiClient(link)
+ val player = RoomPlayer(context, client, scope)
+
+ var room by mutableStateOf(null)
+ private set
+ var me by mutableStateOf(null)
+ private set
+ var isLive by mutableStateOf(false)
+ private set
+
+ /** 凭据失效或被移出房间,不再重连。 */
+ var endedReason by mutableStateOf(null)
+ private set
+
+ /** 给用户看的一次性提示。 */
+ var notice by mutableStateOf(null)
+
+ /** 本机已经报告放不了的歌。 */
+ var reported by mutableStateOf(emptySet())
+ private set
+
+ private var clock = PlaybackClock()
+ private var connection: Job? = null
+ private var lastMessage = 0L
+
+ init {
+ player.remote = object : RoomPlayer.Remote {
+ override fun onPlay() {
+ if (canControl && room?.playback?.status == Playback.Status.Paused) togglePause()
+ }
+
+ override fun onNext() {
+ if (canSkip) skip()
+ }
+
+ override fun onSeek(position: Double) = seek(position)
+ override fun onUnplayable(entryId: String) = reportUnplayable(entryId)
+ }
+ connection = scope.launch { run() }
+ }
+
+ fun close() {
+ scope.cancel()
+ player.release()
+ }
+
+ /** 回到前台。后台待久了连接多半已经断了,不等超时,马上重连。 */
+ fun wake() {
+ val isFresh = SystemClock.elapsedRealtime() - lastMessage < PING_INTERVAL + 5_000
+ if (endedReason != null || (isLive && isFresh)) return
+ connection?.cancel()
+ isLive = false
+ connection = scope.launch { run() }
+ }
+
+ val position get() = room?.let { clock.position(it.playback) } ?: 0.0
+
+ /** 歌词跟着耳朵听到的走,没有出声时跟着房间走。 */
+ val lyricsPosition get() = player.heardPosition ?: position
+ val canControl get() = me?.let { room?.canControl(it.id) } ?: false
+ val canSkip get() = me?.let { room?.canSkip(it.id) } ?: false
+ val isOwner get() = me?.let { room?.isOwner(it.id) } ?: false
+ val hasVoted get() = me?.let { room?.votes?.voters?.contains(it.id) } ?: false
+ fun canRetract(entry: QueueEntry) = me?.let { room?.canRetract(entry, it.id) } ?: false
+
+ // 操作
+
+ /** 执行一个操作,失败时提示。 */
+ fun perform(action: suspend ApiClient.() -> Unit): Job = scope.launch { attempt(action) }
+
+ suspend fun attempt(action: suspend ApiClient.() -> Unit): Boolean = try {
+ client.action()
+ true
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Exception) {
+ notice = error.userMessage
+ false
+ }
+
+ fun retract(entry: QueueEntry) = perform { retract(entry.id) }
+
+ /** 先在本机换好位置,免得松手后先弹回去;真正的顺序以服务端随后发来的为准。 */
+ fun move(entryId: String, position: Int) {
+ val before = room ?: return
+ val entry = before.queue.find { it.id == entryId } ?: return
+ if (before.queue.indexOf(entry) == position) return
+ val moved = before.queue.minus(entry).toMutableList().apply { add(position.coerceIn(0, size), entry) }
+ room = before.copy(queue = moved)
+ scope.launch {
+ val done = attempt { move(entryId, position) }
+ val now = room
+ if (!done && now?.queue == moved) room = now.copy(queue = before.queue)
+ }
+ }
+
+ /** 本机放不了当前这首,投一票切歌。每首只报一次。 */
+ fun reportUnplayable(entryId: String) {
+ if (entryId in reported) return
+ reported = reported + entryId
+ scope.launch {
+ try {
+ client.reportUnplayable(entryId)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Exception) {
+ if ((error as? ApiException)?.isRefusal != true) reported = reported - entryId
+ }
+ }
+ }
+
+ fun togglePause() {
+ val isPaused = room?.playback?.status == Playback.Status.Paused
+ perform { if (isPaused) resume() else pause() }
+ }
+
+ fun seek(position: Double) {
+ val entry = room?.playback?.entry ?: return
+ if (canControl) perform { seek(entry.id, position) }
+ }
+
+ fun skip() {
+ val entry = room?.playback?.entry ?: return
+ if (canSkip) perform { skip(entry.id) }
+ }
+
+ /** 投一票,和网页版一样谁都能投,房主也可以;每首歌每人一票。 */
+ fun voteSkip() {
+ val entry = room?.playback?.entry ?: return
+ if (!hasVoted) perform { voteSkip(entry.id) }
+ }
+
+ // 连接
+
+ private suspend fun run() {
+ var wait = 1000L
+ while (true) {
+ try {
+ // 连上过再断开的,马上重连。
+ connectOnce { wait = 200 }
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: ApiException) {
+ if (error.endsSession) {
+ isLive = false
+ endedReason = error.message
+ player.listen(false)
+ player.follow(IDLE, clock, canSkip = false, canControl = false)
+ return
+ }
+ } catch (_: Exception) {
+ // 网络问题,稍后重连。
+ }
+ isLive = false
+ delay(wait)
+ wait = (wait * 2).coerceIn(1000, 15_000)
+ }
+ }
+
+ /** 连到断开为止。 */
+ private suspend fun connectOnce(onLive: () -> Unit) = coroutineScope {
+ me = client.me()
+ clock = client.clock()
+ apply(client.room())
+ player.retry()
+
+ val messages = Channel(Channel.UNLIMITED)
+ val socket = ApiClient.http.newWebSocket(client.webSocketRequest(), object : WebSocketListener() {
+ override fun onMessage(webSocket: WebSocket, text: String) {
+ try {
+ messages.trySend(RoomMessage.parse(text))
+ } catch (error: IllegalArgumentException) {
+ messages.close(error)
+ }
+ }
+
+ override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
+ webSocket.close(1000, null)
+ messages.close()
+ }
+
+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
+ messages.close()
+ }
+
+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
+ messages.close()
+ }
+ })
+ val ping = launch {
+ var count = 0
+ while (isActive) {
+ delay(PING_INTERVAL)
+ socket.send("""{"type":"ping"}""")
+ // 大约每五分钟校一次时钟。
+ if (++count % 12 == 0) {
+ runCatching { client.clock() }.onSuccess {
+ clock = it
+ room?.let(::apply)
+ }
+ }
+ }
+ }
+ try {
+ for (message in messages) {
+ lastMessage = SystemClock.elapsedRealtime()
+ when (message) {
+ is RoomMessage.Snapshot -> {
+ isLive = true
+ onLive()
+ apply(message.room)
+ }
+ RoomMessage.Changed -> socket.send("""{"type":"sync"}""")
+ RoomMessage.Refused -> break
+ RoomMessage.Other -> {}
+ }
+ }
+ } finally {
+ ping.cancel()
+ socket.cancel()
+ }
+ }
+
+ private fun apply(room: Room) {
+ this.room = room
+ player.follow(room.playback, clock, canSkip, canControl)
+ }
+
+ private companion object {
+ const val PING_INTERVAL = 25_000L
+ val IDLE = Playback(status = Playback.Status.Idle)
+ }
+}
diff --git a/android/app/src/main/java/dev/luckybot/musicgo/api/ApiClient.kt b/android/app/src/main/java/dev/luckybot/musicgo/api/ApiClient.kt
new file mode 100644
index 0000000..4df89cf
--- /dev/null
+++ b/android/app/src/main/java/dev/luckybot/musicgo/api/ApiClient.kt
@@ -0,0 +1,238 @@
+package dev.luckybot.musicgo.api
+
+import java.io.IOException
+import java.util.UUID
+import java.util.concurrent.TimeUnit
+import kotlin.math.ceil
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import kotlinx.serialization.serializer
+import okhttp3.HttpUrl.Companion.toHttpUrl
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.coroutines.executeAsync
+
+class ApiException(val status: Int, body: String) : Exception() {
+ @Serializable
+ private data class Body(val error: Detail) {
+ @Serializable
+ data class Detail(val code: String, val message: String, val details: Details? = null)
+
+ @Serializable
+ data class Details(val retryAfterSeconds: Double? = null, val limit: Int? = null)
+ }
+
+ private val detail = runCatching { ApiJson.decodeFromString(Body.serializer(), body).error }.getOrNull()
+ val code = detail?.code ?: "internal"
+
+ override val message: String
+ get() {
+ val fallback = detail?.message ?: "服务器返回了错误(HTTP $status)"
+ return when (code) {
+ "unauthorized" -> "登录凭据无效或已吊销,请重新粘贴进入链接"
+ "stale_entry" -> "歌曲已经切换了"
+ "duplicate_track" -> "这首歌已在待播队列中"
+ "invite_invalid" -> "邀请码无效,请向房主要最新的邀请码"
+ "queue_limit_exceeded" -> detail?.details?.limit?.let { "你的待播歌曲已达上限($it 首)" } ?: fallback
+ "unsupported_url" -> "认不出这个链接,请换一个,或改用歌名搜索"
+ "rate_limited" -> detail?.details?.retryAfterSeconds
+ ?.let { "操作太频繁,请 ${ceil(it).toInt()} 秒后再试" } ?: fallback
+ else -> fallback
+ }
+ }
+
+ /** 服务端明确拒绝的,再试也一样。 */
+ val isRefusal get() = status in 400..499 && status != 429
+
+ /** 重试也没用:凭据失效、不是成员,或房间不存在。 */
+ val endsSession get() = code in setOf("unauthorized", "forbidden", "not_found")
+}
+
+/** 给用户看的错误。 */
+val Throwable.userMessage: String
+ get() = when (this) {
+ is ApiException, is LinkException -> message.orEmpty()
+ is IOException -> "连不上服务器,请检查网络"
+ else -> message ?: "出错了"
+ }
+
+class ApiClient(val link: EntryLink) {
+ private val roomPath = "/v1/rooms/${link.roomId}"
+
+ // 读取
+
+ suspend fun me(): User = get("/v1/me")
+
+ suspend fun clock(): PlaybackClock {
+ @Serializable
+ data class Response(val unixMs: Double)
+ val sent = System.currentTimeMillis()
+ val time: Response = get("/v1/time")
+ return PlaybackClock(sent, System.currentTimeMillis(), time.unixMs)
+ }
+
+ suspend fun room(): Room {
+ @Serializable
+ data class Response(val room: Room)
+ return get(roomPath).room
+ }
+
+ /** 账号所在的房间。 */
+ suspend fun roomIds(): List {
+ @Serializable
+ data class Summary(val id: String)
+
+ @Serializable
+ data class Response(val rooms: List)
+ return get("/v1/rooms").rooms.map { it.id }
+ }
+
+ suspend fun sources(): List {
+ @Serializable
+ data class Response(val sources: List)
+ return get("/v1/sources").sources
+ }
+
+ suspend fun search(query: String, source: String): List