From 729ac5ef1efc68045c281586656eaf43cf4ac771 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:50:03 +0800 Subject: [PATCH 1/9] =?UTF-8?q?feat(ios):=20=E6=9C=80=E5=B0=8F=E5=8F=AF?= =?UTF-8?q?=E7=94=A8=E7=9A=84=20SwiftUI=20=E5=AE=A2=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ios.yml | 72 ++++++ .gitignore | 5 + ios/App/CredentialStore.swift | 35 +++ ios/App/LoginView.swift | 64 +++++ ios/App/MusicGoApp.swift | 24 ++ ios/App/RoomPlayer.swift | 219 ++++++++++++++++++ ios/App/RoomSession.swift | 143 ++++++++++++ ios/App/RoomView.swift | 206 ++++++++++++++++ ios/App/SearchView.swift | 101 ++++++++ ios/MusicGoKit/Package.swift | 13 ++ .../Sources/MusicGoKit/APIClient.swift | 185 +++++++++++++++ .../Sources/MusicGoKit/EntryLink.swift | 52 +++++ .../Sources/MusicGoKit/Models.swift | 148 ++++++++++++ .../Sources/MusicGoKit/PlaybackClock.swift | 41 ++++ .../MusicGoKitTests/MusicGoKitTests.swift | 115 +++++++++ ios/README.md | 29 +++ ios/UITests/MusicGoUITests.swift | 77 ++++++ ios/project.yml | 60 +++++ ios/scripts/test-server.sh | 35 +++ ios/testplugin/index.js | 14 ++ ios/testplugin/plugin.json | 7 + 21 files changed, 1645 insertions(+) create mode 100644 .github/workflows/ios.yml create mode 100644 ios/App/CredentialStore.swift create mode 100644 ios/App/LoginView.swift create mode 100644 ios/App/MusicGoApp.swift create mode 100644 ios/App/RoomPlayer.swift create mode 100644 ios/App/RoomSession.swift create mode 100644 ios/App/RoomView.swift create mode 100644 ios/App/SearchView.swift create mode 100644 ios/MusicGoKit/Package.swift create mode 100644 ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift create mode 100644 ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift create mode 100644 ios/MusicGoKit/Sources/MusicGoKit/Models.swift create mode 100644 ios/MusicGoKit/Sources/MusicGoKit/PlaybackClock.swift create mode 100644 ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift create mode 100644 ios/README.md create mode 100644 ios/UITests/MusicGoUITests.swift create mode 100644 ios/project.yml create mode 100755 ios/scripts/test-server.sh create mode 100644 ios/testplugin/index.js create mode 100644 ios/testplugin/plugin.json diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml new file mode 100644 index 0000000..4715585 --- /dev/null +++ b/.github/workflows/ios.yml @@ -0,0 +1,72 @@ +name: iOS + +on: + push: + branches: [main] + paths: [ios/**, .github/workflows/ios.yml] + pull_request: + paths: [ios/**, .github/workflows/ios.yml] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ios-${{ github.ref }} + cancel-in-progress: true + +jobs: + test: + # 想换机器(如 Hayabuild 的 hayabuild-macos),设仓库变量 IOS_RUNNER 即可,不用改这里。 + runs-on: ${{ vars.IOS_RUNNER || 'macos-26' }} + timeout-minutes: 45 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: server/go.mod + cache-dependency-path: server/go.sum + - name: 生成 Xcode 工程 + run: | + command -v xcodegen >/dev/null || HOMEBREW_NO_AUTO_UPDATE=1 brew install xcodegen + cd ios && xcodegen + - name: 测试 MusicGoKit + run: swift test --package-path ios/MusicGoKit + - name: 选择模拟器 + run: | + id="$(xcrun simctl list devices available --json | python3 -c ' + import json, sys + found = [(r, d) for r, ds in json.load(sys.stdin)["devices"].items() if "iOS" in r for d in ds if d["name"].startswith("iPhone")] + version = lambda r: [int(n) for n in r.rsplit("iOS-", 1)[1].split("-")] + newest = max((r for r, _ in found), key=version) + print(next(d["udid"] for r, d in found if r == newest))')" + xcrun simctl list devices | grep "$id" + echo "DEVICE=$id" >> "$GITHUB_ENV" + - name: 编译 + run: | + set -o pipefail + xcodebuild -version + xcodebuild build-for-testing -quiet -project ios/MusicGo.xcodeproj -scheme MusicGo \ + -destination "id=$DEVICE" + - name: 界面测试 + run: | + link="$(ios/scripts/test-server.sh "$RUNNER_TEMP/server")" + TEST_RUNNER_MUSICGO_LINK="$link" xcodebuild test-without-building \ + -project ios/MusicGo.xcodeproj -scheme MusicGo -destination "id=$DEVICE" \ + -resultBundlePath "$RUNNER_TEMP/result.xcresult" + - name: 取出截图 + if: always() + run: | + kill "$(cat "$RUNNER_TEMP/server/pid")" || true + xcrun xcresulttool export attachments --path "$RUNNER_TEMP/result.xcresult" \ + --output-path "$RUNNER_TEMP/screenshots" + cp "$RUNNER_TEMP/server/log" "$RUNNER_TEMP/screenshots/server.log" + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: ios-screenshots + path: ${{ runner.temp }}/screenshots + if-no-files-found: ignore + retention-days: 14 diff --git a/.gitignore b/.gitignore index f8749af..7ba57ed 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,8 @@ filter-allow.txt .DS_Store .idea/ .vscode/ + +# iOS:Xcode 工程由 ios/project.yml 生成 +/ios/*.xcodeproj/ +/ios/App/Info.plist +.build/ diff --git a/ios/App/CredentialStore.swift b/ios/App/CredentialStore.swift new file mode 100644 index 0000000..814937d --- /dev/null +++ b/ios/App/CredentialStore.swift @@ -0,0 +1,35 @@ +import Foundation +import MusicGoKit +import Security + +/// 进入链接里有令牌,所以存钥匙串,且不随备份换到别的设备。 +enum CredentialStore { + private static let item: [CFString: Any] = [ + kSecClass: kSecClassGenericPassword, + kSecAttrService: "musicgo.entry-link", + kSecAttrAccount: "default", + ] + + static func load() -> EntryLink? { + var query = item + query[kSecReturnData] = true + var result: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { + return nil + } + return try? JSONDecoder().decode(EntryLink.self, from: data) + } + + static func save(_ link: EntryLink) { + clear() + guard let data = try? JSONEncoder().encode(link) else { return } + var attributes = item + attributes[kSecValueData] = data + attributes[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + SecItemAdd(attributes as CFDictionary, nil) + } + + static func clear() { + SecItemDelete(item as CFDictionary) + } +} diff --git a/ios/App/LoginView.swift b/ios/App/LoginView.swift new file mode 100644 index 0000000..0c2928d --- /dev/null +++ b/ios/App/LoginView.swift @@ -0,0 +1,64 @@ +import MusicGoKit +import SwiftUI + +struct LoginView: View { + let onLogin: (EntryLink) -> Void + + @State private var text = "" + @State private var problem: String? + @State private var checking = false + + var body: some View { + NavigationStack { + Form { + Section { + TextField("https://…/rooms/…#token=…", text: $text) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .keyboardType(.URL) + .submitLabel(.go) + .onSubmit(login) + .accessibilityIdentifier("entry-link") + } header: { + Text("进入链接") + } footer: { + if let problem { + Text(problem).foregroundStyle(.red) + } else { + Text("粘贴 MusicGo 房间的完整链接。链接里有你的登录凭据,不要发给别人。") + } + } + Section { + Button(action: login) { + HStack { + Text("进入房间") + if checking { + Spacer() + ProgressView() + } + } + } + .disabled(text.isEmpty || checking) + .accessibilityIdentifier("enter-room") + } + } + .navigationTitle("MusicGo") + } + } + + private func login() { + guard !checking else { return } + problem = nil + checking = true + Task { + defer { checking = false } + do { + let link = try EntryLink(text) + _ = try await APIClient(link: link).room() + onLogin(link) + } catch { + problem = error.localizedDescription + } + } + } +} diff --git a/ios/App/MusicGoApp.swift b/ios/App/MusicGoApp.swift new file mode 100644 index 0000000..9be6863 --- /dev/null +++ b/ios/App/MusicGoApp.swift @@ -0,0 +1,24 @@ +import MusicGoKit +import SwiftUI + +@main +struct MusicGoApp: App { + @State private var session = CredentialStore.load().map { RoomSession(link: $0) } + + var body: some Scene { + WindowGroup { + if let session { + RoomView(session: session) { + session.stop() + CredentialStore.clear() + self.session = nil + } + } else { + LoginView { link in + CredentialStore.save(link) + session = RoomSession(link: link) + } + } + } + } +} diff --git a/ios/App/RoomPlayer.swift b/ios/App/RoomPlayer.swift new file mode 100644 index 0000000..5affa6d --- /dev/null +++ b/ios/App/RoomPlayer.swift @@ -0,0 +1,219 @@ +import AVFoundation +import MediaPlayer +import MusicGoKit +import Observation + +/// 在本机播放房间里正在放的歌,跟着房间的进度走。 +@MainActor @Observable +final class RoomPlayer { + enum State: Equatable { + case idle, loading, playing, paused, off + /// 这首歌的音频不由服务端转发(如 YouTube)。 + case unsupported + case failed(String) + } + + private(set) var state = State.idle + /// 本机是否出声。不影响房间里的其他人。 + var isListening = true { + didSet { update() } + } + + @ObservationIgnored private let client: APIClient + @ObservationIgnored private let player = AVPlayer() + @ObservationIgnored private var playback: Playback? + @ObservationIgnored private var clock = PlaybackClock() + @ObservationIgnored private var loading: Task? + @ObservationIgnored private var ticker: Task? + @ObservationIgnored private var observers: [NSObjectProtocol] = [] + @ObservationIgnored private var tries = 0 + @ObservationIgnored private var failure: String? + @ObservationIgnored private var hasEnded = false + @ObservationIgnored private var isInterrupted = false + @ObservationIgnored private var alignedAt = Date.distantPast + + private static let maxTries = 3 + /// 与房间差多少秒才校准,以及两次校准至少隔多久。 + private static let maxDrift = 1.8 + private static let alignInterval = 5.0 + + init(client: APIClient) { + self.client = client + } + + func follow(_ playback: Playback, clock: PlaybackClock) { + activate() + let changedEntry = playback.entry?.id != self.playback?.entry?.id + let jumped = playback.basePositionSec != self.playback?.basePositionSec + self.playback = playback + self.clock = clock + if changedEntry { + tries = 0 + load() + } else if jumped { + align() + } + update() + } + + func stop() { + ticker?.cancel() + ticker = nil + observers.forEach(NotificationCenter.default.removeObserver) + observers = [] + let remote = MPRemoteCommandCenter.shared() + remote.playCommand.removeTarget(nil) + remote.pauseCommand.removeTarget(nil) + playback = nil + load() + update() + try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) + } + + // MARK: 播放 + + private func load() { + loading?.cancel() + loading = nil + player.replaceCurrentItem(with: nil) + hasEnded = false + failure = nil + guard let entry = playback?.entry, entry.track.isStreamable else { return } + tries += 1 + let wait = tries - 1 + loading = Task { + do { + try await Task.sleep(for: .seconds(wait)) + let url = try await client.streamURL(entry.id) + try Task.checkCancellation() + player.replaceCurrentItem(with: AVPlayerItem(url: url)) + } catch { + guard !Task.isCancelled else { return } + // 服务端明确拒绝的,再试也一样。 + let refused = (error as? APIError).map { (400..<500).contains($0.status) && $0.status != 429 } ?? false + failed(error, retry: !refused) + } + } + } + + private func failed(_ error: Error?, retry: Bool) { + if retry, tries < Self.maxTries { + load() + } else { + player.replaceCurrentItem(with: nil) + failure = error?.localizedDescription ?? "音频无法播放" + } + } + + private func align() { + guard let playback, let item = player.currentItem, item.status == .readyToPlay else { return } + alignedAt = Date() + let target = clock.position(of: playback) + player.seek(to: CMTime(seconds: target, preferredTimescale: 600)) + } + + /// 让播放器符合房间状态。每半秒执行一次,状态变化时也会执行。 + private func update() { + let next = advance() + guard next != state else { return } + state = next + updateNowPlaying() + } + + private func advance() -> State { + guard let playback, let entry = playback.entry else { return .idle } + guard entry.track.isStreamable else { return .unsupported } + if let item = player.currentItem, item.status == .failed { + failed(item.error, retry: true) + } + if let failure { return .failed(failure) } + + guard isListening, playback.status == .playing, !isInterrupted else { + player.pause() + return isListening ? .paused : .off + } + guard let item = player.currentItem, item.status == .readyToPlay else { return .loading } + + let current = player.currentTime().seconds + if !hasEnded, item.duration.isNumeric, current >= item.duration.seconds - 0.3 { + hasEnded = true + if playback.durationSec == nil { + Task { try? await client.reportCompleted(entry.id) } + } + } + if hasEnded { return .playing } + + if player.rate == 0 { + try? AVAudioSession.sharedInstance().setCategory(.playback) + try? AVAudioSession.sharedInstance().setActive(true) + align() + player.play() + } else if player.timeControlStatus == .playing, + abs(current - clock.position(of: playback)) >= Self.maxDrift, + Date().timeIntervalSince(alignedAt) >= Self.alignInterval + { + align() + } + return player.timeControlStatus == .playing ? .playing : .loading + } + + // MARK: 系统 + + private func activate() { + guard ticker == nil else { return } + ticker = Task { [weak self] in + while !Task.isCancelled { + try? await Task.sleep(for: .milliseconds(500)) + self?.update() + } + } + + let center = NotificationCenter.default + observers = [ + center.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { + [weak self] note in + let began = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt + == AVAudioSession.InterruptionType.began.rawValue + MainActor.assumeIsolated { + self?.isInterrupted = began + self?.update() + } + }, + // 拔掉耳机后不要改用扬声器继续放。 + center.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { + [weak self] note in + let unplugged = note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt + == AVAudioSession.RouteChangeReason.oldDeviceUnavailable.rawValue + MainActor.assumeIsolated { + if unplugged { self?.isListening = false } + } + }, + ] + + // 锁屏上的播放、暂停只管本机,不会让整个房间停下来。 + let remote = MPRemoteCommandCenter.shared() + remote.playCommand.addTarget { @Sendable [weak self] _ in + Task { @MainActor in self?.isListening = true } + return .success + } + remote.pauseCommand.addTarget { @Sendable [weak self] _ in + Task { @MainActor in self?.isListening = false } + return .success + } + } + + private func updateNowPlaying() { + guard let playback, let track = playback.entry?.track, track.isStreamable else { + MPNowPlayingInfoCenter.default().nowPlayingInfo = nil + return + } + var info: [String: Any] = [ + MPMediaItemPropertyTitle: track.title, + MPMediaItemPropertyArtist: track.artist, + MPNowPlayingInfoPropertyElapsedPlaybackTime: clock.position(of: playback), + MPNowPlayingInfoPropertyPlaybackRate: state == .playing ? 1.0 : 0.0, + ] + info[MPMediaItemPropertyPlaybackDuration] = playback.durationSec + MPNowPlayingInfoCenter.default().nowPlayingInfo = info + } +} diff --git a/ios/App/RoomSession.swift b/ios/App/RoomSession.swift new file mode 100644 index 0000000..309c13e --- /dev/null +++ b/ios/App/RoomSession.swift @@ -0,0 +1,143 @@ +import Foundation +import MusicGoKit +import Observation + +/// 一个房间的连接和状态。服务端是唯一事实来源,这里只保留它最近一次给的快照。 +@MainActor @Observable +final class RoomSession { + let client: APIClient + let player: RoomPlayer + private(set) var room: Room? + private(set) var me: User? + private(set) var clock = PlaybackClock() + private(set) var isLive = false + /// 凭据失效或被移出房间,不再重连。 + private(set) var endedReason: String? + /// 给用户看的一次性提示。 + var notice: String? + + @ObservationIgnored private var connection: Task? + + init(link: EntryLink) { + client = APIClient(link: link) + player = RoomPlayer(client: client) + } + + func start() { + guard connection == nil else { return } + connection = Task { await run() } + } + + func stop() { + connection?.cancel() + connection = nil + player.stop() + } + + var position: TimeInterval { room.map { clock.position(of: $0.playback) } ?? 0 } + var canControl: Bool { me.flatMap { room?.canControl($0.id) } ?? false } + var canSkip: Bool { me.flatMap { room?.canSkip($0.id) } ?? false } + var hasVoted: Bool { me.map { room?.votes.voters.contains($0.id) ?? false } ?? false } + + // MARK: 操作 + + func togglePause() async { + let paused = room?.playback.status == .paused + await perform { try await paused ? self.client.resume() : self.client.pause() } + } + + func skip() async { + guard let entry = room?.playback.entry else { return } + let direct = canSkip + await perform { + if direct { + try await self.client.skip(entry.id) + } else { + let vote = try await self.client.voteSkip(entry.id) + if !vote.skipped { self.notice = "已投票切歌(\(vote.count)/\(vote.threshold))" } + } + } + } + + private func perform(_ action: () async throws -> Void) async { + do { + try await action() + } catch { + notice = error.localizedDescription + } + } + + // MARK: 连接 + + private func run() async { + var delay = 1 + while !Task.isCancelled { + do { + try await connectOnce { delay = 1 } + } catch let error as APIError where error.endsSession { + endedReason = error.localizedDescription + player.stop() + return + } catch {} + isLive = false + try? await Task.sleep(for: .seconds(delay)) + delay = min(delay * 2, 15) + } + } + + /// 连到断开为止。 + private func connectOnce(onLive: () -> Void) async throws { + me = try await client.me() + clock = try await client.clock() + apply(try await client.room()) + + let socket = URLSession.shared.webSocketTask(with: client.webSocketRequest()) + socket.resume() + let ping = Task { + while !Task.isCancelled { + try await Task.sleep(for: .seconds(25)) + do { + try await socket.send(.string(#"{"type":"ping"}"#)) + } catch { + socket.cancel() + throw error + } + } + } + defer { + ping.cancel() + socket.cancel(with: .goingAway, reason: nil) + } + + try await withTaskCancellationHandler { + while !Task.isCancelled { + let data: Data + switch try await socket.receive() { + case .string(let text): data = Data(text.utf8) + case .data(let raw): data = raw + @unknown default: continue + } + switch try RoomMessage(data) { + case .snapshot(let room): + isLive = true + onLive() + apply(room) + case .changed: + try await socket.send(.string(#"{"type":"sync"}"#)) + case .refused: + return + case .other: + break + } + } + } onCancel: { + socket.cancel() + } + } + + private func apply(_ room: Room) { + guard !Task.isCancelled else { return } + self.room = room + player.follow(room.playback, clock: clock) + } +} diff --git a/ios/App/RoomView.swift b/ios/App/RoomView.swift new file mode 100644 index 0000000..d2f103b --- /dev/null +++ b/ios/App/RoomView.swift @@ -0,0 +1,206 @@ +import MusicGoKit +import SwiftUI + +struct RoomView: View { + let session: RoomSession + let onLeave: () -> Void + + @State private var isSearching = false + @State private var isConfirmingLeave = false + + var body: some View { + @Bindable var session = session + NavigationStack { + Group { + if let reason = session.endedReason { + ContentUnavailableView { + Label("无法进入房间", systemImage: "person.crop.circle.badge.xmark") + } description: { + Text(reason) + } actions: { + Button("换一个链接", action: onLeave) + } + } else if let room = session.room { + content(room) + } else { + ProgressView("正在连接…") + } + } + .navigationTitle(session.room?.name ?? "MusicGo") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button("退出", systemImage: "rectangle.portrait.and.arrow.right") { isConfirmingLeave = true } + } + ToolbarItem(placement: .topBarTrailing) { + Button("点歌", systemImage: "plus") { isSearching = true } + .disabled(session.room == nil || session.endedReason != nil) + .accessibilityIdentifier("open-search") + } + } + } + .sheet(isPresented: $isSearching) { SearchView(client: session.client) } + .confirmationDialog("退出后要重新粘贴进入链接", isPresented: $isConfirmingLeave, titleVisibility: .visible) { + Button("退出", role: .destructive, action: onLeave) + } + .alert( + session.notice ?? "", + isPresented: Binding(get: { session.notice != nil }, set: { if !$0 { session.notice = nil } }) + ) { + Button("好") {} + } + .task { session.start() } + } + + private func content(_ room: Room) -> some View { + List { + Section { + NowPlayingView(session: session, room: room) + .frame(maxWidth: .infinity) + .listRowBackground(Color.clear) + .listRowSeparator(.hidden) + } header: { + Label( + session.isLive ? "\(room.online.count) 人在听" : "正在重新连接…", + systemImage: session.isLive ? "person.2.fill" : "wifi.exclamationmark") + } + Section("待播 \(room.queue.count) 首") { + if room.queue.isEmpty { + Text("还没有待播的歌").foregroundStyle(.secondary) + } + ForEach(room.queue) { entry in + TrackRow(track: entry.track, detail: "\(room.memberName(entry.requestedBy)) 点的") + } + } + } + } +} + +private struct NowPlayingView: View { + let session: RoomSession + let room: Room + + var body: some View { + if let entry = room.playback.entry { + VStack(spacing: 16) { + CoverView(url: entry.track.cover) + .frame(width: 240, height: 240) + .shadow(color: .black.opacity(0.2), radius: 12, y: 6) + VStack(spacing: 4) { + Text(entry.track.title) + .font(.title3.bold()) + .accessibilityIdentifier("now-playing-title") + Text(entry.track.artist).foregroundStyle(.secondary) + Text("\(room.memberName(entry.requestedBy)) 点的").font(.footnote).foregroundStyle(.secondary) + } + .multilineTextAlignment(.center) + TimelineView(.periodic(from: .now, by: 0.5)) { _ in progress } + controls + Label(playerText, systemImage: playerIcon) + .font(.footnote) + .foregroundStyle(.secondary) + .accessibilityIdentifier("player-state") + } + .padding(.vertical, 8) + } else { + ContentUnavailableView("现在没有在放歌", systemImage: "music.note", description: Text("点右上角的 + 点一首")) + } + } + + private var progress: some View { + let duration = room.playback.durationSec + return VStack(spacing: 4) { + ProgressView(value: duration.map { $0 > 0 ? min(1, session.position / $0) : 0 } ?? 0) + HStack { + Text(formatTime(session.position)) + Spacer() + Text(formatTime(duration)) + } + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + + private var controls: some View { + HStack(spacing: 32) { + Button( + session.player.isListening ? "本机静音" : "在本机播放", + systemImage: session.player.isListening ? "speaker.wave.2.fill" : "speaker.slash.fill" + ) { session.player.isListening.toggle() } + if session.canControl { + let paused = room.playback.status == .paused + Button(paused ? "继续" : "暂停", systemImage: paused ? "play.fill" : "pause.fill") { + Task { await session.togglePause() } + } + .font(.largeTitle) + .accessibilityIdentifier("toggle-pause") + } + Button(session.canSkip ? "切歌" : "投票切歌", systemImage: session.canSkip ? "forward.fill" : "hand.thumbsdown") { + Task { await session.skip() } + } + .disabled(!session.canSkip && session.hasVoted) + .accessibilityIdentifier("skip") + } + .font(.title2) + .labelStyle(.iconOnly) + // 列表行里有多个按钮时,默认样式会让整行一起响应。 + .buttonStyle(.borderless) + } + + private var playerText: String { + switch session.player.state { + case .idle: "没有在播放" + case .loading: "正在加载…" + case .playing: "正在本机播放" + case .paused: "已暂停" + case .off: "本机已静音" + case .unsupported: "这首歌暂时不能在 App 里播放,请用网页版收听" + case .failed(let reason): reason + } + } + + private var playerIcon: String { + switch session.player.state { + case .playing: "waveform" + case .unsupported, .failed: "exclamationmark.triangle" + case .off: "speaker.slash" + default: "music.note" + } + } +} + +struct TrackRow: View { + let track: Track + let detail: String + + var body: some View { + HStack(spacing: 12) { + CoverView(url: track.cover).frame(width: 44, height: 44) + VStack(alignment: .leading, spacing: 2) { + Text(track.title).lineLimit(1) + Text([track.artist, detail].filter { !$0.isEmpty }.joined(separator: " · ")) + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + } +} + +struct CoverView: View { + let url: URL? + + var body: some View { + // 先占住方形,图片再大也只能填满它。 + Color(.secondarySystemFill) + .overlay { + AsyncImage(url: url) { image in + image.resizable().scaledToFill() + } placeholder: { + Image(systemName: "music.note").foregroundStyle(.secondary) + } + } + .clipShape(.rect(cornerRadius: 8)) + .accessibilityHidden(true) + } +} diff --git a/ios/App/SearchView.swift b/ios/App/SearchView.swift new file mode 100644 index 0000000..8095b11 --- /dev/null +++ b/ios/App/SearchView.swift @@ -0,0 +1,101 @@ +import MusicGoKit +import SwiftUI + +/// 搜歌名,或粘贴歌曲链接直接点。 +struct SearchView: View { + let client: APIClient + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + @State private var sources: [Source] = [] + @State private var source = "" + @State private var results: [Track] = [] + @State private var searched = "" + @State private var isBusy = false + @State private var problem: String? + + var body: some View { + NavigationStack { + List { + if sources.count > 1 { + Picker("音源", selection: $source) { + ForEach(sources) { Text($0.name).tag($0.id) } + } + .onChange(of: source) { if !searched.isEmpty { submit() } } + } + if let problem { + Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.red) + } + ForEach(results) { track in + Button { + run { try await client.enqueue(track) } then: { _ in dismiss() } + } label: { + HStack { + TrackRow(track: track, detail: formatTime(track.durationSec)) + Spacer() + Image(systemName: "plus.circle").foregroundStyle(.tint) + } + } + .tint(.primary) + .accessibilityIdentifier("search-result") + } + } + .overlay { + if isBusy { + ProgressView() + } else if results.isEmpty, problem == nil, !searched.isEmpty { + ContentUnavailableView.search(text: searched) + } + } + .disabled(isBusy) + .navigationTitle("点歌") + .navigationBarTitleDisplayMode(.inline) + .searchable( + text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "歌名、歌手,或歌曲链接") + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .onSubmit(of: .search, submit) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() } } + } + .task { + do { + sources = try await client.sources() + source = sources.first?.id ?? "" + } catch { + problem = error.localizedDescription + } + } + } + } + + private func submit() { + let text = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty else { return } + if text.contains("://") { + run { try await client.enqueue(url: text) } then: { _ in dismiss() } + } else { + let source = source + run { try await client.search(text, source: source) } then: { + results = $0 + searched = text + } + } + } + + private func run( + _ request: @escaping @Sendable () async throws -> T, then done: @escaping (T) -> Void + ) { + guard !isBusy else { return } + isBusy = true + problem = nil + Task { + defer { isBusy = false } + do { + done(try await request()) + } catch { + problem = error.localizedDescription + } + } + } +} diff --git a/ios/MusicGoKit/Package.swift b/ios/MusicGoKit/Package.swift new file mode 100644 index 0000000..873ce9f --- /dev/null +++ b/ios/MusicGoKit/Package.swift @@ -0,0 +1,13 @@ +// swift-tools-version: 6.0 +import PackageDescription + +// 不依赖界面的部分:接口、数据结构、进入链接、进度推算。在 Linux 上也能编译和测试。 +let package = Package( + name: "MusicGoKit", + platforms: [.iOS(.v17), .macOS(.v14)], + products: [.library(name: "MusicGoKit", targets: ["MusicGoKit"])], + targets: [ + .target(name: "MusicGoKit"), + .testTarget(name: "MusicGoKitTests", dependencies: ["MusicGoKit"]), + ] +) diff --git a/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift new file mode 100644 index 0000000..34ed0d8 --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift @@ -0,0 +1,185 @@ +import Foundation + +#if canImport(FoundationNetworking) + import FoundationNetworking +#endif + +public struct APIError: Error, Sendable, Equatable, LocalizedError { + public let status: Int + public let code: String + public let message: String + + init(status: Int, body: Data) { + struct Body: Decodable { + struct Detail: Decodable { + let code: String + let message: String + } + let error: Detail + } + let detail = try? JSON.decoder.decode(Body.self, from: body).error + self.status = status + code = detail?.code ?? "internal" + message = detail?.message ?? "服务器返回了错误(HTTP \(status))" + } + + public var errorDescription: String? { + switch code { + case "unauthorized": "登录凭据无效或已吊销,请重新粘贴进入链接" + case "stale_entry": "歌曲已经切换了" + case "duplicate_track": "这首歌已在待播队列中" + default: message + } + } + + /// 重试也没用:凭据失效、不是成员,或房间不存在。 + public var endsSession: Bool { ["unauthorized", "forbidden", "not_found"].contains(code) } +} + +public struct APIClient: Sendable { + public let link: EntryLink + private let session: URLSession + + public init(link: EntryLink, session: URLSession = .shared) { + self.link = link + self.session = session + } + + // MARK: 读取 + + public func me() async throws -> User { + try await get("/v1/me") + } + + public func clock() async throws -> PlaybackClock { + struct Response: Decodable { + let unixMs: Double + } + let sent = Date() + let time: Response = try await get("/v1/time") + return PlaybackClock(sent: sent, received: Date(), serverUnixMs: time.unixMs) + } + + public func room() async throws -> Room { + struct Response: Decodable { + let room: Room + } + let response: Response = try await get(roomPath) + return response.room + } + + public func sources() async throws -> [Source] { + struct Response: Decodable { + let sources: [Source] + } + let response: Response = try await get("/v1/sources") + return response.sources + } + + public func search(_ query: String, source: String) async throws -> [Track] { + struct Response: Decodable { + let tracks: [Track] + } + let response: Response = try await get("/v1/tracks/search", query: ["source": source, "q": query, "limit": "20"]) + return response.tracks + } + + // MARK: 点歌与播放 + + @discardableResult + public func enqueue(_ track: Track) async throws -> QueueEntry { + try await enqueue(["source": track.source, "track_id": track.sourceId]) + } + + @discardableResult + public func enqueue(url: String) async throws -> QueueEntry { + try await enqueue(["url": url]) + } + + private func enqueue(_ body: [String: String]) async throws -> QueueEntry { + struct Response: Decodable { + let entry: QueueEntry + } + let response: Response = try await post("\(roomPath)/queue", body) + return response.entry + } + + public func skip(_ entryID: String) async throws { + try await act("skip", ["entry_id": entryID]) + } + + public func voteSkip(_ entryID: String) async throws -> VoteResult { + try await post("\(roomPath)/playback/vote-skip", ["entry_id": entryID]) + } + + public func pause() async throws { try await act("pause", [:]) } + public func resume() async throws { try await act("resume", [:]) } + + /// 时长未知的歌,服务端靠客户端上报播完来切歌。 + public func reportCompleted(_ entryID: String) async throws { + try await act("completed", ["entry_id": entryID]) + } + + /// 当前歌曲的音频地址。地址本身就是凭据,不要记录或分享。 + public func streamURL(_ entryID: String) async throws -> URL { + struct Response: Decodable { + let url: String + } + let response: Response = try await post("\(roomPath)/playback/stream", ["entry_id": entryID]) + guard let url = URL(string: response.url, relativeTo: link.server) else { throw URLError(.badURL) } + return url.absoluteURL + } + + /// 实时连接的请求。连着就算在线收听。 + public func webSocketRequest() -> URLRequest { + var parts = URLComponents(url: link.server, resolvingAgainstBaseURL: false)! + parts.scheme = parts.scheme == "http" ? "ws" : "wss" + parts.path = "\(roomPath)/ws" + var request = URLRequest(url: parts.url!) + request.setValue("Bearer \(link.token)", forHTTPHeaderField: "Authorization") + return request + } + + // MARK: 请求 + + private var roomPath: String { "/v1/rooms/\(link.roomID)" } + + private struct Ignored: Decodable {} + + private func act(_ action: String, _ body: [String: String]) async throws { + let _: Ignored = try await post("\(roomPath)/playback/\(action)", body) + } + + private func get(_ path: String, query: [String: String] = [:]) async throws -> T { + try await send(request(path, query: query)) + } + + private func post(_ path: String, _ body: [String: String]) async throws -> T { + var request = request(path) + request.httpMethod = "POST" + request.httpBody = try JSONEncoder().encode(body) + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue(UUID().uuidString, forHTTPHeaderField: "Idempotency-Key") + return try await send(request) + } + + func request(_ path: String, query: [String: String] = [:]) -> URLRequest { + var parts = URLComponents(url: link.server, resolvingAgainstBaseURL: false)! + parts.path = path + if !query.isEmpty { + parts.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } + // URLComponents 不转义 +,而服务端会把它当成空格。 + parts.percentEncodedQuery = parts.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") + } + var request = URLRequest(url: parts.url!, timeoutInterval: 20) + request.setValue("Bearer \(link.token)", forHTTPHeaderField: "Authorization") + return request + } + + private func send(_ request: URLRequest) async throws -> T { + let (data, response) = try await session.data(for: request) + let status = (response as? HTTPURLResponse)?.statusCode ?? 0 + guard (200..<300).contains(status) else { throw APIError(status: status, body: data) } + return try JSON.decoder.decode(T.self, from: data) + } +} diff --git a/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift b/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift new file mode 100644 index 0000000..e245db0 --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift @@ -0,0 +1,52 @@ +import Foundation + +/// 房间的进入链接:`https://<服务器>/rooms/<房间>#token=<令牌>`, +/// 或 `https://<服务器>/?room=<房间>#token=<令牌>`。服务器地址就来自链接,App 里不写死。 +public struct EntryLink: Codable, Sendable, Equatable { + public let server: URL + public let roomID: String + public let token: String + + public enum Problem: Error, Equatable, LocalizedError { + case notALink, missingRoom, missingToken + + public var errorDescription: String? { + switch self { + case .notALink: "这不是网页链接,请粘贴以 https:// 开头的完整链接" + case .missingRoom: "链接里没有房间,请重新复制完整链接" + case .missingToken: "链接里没有登录凭据,请粘贴自己的进入链接" + } + } + } + + public init(_ text: String) throws(Problem) { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard let link = URLComponents(string: trimmed), + let scheme = link.scheme?.lowercased(), scheme == "https" || scheme == "http", + let host = link.host, !host.isEmpty + else { throw .notALink } + + var origin = URLComponents() + origin.scheme = scheme + origin.host = host + origin.port = link.port + guard let server = origin.url else { throw .notALink } + + var fragment = URLComponents() + fragment.percentEncodedQuery = link.percentEncodedFragment + func value(_ name: String, in parts: URLComponents) -> String? { + parts.queryItems?.first { $0.name == name }?.value.flatMap { $0.isEmpty ? nil : $0 } + } + + let path = link.path.split(separator: "/") + let pathRoom = path.count >= 2 && path[0] == "rooms" ? String(path[1]) : nil + guard let room = pathRoom ?? value("room", in: fragment) ?? value("room", in: link), + room.hasPrefix("r_") + else { throw .missingRoom } + guard let token = value("token", in: fragment) ?? value("token", in: link) else { throw .missingToken } + + self.server = server + self.roomID = room + self.token = token + } +} diff --git a/ios/MusicGoKit/Sources/MusicGoKit/Models.swift b/ios/MusicGoKit/Sources/MusicGoKit/Models.swift new file mode 100644 index 0000000..661f872 --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/Models.swift @@ -0,0 +1,148 @@ +import Foundation + +// 字段含义见 docs/api.md。这里只声明客户端用到的字段。 + +public struct User: Codable, Sendable, Equatable { + public let id: String + public let name: String +} + +public struct Source: Codable, Sendable, Equatable, Identifiable { + public let id: String + public let name: String +} + +public struct Track: Codable, Sendable, Equatable, Identifiable { + public struct Capabilities: Codable, Sendable, Equatable { + /// 音频由服务端转发,可以直接交给播放器。 + public let audioStream: Bool? + } + + public let source: String + public let sourceId: String + public let title: String + public let artist: String + public let durationSec: Double? + public let coverUrl: String + public let capabilities: Capabilities + + public var id: String { "\(source)/\(sourceId)" } + public var isStreamable: Bool { capabilities.audioStream == true } + public var cover: URL? { coverUrl.isEmpty ? nil : URL(string: coverUrl) } +} + +public struct QueueEntry: Codable, Sendable, Equatable, Identifiable { + public let id: String + public let track: Track + public let requestedBy: String +} + +public struct Playback: Codable, Sendable, Equatable { + public enum Status: String, Codable, Sendable { + case playing, paused, idle + } + + public let entry: QueueEntry? + public let status: Status + public let positionSec: Double + public let durationSec: Double? + public let basePositionSec: Double + public let baseAt: Date? +} + +public struct Member: Codable, Sendable, Equatable { + public let userId: String + public let name: String + public let role: String +} + +public struct Votes: Codable, Sendable, Equatable { + public let count: Int + public let threshold: Int + public let voters: [String] +} + +public struct Room: Codable, Sendable, Equatable { + public let id: String + public let name: String + public let revision: Int + public let members: [Member] + public let queue: [QueueEntry] + public let playback: Playback + public let votes: Votes + public let online: [String] + + public func memberName(_ userID: String) -> String { + members.first { $0.userId == userID }?.name ?? "已离开的成员" + } + + /// 暂停、继续只有房主和管理员能用。 + public func canControl(_ userID: String) -> Bool { + members.contains { $0.userId == userID && ($0.role == "owner" || $0.role == "admin") } + } + + /// 能直接切歌;不能的话只能投票。 + public func canSkip(_ userID: String) -> Bool { + canControl(userID) || playback.entry?.requestedBy == userID + } +} + +public struct VoteResult: Codable, Sendable, Equatable { + public let count: Int + public let threshold: Int + public let skipped: Bool +} + +/// WebSocket 消息。房间变化时一律重新要快照,所以事件内容不用解析。 +public enum RoomMessage: Sendable, Equatable { + case snapshot(Room) + case changed + /// 服务端拒绝了连接。重连时的 HTTP 请求会给出具体原因。 + case refused + case other + + public init(_ data: Data) throws { + struct Envelope: Decodable { + let type: String + } + struct Snapshot: Decodable { + let state: Room + } + switch try JSON.decoder.decode(Envelope.self, from: data).type { + case "snapshot": self = .snapshot(try JSON.decoder.decode(Snapshot.self, from: data).state) + case "event": self = .changed + case "error": self = .refused + default: self = .other + } + } +} + +enum JSON { + static var decoder: JSONDecoder { + let d = JSONDecoder() + d.keyDecodingStrategy = .convertFromSnakeCase + d.dateDecodingStrategy = .custom { decoder in + let container = try decoder.singleValueContainer() + let text = try container.decode(String.self) + guard let date = parseDate(text) else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "时间格式错误:\(text)") + } + return date + } + return d + } + + /// 服务端的小数秒最多 9 位,系统的解析器不保证认得,所以自己处理小数部分。 + static func parseDate(_ text: String) -> Date? { + var whole = text + var fraction = 0.0 + if let dot = text.firstIndex(of: ".") { + let end = text[dot...].dropFirst().firstIndex { !$0.isNumber } ?? text.endIndex + guard let value = Double("0" + text[dot.. TimeInterval { + let position: TimeInterval + switch playback.status { + case .idle: return 0 + case .paused: position = playback.basePositionSec + case .playing: + if let base = playback.baseAt { + position = playback.basePositionSec + max(0, now.timeIntervalSince(base) + offset) + } else { + position = playback.positionSec + } + } + return min(max(0, position), playback.durationSec ?? .infinity) + } +} + +public func formatTime(_ seconds: TimeInterval?) -> String { + guard let seconds, seconds.isFinite, seconds >= 0 else { return "--:--" } + let total = Int(seconds) + func pad(_ n: Int) -> String { n < 10 ? "0\(n)" : "\(n)" } + return total >= 3600 + ? "\(total / 3600):\(pad(total / 60 % 60)):\(pad(total % 60))" + : "\(total / 60):\(pad(total % 60))" +} diff --git a/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift new file mode 100644 index 0000000..a0d2a55 --- /dev/null +++ b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift @@ -0,0 +1,115 @@ +import Foundation +import Testing + +@testable import MusicGoKit + +@Suite struct EntryLinkTests { + @Test(arguments: [ + "https://musicgo.example.com/rooms/r_1#token=mgt_a", + " https://musicgo.example.com/rooms/r_1/#token=mgt_a\n", + "https://musicgo.example.com/?room=r_1#token=mgt_a", + "https://musicgo.example.com/#room=r_1&token=mgt_a", + ]) + func parses(_ text: String) throws { + let link = try EntryLink(text) + #expect(link.server.absoluteString == "https://musicgo.example.com") + #expect(link.roomID == "r_1") + #expect(link.token == "mgt_a") + } + + @Test func keepsPort() throws { + #expect(try EntryLink("http://localhost:8870/rooms/r_1#token=t").server.absoluteString == "http://localhost:8870") + } + + @Test func explainsWhatIsMissing() { + #expect(throws: EntryLink.Problem.notALink) { try EntryLink("mgt_a") } + #expect(throws: EntryLink.Problem.notALink) { try EntryLink("") } + #expect(throws: EntryLink.Problem.missingRoom) { try EntryLink("https://musicgo.example.com/#token=t") } + #expect(throws: EntryLink.Problem.missingToken) { try EntryLink("https://musicgo.example.com/rooms/r_1") } + } +} + +@Suite struct DecodingTests { + // 取自真实服务端的响应。 + static let room = """ + {"id":"r_1","name":"test","revision":4,"created_at":"2026-12-05T00:45:00.144804454Z","invite_code":"x", + "settings":{"name":"test","vote_ratio":0.5}, + "members":[{"user_id":"u_1","name":"iOS","kind":"human","role":"owner","joined_at":"2026-12-05T00:45:00.144804454Z"}, + {"user_id":"u_2","name":"B","kind":"human","role":"member","joined_at":"2026-12-05T00:45:00Z"}], + "queue":[],"playback":{"entry_id":"e_1","entry":{"id":"e_1","track":{"source":"fake","source_id":"song1", + "title":"Fake","artist":"A","duration_sec":null,"cover_url":"","url":"fake://track/song1", + "capabilities":{"background_playback":true}},"requested_by":"u_2","queued_at":"2026-12-05T00:45:00.167982579Z"}, + "status":"playing","position_sec":0.01,"duration_sec":null,"base_position_sec":0, + "base_at":"2026-12-05T00:45:00.167982579Z","started_at":"2026-12-05T00:45:00.167982579Z"}, + "votes":{"count":0,"threshold":1,"voters":[]},"online":[],"bindings":[],"history":[]} + """ + + @Test func snapshot() throws { + let message = try RoomMessage(Data(#"{"type":"snapshot","revision":4,"state":\#(Self.room)}"#.utf8)) + guard case .snapshot(let room) = message else { Issue.record("不是快照"); return } + #expect(room.playback.entry?.track.isStreamable == false) + #expect(room.playback.entry?.track.cover == nil) + #expect(room.canControl("u_1") && room.canSkip("u_1")) + #expect(!room.canControl("u_2") && room.canSkip("u_2")) + #expect(!room.canSkip("u_3")) + } + + @Test func idlePlayback() throws { + let text = #"{"entry_id":null,"entry":null,"status":"idle","position_sec":0,"duration_sec":null,"base_position_sec":0,"base_at":null,"started_at":null}"# + let playback = try JSON.decoder.decode(Playback.self, from: Data(text.utf8)) + #expect(playback.entry == nil && PlaybackClock().position(of: playback) == 0) + } + + @Test func otherMessages() throws { + #expect(try RoomMessage(Data(#"{"type":"event","revision":5,"payload":{"type":"x"}}"#.utf8)) == .changed) + #expect(try RoomMessage(Data(#"{"type":"pong"}"#.utf8)) == .other) + #expect(try RoomMessage(Data(#"{"type":"error","error":{}}"#.utf8)) == .refused) + } + + @Test func errors() { + let error = APIError(status: 403, body: Data(#"{"error":{"code":"forbidden","message":"不是房间成员"}}"#.utf8)) + #expect(error.endsSession && error.localizedDescription == "不是房间成员") + #expect(!APIError(status: 502, body: Data("".utf8)).endsSession) + } + + @Test func dates() throws { + let whole = try #require(JSON.parseDate("2026-12-05T00:45:00Z")) + let nano = try #require(JSON.parseDate("2026-12-05T00:45:00.167982579Z")) + #expect(abs(nano.timeIntervalSince(whole) - 0.167982579) < 1e-5) + #expect(JSON.parseDate("yesterday") == nil) + } +} + +@Suite struct PlaybackClockTests { + let base = Date(timeIntervalSince1970: 1000) + + func playback(_ status: Playback.Status, duration: Double? = 60) -> Playback { + Playback(entry: nil, status: status, positionSec: 10, durationSec: duration, basePositionSec: 10, baseAt: base) + } + + @Test func followsTheServerClock() { + let clock = PlaybackClock( + sent: Date(timeIntervalSince1970: 990), received: Date(timeIntervalSince1970: 992), serverUnixMs: 996_000) + #expect(clock.offset == 5) + #expect(clock.position(of: playback(.playing), at: base) == 15) + #expect(clock.position(of: playback(.paused), at: base + 30) == 10) + #expect(clock.position(of: playback(.playing), at: base + 300) == 60) + #expect(clock.position(of: playback(.playing, duration: nil), at: base + 300) == 315) + } + + @Test func formats() { + #expect(formatTime(nil) == "--:--") + #expect(formatTime(65.9) == "1:05") + #expect(formatTime(3661) == "1:01:01") + } +} + +@Suite struct RequestTests { + @Test func escapesQueriesAndKeepsTheTokenOutOfTheURL() throws { + let client = APIClient(link: try EntryLink("https://musicgo.example.com/rooms/r_1#token=mgt_a")) + let request = client.request("/v1/tracks/search", query: ["q": "a+b & 夏"]) + #expect(request.url?.absoluteString == "https://musicgo.example.com/v1/tracks/search?q=a%2Bb%20%26%20%E5%A4%8F") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer mgt_a") + #expect(client.webSocketRequest().url?.absoluteString == "wss://musicgo.example.com/v1/rooms/r_1/ws") + } +} diff --git a/ios/README.md b/ios/README.md new file mode 100644 index 0000000..64b42eb --- /dev/null +++ b/ios/README.md @@ -0,0 +1,29 @@ +# MusicGo iOS 客户端 + +最小可用版:登录、跟着房间一起听、看队列、搜索点歌、暂停和切歌。需要 iOS 17 或更高版本。 + +## 使用 + +粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在钥匙串。 + +- 静音和锁屏上的播放、暂停只管本机;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 +- YouTube 的歌还不能在 App 里播放,会提示改用网页版。 +- 房间空闲或暂停时切到后台,系统可能会挂起 App,回到前台后自动重连。 + +## 开发 + +```sh +brew install xcodegen +cd ios && xcodegen && open MusicGo.xcodeproj +``` + +`MusicGo.xcodeproj` 由 `project.yml` 生成,不进仓库。真机运行时,在 Xcode 里选自己的开发团队,需要时改 `PRODUCT_BUNDLE_IDENTIFIER`。 + +| 目录 | 内容 | +|---|---| +| `MusicGoKit/` | 接口、数据结构、链接解析、进度推算。Linux 上也能 `swift test` | +| `App/` | SwiftUI 界面、实时连接、播放 | +| `UITests/` | 对着真实服务端走完整流程的界面测试 | +| `scripts/test-server.sh` | 启动界面测试用的服务端,音源是 `testplugin/` 里的纯音 | + +没有 Mac 时,改动推到 PR,由 `.github/workflows/ios.yml` 编译、测试并上传模拟器截图(产物 `ios-screenshots`)。 diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift new file mode 100644 index 0000000..cc1d2e9 --- /dev/null +++ b/ios/UITests/MusicGoUITests.swift @@ -0,0 +1,77 @@ +import XCTest + +/// 对着真实的服务端走一遍:登录、搜索、点歌、出声、暂停、切歌。 +/// 服务端由 scripts/test-server.sh 启动,进入链接经 TEST_RUNNER_MUSICGO_LINK 传入。 +@MainActor +final class MusicGoUITests: XCTestCase { + func testListenTogether() throws { + continueAfterFailure = false + let link = try XCTUnwrap(ProcessInfo.processInfo.environment["MUSICGO_LINK"], "缺少 TEST_RUNNER_MUSICGO_LINK") + let app = XCUIApplication() + app.launch() + + let field = app.textFields["entry-link"] + XCTAssertTrue(field.waitForExistence(timeout: 30)) + field.tap() + field.typeText("not a link\n") + XCTAssertTrue(app.staticTexts["这不是网页链接,请粘贴以 https:// 开头的完整链接"].waitForExistence(timeout: 10)) + capture("1-login") + field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 12) + link + "\n") + + XCTAssertTrue(app.staticTexts["现在没有在放歌"].waitForExistence(timeout: 20)) + + order("first", in: app) + let title = app.staticTexts["now-playing-title"] + XCTAssertTrue(title.waitForExistence(timeout: 10)) + XCTAssertEqual(title.label, "first 1") + waitForPlayer("正在本机播放", in: app) + capture("3-playing") + + order("second", in: app) + XCTAssertTrue(app.staticTexts["second 1"].waitForExistence(timeout: 10)) + capture("4-queue") + + app.buttons["toggle-pause"].tap() + waitForPlayer("已暂停", in: app) + app.buttons["toggle-pause"].tap() + waitForPlayer("正在本机播放", in: app) + + app.buttons["skip"].tap() + expectation(for: NSPredicate(format: "label == %@", "second 1"), evaluatedWith: title) + waitForExpectations(timeout: 10) + waitForPlayer("正在本机播放", in: app) + + // 重新打开后仍是登录状态。 + app.terminate() + app.launch() + XCTAssertTrue(title.waitForExistence(timeout: 20)) + waitForPlayer("正在本机播放", in: app) + } + + private func order(_ query: String, in app: XCUIApplication) { + app.buttons["open-search"].tap() + let search = app.searchFields.firstMatch + XCTAssertTrue(search.waitForExistence(timeout: 10)) + search.tap() + search.typeText(query + "\n") + let result = app.buttons["search-result"].firstMatch + XCTAssertTrue(result.waitForExistence(timeout: 10)) + if query == "first" { capture("2-search") } + result.tap() + XCTAssertTrue(search.waitForNonExistence(timeout: 10)) + } + + private func waitForPlayer(_ text: String, in app: XCUIApplication) { + let state = app.descendants(matching: .any)["player-state"].firstMatch + let done = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", text), object: state) + let result = XCTWaiter.wait(for: [done], timeout: 30) + XCTAssertEqual(result, .completed, "播放状态是「\(state.exists ? state.label : "无")」,应为「\(text)」") + } + + private func capture(_ name: String) { + let shot = XCTAttachment(screenshot: XCUIScreen.main.screenshot()) + shot.name = name + shot.lifetime = .keepAlways + add(shot) + } +} diff --git a/ios/project.yml b/ios/project.yml new file mode 100644 index 0000000..f14bc7d --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,60 @@ +# 用 XcodeGen 生成 MusicGo.xcodeproj(不进仓库):cd ios && xcodegen +name: MusicGo +options: + bundleIdPrefix: dev.luckybot + deploymentTarget: + iOS: "17.0" + createIntermediateGroups: true +settings: + base: + SWIFT_VERSION: "6.0" + MARKETING_VERSION: "0.1.0" + CURRENT_PROJECT_VERSION: "1" +packages: + MusicGoKit: + path: MusicGoKit +targets: + MusicGo: + type: application + platform: iOS + sources: [App] + dependencies: + - package: MusicGoKit + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: dev.luckybot.musicgo + TARGETED_DEVICE_FAMILY: "1,2" + info: + path: App/Info.plist + properties: + CFBundleDisplayName: MusicGo + CFBundleShortVersionString: $(MARKETING_VERSION) + CFBundleVersion: $(CURRENT_PROJECT_VERSION) + CFBundleDevelopmentRegion: zh-Hans + UILaunchScreen: {} + UIBackgroundModes: [audio] + UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait] + UISupportedInterfaceOrientations~ipad: + - UIInterfaceOrientationPortrait + - UIInterfaceOrientationPortraitUpsideDown + - UIInterfaceOrientationLandscapeLeft + - UIInterfaceOrientationLandscapeRight + # 只放行本机和局域网的 http,其余必须 https + NSAppTransportSecurity: + NSAllowsLocalNetworking: true + MusicGoUITests: + type: bundle.ui-testing + platform: iOS + sources: [UITests] + dependencies: + - target: MusicGo + settings: + base: + GENERATE_INFOPLIST_FILE: YES +schemes: + MusicGo: + build: + targets: + MusicGo: all + test: + targets: [MusicGoUITests] diff --git a/ios/scripts/test-server.sh b/ios/scripts/test-server.sh new file mode 100755 index 0000000..83c8c80 --- /dev/null +++ b/ios/scripts/test-server.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# 启动一个给界面测试用的 MusicGo:全新的数据库、一个用户、一个房间、一个测试音源。 +# 用法:test-server.sh <空目录> [端口]。输出进入链接;进程号在 <目录>/pid,日志在 <目录>/log。 +set -euo pipefail + +root="$(cd "$(dirname "$0")/../.." && pwd)" +mkdir -p "$1" +dir="$(cd "$1" && pwd -P)" +port="${2:-8870}" +bin="$dir/musicgo" +export MUSICGO_DB="$dir/test.db" MUSICGO_SOURCES=tone +export MUSICGO_LYRICS_NETEASE=off MUSICGO_LYRICS_LRCLIB=off MUSICGO_LYRICS_QQ=off + +(cd "$root/server" && CGO_ENABLED=0 go build -o "$bin" ./cmd/musicgo) + +cp -R "$root/ios/testplugin" "$dir/tone-src" +python3 - "$dir/tone-src/tone.wav" <<'PY' +import math, struct, sys, wave +rate = 22050 +one = b"".join(struct.pack("&2 <<"$dir/log" 2>&1 "$dir/pid" +curl -fsS --retry 30 --retry-delay 1 --retry-connrefused "http://127.0.0.1:$port/v1/time" >/dev/null +room="$(MUSICGO_TOKEN="$token" "$bin" room create --name 周五音乐房 --server "http://127.0.0.1:$port" | grep -o 'r_[0-9a-f]*' | head -n 1)" +echo "http://localhost:$port/rooms/$room#token=$token" diff --git a/ios/testplugin/index.js b/ios/testplugin/index.js new file mode 100644 index 0000000..9891947 --- /dev/null +++ b/ios/testplugin/index.js @@ -0,0 +1,14 @@ +// 只给 iOS 的界面测试用:搜什么都有结果,播放的是 test-server.sh 生成的一段纯音。 +export function search({ query }) { + const tracks = [1, 2, 3].map((n) => ({ + id: `${query}-${n}`, + name: `${query} ${n}`, + artists: [{ name: '测试音' }], + duration: 120000, + })) + return { tracks, more: false } +} + +export function stream() { + return { url: 'file://__TONE__', type: 'wav' } +} diff --git a/ios/testplugin/plugin.json b/ios/testplugin/plugin.json new file mode 100644 index 0000000..f500e11 --- /dev/null +++ b/ios/testplugin/plugin.json @@ -0,0 +1,7 @@ +{ + "id": "tone", + "name": "测试音", + "version": "1.0.0", + "main": "index.js", + "playback": "stream" +} From 533da918efaf58f044eae660188b18500babcf28 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 08:52:49 +0800 Subject: [PATCH 2/9] =?UTF-8?q?fix(ios):=20=E9=80=9A=E8=BF=87=20Swift=206?= =?UTF-8?q?=20=E5=B9=B6=E5=8F=91=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ios.yml | 3 ++- README.md | 1 + ios/App/CredentialStore.swift | 12 +++++++----- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 4715585..ae2aa29 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -51,13 +51,14 @@ jobs: xcodebuild build-for-testing -quiet -project ios/MusicGo.xcodeproj -scheme MusicGo \ -destination "id=$DEVICE" - name: 界面测试 + id: ui run: | link="$(ios/scripts/test-server.sh "$RUNNER_TEMP/server")" TEST_RUNNER_MUSICGO_LINK="$link" xcodebuild test-without-building \ -project ios/MusicGo.xcodeproj -scheme MusicGo -destination "id=$DEVICE" \ -resultBundlePath "$RUNNER_TEMP/result.xcresult" - name: 取出截图 - if: always() + if: always() && steps.ui.outcome != 'skipped' run: | kill "$(cat "$RUNNER_TEMP/server/pid")" || true xcrun xcresulttool export attachments --path "$RUNNER_TEMP/result.xcresult" \ diff --git a/README.md b/README.md index 71a596d..b5230fd 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,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) | | `mcp/` | 给 AI Agent 用的 MCP 工具:服务端自带的 `/mcp` 远程入口,以及本地程序 | | `deploy/` | systemd、Caddy 配置,以及发布、备份、升级脚本 | | `docs/` | 文档 | diff --git a/ios/App/CredentialStore.swift b/ios/App/CredentialStore.swift index 814937d..2008318 100644 --- a/ios/App/CredentialStore.swift +++ b/ios/App/CredentialStore.swift @@ -4,11 +4,13 @@ import Security /// 进入链接里有令牌,所以存钥匙串,且不随备份换到别的设备。 enum CredentialStore { - private static let item: [CFString: Any] = [ - kSecClass: kSecClassGenericPassword, - kSecAttrService: "musicgo.entry-link", - kSecAttrAccount: "default", - ] + private static var item: [CFString: Any] { + [ + kSecClass: kSecClassGenericPassword, + kSecAttrService: "musicgo.entry-link", + kSecAttrAccount: "default", + ] + } static func load() -> EntryLink? { var query = item From e8db61a43678beae66cb7f8a41dd4f77511920e7 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:09:02 +0800 Subject: [PATCH 3/9] =?UTF-8?q?test(ios):=20=E4=BF=AE=E6=AD=A3=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E6=B5=8B=E8=AF=95=EF=BC=8C=E6=8B=86=E5=BC=80=20CI=20?= =?UTF-8?q?=E6=AD=A5=E9=AA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ios.yml | 7 +++++-- ios/UITests/MusicGoUITests.swift | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index ae2aa29..f3c4399 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -50,11 +50,14 @@ jobs: xcodebuild -version xcodebuild build-for-testing -quiet -project ios/MusicGo.xcodeproj -scheme MusicGo \ -destination "id=$DEVICE" + - name: 启动测试服务端 + run: echo "TEST_RUNNER_MUSICGO_LINK=$(ios/scripts/test-server.sh "$RUNNER_TEMP/server")" >> "$GITHUB_ENV" + - name: 启动模拟器 + run: xcrun simctl bootstatus "$DEVICE" -b - name: 界面测试 id: ui run: | - link="$(ios/scripts/test-server.sh "$RUNNER_TEMP/server")" - TEST_RUNNER_MUSICGO_LINK="$link" xcodebuild test-without-building \ + xcodebuild test-without-building \ -project ios/MusicGo.xcodeproj -scheme MusicGo -destination "id=$DEVICE" \ -resultBundlePath "$RUNNER_TEMP/result.xcresult" - name: 取出截图 diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index cc1d2e9..87aea43 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -16,6 +16,8 @@ final class MusicGoUITests: XCTestCase { field.typeText("not a link\n") XCTAssertTrue(app.staticTexts["这不是网页链接,请粘贴以 https:// 开头的完整链接"].waitForExistence(timeout: 10)) capture("1-login") + // 提交后键盘收起了,要重新点一下。 + field.tap() field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 12) + link + "\n") XCTAssertTrue(app.staticTexts["现在没有在放歌"].waitForExistence(timeout: 20)) From 1cb7a266bf3d5df18e1817402cbc7ca1eb7056c5 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:23:24 +0800 Subject: [PATCH 4/9] =?UTF-8?q?fix(ios):=20=E5=B0=81=E9=9D=A2=E5=BA=95?= =?UTF-8?q?=E8=89=B2=E4=B8=8D=E9=80=8F=E5=87=BA=E9=98=B4=E5=BD=B1=EF=BC=8C?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=8C=89=E6=96=87=E5=AD=97=E6=89=BE=E6=92=AD?= =?UTF-8?q?=E6=94=BE=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- ios/App/RoomView.swift | 2 +- ios/UITests/MusicGoUITests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ios/App/RoomView.swift b/ios/App/RoomView.swift index d2f103b..d5ae648 100644 --- a/ios/App/RoomView.swift +++ b/ios/App/RoomView.swift @@ -192,7 +192,7 @@ struct CoverView: View { var body: some View { // 先占住方形,图片再大也只能填满它。 - Color(.secondarySystemFill) + Color(.systemGray5) .overlay { AsyncImage(url: url) { image in image.resizable().scaledToFill() diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index 87aea43..fc65e12 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -64,7 +64,7 @@ final class MusicGoUITests: XCTestCase { } private func waitForPlayer(_ text: String, in app: XCUIApplication) { - let state = app.descendants(matching: .any)["player-state"].firstMatch + let state = app.staticTexts["player-state"] let done = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", text), object: state) let result = XCTWaiter.wait(for: [done], timeout: 30) XCTAssertEqual(result, .completed, "播放状态是「\(state.exists ? state.label : "无")」,应为「\(text)」") From 173bb3ca40dc0a0ba56b32bc7fdcd10e693f9f11 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:42:11 +0800 Subject: [PATCH 5/9] =?UTF-8?q?feat(ios):=20=E5=85=A8=E5=B1=8F=E6=92=AD?= =?UTF-8?q?=E6=94=BE=E9=A1=B5=E5=92=8C=E9=80=90=E5=AD=97=E6=AD=8C=E8=AF=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 播放页布局改写自 AppleMusicStylePlayer(MIT),歌词改写自 Cassette(MPL-2.0)。 最低系统升到 iOS 18。 Co-Authored-By: Claude Opus 5.5 --- THIRD_PARTY_NOTICES.md | 2 + ios/App/Player/Artwork.swift | 78 +++++++ ios/App/Player/ElasticSlider.swift | 88 ++++++++ ios/App/Player/LyricsView.swift | 176 ++++++++++++++++ ios/App/Player/MarqueeText.swift | 64 ++++++ ios/App/Player/MiniPlayer.swift | 94 +++++++++ ios/App/Player/NOTICE.md | 40 ++++ ios/App/Player/PlayerView.swift | 192 ++++++++++++++++++ ios/App/RoomSession.swift | 5 + ios/App/RoomView.swift | 154 ++++---------- .../Sources/MusicGoKit/APIClient.swift | 15 +- .../Sources/MusicGoKit/Lyrics.swift | 41 ++++ .../MusicGoKitTests/MusicGoKitTests.swift | 34 ++++ ios/README.md | 4 +- ios/UITests/MusicGoUITests.swift | 24 ++- ios/project.yml | 6 +- ios/testplugin/index.js | 16 ++ 17 files changed, 907 insertions(+), 126 deletions(-) create mode 100644 ios/App/Player/Artwork.swift create mode 100644 ios/App/Player/ElasticSlider.swift create mode 100644 ios/App/Player/LyricsView.swift create mode 100644 ios/App/Player/MarqueeText.swift create mode 100644 ios/App/Player/MiniPlayer.swift create mode 100644 ios/App/Player/NOTICE.md create mode 100644 ios/App/Player/PlayerView.swift create mode 100644 ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 469ad24..e15214a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -8,6 +8,8 @@ MusicGo 以 [GNU AGPL-3.0](LICENSE) 发布。它包含或改写了下面这些 | [mygoify](https://github.com/aronnaxlin/mygoify)(fork 自 `egoist/mygo-cloudmusic`) | AGPL-3.0 | 歌词,[`server/internal/lyrics`](server/internal/lyrics/NOTICE.md);网页底幕的暗角样式 | | [Lyricify Lyrics Helper](https://github.com/WXRIW/Lyricify-Lyrics-Helper) | Apache-2.0 | 网易云 EAPI 签名算法 | | [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) | +| [Cassette](https://github.com/CassetteLab/cassette) | MPL-2.0 | iOS 歌词页,[`ios/App/Player`](ios/App/Player/NOTICE.md) | 所用的提交、改动和许可全文见各目录的 `NOTICE.md`。 diff --git a/ios/App/Player/Artwork.swift b/ios/App/Player/Artwork.swift new file mode 100644 index 0000000..a2c6499 --- /dev/null +++ b/ios/App/Player/Artwork.swift @@ -0,0 +1,78 @@ +import SwiftUI +import UIKit + +/// 当前歌曲的封面,以及从它取出的背景颜色。 +@MainActor @Observable +final class Artwork { + private(set) var image: UIImage? + /// 3×3 个颜色,按封面上的位置排列;没有封面时用默认颜色。 + private(set) var colors = Artwork.fallback + + static let fallback: [Color] = (0..<9).map { + Color(hue: 0.62 + Double($0 % 3) * 0.04, saturation: 0.35, brightness: 0.35 + Double($0 / 3) * 0.08) + } + + func load(_ url: URL?) async { + var loaded: UIImage? + if let url, let (data, _) = try? await URLSession.shared.data(from: url) { + loaded = UIImage(data: data) + } + guard !Task.isCancelled else { return } + withAnimation(.smooth(duration: 0.6)) { + image = loaded + colors = loaded.flatMap(Self.colors) ?? Self.fallback + } + } + + /// 缩到 30×30,再按九宫格取平均色。 + private static func colors(of image: UIImage) -> [Color]? { + let side = 30 + var pixels = [UInt8](repeating: 0, count: side * side * 4) + guard let cgImage = image.cgImage, + let context = CGContext( + data: &pixels, width: side, height: side, bitsPerComponent: 8, bytesPerRow: side * 4, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) + else { return nil } + context.interpolationQuality = .medium + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: side, height: side)) + + let cell = side / 3 + return (0..<9).map { index in + var sum = [0.0, 0.0, 0.0] + for y in 0.. Void)? + + @State private var dragged: TimeInterval? + @State private var dragStart: TimeInterval = 0 + @GestureState private var isActive = false + + private static let inactiveHeight: CGFloat = 7 + private static let activeHeight: CGFloat = 16 + private static let growth: CGFloat = 8 + + private var shown: TimeInterval { dragged ?? position } + private var fraction: Double { + guard let duration, duration > 0 else { return 0 } + return min(1, max(0, shown / duration)) + } + + var body: some View { + VStack(spacing: 6) { + track + HStack { + Text(formatTime(shown)) + Spacer() + Text(duration.map { "-" + formatTime(max(0, $0 - shown)) } ?? formatTime(nil)) + } + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(.white.opacity(isActive ? 1 : 0.6)) + .padding(.horizontal, isActive ? 0 : Self.growth) + } + .animation(.smooth(duration: 0.3, extraBounce: 0.3), value: isActive) + .onChange(of: isActive) { _, active in + // 手势被系统打断时不会走 onEnded。 + if !active { dragged = nil } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel("播放进度") + .accessibilityValue("\(formatTime(shown)),共 \(formatTime(duration))") + .accessibilityAdjustableAction { direction in + guard let onSeek, let duration else { return } + let step: TimeInterval = direction == .increment ? 10 : -10 + onSeek(min(duration, max(0, position + step))) + } + } + + private var track: some View { + GeometryReader { proxy in + Capsule() + .fill(.white.opacity(0.25)) + .overlay(alignment: .leading) { + Rectangle() + .fill(.white.opacity(isActive ? 1 : 0.7)) + .frame(width: (proxy.size.width - (isActive ? 0 : Self.growth * 2)) * fraction) + } + .clipShape(.capsule) + .padding(.horizontal, isActive ? 0 : Self.growth) + .frame(height: isActive ? Self.activeHeight : Self.inactiveHeight) + .frame(maxHeight: .infinity) + .contentShape(.rect) + .highPriorityGesture(drag(width: proxy.size.width), isEnabled: onSeek != nil) + } + .frame(height: 24) + } + + private func drag(width: CGFloat) -> some Gesture { + DragGesture(minimumDistance: 0) + .updating($isActive) { _, active, _ in active = true } + .onChanged { value in + guard let duration, width > 0 else { return } + if dragged == nil { dragStart = position } + dragged = min(duration, max(0, dragStart + value.translation.width / width * duration)) + } + .onEnded { value in + // 只是碰了一下,不算跳转。 + if let dragged, abs(value.translation.width) > 2 { onSeek?(dragged) } + dragged = nil + } + } +} diff --git a/ios/App/Player/LyricsView.swift b/ios/App/Player/LyricsView.swift new file mode 100644 index 0000000..02ea760 --- /dev/null +++ b/ios/App/Player/LyricsView.swift @@ -0,0 +1,176 @@ +// 改写自 Cassette 的 LyricsView.swift、LyricsLineView.swift 和 LyricsViewModel.swift +// Copyright (C) 2026 Mathieu Dubart +// 本文件按 Mozilla Public License 2.0 授权:https://mozilla.org/MPL/2.0/ + +import MusicGoKit +import SwiftUI + +/// 跟着房间进度滚动的歌词。手动滑动后停几秒再继续跟随。 +struct LyricsView: View { + let session: RoomSession + let entryID: String + + private enum Phase { + case loading + case loaded(Lyrics) + case failed(String) + } + + @State private var phase = Phase.loading + @State private var attempt = 0 + @State private var currentIndex: Int? + @State private var isBrowsing = false + @State private var resume: Task? + + private struct Request: Hashable { + let entryID: String + let attempt: Int + } + + var body: some View { + Group { + switch phase { + case .loading: + ProgressView().tint(.white) + case .failed(let reason): + message(reason, canRetry: true) + case .loaded(let lyrics): + switch lyrics.status { + case .found: lines(lyrics) + case .none: message("这首歌没有歌词", canRetry: false) + case .unavailable: message("暂时查不到歌词", canRetry: true) + } + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + .task(id: Request(entryID: entryID, attempt: attempt)) { await load() } + .onDisappear { resume?.cancel() } + } + + private func load() async { + phase = .loading + currentIndex = nil + isBrowsing = false + let lyrics: Lyrics + do { + lyrics = try await session.client.lyrics(entryID) + } catch { + if !Task.isCancelled { phase = .failed(error.localizedDescription) } + return + } + guard !Task.isCancelled else { return } + currentIndex = lyrics.lineIndex(at: session.position) + phase = .loaded(lyrics) + while lyrics.isSynced, !Task.isCancelled { + let index = lyrics.lineIndex(at: session.position) + if index != currentIndex { currentIndex = index } + try? await Task.sleep(for: .milliseconds(100)) + } + } + + private func message(_ text: String, canRetry: Bool) -> some View { + VStack(spacing: 12) { + Image(systemName: "quote.bubble").font(.largeTitle) + Text(text) + if canRetry { + Button("重试") { attempt += 1 }.buttonStyle(.bordered).tint(.white) + } + } + .foregroundStyle(.white.opacity(0.7)) + } + + private func lines(_ lyrics: Lyrics) -> some View { + ScrollViewReader { proxy in + ScrollView { + LazyVStack(alignment: .leading, spacing: 26) { + ForEach(Array(lyrics.lines.enumerated()), id: \.offset) { index, line in + LyricsLineView( + line: line, + distance: lyrics.isSynced && !isBrowsing ? currentIndex.map { abs(index - $0) } : nil, + isCurrent: index == currentIndex, + position: { session.position } + ) + .contentShape(.rect) + .onTapGesture { + guard lyrics.isSynced, session.canControl else { return } + isBrowsing = false + Task { await session.seek(to: Double(line.atMs) / 1000) } + } + } + } + .padding(.vertical, 120) + } + .scrollIndicators(.hidden) + .mask { + LinearGradient( + stops: [ + .init(color: .clear, location: 0), .init(color: .black, location: 0.12), + .init(color: .black, location: 0.85), .init(color: .clear, location: 1), + ], startPoint: .top, endPoint: .bottom) + } + .onAppear { proxy.scrollTo(currentIndex ?? 0, anchor: .center) } + .onChange(of: currentIndex) { _, index in + guard !isBrowsing, let index else { return } + withAnimation(.smooth(duration: 0.5)) { proxy.scrollTo(index, anchor: .center) } + } + .onScrollPhaseChange { _, phase in + if phase == .interacting { + browse() + } else if phase == .idle, isBrowsing { + browse() + } + } + } + } + + private func browse() { + isBrowsing = true + resume?.cancel() + resume = Task { + try? await Task.sleep(for: .seconds(3)) + if !Task.isCancelled { isBrowsing = false } + } + } +} + +/// 离当前行越远越淡、越模糊;当前行逐字点亮。 +private struct LyricsLineView: View { + let line: LyricLine + /// 与当前行隔几行;nil 表示不分远近,都清楚显示。 + let distance: Int? + let isCurrent: Bool + let position: () -> TimeInterval + + private static let blurs: [CGFloat] = [0, 1, 2, 3.5] + private static let opacities = [1, 0.6, 0.4, 0.25] + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + if isCurrent { + TimelineView(.periodic(from: .now, by: 0.1)) { _ in text(sung: line.sungPrefix(at: position())) } + } else { + text(sung: line.text) + } + if !line.translation.isEmpty { + Text(line.translation).font(.body.weight(.medium)).foregroundStyle(.white.opacity(0.7)) + } + } + .multilineTextAlignment(.leading) + .frame(maxWidth: .infinity, alignment: .leading) + .opacity(distance.map { Self.opacities[min($0, 3)] } ?? 0.9) + .blur(radius: distance.map { Self.blurs[min($0, 3)] } ?? 0) + .scaleEffect(isCurrent ? 1 : 0.96, anchor: .leading) + .animation(.easeInOut(duration: 0.3), value: distance) + } + + private func text(sung: String) -> some View { + var shown = AttributedString(line.text.isEmpty ? "♪" : line.text) + shown.foregroundColor = .white + if let start = shown.characters.index( + shown.startIndex, offsetBy: sung.count, limitedBy: shown.endIndex), !line.text.isEmpty + { + shown[start.. viewWidth && viewWidth > 0 } + + var body: some View { + // 占位的这份决定高度,并在放不下时省略。 + Text(text) + .lineLimit(1) + .opacity(overflows && !reduceMotion ? 0 : 1) + .frame(maxWidth: .infinity, alignment: .leading) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { viewWidth = $0 } + .background { + Text(text).fixedSize().hidden() + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { textWidth = $0 } + } + .overlay(alignment: .leading) { + if overflows, !reduceMotion { moving } + } + .accessibilityElement(children: .ignore) + .accessibilityLabel(text) + .accessibilityAddTraits(.isStaticText) + .id(text) + } + + private var moving: some View { + HStack(spacing: Self.spacing) { + Text(text).fixedSize() + Text(text).fixedSize() + } + .offset(x: isMoving ? -(textWidth + Self.spacing) : 0) + .frame(width: viewWidth, alignment: .leading) + .mask { + HStack(spacing: 0) { + Color.black + LinearGradient(colors: [.black, .clear], startPoint: .leading, endPoint: .trailing) + .frame(width: Self.fade) + } + } + .onAppear { + withAnimation(.linear(duration: textWidth / 30).delay(2).repeatForever(autoreverses: false)) { + isMoving = true + } + } + } +} diff --git a/ios/App/Player/MiniPlayer.swift b/ios/App/Player/MiniPlayer.swift new file mode 100644 index 0000000..86677b5 --- /dev/null +++ b/ios/App/Player/MiniPlayer.swift @@ -0,0 +1,94 @@ +// 布局改写自 AppleMusicStylePlayer 的 CompactNowPlaying.swift +// Copyright (c) 2025 Alexey Vorobyov,MIT 许可,全文见本目录的 NOTICE.md。 + +import MusicGoKit +import SwiftUI + +/// 列表底部的播放条,点开是完整的播放页。 +struct MiniPlayer: View { + let session: RoomSession + let entry: QueueEntry + let artwork: Artwork + let onExpand: () -> Void + + var body: some View { + HStack(spacing: 12) { + Button(action: onExpand) { + HStack(spacing: 12) { + ArtworkImage(image: artwork.image, cornerRadius: 7).frame(width: 40, height: 40) + VStack(alignment: .leading, spacing: 1) { + Text(entry.track.title).font(.subheadline.weight(.semibold)) + Text(detail).font(.caption).foregroundStyle(.secondary) + } + .lineLimit(1) + Spacer(minLength: 0) + } + .contentShape(.rect) + } + .buttonStyle(.plain) + .accessibilityElement(children: .ignore) + .accessibilityLabel(entry.track.title) + .accessibilityHint("打开播放页") + .accessibilityAddTraits(.isButton) + .accessibilityIdentifier("mini-player") + + Button( + session.player.isListening ? "本机静音" : "在本机播放", + systemImage: session.player.isListening ? "speaker.wave.2.fill" : "speaker.slash.fill" + ) { session.player.isListening.toggle() } + .labelStyle(.iconOnly) + .frame(width: 44, height: 44) + .tint(.primary) + } + .padding(.leading, 8) + .padding(.trailing, 4) + .frame(height: 56) + .background(.thickMaterial, in: .rect(cornerRadius: 14)) + .shadow(color: .black.opacity(0.15), radius: 8, y: 2) + } + + private var detail: String { + switch session.player.state { + case .playing, .idle: entry.track.artist + default: session.player.state.text + } + } +} + +struct ArtworkImage: View { + let image: UIImage? + let cornerRadius: CGFloat + + var body: some View { + Color(.systemGray4) + .aspectRatio(1, contentMode: .fit) + .overlay { + if let image { + Image(uiImage: image).resizable().scaledToFill() + } else { + GeometryReader { proxy in + Image(systemName: "music.note") + .font(.system(size: proxy.size.width * 0.35)) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + } + .clipShape(.rect(cornerRadius: cornerRadius, style: .continuous)) + .accessibilityHidden(true) + } +} + +extension RoomPlayer.State { + var text: String { + switch self { + case .idle: "没有在播放" + case .loading: "正在加载…" + case .playing: "正在本机播放" + case .paused: "已暂停" + case .off: "本机已静音" + case .unsupported: "这首歌暂时不能在 App 里播放,请用网页版收听" + case .failed(let reason): reason + } + } +} diff --git a/ios/App/Player/NOTICE.md b/ios/App/Player/NOTICE.md new file mode 100644 index 0000000..e0215ea --- /dev/null +++ b/ios/App/Player/NOTICE.md @@ -0,0 +1,40 @@ +# 第三方代码 + +| 文件 | 改写自 | 许可 | +|---|---|---| +| `PlayerView.swift`、`MiniPlayer.swift`(布局),`ElasticSlider.swift`、`MarqueeText.swift` | [AppleMusicStylePlayer](https://github.com/f728743/AppleMusicStylePlayer) `a0b5631417de` | MIT | +| `LyricsView.swift` | [Cassette](https://github.com/CassetteLab/cassette) `aed1663d21df` | MPL-2.0 | + +主要改动: + +- 数据和操作换成 MusicGo 的房间状态;进度条接上房间跳转,松手才生效。 +- 展开和收起改用系统的缩放转场,背景改用 `MeshGradient`,不再依赖 Kingfisher 和 Metal。 +- 歌词加上翻译和逐字高亮。 + +`LyricsView.swift` 仍按 [MPL-2.0](https://mozilla.org/MPL/2.0/) 授权,其余按 MusicGo 的 AGPL-3.0 发布,并保留下面的声明。 + +## AppleMusicStylePlayer + +```text +MIT License + +Copyright (c) 2025 Alexey Vorobyov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/ios/App/Player/PlayerView.swift b/ios/App/Player/PlayerView.swift new file mode 100644 index 0000000..7d7af46 --- /dev/null +++ b/ios/App/Player/PlayerView.swift @@ -0,0 +1,192 @@ +// 布局改写自 AppleMusicStylePlayer 的 RegularNowPlaying.swift、PlayerControls.swift 和 PlayerButtons.swift +// Copyright (c) 2025 Alexey Vorobyov,MIT 许可,全文见本目录的 NOTICE.md。 + +import MusicGoKit +import SwiftUI + +/// 完整的播放页:封面、歌词或队列,下面是控制。 +struct PlayerView: View { + let session: RoomSession + let artwork: Artwork + + private enum Panel { + case artwork, lyrics, queue + } + + @Environment(\.dismiss) private var dismiss + @State private var panel = Panel.artwork + + var body: some View { + ZStack { + ArtworkBackground(colors: artwork.colors).ignoresSafeArea() + if let room = session.room, let entry = room.playback.entry { + content(room, entry) + } + } + .foregroundStyle(.white) + .environment(\.colorScheme, .dark) + .onChange(of: session.room?.playback.entry == nil) { _, isIdle in + if isIdle { dismiss() } + } + .noticeAlert(session) + } + + private func content(_ room: Room, _ entry: QueueEntry) -> some View { + VStack(spacing: 0) { + Button("收起", systemImage: "chevron.compact.down") { dismiss() } + .labelStyle(.iconOnly) + .font(.title.weight(.semibold)) + .foregroundStyle(.white.opacity(0.6)) + .frame(width: 80, height: 36) + .accessibilityIdentifier("close-player") + + Group { + switch panel { + case .artwork: + // 暂停时封面缩小。 + ArtworkImage(image: artwork.image, cornerRadius: 12) + .shadow(color: .black.opacity(0.3), radius: 16, y: 10) + .scaleEffect(room.playback.status == .playing ? 1 : 0.8) + .animation(.smooth, value: room.playback.status) + .frame(maxHeight: .infinity) + case .lyrics: + LyricsView(session: session, entryID: entry.id) + case .queue: + queue(room) + } + } + .transition(.opacity) + .padding(.vertical, 12) + + info(room, entry) + TimelineView(.periodic(from: .now, by: 0.5)) { _ in + ElasticSlider( + position: session.position, duration: room.playback.durationSec, + onSeek: session.canControl && room.playback.durationSec != nil + ? { target in Task { await session.seek(to: target) } } : nil) + } + .padding(.top, 18) + buttons(room).padding(.vertical, 14) + footer + } + .padding(.horizontal, 28) + .padding(.bottom, 12) + .frame(maxWidth: 560) + } + + private func info(_ room: Room, _ entry: QueueEntry) -> some View { + HStack(spacing: 12) { + if panel != .artwork { + ArtworkImage(image: artwork.image, cornerRadius: 8).frame(width: 52, height: 52) + } + VStack(alignment: .leading, spacing: 3) { + MarqueeText(entry.track.title) + .font(.title3.bold()) + .accessibilityIdentifier("now-playing-title") + Text("\(entry.track.artist) · \(room.memberName(entry.requestedBy)) 点的") + .lineLimit(1) + .foregroundStyle(.white.opacity(0.65)) + } + } + } + + private func buttons(_ room: Room) -> some View { + let isPaused = room.playback.status == .paused + return HStack { + Button( + session.player.isListening ? "本机静音" : "在本机播放", + systemImage: session.player.isListening ? "speaker.wave.2.fill" : "speaker.slash.fill" + ) { session.player.isListening.toggle() } + .font(.title2) + .frame(maxWidth: .infinity) + + if session.canControl { + Button(isPaused ? "继续" : "暂停", systemImage: isPaused ? "play.fill" : "pause.fill") { + Task { await session.togglePause() } + } + .font(.system(size: 42)) + .contentTransition(.symbolEffect(.replace)) + .frame(maxWidth: .infinity) + .accessibilityIdentifier("toggle-pause") + } + + Button(session.canSkip ? "切歌" : "投票切歌", systemImage: session.canSkip ? "forward.fill" : "hand.thumbsdown.fill") { + Task { await session.skip() } + } + .font(session.canSkip ? .title : .title2) + .frame(maxWidth: .infinity) + .disabled(!session.canSkip && session.hasVoted) + .accessibilityIdentifier("skip") + } + .labelStyle(.iconOnly) + .buttonStyle(PlayerButtonStyle()) + .frame(height: 68) + } + + private var footer: some View { + HStack { + panelButton(.lyrics, "歌词", "quote.bubble") + Text(session.player.state.text) + .font(.caption) + .foregroundStyle(.white.opacity(0.65)) + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .accessibilityIdentifier("player-state") + panelButton(.queue, "待播", "list.bullet") + } + } + + private func panelButton(_ target: Panel, _ title: String, _ icon: String) -> some View { + Button(title, systemImage: icon) { + withAnimation(.smooth(duration: 0.35)) { panel = panel == target ? .artwork : target } + } + .labelStyle(.iconOnly) + .font(.title3) + .frame(width: 44, height: 44) + .background(.white.opacity(panel == target ? 0.25 : 0), in: .circle) + .accessibilityAddTraits(panel == target ? .isSelected : []) + .accessibilityIdentifier(target == .lyrics ? "show-lyrics" : "show-queue") + } + + private func queue(_ room: Room) -> some View { + ScrollView { + LazyVStack(alignment: .leading, spacing: 14) { + Text("待播 \(room.queue.count) 首").font(.headline) + ForEach(room.queue) { entry in + TrackRow(track: entry.track, detail: "\(room.memberName(entry.requestedBy)) 点的") + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .scrollIndicators(.hidden) + } +} + +/// 按下时缩小,并亮起一圈底色。 +private struct PlayerButtonStyle: ButtonStyle { + @Environment(\.isEnabled) private var isEnabled + + func makeBody(configuration: Configuration) -> some View { + configuration.label + .frame(width: 68, height: 68) + .background(.white.opacity(configuration.isPressed ? 0.2 : 0), in: .circle) + .contentShape(.circle) + .scaleEffect(configuration.isPressed ? 0.85 : 1) + .opacity(isEnabled ? 1 : 0.4) + .animation(.smooth(duration: 0.2), value: configuration.isPressed) + } +} + +extension View { + /// 一次性提示。播放页盖在房间页上面,两边都要能弹。 + func noticeAlert(_ session: RoomSession, isActive: Bool = true) -> some View { + alert( + session.notice ?? "", + isPresented: Binding( + get: { isActive && session.notice != nil }, + set: { if !$0 { session.notice = nil } }) + ) { + Button("好") {} + } + } +} diff --git a/ios/App/RoomSession.swift b/ios/App/RoomSession.swift index 309c13e..1669fb3 100644 --- a/ios/App/RoomSession.swift +++ b/ios/App/RoomSession.swift @@ -46,6 +46,11 @@ final class RoomSession { await perform { try await paused ? self.client.resume() : self.client.pause() } } + func seek(to position: TimeInterval) async { + guard canControl, let entry = room?.playback.entry else { return } + await perform { try await self.client.seek(entry.id, to: position) } + } + func skip() async { guard let entry = room?.playback.entry else { return } let direct = canSkip diff --git a/ios/App/RoomView.swift b/ios/App/RoomView.swift index d5ae648..5ec55e5 100644 --- a/ios/App/RoomView.swift +++ b/ios/App/RoomView.swift @@ -5,11 +5,15 @@ struct RoomView: View { let session: RoomSession let onLeave: () -> Void + @State private var artwork = Artwork() @State private var isSearching = false + @State private var isPlayerOpen = false @State private var isConfirmingLeave = false + @Namespace private var transition + + private var current: QueueEntry? { session.endedReason == nil ? session.room?.playback.entry : nil } var body: some View { - @Bindable var session = session NavigationStack { Group { if let reason = session.endedReason { @@ -21,13 +25,12 @@ struct RoomView: View { Button("换一个链接", action: onLeave) } } else if let room = session.room { - content(room) + queue(room) } else { ProgressView("正在连接…") } } .navigationTitle(session.room?.name ?? "MusicGo") - .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .topBarLeading) { Button("退出", systemImage: "rectangle.portrait.and.arrow.right") { isConfirmingLeave = true } @@ -38,133 +41,52 @@ struct RoomView: View { .accessibilityIdentifier("open-search") } } + .safeAreaInset(edge: .bottom) { + if let current { + MiniPlayer(session: session, entry: current, artwork: artwork) { isPlayerOpen = true } + .matchedTransitionSource(id: "player", in: transition) + .padding(.horizontal, 12) + .padding(.bottom, 6) + .frame(maxWidth: 560) + } + } } .sheet(isPresented: $isSearching) { SearchView(client: session.client) } + .fullScreenCover(isPresented: $isPlayerOpen) { + PlayerView(session: session, artwork: artwork) + .navigationTransition(.zoom(sourceID: "player", in: transition)) + } .confirmationDialog("退出后要重新粘贴进入链接", isPresented: $isConfirmingLeave, titleVisibility: .visible) { Button("退出", role: .destructive, action: onLeave) } - .alert( - session.notice ?? "", - isPresented: Binding(get: { session.notice != nil }, set: { if !$0 { session.notice = nil } }) - ) { - Button("好") {} - } + .noticeAlert(session, isActive: !isPlayerOpen) .task { session.start() } + .task(id: current?.track.cover) { await artwork.load(current?.track.cover) } } - private func content(_ room: Room) -> some View { + private func queue(_ room: Room) -> some View { List { Section { - NowPlayingView(session: session, room: room) - .frame(maxWidth: .infinity) - .listRowBackground(Color.clear) - .listRowSeparator(.hidden) - } header: { - Label( - session.isLive ? "\(room.online.count) 人在听" : "正在重新连接…", - systemImage: session.isLive ? "person.2.fill" : "wifi.exclamationmark") - } - Section("待播 \(room.queue.count) 首") { - if room.queue.isEmpty { - Text("还没有待播的歌").foregroundStyle(.secondary) - } ForEach(room.queue) { entry in TrackRow(track: entry.track, detail: "\(room.memberName(entry.requestedBy)) 点的") } - } - } - } -} - -private struct NowPlayingView: View { - let session: RoomSession - let room: Room - - var body: some View { - if let entry = room.playback.entry { - VStack(spacing: 16) { - CoverView(url: entry.track.cover) - .frame(width: 240, height: 240) - .shadow(color: .black.opacity(0.2), radius: 12, y: 6) - VStack(spacing: 4) { - Text(entry.track.title) - .font(.title3.bold()) - .accessibilityIdentifier("now-playing-title") - Text(entry.track.artist).foregroundStyle(.secondary) - Text("\(room.memberName(entry.requestedBy)) 点的").font(.footnote).foregroundStyle(.secondary) + } header: { + HStack { + Text("待播 \(room.queue.count) 首") + Spacer() + Label( + session.isLive ? "\(room.online.count) 人在听" : "正在重新连接…", + systemImage: session.isLive ? "person.2.fill" : "wifi.exclamationmark") } - .multilineTextAlignment(.center) - TimelineView(.periodic(from: .now, by: 0.5)) { _ in progress } - controls - Label(playerText, systemImage: playerIcon) - .font(.footnote) - .foregroundStyle(.secondary) - .accessibilityIdentifier("player-state") - } - .padding(.vertical, 8) - } else { - ContentUnavailableView("现在没有在放歌", systemImage: "music.note", description: Text("点右上角的 + 点一首")) - } - } - - private var progress: some View { - let duration = room.playback.durationSec - return VStack(spacing: 4) { - ProgressView(value: duration.map { $0 > 0 ? min(1, session.position / $0) : 0 } ?? 0) - HStack { - Text(formatTime(session.position)) - Spacer() - Text(formatTime(duration)) } - .font(.caption.monospacedDigit()) - .foregroundStyle(.secondary) } - } - - private var controls: some View { - HStack(spacing: 32) { - Button( - session.player.isListening ? "本机静音" : "在本机播放", - systemImage: session.player.isListening ? "speaker.wave.2.fill" : "speaker.slash.fill" - ) { session.player.isListening.toggle() } - if session.canControl { - let paused = room.playback.status == .paused - Button(paused ? "继续" : "暂停", systemImage: paused ? "play.fill" : "pause.fill") { - Task { await session.togglePause() } - } - .font(.largeTitle) - .accessibilityIdentifier("toggle-pause") - } - Button(session.canSkip ? "切歌" : "投票切歌", systemImage: session.canSkip ? "forward.fill" : "hand.thumbsdown") { - Task { await session.skip() } + .listStyle(.plain) + .overlay { + if room.queue.isEmpty { + ContentUnavailableView( + room.playback.entry == nil ? "现在没有在放歌" : "后面还没有歌", systemImage: "music.note.list", + description: Text("点右上角的 + 点一首")) } - .disabled(!session.canSkip && session.hasVoted) - .accessibilityIdentifier("skip") - } - .font(.title2) - .labelStyle(.iconOnly) - // 列表行里有多个按钮时,默认样式会让整行一起响应。 - .buttonStyle(.borderless) - } - - private var playerText: String { - switch session.player.state { - case .idle: "没有在播放" - case .loading: "正在加载…" - case .playing: "正在本机播放" - case .paused: "已暂停" - case .off: "本机已静音" - case .unsupported: "这首歌暂时不能在 App 里播放,请用网页版收听" - case .failed(let reason): reason - } - } - - private var playerIcon: String { - switch session.player.state { - case .playing: "waveform" - case .unsupported, .failed: "exclamationmark.triangle" - case .off: "speaker.slash" - default: "music.note" } } } @@ -175,7 +97,7 @@ struct TrackRow: View { var body: some View { HStack(spacing: 12) { - CoverView(url: track.cover).frame(width: 44, height: 44) + CoverView(url: track.cover).frame(width: 48, height: 48) VStack(alignment: .leading, spacing: 2) { Text(track.title).lineLimit(1) Text([track.artist, detail].filter { !$0.isEmpty }.joined(separator: " · ")) @@ -187,7 +109,7 @@ struct TrackRow: View { } } -struct CoverView: View { +private struct CoverView: View { let url: URL? var body: some View { @@ -200,7 +122,7 @@ struct CoverView: View { Image(systemName: "music.note").foregroundStyle(.secondary) } } - .clipShape(.rect(cornerRadius: 8)) + .clipShape(.rect(cornerRadius: 7)) .accessibilityHidden(true) } } diff --git a/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift index 34ed0d8..7b4c838 100644 --- a/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift +++ b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift @@ -84,6 +84,10 @@ public struct APIClient: Sendable { return response.tracks } + public func lyrics(_ entryID: String) async throws -> Lyrics { + try await get("\(roomPath)/lyrics", query: ["entry_id": entryID]) + } + // MARK: 点歌与播放 @discardableResult @@ -112,6 +116,15 @@ public struct APIClient: Sendable { try await post("\(roomPath)/playback/vote-skip", ["entry_id": entryID]) } + /// 房主和管理员能调整整个房间的进度。 + public func seek(_ entryID: String, to position: TimeInterval) async throws { + struct Body: Encodable { + let entry_id: String + let position_sec: Double + } + let _: Ignored = try await post("\(roomPath)/playback/seek", Body(entry_id: entryID, position_sec: position)) + } + public func pause() async throws { try await act("pause", [:]) } public func resume() async throws { try await act("resume", [:]) } @@ -154,7 +167,7 @@ public struct APIClient: Sendable { try await send(request(path, query: query)) } - private func post(_ path: String, _ body: [String: String]) async throws -> T { + private func post(_ path: String, _ body: some Encodable) async throws -> T { var request = request(path) request.httpMethod = "POST" request.httpBody = try JSONEncoder().encode(body) diff --git a/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift b/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift new file mode 100644 index 0000000..22ab268 --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift @@ -0,0 +1,41 @@ +import Foundation + +public struct Lyrics: Codable, Sendable, Equatable { + public enum Status: String, Codable, Sendable { + case found + /// 确实没有。 + case none + /// 暂时问不到,可以重试。 + case unavailable + } + + public let status: Status + public let lines: [LyricLine] + + public var isSynced: Bool { lines.contains { $0.atMs > 0 } } + + /// 唱到哪一行;还没开始时为 nil。 + public func lineIndex(at position: TimeInterval) -> Int? { + guard isSynced else { return nil } + return lines.lastIndex { Double($0.atMs) <= position * 1000 } + } +} + +public struct LyricLine: Codable, Sendable, Equatable { + public struct Word: Codable, Sendable, Equatable { + public let text: String + public let startMs: Int + public let endMs: Int + } + + public let atMs: Int + public let text: String + public let translation: String + public let words: [Word] + + /// 这一行里已经唱到的部分。 + public func sungPrefix(at position: TimeInterval) -> String { + guard !words.isEmpty, words.map(\.text).joined() == text else { return text } + return words.prefix { Double($0.startMs) <= position * 1000 }.map(\.text).joined() + } +} diff --git a/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift index a0d2a55..35ef58f 100644 --- a/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift +++ b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift @@ -113,3 +113,37 @@ import Testing #expect(client.webSocketRequest().url?.absoluteString == "wss://musicgo.example.com/v1/rooms/r_1/ws") } } + +@Suite struct LyricsTests { + static let found = """ + {"entry_id":"e_1","status":"found","source":"netease","lines":[ + {"at_ms":1000,"end_ms":3000,"text":"春日影","translation":"春日之影","timed":true, + "words":[{"text":"春","start_ms":1000,"end_ms":1500},{"text":"日影","start_ms":1500,"end_ms":3000}]}, + {"at_ms":4000,"end_ms":6000,"text":"hello world","translation":"","timed":true, + "words":[{"text":"hello","start_ms":4000,"end_ms":5000},{"text":"world","start_ms":5000,"end_ms":6000}]}]} + """ + + @Test func followsThePosition() throws { + let lyrics = try JSON.decoder.decode(Lyrics.self, from: Data(Self.found.utf8)) + #expect(lyrics.isSynced) + #expect(lyrics.lineIndex(at: 0.5) == nil) + #expect(lyrics.lineIndex(at: 1) == 0) + #expect(lyrics.lineIndex(at: 3.5) == 0) + #expect(lyrics.lineIndex(at: 99) == 1) + } + + @Test func highlightsSungWords() throws { + let lines = try JSON.decoder.decode(Lyrics.self, from: Data(Self.found.utf8)).lines + #expect(lines[0].sungPrefix(at: 0.5) == "") + #expect(lines[0].sungPrefix(at: 1.2) == "春") + #expect(lines[0].sungPrefix(at: 2) == "春日影") + // 逐字内容拼不回原文时整行高亮,不能丢字。 + #expect(lines[1].sungPrefix(at: 4.5) == "hello world") + } + + @Test func missing() throws { + let text = #"{"entry_id":"e_1","status":"unavailable","source":"","lines":[]}"# + let lyrics = try JSON.decoder.decode(Lyrics.self, from: Data(text.utf8)) + #expect(lyrics.status == .unavailable && !lyrics.isSynced && lyrics.lineIndex(at: 5) == nil) + } +} diff --git a/ios/README.md b/ios/README.md index 64b42eb..08ea287 100644 --- a/ios/README.md +++ b/ios/README.md @@ -1,6 +1,6 @@ # MusicGo iOS 客户端 -最小可用版:登录、跟着房间一起听、看队列、搜索点歌、暂停和切歌。需要 iOS 17 或更高版本。 +最小可用版:登录、跟着房间一起听、看歌词和队列、搜索点歌、暂停、切歌和调进度。需要 iOS 18 或更高版本。 ## 使用 @@ -22,7 +22,7 @@ cd ios && xcodegen && open MusicGo.xcodeproj | 目录 | 内容 | |---|---| | `MusicGoKit/` | 接口、数据结构、链接解析、进度推算。Linux 上也能 `swift test` | -| `App/` | SwiftUI 界面、实时连接、播放 | +| `App/` | SwiftUI 界面、实时连接、播放。播放页和歌词改写自开源项目,见 [NOTICE](App/Player/NOTICE.md) | | `UITests/` | 对着真实服务端走完整流程的界面测试 | | `scripts/test-server.sh` | 启动界面测试用的服务端,音源是 `testplugin/` 里的纯音 | diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index fc65e12..0c660f9 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -23,15 +23,26 @@ final class MusicGoUITests: XCTestCase { XCTAssertTrue(app.staticTexts["现在没有在放歌"].waitForExistence(timeout: 20)) order("first", in: app) + let mini = app.buttons["mini-player"] + XCTAssertTrue(mini.waitForExistence(timeout: 10)) + XCTAssertEqual(mini.label, "first 1") + order("second", in: app) + XCTAssertTrue(app.staticTexts["second 1"].waitForExistence(timeout: 10)) + capture("3-room") + + mini.tap() let title = app.staticTexts["now-playing-title"] XCTAssertTrue(title.waitForExistence(timeout: 10)) XCTAssertEqual(title.label, "first 1") waitForPlayer("正在本机播放", in: app) - capture("3-playing") + capture("4-player") - order("second", in: app) - XCTAssertTrue(app.staticTexts["second 1"].waitForExistence(timeout: 10)) - capture("4-queue") + app.buttons["show-lyrics"].tap() + let line = app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "一起听歌")).firstMatch + XCTAssertTrue(line.waitForExistence(timeout: 10)) + capture("5-lyrics") + app.buttons["show-queue"].tap() + XCTAssertTrue(app.staticTexts["待播 1 首"].waitForExistence(timeout: 10)) app.buttons["toggle-pause"].tap() waitForPlayer("已暂停", in: app) @@ -42,11 +53,14 @@ final class MusicGoUITests: XCTestCase { expectation(for: NSPredicate(format: "label == %@", "second 1"), evaluatedWith: title) waitForExpectations(timeout: 10) waitForPlayer("正在本机播放", in: app) + app.buttons["close-player"].tap() + XCTAssertTrue(title.waitForNonExistence(timeout: 10)) // 重新打开后仍是登录状态。 app.terminate() app.launch() - XCTAssertTrue(title.waitForExistence(timeout: 20)) + XCTAssertTrue(mini.waitForExistence(timeout: 20)) + mini.tap() waitForPlayer("正在本机播放", in: app) } diff --git a/ios/project.yml b/ios/project.yml index f14bc7d..8f8a4b4 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -3,7 +3,7 @@ name: MusicGo options: bundleIdPrefix: dev.luckybot deploymentTarget: - iOS: "17.0" + iOS: "18.0" createIntermediateGroups: true settings: base: @@ -17,7 +17,9 @@ targets: MusicGo: type: application platform: iOS - sources: [App] + sources: + - path: App + excludes: ['**/*.md'] dependencies: - package: MusicGoKit settings: diff --git a/ios/testplugin/index.js b/ios/testplugin/index.js index 9891947..5609c72 100644 --- a/ios/testplugin/index.js +++ b/ios/testplugin/index.js @@ -12,3 +12,19 @@ export function search({ query }) { export function stream() { return { url: 'file://__TONE__', type: 'wav' } } + +// 每 4 秒一行,每行两个词。 +export function lyrics() { + const lines = Array.from({ length: 30 }, (_, i) => { + const start = i * 4000 + return { + start, + end: start + 4000, + words: [ + { start, end: start + 2000, text: `第 ${i + 1} 行` }, + { start: start + 2000, end: start + 4000, text: ',一起听歌' }, + ], + } + }) + return { lines } +} From a63e65cdda676771cb526451cb49ea4be58f9c99 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 09:54:27 +0800 Subject: [PATCH 6/9] =?UTF-8?q?feat(ios):=20=E9=94=81=E5=B1=8F=E5=88=87?= =?UTF-8?q?=E6=AD=8C=EF=BC=8C=E5=90=8E=E5=8F=B0=E6=8E=A5=E7=9D=80=E6=94=BE?= =?UTF-8?q?=E4=B8=8B=E4=B8=80=E9=A6=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 两首歌之间申请后台时间,免得 App 被挂起;从后台回来后马上重连。 Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + ios/App/RoomPlayer.swift | 40 +++++++++++++++++++++++++++++++++++++-- ios/App/RoomSession.swift | 13 +++++++++---- ios/README.md | 2 +- 4 files changed, 49 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 7ba57ed..d964ef6 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,4 @@ filter-allow.txt /ios/*.xcodeproj/ /ios/App/Info.plist .build/ +/ios/build/ diff --git a/ios/App/RoomPlayer.swift b/ios/App/RoomPlayer.swift index 5affa6d..6f2f328 100644 --- a/ios/App/RoomPlayer.swift +++ b/ios/App/RoomPlayer.swift @@ -2,6 +2,7 @@ import AVFoundation import MediaPlayer import MusicGoKit import Observation +import UIKit /// 在本机播放房间里正在放的歌,跟着房间的进度走。 @MainActor @Observable @@ -19,6 +20,9 @@ final class RoomPlayer { didSet { update() } } + /// 锁屏或耳机上按了「下一首」。 + @ObservationIgnored var onNext: (() -> Void)? + @ObservationIgnored private let client: APIClient @ObservationIgnored private let player = AVPlayer() @ObservationIgnored private var playback: Playback? @@ -31,6 +35,8 @@ final class RoomPlayer { @ObservationIgnored private var hasEnded = false @ObservationIgnored private var isInterrupted = false @ObservationIgnored private var alignedAt = Date.distantPast + @ObservationIgnored private var backgroundTask = UIBackgroundTaskIdentifier.invalid + @ObservationIgnored private var usedBackgroundTime = false private static let maxTries = 3 /// 与房间差多少秒才校准,以及两次校准至少隔多久。 @@ -41,8 +47,9 @@ final class RoomPlayer { self.client = client } - func follow(_ playback: Playback, clock: PlaybackClock) { + func follow(_ playback: Playback, clock: PlaybackClock, canSkip: Bool) { activate() + MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = canSkip && playback.entry != nil let changedEntry = playback.entry?.id != self.playback?.entry?.id let jumped = playback.basePositionSec != self.playback?.basePositionSec self.playback = playback @@ -54,6 +61,7 @@ final class RoomPlayer { align() } update() + if changedEntry || jumped { updateNowPlaying() } } func stop() { @@ -64,6 +72,7 @@ final class RoomPlayer { let remote = MPRemoteCommandCenter.shared() remote.playCommand.removeTarget(nil) remote.pauseCommand.removeTarget(nil) + remote.nextTrackCommand.removeTarget(nil) playback = nil load() update() @@ -115,11 +124,34 @@ final class RoomPlayer { /// 让播放器符合房间状态。每半秒执行一次,状态变化时也会执行。 private func update() { let next = advance() + keepAwakeBetweenSongs() guard next != state else { return } state = next updateNowPlaying() } + /// 没有声音时,后台的 App 很快会被挂起。换歌和加载时申请一点时间,好接上下一首。 + private func keepAwakeBetweenSongs() { + let isSilent = hasEnded || player.timeControlStatus != .playing + let isWaiting = isListening && !isInterrupted && failure == nil && isSilent + && playback?.status == .playing && playback?.entry?.track.isStreamable == true + if !isWaiting { + endBackgroundTask() + usedBackgroundTime = false + } else if backgroundTask == .invalid, !usedBackgroundTime { + usedBackgroundTime = true + backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "next-song") { [weak self] in + MainActor.assumeIsolated { self?.endBackgroundTask() } + } + } + } + + private func endBackgroundTask() { + guard backgroundTask != .invalid else { return } + UIApplication.shared.endBackgroundTask(backgroundTask) + backgroundTask = .invalid + } + private func advance() -> State { guard let playback, let entry = playback.entry else { return .idle } guard entry.track.isStreamable else { return .unsupported } @@ -190,7 +222,7 @@ final class RoomPlayer { }, ] - // 锁屏上的播放、暂停只管本机,不会让整个房间停下来。 + // 锁屏上的播放、暂停只管本机,不会让整个房间停下来;「下一首」是切整个房间的歌。 let remote = MPRemoteCommandCenter.shared() remote.playCommand.addTarget { @Sendable [weak self] _ in Task { @MainActor in self?.isListening = true } @@ -200,6 +232,10 @@ final class RoomPlayer { Task { @MainActor in self?.isListening = false } return .success } + remote.nextTrackCommand.addTarget { @Sendable [weak self] _ in + Task { @MainActor in self?.onNext?() } + return .success + } } private func updateNowPlaying() { diff --git a/ios/App/RoomSession.swift b/ios/App/RoomSession.swift index 1669fb3..f485ca2 100644 --- a/ios/App/RoomSession.swift +++ b/ios/App/RoomSession.swift @@ -21,6 +21,10 @@ final class RoomSession { init(link: EntryLink) { client = APIClient(link: link) player = RoomPlayer(client: client) + player.onNext = { [weak self] in + guard let self, canSkip else { return } + Task { await self.skip() } + } } func start() { @@ -75,10 +79,11 @@ final class RoomSession { // MARK: 连接 private func run() async { - var delay = 1 + var delay = 1.0 while !Task.isCancelled { do { - try await connectOnce { delay = 1 } + // 连上过再断开的(如从后台回来),马上重连。 + try await connectOnce { delay = 0.2 } } catch let error as APIError where error.endsSession { endedReason = error.localizedDescription player.stop() @@ -86,7 +91,7 @@ final class RoomSession { } catch {} isLive = false try? await Task.sleep(for: .seconds(delay)) - delay = min(delay * 2, 15) + delay = min(max(1, delay * 2), 15) } } @@ -143,6 +148,6 @@ final class RoomSession { private func apply(_ room: Room) { guard !Task.isCancelled else { return } self.room = room - player.follow(room.playback, clock: clock) + player.follow(room.playback, clock: clock, canSkip: canSkip) } } diff --git a/ios/README.md b/ios/README.md index 08ea287..2293bfa 100644 --- a/ios/README.md +++ b/ios/README.md @@ -6,7 +6,7 @@ 粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在钥匙串。 -- 静音和锁屏上的播放、暂停只管本机;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 +- 静音和锁屏上的播放、暂停只管本机,锁屏上的「下一首」会切整个房间的歌;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 - YouTube 的歌还不能在 App 里播放,会提示改用网页版。 - 房间空闲或暂停时切到后台,系统可能会挂起 App,回到前台后自动重连。 From b1f52b26212707d8223cb7be56710dcb4df7aacb Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:09:45 +0800 Subject: [PATCH 7/9] =?UTF-8?q?feat(ios):=20=E5=8A=9F=E8=83=BD=E8=A1=A5?= =?UTF-8?q?=E9=BD=90=E5=88=B0=E4=B8=8E=E7=BD=91=E9=A1=B5=E7=89=88=E7=9B=B8?= =?UTF-8?q?=E5=90=8C=EF=BC=8C=E4=BF=AE=E5=A5=BD=E8=87=AA=E5=8A=A8=E6=92=AD?= =?UTF-8?q?=E6=94=BE=E3=80=81=E5=B0=81=E9=9D=A2=E5=92=8C=E6=AD=8C=E8=AF=8D?= =?UTF-8?q?=E5=8D=A1=E9=A1=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 播放:系统挂起 App 后补发的「打断」不再让播放停住;换歌和等人点歌时在后台保持运行 - 锁屏和 Control Center 显示封面,能拖进度 - 歌词改用 MelismaKit 绘制,可调时间、手动搜索 - 队列可撤回和排序;新增房间信息、成员管理、房间设置、最近播放 - YouTube 用官方内嵌播放器;登录支持邀请码和不带房间的链接 Co-Authored-By: Claude Opus 5.5 --- THIRD_PARTY_NOTICES.md | 2 +- ios/App/LoginView.swift | 4 +- ios/App/Player/Artwork.swift | 32 ++- ios/App/Player/LyricsModel.swift | 199 +++++++++++++ ios/App/Player/LyricsPanel.swift | 172 +++++++++++ ios/App/Player/LyricsView.swift | 176 ------------ ios/App/Player/MiniPlayer.swift | 7 +- ios/App/Player/NOTICE.md | 6 +- ios/App/Player/PlayerView.swift | 145 +++++++--- ios/App/Player/YouTubePlayer.swift | 221 ++++++++++++++ ios/App/QueueRows.swift | 71 +++++ ios/App/RoomInfoView.swift | 271 ++++++++++++++++++ ios/App/RoomPlayer.swift | 213 +++++++++++--- ios/App/RoomSession.swift | 89 +++++- ios/App/RoomView.swift | 63 +--- ios/App/SearchView.swift | 63 +++- .../Sources/MusicGoKit/APIClient.swift | 124 +++++++- .../Sources/MusicGoKit/EntryLink.swift | 38 ++- .../Sources/MusicGoKit/Lyrics.swift | 113 +++++++- .../Sources/MusicGoKit/Models.swift | 98 ++++++- .../MusicGoKitTests/MusicGoKitTests.swift | 86 ++++-- ios/README.md | 14 +- ios/UITests/MusicGoUITests.swift | 38 ++- ios/project.yml | 8 + 24 files changed, 1861 insertions(+), 392 deletions(-) create mode 100644 ios/App/Player/LyricsModel.swift create mode 100644 ios/App/Player/LyricsPanel.swift delete mode 100644 ios/App/Player/LyricsView.swift create mode 100644 ios/App/Player/YouTubePlayer.swift create mode 100644 ios/App/QueueRows.swift create mode 100644 ios/App/RoomInfoView.swift diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index e15214a..6ee4aaf 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -9,7 +9,7 @@ MusicGo 以 [GNU AGPL-3.0](LICENSE) 发布。它包含或改写了下面这些 | [Lyricify Lyrics Helper](https://github.com/WXRIW/Lyricify-Lyrics-Helper) | Apache-2.0 | 网易云 EAPI 签名算法 | | [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) | -| [Cassette](https://github.com/CassetteLab/cassette) | MPL-2.0 | 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) | 所用的提交、改动和许可全文见各目录的 `NOTICE.md`。 diff --git a/ios/App/LoginView.swift b/ios/App/LoginView.swift index 0c2928d..7fad1a2 100644 --- a/ios/App/LoginView.swift +++ b/ios/App/LoginView.swift @@ -53,9 +53,7 @@ struct LoginView: View { Task { defer { checking = false } do { - let link = try EntryLink(text) - _ = try await APIClient(link: link).room() - onLogin(link) + onLogin(try await EntryLink(text).enter()) } catch { problem = error.localizedDescription } diff --git a/ios/App/Player/Artwork.swift b/ios/App/Player/Artwork.swift index a2c6499..4eda109 100644 --- a/ios/App/Player/Artwork.swift +++ b/ios/App/Player/Artwork.swift @@ -9,14 +9,12 @@ final class Artwork { private(set) var colors = Artwork.fallback static let fallback: [Color] = (0..<9).map { - Color(hue: 0.62 + Double($0 % 3) * 0.04, saturation: 0.35, brightness: 0.35 + Double($0 / 3) * 0.08) + Color(hue: 0.62 + Double($0 % 3) * 0.04, saturation: 0.45, brightness: 0.23 + Double($0 / 3) * 0.05) } func load(_ url: URL?) async { var loaded: UIImage? - if let url, let (data, _) = try? await URLSession.shared.data(from: url) { - loaded = UIImage(data: data) - } + if let url { loaded = await Self.fetch(url) } guard !Task.isCancelled else { return } withAnimation(.smooth(duration: 0.6)) { image = loaded @@ -24,6 +22,21 @@ final class Artwork { } } + /// 原图可能有几千像素,先在后台缩小,显示时才不会卡。 + private static func fetch(_ url: URL) async -> UIImage? { + for attempt in 0..<3 { + if attempt > 0 { try? await Task.sleep(for: .seconds(attempt * 2)) } + guard !Task.isCancelled else { return nil } + guard let (data, _) = try? await URLSession.shared.data(from: url) else { continue } + guard let image = UIImage(data: data) else { return nil } + let pixels = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale) + let ratio = min(1, 1000 / max(pixels.width, pixels.height, 1)) + return await image.byPreparingThumbnail( + ofSize: CGSize(width: pixels.width * ratio, height: pixels.height * ratio)) ?? image + } + return nil + } + /// 缩到 30×30,再按九宫格取平均色。 private static func colors(of image: UIImage) -> [Color]? { let side = 30 @@ -45,13 +58,16 @@ final class Artwork { for channel in 0..<3 { sum[channel] += Double(pixels[offset + channel]) } } } - let scale = 255 * Double(cell * cell) - return Color(red: sum[0] / scale, green: sum[1] / scale, blue: sum[2] / scale) + // 更鲜艳一些,再压暗,保证白字看得清。在这里算好,背景就不用每帧套滤镜。 + let average = sum.map { $0 / (255 * Double(cell * cell)) } + let gray = 0.21 * average[0] + 0.72 * average[1] + 0.07 * average[2] + let vivid = average.map { min(1, max(0, gray + ($0 - gray) * 1.3)) * 0.65 } + return Color(red: vivid[0], green: vivid[1], blue: vivid[2]) } } } -/// 封面颜色铺成的背景,缓慢流动。压暗一层,保证白字看得清。 +/// 封面颜色铺成的背景,缓慢流动。 struct ArtworkBackground: View { let colors: [Color] @@ -68,8 +84,6 @@ struct ArtworkBackground: View { ], colors: colors ) - .saturation(1.3) - .overlay(.black.opacity(0.35)) .onAppear { guard !reduceMotion else { return } withAnimation(.easeInOut(duration: 9).repeatForever(autoreverses: true)) { isDrifting = true } diff --git a/ios/App/Player/LyricsModel.swift b/ios/App/Player/LyricsModel.swift new file mode 100644 index 0000000..619e2e8 --- /dev/null +++ b/ios/App/Player/LyricsModel.swift @@ -0,0 +1,199 @@ +import MelismaKit +import MusicGoKit +import SwiftUI +import UIKit + +/// 当前歌曲的歌词。滚动和逐字高亮由 MelismaKit 按屏幕刷新率绘制,这里只负责取歌词和对时间。 +@MainActor @Observable +final class LyricsModel { + enum Phase { + case loading + case loaded(Lyrics) + /// `retryIn` 是几秒后自动重试。 + case failed(String, retryIn: Int?) + } + + private(set) var phase = Phase.loading + /// 用的是手动选的歌词。 + private(set) var isOverridden = false + /// 歌词提前几秒,按歌保存在本机。 + private(set) var offset = 0.0 + + @ObservationIgnored let surface = MelismaKit.LyricsView(frame: .zero) + @ObservationIgnored private let session: RoomSession + @ObservationIgnored private var entry: QueueEntry? + + private static let retryDelays = [5, 10, 20] + + init(session: RoomSession) { + self.session = session + var style = LyricsConfiguration() + style.fontSize = 30 + style.palette.mainInactive = LyricsColor(1, 1, 1, alpha: 0.4) + style.palette.lineTimingInactive = LyricsColor(1, 1, 1, alpha: 0.4) + style.palette.translation = LyricsColor(1, 1, 1, alpha: 0.6) + style.palette.lineTimingSubInactive = LyricsColor(1, 1, 1, alpha: 0.6) + if UIAccessibility.isReduceMotionEnabled { + style.spring = false + style.blur = false + style.scale = false + style.emphasis = false + style.highlightMode = .discrete + } + surface.configuration = style + surface.accessibilityLabel = "歌词" + surface.accessibilityIdentifier = "lyrics" + surface.onSeek = { [weak self] time in self?.seek(toLyric: time) } + surface.onFrame = { [weak surface] frame in + // 读屏时念当前这一行。 + guard let surface, let groups = surface.document?.groups, groups.indices.contains(frame.timeline.focus) else { + return + } + let text = groups[frame.timeline.focus].main.text + if surface.accessibilityValue != text { surface.accessibilityValue = text } + } + } + + // MARK: 加载 + + /// 换歌时调用;同一首歌已经有结果时不重新取。 + func load(_ entry: QueueEntry, force: Bool = false) async { + if !force, entry.id == self.entry?.id, case .loaded(let lyrics) = phase, lyrics.status != .unavailable { return } + self.entry = entry + offset = LyricsPreferences.offset(for: entry.track) + if let record = LyricsPreferences.override(for: entry.track) { + show(record.lyrics, isOverridden: true) + return + } + + phase = .loading + for delay in Self.retryDelays + [nil] { + var reason = "暂时查不到歌词" + do { + let lyrics = try await session.client.lyrics(entry.id) + guard !Task.isCancelled else { return } + if lyrics.status != .unavailable { + show(lyrics, isOverridden: false) + return + } + } catch { + guard !Task.isCancelled else { return } + reason = error.localizedDescription + if (error as? APIError)?.isRefusal == true { + phase = .failed(reason, retryIn: nil) + return + } + } + phase = .failed(reason, retryIn: delay) + guard let delay else { return } + try? await Task.sleep(for: .seconds(delay)) + guard !Task.isCancelled else { return } + } + } + + private func show(_ lyrics: Lyrics, isOverridden: Bool) { + self.isOverridden = isOverridden + applyOffset() + if lyrics.status == .found, lyrics.isSynced { + surface.install(document: LyricsDocument(lyrics), time: session.lyricsPosition, playing: isMoving) + } else { + surface.clear() + } + phase = .loaded(lyrics) + } + + // MARK: 本机调整 + + func setOffset(_ value: Double) { + guard let entry else { return } + offset = (value * 10).rounded() / 10 + LyricsPreferences.setOffset(offset, for: entry.track) + applyOffset() + } + + /// 选用手动搜到的歌词;传 nil 恢复服务端的歌词。 + func choose(_ record: LRCLIBRecord?) async { + guard let entry else { return } + LyricsPreferences.setOverride(record, for: entry.track) + await load(entry, force: true) + } + + var searchQuery: String { entry.map { "\($0.track.title) \($0.track.artist)" } ?? "" } + + private func applyOffset() { + surface.configuration.timing.trackOffset = -offset + } + + // MARK: 对时间 + + /// MelismaKit 会自己往前推算,这里定期校准即可。 + func synchronize() { + surface.synchronize(time: session.lyricsPosition, playing: isMoving, motion: .cascade) + } + + private var isMoving: Bool { + session.room?.playback.status == .playing && session.player.state != .loading + } + + private func seek(toLyric time: TimeInterval) { + guard session.canControl, session.room?.playback.durationSec != nil else { return } + Task { await session.seek(to: max(0, time - offset)) } + } +} + +extension LyricsDocument { + init(_ lyrics: Lyrics) { + let lines = lyrics.lines.filter { !$0.text.isEmpty }.sorted { $0.atMs < $1.atMs } + func range(_ start: Int, _ end: Int) -> LyricRange { + LyricRange(Double(start) / 1000, Double(max(start, end)) / 1000) + } + let groups = lines.enumerated().map { index, line -> LyricGroup in + let timed = line.timedWords + let words = timed.isEmpty + ? [LyricLine.Word(text: line.text, startMs: line.atMs, endMs: max(line.endMs, line.atMs + 500))] : timed + return LyricGroup( + main: MelismaKit.LyricLine( + id: "\(index)", range: range(words[0].startMs, words[words.count - 1].endMs), + words: words.enumerated().map { n, word in + LyricWord(id: "\(index)-\(n)", text: word.text, range: range(word.startMs, word.endMs)) + }, + translations: line.translation.isEmpty + ? [] : [LyricTextLayer(language: "zh-Hans", text: line.translation)], + isWordTimed: !timed.isEmpty)) + } + self.init( + groups: groups, title: "", duration: groups.map(\.main.range.end).max() ?? 0, diagnostics: [], + timingMode: groups.contains { $0.main.isWordTimed } ? .word : .line) + } + + private typealias LyricLine = MusicGoKit.LyricLine +} + +/// 每首歌的歌词偏移和手动选的歌词,只存在本机。 +private enum LyricsPreferences { + private static let offsets = "lyrics.offsets" + private static let overrides = "lyrics.overrides" + + static func offset(for track: Track) -> Double { + UserDefaults.standard.dictionary(forKey: offsets)?[track.id] as? Double ?? 0 + } + + static func setOffset(_ value: Double, for track: Track) { + set(value == 0 ? nil : value, in: offsets, for: track) + } + + static func override(for track: Track) -> LRCLIBRecord? { + (UserDefaults.standard.dictionary(forKey: overrides)?[track.id] as? Data) + .flatMap { try? JSONDecoder().decode(LRCLIBRecord.self, from: $0) } + } + + static func setOverride(_ record: LRCLIBRecord?, for track: Track) { + set(record.flatMap { try? JSONEncoder().encode($0) }, in: overrides, for: track) + } + + private static func set(_ value: Any?, in key: String, for track: Track) { + var all = UserDefaults.standard.dictionary(forKey: key) ?? [:] + all[track.id] = value + UserDefaults.standard.set(all, forKey: key) + } +} diff --git a/ios/App/Player/LyricsPanel.swift b/ios/App/Player/LyricsPanel.swift new file mode 100644 index 0000000..e97e6a0 --- /dev/null +++ b/ios/App/Player/LyricsPanel.swift @@ -0,0 +1,172 @@ +import MelismaKitSwiftUI +import MusicGoKit +import SwiftUI + +/// 播放页里的歌词。滑动浏览,点一行跳到那里(要有控制权限),长按复制。 +struct LyricsPanel: View { + let session: RoomSession + let model: LyricsModel + let entry: QueueEntry + + @Environment(\.scenePhase) private var scenePhase + @State private var isAdjusting = false + + var body: some View { + content + .frame(maxWidth: .infinity, maxHeight: .infinity) + .overlay(alignment: .bottomTrailing) { + Button("歌词设置", systemImage: "slider.horizontal.3") { isAdjusting = true } + .labelStyle(.iconOnly) + .frame(width: 40, height: 40) + .background(.black.opacity(0.25), in: .circle) + .accessibilityIdentifier("lyrics-options") + } + .sheet(isPresented: $isAdjusting) { LyricsOptions(session: session, model: model) } + .task(id: entry.id) { await model.load(entry) } + .task { + while !Task.isCancelled { + model.synchronize() + try? await Task.sleep(for: .seconds(1)) + } + } + .onChange(of: session.room?.playback) { model.synchronize() } + .onChange(of: session.player.state) { model.synchronize() } + .onChange(of: scenePhase) { model.synchronize() } + } + + @ViewBuilder private var content: some View { + switch model.phase { + case .loading: + ProgressView().tint(.white) + case .failed(let reason, let retryIn): + message(retryIn.map { "\(reason),\($0) 秒后重试" } ?? reason, canRetry: true) + case .loaded(let lyrics) where lyrics.status != .found: + message("这首歌没有歌词", canRetry: false) + case .loaded(let lyrics) where !lyrics.isSynced: + ScrollView { + Text(lyrics.lines.map(\.text).joined(separator: "\n")) + .font(.title3.weight(.semibold)) + .lineSpacing(12) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.bottom, 48) + } + .scrollIndicators(.hidden) + case .loaded: + MelismaKitViewRepresentable(view: model.surface) + .mask { + LinearGradient( + stops: [ + .init(color: .clear, location: 0), .init(color: .black, location: 0.1), + .init(color: .black, location: 0.88), .init(color: .clear, location: 1), + ], startPoint: .top, endPoint: .bottom) + } + // 歌词自带 20 点边距,抵消掉,好与下面的歌名对齐。 + .padding(.horizontal, -20) + } + } + + private func message(_ text: String, canRetry: Bool) -> some View { + VStack(spacing: 12) { + Image(systemName: "quote.bubble").font(.largeTitle) + Text(text).multilineTextAlignment(.center) + HStack { + if canRetry { + Button("重试") { Task { await model.load(entry, force: true) } } + } + Button("手动搜索") { isAdjusting = true } + } + .buttonStyle(.bordered) + .tint(.white) + } + .foregroundStyle(.white.opacity(0.7)) + } +} + +/// 调整歌词的时间,或换一份歌词。只影响本机。 +private struct LyricsOptions: View { + let session: RoomSession + let model: LyricsModel + + @Environment(\.dismiss) private var dismiss + @State private var query = "" + @State private var results: [LRCLIBRecord]? + @State private var problem: String? + @State private var isSearching = false + + var body: some View { + NavigationStack { + Form { + Section { + Stepper(value: Binding(get: { model.offset }, set: { model.setOffset($0) }), in: -20...20, step: 0.1) { + Text(offsetText).monospacedDigit() + } + if model.offset != 0 { + Button("恢复原来的时间") { model.setOffset(0) } + } + if case .loaded(let lyrics) = model.phase, lyrics.status == .found { + LabeledContent("歌词来源", value: lyrics.sourceName + (model.isOverridden ? "(手动选的)" : "")) + } + if model.isOverridden { + Button("恢复自动匹配的歌词") { choose(nil) } + } + } footer: { + Text("只影响这首歌在本机的显示。") + } + Section("在 LRCLIB 搜索歌词") { + TextField("歌名和歌手", text: $query) + .submitLabel(.search) + .onSubmit(search) + if isSearching { ProgressView() } + if let problem { Text(problem).foregroundStyle(.red) } + if results?.isEmpty == true { Text("没有找到,换个关键词试试").foregroundStyle(.secondary) } + ForEach(results ?? []) { record in + Button { choose(record) } label: { + VStack(alignment: .leading, spacing: 2) { + Text(record.trackName) + Text( + "\(record.artistName) · \(formatTime(record.duration)) · \(record.syncedLyrics == nil ? "没有时间轴" : "逐行")" + ) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + .tint(.primary) + } + } + } + .navigationTitle("歌词设置") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { Button("完成") { dismiss() } } + } + } + .presentationDetents([.medium, .large]) + .onAppear { query = model.searchQuery } + } + + private var offsetText: String { + let seconds = abs(model.offset).formatted(.number.precision(.fractionLength(1))) + if model.offset == 0 { return "歌词时间:原样" } + return model.offset > 0 ? "歌词提前 \(seconds) 秒" : "歌词延后 \(seconds) 秒" + } + + private func choose(_ record: LRCLIBRecord?) { + Task { await model.choose(record) } + dismiss() + } + + private func search() { + let text = query.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, !isSearching else { return } + isSearching = true + problem = nil + Task { + defer { isSearching = false } + do { + results = try await session.client.searchLRCLIB(text) + } catch { + problem = error.localizedDescription + } + } + } +} diff --git a/ios/App/Player/LyricsView.swift b/ios/App/Player/LyricsView.swift deleted file mode 100644 index 02ea760..0000000 --- a/ios/App/Player/LyricsView.swift +++ /dev/null @@ -1,176 +0,0 @@ -// 改写自 Cassette 的 LyricsView.swift、LyricsLineView.swift 和 LyricsViewModel.swift -// Copyright (C) 2026 Mathieu Dubart -// 本文件按 Mozilla Public License 2.0 授权:https://mozilla.org/MPL/2.0/ - -import MusicGoKit -import SwiftUI - -/// 跟着房间进度滚动的歌词。手动滑动后停几秒再继续跟随。 -struct LyricsView: View { - let session: RoomSession - let entryID: String - - private enum Phase { - case loading - case loaded(Lyrics) - case failed(String) - } - - @State private var phase = Phase.loading - @State private var attempt = 0 - @State private var currentIndex: Int? - @State private var isBrowsing = false - @State private var resume: Task? - - private struct Request: Hashable { - let entryID: String - let attempt: Int - } - - var body: some View { - Group { - switch phase { - case .loading: - ProgressView().tint(.white) - case .failed(let reason): - message(reason, canRetry: true) - case .loaded(let lyrics): - switch lyrics.status { - case .found: lines(lyrics) - case .none: message("这首歌没有歌词", canRetry: false) - case .unavailable: message("暂时查不到歌词", canRetry: true) - } - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .task(id: Request(entryID: entryID, attempt: attempt)) { await load() } - .onDisappear { resume?.cancel() } - } - - private func load() async { - phase = .loading - currentIndex = nil - isBrowsing = false - let lyrics: Lyrics - do { - lyrics = try await session.client.lyrics(entryID) - } catch { - if !Task.isCancelled { phase = .failed(error.localizedDescription) } - return - } - guard !Task.isCancelled else { return } - currentIndex = lyrics.lineIndex(at: session.position) - phase = .loaded(lyrics) - while lyrics.isSynced, !Task.isCancelled { - let index = lyrics.lineIndex(at: session.position) - if index != currentIndex { currentIndex = index } - try? await Task.sleep(for: .milliseconds(100)) - } - } - - private func message(_ text: String, canRetry: Bool) -> some View { - VStack(spacing: 12) { - Image(systemName: "quote.bubble").font(.largeTitle) - Text(text) - if canRetry { - Button("重试") { attempt += 1 }.buttonStyle(.bordered).tint(.white) - } - } - .foregroundStyle(.white.opacity(0.7)) - } - - private func lines(_ lyrics: Lyrics) -> some View { - ScrollViewReader { proxy in - ScrollView { - LazyVStack(alignment: .leading, spacing: 26) { - ForEach(Array(lyrics.lines.enumerated()), id: \.offset) { index, line in - LyricsLineView( - line: line, - distance: lyrics.isSynced && !isBrowsing ? currentIndex.map { abs(index - $0) } : nil, - isCurrent: index == currentIndex, - position: { session.position } - ) - .contentShape(.rect) - .onTapGesture { - guard lyrics.isSynced, session.canControl else { return } - isBrowsing = false - Task { await session.seek(to: Double(line.atMs) / 1000) } - } - } - } - .padding(.vertical, 120) - } - .scrollIndicators(.hidden) - .mask { - LinearGradient( - stops: [ - .init(color: .clear, location: 0), .init(color: .black, location: 0.12), - .init(color: .black, location: 0.85), .init(color: .clear, location: 1), - ], startPoint: .top, endPoint: .bottom) - } - .onAppear { proxy.scrollTo(currentIndex ?? 0, anchor: .center) } - .onChange(of: currentIndex) { _, index in - guard !isBrowsing, let index else { return } - withAnimation(.smooth(duration: 0.5)) { proxy.scrollTo(index, anchor: .center) } - } - .onScrollPhaseChange { _, phase in - if phase == .interacting { - browse() - } else if phase == .idle, isBrowsing { - browse() - } - } - } - } - - private func browse() { - isBrowsing = true - resume?.cancel() - resume = Task { - try? await Task.sleep(for: .seconds(3)) - if !Task.isCancelled { isBrowsing = false } - } - } -} - -/// 离当前行越远越淡、越模糊;当前行逐字点亮。 -private struct LyricsLineView: View { - let line: LyricLine - /// 与当前行隔几行;nil 表示不分远近,都清楚显示。 - let distance: Int? - let isCurrent: Bool - let position: () -> TimeInterval - - private static let blurs: [CGFloat] = [0, 1, 2, 3.5] - private static let opacities = [1, 0.6, 0.4, 0.25] - - var body: some View { - VStack(alignment: .leading, spacing: 6) { - if isCurrent { - TimelineView(.periodic(from: .now, by: 0.1)) { _ in text(sung: line.sungPrefix(at: position())) } - } else { - text(sung: line.text) - } - if !line.translation.isEmpty { - Text(line.translation).font(.body.weight(.medium)).foregroundStyle(.white.opacity(0.7)) - } - } - .multilineTextAlignment(.leading) - .frame(maxWidth: .infinity, alignment: .leading) - .opacity(distance.map { Self.opacities[min($0, 3)] } ?? 0.9) - .blur(radius: distance.map { Self.blurs[min($0, 3)] } ?? 0) - .scaleEffect(isCurrent ? 1 : 0.96, anchor: .leading) - .animation(.easeInOut(duration: 0.3), value: distance) - } - - private func text(sung: String) -> some View { - var shown = AttributedString(line.text.isEmpty ? "♪" : line.text) - shown.foregroundColor = .white - if let start = shown.characters.index( - shown.startIndex, offsetBy: sung.count, limitedBy: shown.endIndex), !line.text.isEmpty - { - shown[start.. Void var body: some View { HStack(spacing: 12) { Button(action: onExpand) { HStack(spacing: 12) { - ArtworkImage(image: artwork.image, cornerRadius: 7).frame(width: 40, height: 40) + ArtworkImage(image: session.artwork.image, cornerRadius: 7).frame(width: 40, height: 40) VStack(alignment: .leading, spacing: 1) { Text(entry.track.title).font(.subheadline.weight(.semibold)) Text(detail).font(.caption).foregroundStyle(.secondary) @@ -50,6 +49,7 @@ struct MiniPlayer: View { private var detail: String { switch session.player.state { case .playing, .idle: entry.track.artist + case .video: "打开播放页观看" default: session.player.state.text } } @@ -87,7 +87,8 @@ extension RoomPlayer.State { case .playing: "正在本机播放" case .paused: "已暂停" case .off: "本机已静音" - case .unsupported: "这首歌暂时不能在 App 里播放,请用网页版收听" + case .video: "视频只在播放页打开时播放" + case .unsupported: "这首歌不能在 App 里播放" case .failed(let reason): reason } } diff --git a/ios/App/Player/NOTICE.md b/ios/App/Player/NOTICE.md index e0215ea..7891991 100644 --- a/ios/App/Player/NOTICE.md +++ b/ios/App/Player/NOTICE.md @@ -3,15 +3,15 @@ | 文件 | 改写自 | 许可 | |---|---|---| | `PlayerView.swift`、`MiniPlayer.swift`(布局),`ElasticSlider.swift`、`MarqueeText.swift` | [AppleMusicStylePlayer](https://github.com/f728743/AppleMusicStylePlayer) `a0b5631417de` | MIT | -| `LyricsView.swift` | [Cassette](https://github.com/CassetteLab/cassette) `aed1663d21df` | MPL-2.0 | 主要改动: - 数据和操作换成 MusicGo 的房间状态;进度条接上房间跳转,松手才生效。 - 展开和收起改用系统的缩放转场,背景改用 `MeshGradient`,不再依赖 Kingfisher 和 Metal。 -- 歌词加上翻译和逐字高亮。 -`LyricsView.swift` 仍按 [MPL-2.0](https://mozilla.org/MPL/2.0/) 授权,其余按 MusicGo 的 AGPL-3.0 发布,并保留下面的声明。 +改写后的文件按 MusicGo 的 AGPL-3.0 发布,并保留下面的声明。 + +歌词的滚动和逐字高亮由依赖库 [MelismaKit for iOS](https://github.com/kmgcc/melismakit-ios)(AGPL-3.0,源自 [AMLL](https://github.com/amll-dev/applemusic-like-lyrics))绘制,代码不在本仓库,版本固定在 `ios/project.yml`。 ## AppleMusicStylePlayer diff --git a/ios/App/Player/PlayerView.swift b/ios/App/Player/PlayerView.swift index 7d7af46..15681e4 100644 --- a/ios/App/Player/PlayerView.swift +++ b/ios/App/Player/PlayerView.swift @@ -7,7 +7,6 @@ import SwiftUI /// 完整的播放页:封面、歌词或队列,下面是控制。 struct PlayerView: View { let session: RoomSession - let artwork: Artwork private enum Panel { case artwork, lyrics, queue @@ -15,50 +14,105 @@ struct PlayerView: View { @Environment(\.dismiss) private var dismiss @State private var panel = Panel.artwork + /// 打开页面后才创建:里面有一个较重的原生视图,不能每次刷新都新建。 + @State private var lyrics: LyricsModel? + @State private var isFindingAnother = false + + private var artwork: Artwork { session.artwork } var body: some View { ZStack { ArtworkBackground(colors: artwork.colors).ignoresSafeArea() if let room = session.room, let entry = room.playback.entry { - content(room, entry) + GeometryReader { proxy in + // iPad 横屏:左边播放,右边歌词或队列。 + if proxy.size.width > proxy.size.height, proxy.size.width > 800 { + wide(room, entry) + } else { + narrow(room, entry).frame(maxWidth: .infinity) + } + } } } .foregroundStyle(.white) .environment(\.colorScheme, .dark) + .onAppear { lyrics = lyrics ?? LyricsModel(session: session) } .onChange(of: session.room?.playback.entry == nil) { _, isIdle in if isIdle { dismiss() } } - .noticeAlert(session) + .sheet(isPresented: $isFindingAnother) { + if let track = session.room?.playback.entry?.track { + SearchView(session: session, initialQuery: "\(track.title) \(track.artist)", initialSource: track.source) + } + } + .noticeAlert(session, isActive: !isFindingAnother) } - private func content(_ room: Room, _ entry: QueueEntry) -> some View { + private func narrow(_ room: Room, _ entry: QueueEntry) -> some View { VStack(spacing: 0) { - Button("收起", systemImage: "chevron.compact.down") { dismiss() } - .labelStyle(.iconOnly) - .font(.title.weight(.semibold)) - .foregroundStyle(.white.opacity(0.6)) - .frame(width: 80, height: 36) - .accessibilityIdentifier("close-player") - - Group { - switch panel { - case .artwork: - // 暂停时封面缩小。 - ArtworkImage(image: artwork.image, cornerRadius: 12) - .shadow(color: .black.opacity(0.3), radius: 16, y: 10) - .scaleEffect(room.playback.status == .playing ? 1 : 0.8) - .animation(.smooth, value: room.playback.status) - .frame(maxHeight: .infinity) - case .lyrics: - LyricsView(session: session, entryID: entry.id) - case .queue: - queue(room) - } + closeButton + VStack(spacing: 12) { + // 视频必须看得见,所以看歌词和队列时也留在上面。 + if entry.track.youTubeID != nil || panel == .artwork { media(room, entry) } + if panel != .artwork { side(room, entry) } } .transition(.opacity) .padding(.vertical, 12) + controls(room, entry, showsThumbnail: panel != .artwork && entry.track.youTubeID == nil) + } + .padding(.horizontal, 28) + .padding(.bottom, 12) + .frame(maxWidth: 560) + } - info(room, entry) + private func wide(_ room: Room, _ entry: QueueEntry) -> some View { + HStack(spacing: 48) { + VStack(spacing: 0) { + closeButton + media(room, entry).padding(.vertical, 12) + controls(room, entry, showsThumbnail: false) + } + .frame(maxWidth: 480) + side(room, entry).frame(maxWidth: .infinity) + } + .padding(.horizontal, 48) + .padding(.vertical, 12) + } + + private var closeButton: some View { + Button("收起", systemImage: "chevron.compact.down") { dismiss() } + .labelStyle(.iconOnly) + .font(.title.weight(.semibold)) + .foregroundStyle(.white.opacity(0.6)) + .frame(width: 80, height: 36) + .accessibilityIdentifier("close-player") + } + + @ViewBuilder private func media(_ room: Room, _ entry: QueueEntry) -> some View { + if let videoID = entry.track.youTubeID { + YouTubeView(session: session, entry: entry, videoID: videoID) { isFindingAnother = true } + .frame(maxHeight: panel == .artwork ? .infinity : nil) + } else { + // 暂停时封面缩小。 + ArtworkImage(image: artwork.image, cornerRadius: 12) + .shadow(color: .black.opacity(0.3), radius: 16, y: 10) + .scaleEffect(room.playback.status == .playing ? 1 : 0.8) + .animation(.smooth, value: room.playback.status) + .frame(maxHeight: .infinity) + } + } + + @ViewBuilder private func side(_ room: Room, _ entry: QueueEntry) -> some View { + if panel == .queue { + queue(room) + } else if let lyrics { + LyricsPanel(session: session, model: lyrics, entry: entry) + } + } + + private func controls(_ room: Room, _ entry: QueueEntry, showsThumbnail: Bool) -> some View { + VStack(spacing: 0) { + info(room, entry, showsThumbnail: showsThumbnail) TimelineView(.periodic(from: .now, by: 0.5)) { _ in ElasticSlider( position: session.position, duration: room.playback.durationSec, @@ -67,23 +121,20 @@ struct PlayerView: View { } .padding(.top, 18) buttons(room).padding(.vertical, 14) - footer + footer(room) } - .padding(.horizontal, 28) - .padding(.bottom, 12) - .frame(maxWidth: 560) } - private func info(_ room: Room, _ entry: QueueEntry) -> some View { + private func info(_ room: Room, _ entry: QueueEntry, showsThumbnail: Bool) -> some View { HStack(spacing: 12) { - if panel != .artwork { + if showsThumbnail { ArtworkImage(image: artwork.image, cornerRadius: 8).frame(width: 52, height: 52) } VStack(alignment: .leading, spacing: 3) { MarqueeText(entry.track.title) .font(.title3.bold()) .accessibilityIdentifier("now-playing-title") - Text("\(entry.track.artist) · \(room.memberName(entry.requestedBy)) 点的") + Text("\(entry.track.artist) · \(room.requester(entry.requestedBy, onBehalfOf: entry.onBehalfOf))") .lineLimit(1) .foregroundStyle(.white.opacity(0.65)) } @@ -123,10 +174,10 @@ struct PlayerView: View { .frame(height: 68) } - private var footer: some View { + private func footer(_ room: Room) -> some View { HStack { panelButton(.lyrics, "歌词", "quote.bubble") - Text(session.player.state.text) + Text(status(room)) .font(.caption) .foregroundStyle(.white.opacity(0.65)) .multilineTextAlignment(.center) @@ -136,6 +187,12 @@ struct PlayerView: View { } } + private func status(_ room: Room) -> String { + if !session.isLive { return "正在重新连接…" } + if room.votes.count > 0 { return "切歌投票 \(room.votes.count) / \(room.votes.threshold)" } + return session.player.state.text + } + private func panelButton(_ target: Panel, _ title: String, _ icon: String) -> some View { Button(title, systemImage: icon) { withAnimation(.smooth(duration: 0.35)) { panel = panel == target ? .artwork : target } @@ -149,15 +206,19 @@ struct PlayerView: View { } private func queue(_ room: Room) -> some View { - ScrollView { - LazyVStack(alignment: .leading, spacing: 14) { - Text("待播 \(room.queue.count) 首").font(.headline) - ForEach(room.queue) { entry in - TrackRow(track: entry.track, detail: "\(room.memberName(entry.requestedBy)) 点的") - } + List { + Section { + QueueRows(session: session, room: room) + .listRowBackground(Color.clear) + .listRowInsets(EdgeInsets(top: 7, leading: 0, bottom: 7, trailing: 0)) + .listRowSeparator(.hidden) + } header: { + Text("待播 \(room.queue.count) 首").font(.headline).foregroundStyle(.white) + .listRowInsets(EdgeInsets()) } - .frame(maxWidth: .infinity, alignment: .leading) } + .listStyle(.plain) + .scrollContentBackground(.hidden) .scrollIndicators(.hidden) } } diff --git a/ios/App/Player/YouTubePlayer.swift b/ios/App/Player/YouTubePlayer.swift new file mode 100644 index 0000000..aa72673 --- /dev/null +++ b/ios/App/Player/YouTubePlayer.swift @@ -0,0 +1,221 @@ +import MusicGoKit +import SwiftUI +import WebKit + +/// YouTube 官方的内嵌播放器。按 YouTube 的规定,视频必须看得见,也不能在后台播放。 +@MainActor @Observable +final class YouTubePlayer { + /// YouTube 给的错误码;-1 表示播放器加载不出来。 + private(set) var errorCode: Int? + + @ObservationIgnored private(set) var webView: WKWebView + @ObservationIgnored var onEnded: (() -> Void)? + @ObservationIgnored private let server: URL + + init(server: URL) { + self.server = server + let configuration = WKWebViewConfiguration() + configuration.allowsInlineMediaPlayback = true + configuration.mediaTypesRequiringUserActionForPlayback = [] + webView = WKWebView(frame: .zero, configuration: configuration) + webView.isOpaque = false + webView.backgroundColor = .black + webView.scrollView.isScrollEnabled = false + configuration.userContentController.add(Receiver(self), name: "player") + reload() + } + + func reload() { + errorCode = nil + // YouTube 要知道是哪个网站在内嵌,所以用房间服务器的地址。 + webView.loadHTMLString(Self.page, baseURL: server) + } + + func clearError() { errorCode = nil } + + func synchronize(videoID: String, position: TimeInterval, isPlaying: Bool, isMuted: Bool) { + struct Wanted: Encodable { + let id: String + let at: Double + let playing: Bool + let muted: Bool + } + let wanted = Wanted(id: videoID, at: position, playing: isPlaying, muted: isMuted) + guard let json = try? JSONEncoder().encode(wanted) else { return } + webView.evaluateJavaScript("window.sync && sync(\(String(decoding: json, as: UTF8.self)))") { _, _ in } + } + + fileprivate func receive(_ body: Any) { + guard let message = body as? [String: Int] else { return } + if let code = message["error"] { errorCode = code } + switch message["state"] { + case 0: onEnded?() + case 1: errorCode = nil + default: break + } + } + + /// WebKit 会一直持有接收者,所以隔一层弱引用。 + private final class Receiver: NSObject, WKScriptMessageHandler { + private weak var owner: YouTubePlayer? + + init(_ owner: YouTubePlayer) { self.owner = owner } + + func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) { + owner?.receive(message.body) + } + } + + private static let page = """ + + +
+ + + """ +} + +/// 播放页里的视频,以及放不了时的处理办法。 +struct YouTubeView: View { + let session: RoomSession + let entry: QueueEntry + let videoID: String + let onFindAnother: () -> Void + + /// 显示后才创建,免得每次刷新都新建一个网页。 + @State private var player: YouTubePlayer? + /// 到时间没人处理,就自动投票切歌。 + @State private var deadline: Date? + + /// 多半是要登录,或不让站外播放;给两分钟处理。 + private static let recoverable = [101, 150, 153] + private static let broken = [2, 100] + + var body: some View { + VStack(spacing: 12) { + Color.black + .overlay { if let player { WebView(view: player.webView) } } + .aspectRatio(16 / 9, contentMode: .fit) + .clipShape(.rect(cornerRadius: 12)) + if let code = player?.errorCode { failure(code) } + } + .task(id: entry.id) { + let player = player ?? YouTubePlayer(server: session.client.link.server) + self.player = player + player.clearError() + let id = entry.id + player.onEnded = { [session] in + // 已知时长的歌由服务端切换。 + guard let playback = session.room?.playback, playback.entry?.id == id, playback.durationSec == nil else { + return + } + Task { try? await session.client.reportCompleted(id) } + } + while !Task.isCancelled { + synchronize() + if let deadline, Date() >= deadline { + self.deadline = nil + await session.reportUnplayable(id) + } + try? await Task.sleep(for: .seconds(1)) + } + } + .onChange(of: session.room?.playback) { synchronize() } + .onChange(of: session.player.isListening) { synchronize() } + .onChange(of: player?.errorCode) { _, code in + deadline = nil + guard let code else { return } + if Self.recoverable.contains(code) { + deadline = Date().addingTimeInterval(120) + } else if Self.broken.contains(code) { + Task { await session.reportUnplayable(entry.id) } + } + } + } + + private func synchronize() { + player?.synchronize( + videoID: videoID, position: session.position, isPlaying: session.room?.playback.status == .playing, + isMuted: !session.player.isListening) + } + + private func failure(_ code: Int) -> some View { + VStack(spacing: 10) { + Text(reason(code)).font(.footnote).multilineTextAlignment(.center) + if let deadline, !session.hasReported(entry.id) { + Text("\(Text(timerInterval: Date()...max(Date(), deadline))) 后自动投票切歌").font(.caption).monospacedDigit() + } + HStack { + Button("重试") { player?.reload() } + Button("换个版本", action: onFindAnother) + if let url = URL(string: entry.track.url) { Link("去 YouTube 看", destination: url) } + } + if session.hasReported(entry.id) { + Text("已投票切歌").font(.caption) + } else { + Button("我这里放不了,投票切歌") { + deadline = nil + Task { await session.reportUnplayable(entry.id) } + } + } + } + .buttonStyle(.bordered) + .tint(.white) + .font(.footnote) + } + + private func reason(_ code: Int) -> String { + switch code { + case -1: "YouTube 播放器加载不出来,请检查网络" + case 2: "这个视频的地址无效" + case 100: "这个视频已被删除或设为私密" + case 101, 150, 153: "YouTube 不让在这里播放这个视频(错误码 \(code))" + default: "YouTube 播放器出错了(错误码 \(code))" + } + } +} + +private struct WebView: UIViewRepresentable { + let view: WKWebView + + func makeUIView(context: Context) -> WKWebView { view } + func updateUIView(_: WKWebView, context: Context) {} +} diff --git a/ios/App/QueueRows.swift b/ios/App/QueueRows.swift new file mode 100644 index 0000000..7a7ff4b --- /dev/null +++ b/ios/App/QueueRows.swift @@ -0,0 +1,71 @@ +import MusicGoKit +import SwiftUI + +/// 待播队列的各行,放在 List 里用。左滑撤回;房主和管理员可以长按拖动,调整顺序。 +struct QueueRows: View { + let session: RoomSession + let room: Room + + var body: some View { + ForEach(room.queue) { entry in + TrackRow(track: entry.track, detail: room.requester(entry.requestedBy, onBehalfOf: entry.onBehalfOf)) + .swipeActions { + if session.canRetract(entry) { + Button("撤回", systemImage: "trash", role: .destructive) { + Task { await session.retract(entry) } + } + } + } + .accessibilityIdentifier("queue-entry") + } + .onMove { move(from: $0, to: $1) } + .moveDisabled(!session.canControl) + } + + private func move(from source: IndexSet, to destination: Int) { + guard let from = source.first else { return } + let entry = room.queue[from] + // SwiftUI 给的是移走之前的位置。 + Task { await session.move(entry, to: destination > from ? destination - 1 : destination) } + } +} + +struct TrackRow: View { + let track: Track + let detail: String + + var body: some View { + HStack(spacing: 12) { + CoverView(url: track.cover).frame(width: 48, height: 48) + VStack(alignment: .leading, spacing: 2) { + Text(track.title).lineLimit(1) + Text([track.artist, detail].filter { !$0.isEmpty }.joined(separator: " · ")) + .font(.footnote) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 0) + Text(formatTime(track.durationSec)) + .font(.footnote.monospacedDigit()) + .foregroundStyle(.secondary) + } + } +} + +private struct CoverView: View { + let url: URL? + + var body: some View { + // 先占住方形,图片再大也只能填满它。 + Color(.systemGray5) + .overlay { + AsyncImage(url: url) { image in + image.resizable().scaledToFill() + } placeholder: { + Image(systemName: "music.note").foregroundStyle(.secondary) + } + } + .clipShape(.rect(cornerRadius: 7)) + .accessibilityHidden(true) + } +} diff --git a/ios/App/RoomInfoView.swift b/ios/App/RoomInfoView.swift new file mode 100644 index 0000000..bb272bc --- /dev/null +++ b/ios/App/RoomInfoView.swift @@ -0,0 +1,271 @@ +import MusicGoKit +import SwiftUI +import UIKit + +/// 房间信息:投票、邀请、成员、设置、最近播放。能做什么由服务端的权限决定。 +struct RoomInfoView: View { + let session: RoomSession + let onLeave: () -> Void + + private enum Confirmation: Identifiable { + case resetInvite, leave + case transfer(Member), kick(Member) + + var id: String { + switch self { + case .resetInvite: "reset" + case .leave: "leave" + case .transfer(let member): "transfer-\(member.id)" + case .kick(let member): "kick-\(member.id)" + } + } + } + + @Environment(\.dismiss) private var dismiss + @State private var confirmation: Confirmation? + @State private var hasCopied = false + + private var isOwner: Bool { session.me.flatMap { session.room?.isOwner($0.id) } ?? false } + + var body: some View { + NavigationStack { + List { + if let room = session.room { + votes(room) + if let code = room.inviteCode { invite(room, code) } + members(room) + Section { + NavigationLink("房间设置") { RoomSettingsView(session: session, room: room, canEdit: isOwner) } + NavigationLink("最近播放") { HistoryView(room: room) } + } + } + Section { + Button("退出房间", role: .destructive) { confirmation = .leave } + } footer: { + Link("源码 · AGPL-3.0", destination: sourceURL).font(.footnote) + } + } + .navigationTitle(session.room?.name ?? "房间") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { Button("完成") { dismiss() } } + } + .alert( + confirmation.map(title) ?? "", isPresented: Binding( + get: { confirmation != nil }, set: { if !$0 { confirmation = nil } }), + presenting: confirmation + ) { item in + Button("取消", role: .cancel) {} + Button(action(item), role: .destructive) { confirm(item) } + } message: { + Text(message($0)) + } + } + .noticeAlert(session) + } + + private var sourceURL: URL { + session.room?.sourceUrl.flatMap { URL(string: $0) } ?? URL(string: "https://github.com/luckybot-dev/MusicGo")! + } + + private func votes(_ room: Room) -> some View { + Section("切歌投票") { + LabeledContent("当前这首", value: "\(room.votes.count) / \(room.votes.threshold) 票") + if !room.votes.voters.isEmpty { + Text(room.votes.voters.map(room.memberName).joined(separator: "、")) + .font(.footnote) + .foregroundStyle(.secondary) + } + } + } + + private func invite(_ room: Room, _ code: String) -> some View { + Section { + LabeledContent("邀请码") { Text(code).monospaced().textSelection(.enabled) } + Button(hasCopied ? "已复制" : "复制邀请码", systemImage: hasCopied ? "checkmark" : "doc.on.doc") { + UIPasteboard.general.string = code + hasCopied = true + } + if isOwner { + Button("重置邀请码", systemImage: "arrow.clockwise") { confirmation = .resetInvite } + } + } header: { + Text("邀请") + } footer: { + Text("房间号:\(room.id)").textSelection(.enabled) + } + } + + private func members(_ room: Room) -> some View { + Section("成员(在线 \(room.online.count) / \(room.members.count))") { + ForEach(room.members) { member in + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(member.name + (member.id == session.me?.id ? "(我)" : "")) + Text(detail(member, isOnline: room.online.contains(member.id))) + .font(.footnote) + .foregroundStyle(.secondary) + } + Spacer() + if isOwner, member.role != .owner { actions(member) } + } + } + } + } + + private func detail(_ member: Member, isOnline: Bool) -> String { + let role = + switch member.role { + case .owner: "房主" + case .admin: "管理员" + case .member: "成员" + } + return [role, member.kind == .agent ? "AI" : nil, isOnline ? "在听" : "离线"].compactMap { $0 }.joined(separator: " · ") + } + + private func actions(_ member: Member) -> some View { + Menu("管理\(member.name)", systemImage: "ellipsis.circle") { + Button( + member.role == .admin ? "取消管理员" : "设为管理员", + systemImage: member.role == .admin ? "person.badge.minus" : "person.badge.shield.checkmark" + ) { + perform { try await $0.setRole(member.role == .admin ? .member : .admin, of: member.id) } + } + Button("转让房主", systemImage: "crown") { confirmation = .transfer(member) } + Button("移出房间", systemImage: "person.slash", role: .destructive) { confirmation = .kick(member) } + } + .labelStyle(.iconOnly) + } + + // MARK: 确认 + + private func title(_ item: Confirmation) -> String { + switch item { + case .resetInvite: "重置邀请码?" + case .leave: "退出房间?" + case .transfer(let member): "把房主转让给\(member.name)?" + case .kick(let member): "把\(member.name)移出房间?" + } + } + + private func message(_ item: Confirmation) -> String { + switch item { + case .resetInvite: "原来的邀请码会失效。" + case .leave: "只清除本机的登录,再进来要重新粘贴进入链接。" + case .transfer: "你会变成管理员,自己不能撤销。" + case .kick: "TA 点的待播歌曲也会一起移除。" + } + } + + private func action(_ item: Confirmation) -> String { + switch item { + case .resetInvite: "重置" + case .leave: "退出" + case .transfer: "转让" + case .kick: "移出" + } + } + + private func confirm(_ item: Confirmation) { + switch item { + case .leave: onLeave() + case .transfer(let member): perform { try await $0.transferOwner(to: member.id) } + case .kick(let member): perform { try await $0.kick(member.id) } + case .resetInvite: + hasCopied = false + perform { try await $0.resetInvite() } + } + } + + private func perform(_ action: @escaping @Sendable (APIClient) async throws -> Void) { + let client = session.client + Task { await session.perform { try await action(client) } } + } +} + +private struct RoomSettingsView: View { + let session: RoomSession + let canEdit: Bool + + @Environment(\.dismiss) private var dismiss + @State private var name: String + @State private var settings: RoomSettings + @State private var isSaving = false + private let original: Room + + init(session: RoomSession, room: Room, canEdit: Bool) { + self.session = session + self.canEdit = canEdit + original = room + _name = State(initialValue: room.name) + _settings = State(initialValue: room.settings) + } + + private var trimmedName: String { name.trimmingCharacters(in: .whitespacesAndNewlines) } + + var body: some View { + Form { + Section { + TextField("房间名称", text: $name) + Picker("播放顺序", selection: $settings.orderMode) { + Text("轮流播放").tag(RoomSettings.OrderMode.fair) + Text("先点先播").tag(RoomSettings.OrderMode.fifo) + } + } footer: { + Text("轮流播放:大家点的歌穿插着放,不会被一个人占满。") + } + Section("切歌") { + Stepper( + "投票达到在线人数的 \(Int((settings.voteRatio * 100).rounded()))%", value: $settings.voteRatio, + in: 0.1...1, step: 0.05) + Stepper( + "放完后等 \(settings.autoAdvanceGraceSeconds) 秒再切", value: $settings.autoAdvanceGraceSeconds, in: 0...60) + } + Section("每人最多待播") { + Stepper("成员 \(settings.maxPendingHuman) 首", value: $settings.maxPendingHuman, in: 1...100) + Stepper("AI \(settings.maxPendingAgent) 首", value: $settings.maxPendingAgent, in: 0...100) + } + if !canEdit { + Text("只有房主能修改。").font(.footnote).foregroundStyle(.secondary) + } + } + .disabled(!canEdit || isSaving) + .navigationTitle("房间设置") + .toolbar { + if canEdit { + ToolbarItem(placement: .confirmationAction) { + Button("保存", action: save) + .disabled( + isSaving || trimmedName.isEmpty + || (trimmedName == original.name && settings == original.settings)) + } + } + } + } + + private func save() { + isSaving = true + Task { + let name = trimmedName + let settings = settings + let saved = await session.perform { try await session.client.update(name: name, settings: settings) } + isSaving = false + if saved { dismiss() } + } + } +} + +private struct HistoryView: View { + let room: Room + + var body: some View { + List(room.history.prefix(20)) { item in + TrackRow(track: item.track, detail: room.requester(item.requestedBy, onBehalfOf: item.onBehalfOf)) + } + .listStyle(.plain) + .overlay { + if room.history.isEmpty { ContentUnavailableView("还没有放过歌", systemImage: "clock") } + } + .navigationTitle("最近播放") + } +} diff --git a/ios/App/RoomPlayer.swift b/ios/App/RoomPlayer.swift index 6f2f328..79dd27e 100644 --- a/ios/App/RoomPlayer.swift +++ b/ios/App/RoomPlayer.swift @@ -9,7 +9,8 @@ import UIKit final class RoomPlayer { enum State: Equatable { case idle, loading, playing, paused, off - /// 这首歌的音频不由服务端转发(如 YouTube)。 + /// 由播放页里的 YouTube 播放器播放。 + case video case unsupported case failed(String) } @@ -17,11 +18,21 @@ final class RoomPlayer { private(set) var state = State.idle /// 本机是否出声。不影响房间里的其他人。 var isListening = true { - didSet { update() } + didSet { + // 用户要求播放,就不管有没有被别的声音打断了。 + if isListening { isInterrupted = false } + update() + } } /// 锁屏或耳机上按了「下一首」。 @ObservationIgnored var onNext: (() -> Void)? + /// 锁屏或耳机上按了「播放」。 + @ObservationIgnored var onPlay: (() -> Void)? + /// 锁屏上拖了进度。 + @ObservationIgnored var onSeek: ((TimeInterval) -> Void)? + /// 服务端给不出音频,或音频放不了。网络不通不算。 + @ObservationIgnored var onUnplayable: ((String) -> Void)? @ObservationIgnored private let client: APIClient @ObservationIgnored private let player = AVPlayer() @@ -33,25 +44,48 @@ final class RoomPlayer { @ObservationIgnored private var tries = 0 @ObservationIgnored private var failure: String? @ObservationIgnored private var hasEnded = false + /// 别的 App 或来电占用了声音。 @ObservationIgnored private var isInterrupted = false + @ObservationIgnored private var cover: UIImage? @ObservationIgnored private var alignedAt = Date.distantPast - @ObservationIgnored private var backgroundTask = UIBackgroundTaskIdentifier.invalid - @ObservationIgnored private var usedBackgroundTime = false + @ObservationIgnored private let silence = try? AVAudioPlayer(data: RoomPlayer.silentWAV) + @ObservationIgnored private var hasSession = false + @ObservationIgnored private var retrySessionAt: Date? + @ObservationIgnored private var idleSince = Date.distantPast + @ObservationIgnored private var isAwaitingSong = false private static let maxTries = 3 /// 与房间差多少秒才校准,以及两次校准至少隔多久。 private static let maxDrift = 1.8 private static let alignInterval = 5.0 + /// 歌放完后,在后台等下一首多久。 + private static let maxIdle: TimeInterval = 30 * 60 init(client: APIClient) { self.client = client } - func follow(_ playback: Playback, clock: PlaybackClock, canSkip: Bool) { + /// 耳朵实际听到的进度。没有在出声时为 nil。 + var heardPosition: TimeInterval? { + guard state == .playing, !hasEnded, player.timeControlStatus == .playing else { return nil } + return player.currentTime().seconds + } + + func setCover(_ image: UIImage?) { + cover = image + updateNowPlaying() + } + + func follow(_ playback: Playback, clock: PlaybackClock, canSkip: Bool, canControl: Bool) { activate() - MPRemoteCommandCenter.shared().nextTrackCommand.isEnabled = canSkip && playback.entry != nil + let remote = MPRemoteCommandCenter.shared() + remote.nextTrackCommand.isEnabled = canSkip && playback.entry != nil + remote.changePlaybackPositionCommand.isEnabled = canControl && playback.durationSec != nil let changedEntry = playback.entry?.id != self.playback?.entry?.id let jumped = playback.basePositionSec != self.playback?.basePositionSec + let started = playback.status == .playing && (changedEntry || self.playback?.status != .playing) + if playback.entry == nil, self.playback?.entry != nil { idleSince = Date() } + if started { resumeIfQuiet() } self.playback = playback self.clock = clock if changedEntry { @@ -72,13 +106,26 @@ final class RoomPlayer { let remote = MPRemoteCommandCenter.shared() remote.playCommand.removeTarget(nil) remote.pauseCommand.removeTarget(nil) + remote.togglePlayPauseCommand.removeTarget(nil) remote.nextTrackCommand.removeTarget(nil) + remote.changePlaybackPositionCommand.removeTarget(nil) playback = nil + idleSince = .distantPast + cover = nil load() update() + hasSession = false try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } + /// 网络恢复后,再试一次刚才没放成的歌。 + func retry() { + guard failure != nil else { return } + tries = 0 + load() + update() + } + // MARK: 播放 private func load() { @@ -98,9 +145,10 @@ final class RoomPlayer { player.replaceCurrentItem(with: AVPlayerItem(url: url)) } catch { guard !Task.isCancelled else { return } - // 服务端明确拒绝的,再试也一样。 - let refused = (error as? APIError).map { (400..<500).contains($0.status) && $0.status != 429 } ?? false - failed(error, retry: !refused) + let refusal = error as? APIError + // 刚好切歌了,新的状态马上就到。 + guard refusal?.code != "stale_entry" else { return } + failed(error, retry: refusal?.isRefusal != true) } } } @@ -108,21 +156,28 @@ final class RoomPlayer { private func failed(_ error: Error?, retry: Bool) { if retry, tries < Self.maxTries { load() - } else { - player.replaceCurrentItem(with: nil) - failure = error?.localizedDescription ?? "音频无法播放" + return } + player.replaceCurrentItem(with: nil) + failure = error?.localizedDescription ?? "音频无法播放" + if !(error is URLError), let entry = playback?.entry { onUnplayable?(entry.id) } } private func align() { guard let playback, let item = player.currentItem, item.status == .readyToPlay else { return } alignedAt = Date() let target = clock.position(of: playback) - player.seek(to: CMTime(seconds: target, preferredTimescale: 600)) + let tolerance = CMTime(seconds: 0.1, preferredTimescale: 600) + player.seek( + to: CMTime(seconds: target, preferredTimescale: 600), toleranceBefore: tolerance, toleranceAfter: tolerance) } /// 让播放器符合房间状态。每半秒执行一次,状态变化时也会执行。 private func update() { + if let retrySessionAt, Date() >= retrySessionAt { + self.retrySessionAt = nil + resumeIfQuiet() + } let next = advance() keepAwakeBetweenSongs() guard next != state else { return } @@ -130,31 +185,71 @@ final class RoomPlayer { updateNowPlaying() } - /// 没有声音时,后台的 App 很快会被挂起。换歌和加载时申请一点时间,好接上下一首。 + /// 没有声音时,后台的 App 几秒后就会被挂起,接不上下一首。 + /// 换歌、加载和等人点歌时放一段无声音频,让 App 继续运行。 private func keepAwakeBetweenSongs() { - let isSilent = hasEnded || player.timeControlStatus != .playing - let isWaiting = isListening && !isInterrupted && failure == nil && isSilent - && playback?.status == .playing && playback?.entry?.track.isStreamable == true - if !isWaiting { - endBackgroundTask() - usedBackgroundTime = false - } else if backgroundTask == .invalid, !usedBackgroundTime { - usedBackgroundTime = true - backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "next-song") { [weak self] in - MainActor.assumeIsolated { self?.endBackgroundTask() } - } + let isLoading = playback?.status == .playing && playback?.entry?.track.isStreamable == true + && failure == nil && (hasEnded || player.timeControlStatus != .playing) + // 只有刚才在放歌才等,免得一打开空房间就停掉别的 App 的声音。 + let isAwaiting = playback != nil && playback?.entry == nil && hasSession + && Date().timeIntervalSince(idleSince) < Self.maxIdle + let isNeeded = isListening && !isInterrupted && (isLoading || isAwaiting) + if isNeeded, silence?.isPlaying == false { + if takeSession() { silence?.play() } + } else if !isNeeded, silence?.isPlaying == true { + silence?.pause() + } + if isAwaitingSong != (isNeeded && isAwaiting) { + isAwaitingSong.toggle() + updateNowPlaying() + } + } + + /// 一秒钟的无声音频:8 kHz、单声道、16 位。 + private static let silentWAV: Data = { + func bytes(_ value: T) -> Data { withUnsafeBytes(of: value.littleEndian) { Data($0) } } + let length: UInt32 = 16000 + var wav = Data("RIFF".utf8) + wav += bytes(36 + length) + wav += Data("WAVEfmt ".utf8) + wav += bytes(UInt32(16)) + wav += bytes(UInt16(1)) // PCM + wav += bytes(UInt16(1)) + wav += bytes(UInt32(8000)) + wav += bytes(length) + wav += bytes(UInt16(2)) + wav += bytes(UInt16(16)) + wav += Data("data".utf8) + wav += bytes(length) + wav += Data(count: Int(length)) + return wav + }() + + /// 取得系统的声音输出。拿不到(如正在通话)就当作被打断,过几秒再试。 + private func takeSession() -> Bool { + do { + let session = AVAudioSession.sharedInstance() + try session.setCategory(.playback) + try session.setActive(true) + hasSession = true + retrySessionAt = nil + return true + } catch { + isInterrupted = true + retrySessionAt = Date().addingTimeInterval(5) + return false } } - private func endBackgroundTask() { - guard backgroundTask != .invalid else { return } - UIApplication.shared.endBackgroundTask(backgroundTask) - backgroundTask = .invalid + /// 「打断已结束」的通知不一定会来。回到 App 或开始放新歌时,只要没有别的声音就接着放。 + private func resumeIfQuiet() { + guard isInterrupted, !AVAudioSession.sharedInstance().isOtherAudioPlaying else { return } + isInterrupted = false } private func advance() -> State { guard let playback, let entry = playback.entry else { return .idle } - guard entry.track.isStreamable else { return .unsupported } + guard entry.track.isStreamable else { return entry.track.youTubeID == nil ? .unsupported : .video } if let item = player.currentItem, item.status == .failed { failed(item.error, retry: true) } @@ -176,8 +271,7 @@ final class RoomPlayer { if hasEnded { return .playing } if player.rate == 0 { - try? AVAudioSession.sharedInstance().setCategory(.playback) - try? AVAudioSession.sharedInstance().setActive(true) + guard takeSession() else { return .paused } align() player.play() } else if player.timeControlStatus == .playing, @@ -193,6 +287,7 @@ final class RoomPlayer { private func activate() { guard ticker == nil else { return } + silence?.numberOfLoops = -1 ticker = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(for: .milliseconds(500)) @@ -206,11 +301,31 @@ final class RoomPlayer { [weak self] note in let began = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt == AVAudioSession.InterruptionType.began.rawValue + // App 被挂起过,回来时系统会补发一次「打断开始」,但永远没有对应的「结束」。这时没有别人占用声音。 + let wasSuspended = note.userInfo?[AVAudioSessionInterruptionReasonKey] as? UInt == 1 + MainActor.assumeIsolated { + guard let self else { return } + if began { self.hasSession = false } + self.isInterrupted = began && !wasSuspended + self.update() + } + }, + center.addObserver(forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main) { + [weak self] _ in MainActor.assumeIsolated { - self?.isInterrupted = began + self?.resumeIfQuiet() self?.update() } }, + // 系统的音频服务重启后,原来的播放内容都作废了。 + center.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: nil, queue: .main) { + [weak self] _ in + MainActor.assumeIsolated { + self?.hasSession = false + self?.tries = 0 + self?.load() + } + }, // 拔掉耳机后不要改用扬声器继续放。 center.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] note in @@ -225,7 +340,21 @@ final class RoomPlayer { // 锁屏上的播放、暂停只管本机,不会让整个房间停下来;「下一首」是切整个房间的歌。 let remote = MPRemoteCommandCenter.shared() remote.playCommand.addTarget { @Sendable [weak self] _ in - Task { @MainActor in self?.isListening = true } + Task { @MainActor in self?.play() } + return .success + } + remote.togglePlayPauseCommand.addTarget { @Sendable [weak self] _ in + Task { @MainActor in + guard let self else { return } + if self.state == .playing { self.isListening = false } else { self.play() } + } + return .success + } + remote.changePlaybackPositionCommand.addTarget { @Sendable [weak self] event in + guard let position = (event as? MPChangePlaybackPositionCommandEvent)?.positionTime else { + return .commandFailed + } + Task { @MainActor in self?.onSeek?(position) } return .success } remote.pauseCommand.addTarget { @Sendable [weak self] _ in @@ -238,9 +367,15 @@ final class RoomPlayer { } } + private func play() { + isListening = true + onPlay?() + } + private func updateNowPlaying() { + let center = MPNowPlayingInfoCenter.default() guard let playback, let track = playback.entry?.track, track.isStreamable else { - MPNowPlayingInfoCenter.default().nowPlayingInfo = nil + center.nowPlayingInfo = isAwaitingSong ? [MPMediaItemPropertyTitle: "等人点下一首"] : nil return } var info: [String: Any] = [ @@ -250,6 +385,12 @@ final class RoomPlayer { MPNowPlayingInfoPropertyPlaybackRate: state == .playing ? 1.0 : 0.0, ] info[MPMediaItemPropertyPlaybackDuration] = playback.durationSec - MPNowPlayingInfoCenter.default().nowPlayingInfo = info + info[MPMediaItemPropertyArtwork] = cover.map(Self.artwork) + center.nowPlayingInfo = info + } + + /// 系统在别的线程上取图,所以闭包不能属于主线程。 + private nonisolated static func artwork(_ image: UIImage) -> MPMediaItemArtwork { + MPMediaItemArtwork(boundsSize: image.size) { @Sendable _ in image } } } diff --git a/ios/App/RoomSession.swift b/ios/App/RoomSession.swift index f485ca2..5e01229 100644 --- a/ios/App/RoomSession.swift +++ b/ios/App/RoomSession.swift @@ -7,6 +7,7 @@ import Observation final class RoomSession { let client: APIClient let player: RoomPlayer + let artwork = Artwork() private(set) var room: Room? private(set) var me: User? private(set) var clock = PlaybackClock() @@ -17,6 +18,11 @@ final class RoomSession { var notice: String? @ObservationIgnored private var connection: Task? + @ObservationIgnored private var coverLoad: Task? + @ObservationIgnored private var lastMessage = Date.distantPast + @ObservationIgnored private var reported: Set = [] + + private static let pingInterval = 25.0 init(link: EntryLink) { client = APIClient(link: link) @@ -25,6 +31,18 @@ final class RoomSession { guard let self, canSkip else { return } Task { await self.skip() } } + player.onPlay = { [weak self] in + guard let self, canControl, room?.playback.status == .paused else { return } + Task { await self.togglePause() } + } + player.onSeek = { [weak self] position in + guard let self else { return } + Task { await self.seek(to: position) } + } + player.onUnplayable = { [weak self] entryID in + guard let self else { return } + Task { await self.reportUnplayable(entryID) } + } } func start() { @@ -35,16 +53,59 @@ final class RoomSession { func stop() { connection?.cancel() connection = nil + coverLoad?.cancel() player.stop() } + /// 回到前台。挂起期间连接多半已经断了,不等超时,马上重连。 + func wake() { + guard connection != nil, endedReason == nil, + !isLive || Date().timeIntervalSince(lastMessage) > Self.pingInterval + 5 + else { return } + connection?.cancel() + isLive = false + connection = Task { await run() } + } + + /// 歌词跟着耳朵听到的走,没有出声时跟着房间走。 + var lyricsPosition: TimeInterval { player.heardPosition ?? position } var position: TimeInterval { room.map { clock.position(of: $0.playback) } ?? 0 } var canControl: Bool { me.flatMap { room?.canControl($0.id) } ?? false } var canSkip: Bool { me.flatMap { room?.canSkip($0.id) } ?? false } var hasVoted: Bool { me.map { room?.votes.voters.contains($0.id) ?? false } ?? false } + func canRetract(_ entry: QueueEntry) -> Bool { me.flatMap { room?.canRetract(entry, $0.id) } ?? false } + // MARK: 操作 + func retract(_ entry: QueueEntry) async { + await perform { try await self.client.retract(entry.id) } + } + + /// 先在本机换好位置,免得松手后先弹回去;真正的顺序以服务端随后发来的为准。 + func move(_ entry: QueueEntry, to position: Int) async { + guard let before = room?.queue, let from = before.firstIndex(where: { $0.id == entry.id }), from != position + else { return } + room?.queue.remove(at: from) + room?.queue.insert(entry, at: position) + let moved = room?.queue + let done = await perform { try await self.client.move(entry.id, to: position) } + if !done, room?.queue == moved { room?.queue = before } + } + + /// 本机放不了当前这首,投一票切歌。每首只报一次。 + func reportUnplayable(_ entryID: String) async { + guard reported.insert(entryID).inserted else { return } + do { + try await client.reportUnplayable(entryID) + } catch let error as APIError where error.isRefusal { + } catch { + reported.remove(entryID) + } + } + + func hasReported(_ entryID: String) -> Bool { reported.contains(entryID) } + func togglePause() async { let paused = room?.playback.status == .paused await perform { try await paused ? self.client.resume() : self.client.pause() } @@ -68,11 +129,14 @@ final class RoomSession { } } - private func perform(_ action: () async throws -> Void) async { + @discardableResult + func perform(_ action: () async throws -> Void) async -> Bool { do { try await action() + return true } catch { notice = error.localizedDescription + return false } } @@ -89,6 +153,7 @@ final class RoomSession { player.stop() return } catch {} + guard !Task.isCancelled else { return } isLive = false try? await Task.sleep(for: .seconds(delay)) delay = min(max(1, delay * 2), 15) @@ -100,12 +165,20 @@ final class RoomSession { me = try await client.me() clock = try await client.clock() apply(try await client.room()) + player.retry() let socket = URLSession.shared.webSocketTask(with: client.webSocketRequest()) socket.resume() let ping = Task { + var count = 0 while !Task.isCancelled { - try await Task.sleep(for: .seconds(25)) + try await Task.sleep(for: .seconds(Self.pingInterval)) + count += 1 + // 大约每五分钟校一次时钟。 + if count % 12 == 0, let fresh = try? await client.clock() { + clock = fresh + if let room { apply(room) } + } do { try await socket.send(.string(#"{"type":"ping"}"#)) } catch { @@ -127,6 +200,7 @@ final class RoomSession { case .data(let raw): data = raw @unknown default: continue } + lastMessage = Date() switch try RoomMessage(data) { case .snapshot(let room): isLive = true @@ -147,7 +221,16 @@ final class RoomSession { private func apply(_ room: Room) { guard !Task.isCancelled else { return } + let oldCover = self.room?.playback.entry?.track.cover self.room = room - player.follow(room.playback, clock: clock, canSkip: canSkip) + player.follow(room.playback, clock: clock, canSkip: canSkip, canControl: canControl) + let cover = room.playback.entry?.track.cover + guard cover != oldCover else { return } + coverLoad?.cancel() + player.setCover(nil) + coverLoad = Task { + await artwork.load(cover) + if !Task.isCancelled { player.setCover(artwork.image) } + } } } diff --git a/ios/App/RoomView.swift b/ios/App/RoomView.swift index 5ec55e5..ee8ec6e 100644 --- a/ios/App/RoomView.swift +++ b/ios/App/RoomView.swift @@ -5,10 +5,10 @@ struct RoomView: View { let session: RoomSession let onLeave: () -> Void - @State private var artwork = Artwork() + @Environment(\.scenePhase) private var scenePhase @State private var isSearching = false @State private var isPlayerOpen = false - @State private var isConfirmingLeave = false + @State private var isShowingInfo = false @Namespace private var transition private var current: QueueEntry? { session.endedReason == nil ? session.room?.playback.entry : nil } @@ -33,7 +33,8 @@ struct RoomView: View { .navigationTitle(session.room?.name ?? "MusicGo") .toolbar { ToolbarItem(placement: .topBarLeading) { - Button("退出", systemImage: "rectangle.portrait.and.arrow.right") { isConfirmingLeave = true } + Button("房间", systemImage: "person.2") { isShowingInfo = true } + .accessibilityIdentifier("open-room-info") } ToolbarItem(placement: .topBarTrailing) { Button("点歌", systemImage: "plus") { isSearching = true } @@ -43,7 +44,7 @@ struct RoomView: View { } .safeAreaInset(edge: .bottom) { if let current { - MiniPlayer(session: session, entry: current, artwork: artwork) { isPlayerOpen = true } + MiniPlayer(session: session, entry: current) { isPlayerOpen = true } .matchedTransitionSource(id: "player", in: transition) .padding(.horizontal, 12) .padding(.bottom, 6) @@ -51,25 +52,23 @@ struct RoomView: View { } } } - .sheet(isPresented: $isSearching) { SearchView(client: session.client) } + .sheet(isPresented: $isSearching) { SearchView(session: session) } + .sheet(isPresented: $isShowingInfo) { RoomInfoView(session: session, onLeave: onLeave) } .fullScreenCover(isPresented: $isPlayerOpen) { - PlayerView(session: session, artwork: artwork) + PlayerView(session: session) .navigationTransition(.zoom(sourceID: "player", in: transition)) } - .confirmationDialog("退出后要重新粘贴进入链接", isPresented: $isConfirmingLeave, titleVisibility: .visible) { - Button("退出", role: .destructive, action: onLeave) - } - .noticeAlert(session, isActive: !isPlayerOpen) + .noticeAlert(session, isActive: !isPlayerOpen && !isShowingInfo && !isSearching) .task { session.start() } - .task(id: current?.track.cover) { await artwork.load(current?.track.cover) } + .onChange(of: scenePhase) { _, phase in + if phase == .active { session.wake() } + } } private func queue(_ room: Room) -> some View { List { Section { - ForEach(room.queue) { entry in - TrackRow(track: entry.track, detail: "\(room.memberName(entry.requestedBy)) 点的") - } + QueueRows(session: session, room: room) } header: { HStack { Text("待播 \(room.queue.count) 首") @@ -90,39 +89,3 @@ struct RoomView: View { } } } - -struct TrackRow: View { - let track: Track - let detail: String - - var body: some View { - HStack(spacing: 12) { - CoverView(url: track.cover).frame(width: 48, height: 48) - VStack(alignment: .leading, spacing: 2) { - Text(track.title).lineLimit(1) - Text([track.artist, detail].filter { !$0.isEmpty }.joined(separator: " · ")) - .font(.footnote) - .foregroundStyle(.secondary) - .lineLimit(1) - } - } - } -} - -private struct CoverView: View { - let url: URL? - - var body: some View { - // 先占住方形,图片再大也只能填满它。 - Color(.systemGray5) - .overlay { - AsyncImage(url: url) { image in - image.resizable().scaledToFill() - } placeholder: { - Image(systemName: "music.note").foregroundStyle(.secondary) - } - } - .clipShape(.rect(cornerRadius: 7)) - .accessibilityHidden(true) - } -} diff --git a/ios/App/SearchView.swift b/ios/App/SearchView.swift index 8095b11..f9ed4ce 100644 --- a/ios/App/SearchView.swift +++ b/ios/App/SearchView.swift @@ -1,9 +1,12 @@ import MusicGoKit import SwiftUI -/// 搜歌名,或粘贴歌曲链接直接点。 +/// 搜歌名,或粘贴歌曲链接。点完留在这里,可以接着点。 struct SearchView: View { - let client: APIClient + let session: RoomSession + /// 打开时先搜这个。 + var initialQuery = "" + var initialSource: String? @Environment(\.dismiss) private var dismiss @State private var query = "" @@ -12,6 +15,7 @@ struct SearchView: View { @State private var results: [Track] = [] @State private var searched = "" @State private var isBusy = false + @State private var ordered: Set = [] @State private var problem: String? var body: some View { @@ -23,20 +27,23 @@ struct SearchView: View { } .onChange(of: source) { if !searched.isEmpty { submit() } } } + if let limitText { + Text(limitText).font(.footnote).foregroundStyle(.secondary) + } if let problem { Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.red) } ForEach(results) { track in - Button { - run { try await client.enqueue(track) } then: { _ in dismiss() } - } label: { + let isQueued = isQueued(track) + Button { order(track) } label: { HStack { - TrackRow(track: track, detail: formatTime(track.durationSec)) - Spacer() - Image(systemName: "plus.circle").foregroundStyle(.tint) + TrackRow(track: track, detail: "") + Image(systemName: isQueued ? "checkmark.circle.fill" : "plus.circle").foregroundStyle(.tint) } } .tint(.primary) + .disabled(isQueued || isFull) + .accessibilityValue(isQueued ? "已点" : "") .accessibilityIdentifier("search-result") } } @@ -56,12 +63,18 @@ struct SearchView: View { .textInputAutocapitalization(.never) .onSubmit(of: .search, submit) .toolbar { - ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() }.accessibilityIdentifier("close-search") + } } .task { do { sources = try await client.sources() - source = sources.first?.id ?? "" + source = sources.first { $0.id == initialSource }?.id ?? sources.first?.id ?? "" + if !initialQuery.isEmpty { + query = initialQuery + submit() + } } catch { problem = error.localizedDescription } @@ -69,14 +82,40 @@ struct SearchView: View { } } + private var client: APIClient { session.client } + + private var pending: (count: Int, limit: Int?) { + guard let me = session.me, let room = session.room else { return (0, nil) } + return (room.pendingCount(me.id), room.pendingLimit(me.id)) + } + + private var isFull: Bool { pending.limit.map { pending.count >= $0 } ?? false } + + private var limitText: String? { + let (count, limit) = pending + guard let limit else { return nil } + return isFull ? "你的待播歌曲已达上限(\(count) / \(limit) 首)" : "你的待播 \(count) / \(limit) 首" + } + + private func isQueued(_ track: Track) -> Bool { + ordered.contains(track.id) || session.room?.queue.contains { $0.track.id == track.id } == true + } + + private func order(_ track: Track) { + run { [client] in try await client.enqueue(track) } then: { _ in ordered.insert(track.id) } + } + private func submit() { let text = query.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { return } if text.contains("://") { - run { try await client.enqueue(url: text) } then: { _ in dismiss() } + run { [client] in try await client.resolve(url: text) } then: { + results = [$0] + searched = text + } } else { let source = source - run { try await client.search(text, source: source) } then: { + run { [client] in try await client.search(text, source: source) } then: { results = $0 searched = text } diff --git a/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift index 7b4c838..ef7d23d 100644 --- a/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift +++ b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift @@ -8,12 +8,20 @@ public struct APIError: Error, Sendable, Equatable, LocalizedError { public let status: Int public let code: String public let message: String + /// 限流时,多少秒后可以再试。 + public let retryAfter: Double? + private let limit: Int? init(status: Int, body: Data) { struct Body: Decodable { struct Detail: Decodable { + struct Details: Decodable { + let retryAfterSeconds: Double? + let limit: Int? + } let code: String let message: String + let details: Details? } let error: Detail } @@ -21,6 +29,8 @@ public struct APIError: Error, Sendable, Equatable, LocalizedError { self.status = status code = detail?.code ?? "internal" message = detail?.message ?? "服务器返回了错误(HTTP \(status))" + retryAfter = detail?.details?.retryAfterSeconds + limit = detail?.details?.limit } public var errorDescription: String? { @@ -28,10 +38,17 @@ public struct APIError: Error, Sendable, Equatable, LocalizedError { case "unauthorized": "登录凭据无效或已吊销,请重新粘贴进入链接" case "stale_entry": "歌曲已经切换了" case "duplicate_track": "这首歌已在待播队列中" + case "invite_invalid": "邀请码无效,请向房主要最新的邀请码" + case "queue_limit_exceeded": limit.map { "你的待播歌曲已达上限(\($0) 首)" } ?? message + case "unsupported_url": "认不出这个链接,请换一个,或改用歌名搜索" + case "rate_limited": retryAfter.map { "操作太频繁,请 \(Int($0.rounded(.up))) 秒后再试" } ?? message default: message } } + /// 服务端明确拒绝的,再试也一样。 + public var isRefusal: Bool { (400..<500).contains(status) && status != 429 } + /// 重试也没用:凭据失效、不是成员,或房间不存在。 public var endsSession: Bool { ["unauthorized", "forbidden", "not_found"].contains(code) } } @@ -68,6 +85,18 @@ public struct APIClient: Sendable { return response.room } + /// 账号所在的房间。 + public func roomIDs() async throws -> [String] { + struct Response: Decodable { + struct Summary: Decodable { + let id: String + } + let rooms: [Summary] + } + let response: Response = try await get("/v1/rooms") + return response.rooms.map(\.id) + } + public func sources() async throws -> [Source] { struct Response: Decodable { let sources: [Source] @@ -88,8 +117,22 @@ public struct APIClient: Sendable { try await get("\(roomPath)/lyrics", query: ["entry_id": entryID]) } + /// 在 LRCLIB 上手动找歌词。直接访问第三方网站,不带房间的令牌。 + public func searchLRCLIB(_ query: String) async throws -> [LRCLIBRecord] { + var parts = URLComponents(string: "https://lrclib.net/api/search")! + parts.setQuery(["q": query]) + let (data, response) = try await session.data(from: parts.url!) + guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } + return try JSONDecoder().decode([LRCLIBRecord].self, from: data).filter { $0.lyrics.status == .found } + } + // MARK: 点歌与播放 + /// 认出链接是哪首歌,不点歌。 + public func resolve(url: String) async throws -> Track { + try await post("/v1/tracks/resolve", ["url": url]) + } + @discardableResult public func enqueue(_ track: Track) async throws -> QueueEntry { try await enqueue(["source": track.source, "track_id": track.sourceId]) @@ -108,6 +151,20 @@ public struct APIClient: Sendable { return response.entry } + public func retract(_ entryID: String) async throws { + try await change("DELETE", "\(roomPath)/queue/\(entryID)") + } + + /// `position` 是移动后在待播队列里的下标。 + public func move(_ entryID: String, to position: Int) async throws { + try await change("POST", "\(roomPath)/queue/\(entryID)/move", ["position": position]) + } + + /// 本机放不了这首歌。等于投一票切歌。 + public func reportUnplayable(_ entryID: String) async throws { + try await act("unplayable", ["entry_id": entryID]) + } + public func skip(_ entryID: String) async throws { try await act("skip", ["entry_id": entryID]) } @@ -122,7 +179,7 @@ public struct APIClient: Sendable { let entry_id: String let position_sec: Double } - let _: Ignored = try await post("\(roomPath)/playback/seek", Body(entry_id: entryID, position_sec: position)) + try await change("POST", "\(roomPath)/playback/seek", Body(entry_id: entryID, position_sec: position)) } public func pause() async throws { try await act("pause", [:]) } @@ -153,6 +210,44 @@ public struct APIClient: Sendable { return request } + // MARK: 房间管理 + + public func join(inviteCode: String) async throws { + try await change("POST", "\(roomPath)/join", ["invite_code": inviteCode]) + } + + public func resetInvite() async throws { + try await change("POST", "\(roomPath)/invite/reset") + } + + public func setRole(_ role: Role, of userID: String) async throws { + try await change("POST", "\(roomPath)/members/\(userID)/role", ["role": role]) + } + + public func kick(_ userID: String) async throws { + try await change("POST", "\(roomPath)/members/\(userID)/kick") + } + + public func transferOwner(to userID: String) async throws { + try await change("POST", "\(roomPath)/owner/transfer", ["user_id": userID]) + } + + public func update(name: String, settings: RoomSettings) async throws { + struct Body: Encodable { + let name: String + let settings: RoomSettings + + enum Key: CodingKey { case name } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: Key.self) + try container.encode(name, forKey: .name) + try settings.encode(to: encoder) + } + } + try await change("PATCH", "\(roomPath)/settings", Body(name: name, settings: settings)) + } + // MARK: 请求 private var roomPath: String { "/v1/rooms/\(link.roomID)" } @@ -160,7 +255,12 @@ public struct APIClient: Sendable { private struct Ignored: Decodable {} private func act(_ action: String, _ body: [String: String]) async throws { - let _: Ignored = try await post("\(roomPath)/playback/\(action)", body) + try await change("POST", "\(roomPath)/playback/\(action)", body) + } + + /// 只关心成不成功的写请求。 + private func change(_ method: String, _ path: String, _ body: some Encodable = [String: String]()) async throws { + let _: Ignored = try await write(method, path, body) } private func get(_ path: String, query: [String: String] = [:]) async throws -> T { @@ -168,9 +268,13 @@ public struct APIClient: Sendable { } private func post(_ path: String, _ body: some Encodable) async throws -> T { + try await write("POST", path, body) + } + + private func write(_ method: String, _ path: String, _ body: some Encodable) async throws -> T { var request = request(path) - request.httpMethod = "POST" - request.httpBody = try JSONEncoder().encode(body) + request.httpMethod = method + request.httpBody = try JSON.encoder.encode(body) request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(UUID().uuidString, forHTTPHeaderField: "Idempotency-Key") return try await send(request) @@ -180,9 +284,7 @@ public struct APIClient: Sendable { var parts = URLComponents(url: link.server, resolvingAgainstBaseURL: false)! parts.path = path if !query.isEmpty { - parts.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } - // URLComponents 不转义 +,而服务端会把它当成空格。 - parts.percentEncodedQuery = parts.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") + parts.setQuery(query) } var request = URLRequest(url: parts.url!, timeoutInterval: 20) request.setValue("Bearer \(link.token)", forHTTPHeaderField: "Authorization") @@ -196,3 +298,11 @@ public struct APIClient: Sendable { return try JSON.decoder.decode(T.self, from: data) } } + +extension URLComponents { + fileprivate mutating func setQuery(_ query: [String: String]) { + queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } + // URLComponents 不转义 +,而服务端会把它当成空格。 + percentEncodedQuery = percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") + } +} diff --git a/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift b/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift index e245db0..2357708 100644 --- a/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift +++ b/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift @@ -2,10 +2,12 @@ import Foundation /// 房间的进入链接:`https://<服务器>/rooms/<房间>#token=<令牌>`, /// 或 `https://<服务器>/?room=<房间>#token=<令牌>`。服务器地址就来自链接,App 里不写死。 +/// 没有房间时进入账号所在的第一个房间;还不是成员时可以带 `invite=<邀请码>` 加入。 public struct EntryLink: Codable, Sendable, Equatable { public let server: URL public let roomID: String public let token: String + public let inviteCode: String? public enum Problem: Error, Equatable, LocalizedError { case notALink, missingRoom, missingToken @@ -13,7 +15,7 @@ public struct EntryLink: Codable, Sendable, Equatable { public var errorDescription: String? { switch self { case .notALink: "这不是网页链接,请粘贴以 https:// 开头的完整链接" - case .missingRoom: "链接里没有房间,请重新复制完整链接" + case .missingRoom: "这个账号还没有加入任何房间,请粘贴带房间的链接" case .missingToken: "链接里没有登录凭据,请粘贴自己的进入链接" } } @@ -40,13 +42,37 @@ public struct EntryLink: Codable, Sendable, Equatable { let path = link.path.split(separator: "/") let pathRoom = path.count >= 2 && path[0] == "rooms" ? String(path[1]) : nil - guard let room = pathRoom ?? value("room", in: fragment) ?? value("room", in: link), - room.hasPrefix("r_") - else { throw .missingRoom } - guard let token = value("token", in: fragment) ?? value("token", in: link) else { throw .missingToken } + func value(_ name: String) -> String? { value(name, in: fragment) ?? value(name, in: link) } + guard let token = value("token") else { throw .missingToken } self.server = server - self.roomID = room + self.roomID = pathRoom ?? value("room") ?? "" self.token = token + inviteCode = value("invite") ?? value("invite_code") + } + + private init(server: URL, roomID: String, token: String) { + self.server = server + self.roomID = roomID + self.token = token + inviteCode = nil + } + + /// 确认能进入房间:需要时选定房间,或用邀请码加入。返回的链接可以存起来反复使用。 + public func enter() async throws -> EntryLink { + var room = roomID + if room.isEmpty { + room = try await APIClient(link: self).roomIDs().first ?? "" + guard !room.isEmpty else { throw Problem.missingRoom } + } + let link = EntryLink(server: server, roomID: room, token: token) + let client = APIClient(link: link) + do { + _ = try await client.room() + } catch let error as APIError where error.code == "forbidden" { + guard let inviteCode else { throw error } + try await client.join(inviteCode: inviteCode) + } + return link } } diff --git a/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift b/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift index 22ab268..85f2abf 100644 --- a/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift +++ b/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift @@ -10,14 +10,18 @@ public struct Lyrics: Codable, Sendable, Equatable { } public let status: Status + public let source: String public let lines: [LyricLine] public var isSynced: Bool { lines.contains { $0.atMs > 0 } } - /// 唱到哪一行;还没开始时为 nil。 - public func lineIndex(at position: TimeInterval) -> Int? { - guard isSynced else { return nil } - return lines.lastIndex { Double($0.atMs) <= position * 1000 } + public var sourceName: String { + switch source { + case "netease": "网易云音乐" + case "qq": "QQ 音乐" + case "lrclib": "LRCLIB" + default: source + } } } @@ -26,16 +30,109 @@ public struct LyricLine: Codable, Sendable, Equatable { public let text: String public let startMs: Int public let endMs: Int + + public init(text: String, startMs: Int, endMs: Int) { + self.text = text + self.startMs = startMs + self.endMs = endMs + } } public let atMs: Int + public let endMs: Int public let text: String public let translation: String + /// `words` 是真的逐字时间,不是按字数估算的。 + public let timed: Bool public let words: [Word] - /// 这一行里已经唱到的部分。 - public func sungPrefix(at position: TimeInterval) -> String { - guard !words.isEmpty, words.map(\.text).joined() == text else { return text } - return words.prefix { Double($0.startMs) <= position * 1000 }.map(\.text).joined() + /// 逐字时间,拼起来正好是 `text`。没有逐字时间,或与原文对不上时为空。 + public var timedWords: [Word] { + guard timed else { return [] } + var rest = text[...] + var result: [Word] = [] + for word in words { + let core = word.text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !core.isEmpty else { continue } + guard let found = rest.range(of: core) else { return [] } + // 词与词之间的空格归前一个词。中间缺了字,说明对不上。 + let gap = rest[.. Member? { + members.first { $0.userId == userID } + } public func memberName(_ userID: String) -> String { - members.first { $0.userId == userID }?.name ?? "已离开的成员" + member(userID)?.name ?? "已离开的成员" + } + + /// 「小明 点的」;AI 代人点歌时是「助手(AI)代小明 点的」。 + public func requester(_ userID: String, onBehalfOf: String?) -> String { + var name = memberName(userID) + if member(userID)?.kind == .agent { name += "(AI)" } + if let onBehalfOf, !onBehalfOf.isEmpty { name += "代\(memberName(onBehalfOf))" } + return "\(name) 点的" } - /// 暂停、继续只有房主和管理员能用。 + // MARK: 权限,见 docs/api.md 的权限矩阵 + + public func isOwner(_ userID: String) -> Bool { member(userID)?.role == .owner } + + /// 暂停、继续、跳转、调整顺序,只有房主和管理员能用。 public func canControl(_ userID: String) -> Bool { - members.contains { $0.userId == userID && ($0.role == "owner" || $0.role == "admin") } + member(userID).map { $0.role != .member } ?? false } /// 能直接切歌;不能的话只能投票。 public func canSkip(_ userID: String) -> Bool { canControl(userID) || playback.entry?.requestedBy == userID } + + public func canRetract(_ entry: QueueEntry, _ userID: String) -> Bool { + canControl(userID) || entry.requestedBy == userID + } + + public func pendingCount(_ userID: String) -> Int { + queue.count { $0.requestedBy == userID } + } + + /// 最多能有几首待播;nil 表示不限。 + public func pendingLimit(_ userID: String) -> Int? { + guard let member = member(userID) else { return nil } + if member.kind == .agent { return settings.maxPendingAgent } + return member.role == .member ? settings.maxPendingHuman : nil + } } public struct VoteResult: Codable, Sendable, Equatable { @@ -118,6 +196,12 @@ public enum RoomMessage: Sendable, Equatable { } enum JSON { + static var encoder: JSONEncoder { + let e = JSONEncoder() + e.keyEncodingStrategy = .convertToSnakeCase + return e + } + static var decoder: JSONDecoder { let d = JSONDecoder() d.keyDecodingStrategy = .convertFromSnakeCase diff --git a/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift index 35ef58f..fca0570 100644 --- a/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift +++ b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift @@ -21,10 +21,21 @@ import Testing #expect(try EntryLink("http://localhost:8870/rooms/r_1#token=t").server.absoluteString == "http://localhost:8870") } + @Test func roomIsOptionalAndInviteIsKept() throws { + #expect(try EntryLink("https://musicgo.example.com/#token=t").roomID.isEmpty) + let link = try EntryLink("https://musicgo.example.com/rooms/r_1?invite=Ab3xK9mQ#token=t") + #expect(link.roomID == "r_1" && link.inviteCode == "Ab3xK9mQ") + } + + /// 以前存在钥匙串里的链接没有邀请码。 + @Test func readsStoredLinks() throws { + let old = #"{"server":"https://musicgo.example.com","roomID":"r_1","token":"t"}"# + #expect(try JSONDecoder().decode(EntryLink.self, from: Data(old.utf8)).roomID == "r_1") + } + @Test func explainsWhatIsMissing() { #expect(throws: EntryLink.Problem.notALink) { try EntryLink("mgt_a") } #expect(throws: EntryLink.Problem.notALink) { try EntryLink("") } - #expect(throws: EntryLink.Problem.missingRoom) { try EntryLink("https://musicgo.example.com/#token=t") } #expect(throws: EntryLink.Problem.missingToken) { try EntryLink("https://musicgo.example.com/rooms/r_1") } } } @@ -33,9 +44,11 @@ import Testing // 取自真实服务端的响应。 static let room = """ {"id":"r_1","name":"test","revision":4,"created_at":"2026-12-05T00:45:00.144804454Z","invite_code":"x", - "settings":{"name":"test","vote_ratio":0.5}, + "settings":{"name":"test","vote_ratio":0.5,"max_pending_human":5,"max_pending_agent":2,"order_mode":"fair", + "auto_advance_grace_seconds":3}, "members":[{"user_id":"u_1","name":"iOS","kind":"human","role":"owner","joined_at":"2026-12-05T00:45:00.144804454Z"}, - {"user_id":"u_2","name":"B","kind":"human","role":"member","joined_at":"2026-12-05T00:45:00Z"}], + {"user_id":"u_2","name":"B","kind":"human","role":"member","joined_at":"2026-12-05T00:45:00Z"}, + {"user_id":"u_3","name":"C","kind":"agent","role":"admin","joined_at":"2026-12-05T00:45:00Z"}], "queue":[],"playback":{"entry_id":"e_1","entry":{"id":"e_1","track":{"source":"fake","source_id":"song1", "title":"Fake","artist":"A","duration_sec":null,"cover_url":"","url":"fake://track/song1", "capabilities":{"background_playback":true}},"requested_by":"u_2","queued_at":"2026-12-05T00:45:00.167982579Z"}, @@ -51,7 +64,25 @@ import Testing #expect(room.playback.entry?.track.cover == nil) #expect(room.canControl("u_1") && room.canSkip("u_1")) #expect(!room.canControl("u_2") && room.canSkip("u_2")) - #expect(!room.canSkip("u_3")) + #expect(!room.canSkip("u_4") && !room.isOwner("u_3")) + #expect(room.pendingLimit("u_1") == nil && room.pendingLimit("u_2") == 5 && room.pendingLimit("u_3") == 2) + #expect(room.requester("u_3", onBehalfOf: "u_2") == "C(AI)代B 点的") + #expect(room.requester("u_2", onBehalfOf: "") == "B 点的") + } + + @Test func coversUseHTTPS() throws { + let text = #"{"source":"s","source_id":"1","title":"","artist":"","duration_sec":null,"cover_url":"http://img.example.com/a.jpg?x=1","url":"","capabilities":{}}"# + let track = try JSON.decoder.decode(Track.self, from: Data(text.utf8)) + #expect(track.cover?.absoluteString == "https://img.example.com/a.jpg?x=1") + } + + @Test func settingsUseTheServersNames() throws { + let settings = RoomSettings( + voteRatio: 0.5, maxPendingHuman: 5, maxPendingAgent: 2, orderMode: .fifo, autoAdvanceGraceSeconds: 3) + let text = String(decoding: try JSON.encoder.encode(settings), as: UTF8.self) + for field in ["\"vote_ratio\":0.5", "\"max_pending_human\":5", "\"order_mode\":\"fifo\"", "\"auto_advance_grace_seconds\":3"] { + #expect(text.contains(field)) + } } @Test func idlePlayback() throws { @@ -69,6 +100,9 @@ import Testing @Test func errors() { let error = APIError(status: 403, body: Data(#"{"error":{"code":"forbidden","message":"不是房间成员"}}"#.utf8)) #expect(error.endsSession && error.localizedDescription == "不是房间成员") + let limited = APIError( + status: 429, body: Data(#"{"error":{"code":"rate_limited","message":"","details":{"retry_after_seconds":8}}}"#.utf8)) + #expect(limited.localizedDescription.contains("8 秒") && !limited.isRefusal) #expect(!APIError(status: 502, body: Data("".utf8)).endsSession) } @@ -123,27 +157,43 @@ import Testing "words":[{"text":"hello","start_ms":4000,"end_ms":5000},{"text":"world","start_ms":5000,"end_ms":6000}]}]} """ - @Test func followsThePosition() throws { + @Test func wordsCoverTheWholeLine() throws { let lyrics = try JSON.decoder.decode(Lyrics.self, from: Data(Self.found.utf8)) - #expect(lyrics.isSynced) - #expect(lyrics.lineIndex(at: 0.5) == nil) - #expect(lyrics.lineIndex(at: 1) == 0) - #expect(lyrics.lineIndex(at: 3.5) == 0) - #expect(lyrics.lineIndex(at: 99) == 1) + #expect(lyrics.isSynced && lyrics.sourceName == "网易云音乐") + #expect(lyrics.lines[0].timedWords.map(\.text) == ["春", "日影"]) + // 逐字内容里没有空格,要从原文补回来。 + #expect(lyrics.lines[1].timedWords.map(\.text) == ["hello ", "world"]) + } + + @Test func ignoresWordsThatDoNotMatch() { + func words(_ text: String, _ words: [String], timed: Bool = true) -> [String] { + let timedWords = words.map { LyricLine.Word(text: $0, startMs: 0, endMs: 1) } + return LyricLine(atMs: 0, endMs: 1, text: text, translation: "", timed: timed, words: timedWords).timedWords.map(\.text) + } + #expect(words("春日影", ["春", "影"]).isEmpty) + #expect(words("春日影", ["春日"]).isEmpty) + #expect(words("春日影", ["春日影"], timed: false).isEmpty) + #expect(words("a b", ["a", " ", "b"]) == ["a ", "b"]) + } + + @Test func parsesLRC() { + let lyrics = Lyrics( + lrc: "[ti:x]\n[offset:500]\n[00:03.50][00:10]合唱\n[00:01.00]hello\n[00:01.00]你好\n[00:02.00]", plain: nil, source: "lrclib") + #expect(lyrics.lines.map(\.atMs) == [500, 3000, 9500]) + #expect(lyrics.lines.map(\.endMs) == [3000, 9500, 14500]) + #expect(lyrics.lines.map(\.text) == ["hello", "合唱", "合唱"]) + #expect(lyrics.lines[0].translation == "你好") } - @Test func highlightsSungWords() throws { - let lines = try JSON.decoder.decode(Lyrics.self, from: Data(Self.found.utf8)).lines - #expect(lines[0].sungPrefix(at: 0.5) == "") - #expect(lines[0].sungPrefix(at: 1.2) == "春") - #expect(lines[0].sungPrefix(at: 2) == "春日影") - // 逐字内容拼不回原文时整行高亮,不能丢字。 - #expect(lines[1].sungPrefix(at: 4.5) == "hello world") + @Test func plainLyricsHaveNoTimeline() { + let lyrics = Lyrics(lrc: nil, plain: "a\n\nb", source: "lrclib") + #expect(lyrics.lines.count == 2 && !lyrics.isSynced) + #expect(Lyrics(lrc: "", plain: " ", source: "").status == .none) } @Test func missing() throws { let text = #"{"entry_id":"e_1","status":"unavailable","source":"","lines":[]}"# let lyrics = try JSON.decoder.decode(Lyrics.self, from: Data(text.utf8)) - #expect(lyrics.status == .unavailable && !lyrics.isSynced && lyrics.lineIndex(at: 5) == nil) + #expect(lyrics.status == .unavailable && !lyrics.isSynced) } } diff --git a/ios/README.md b/ios/README.md index 2293bfa..f29b5ee 100644 --- a/ios/README.md +++ b/ios/README.md @@ -1,14 +1,16 @@ # MusicGo iOS 客户端 -最小可用版:登录、跟着房间一起听、看歌词和队列、搜索点歌、暂停、切歌和调进度。需要 iOS 18 或更高版本。 +功能与网页版相同:一起听、点歌、调整队列、逐字歌词、投票切歌、管理成员和房间设置。需要 iOS 18 或更高版本。 ## 使用 -粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在钥匙串。 +粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在钥匙串。还不是成员时,链接里可以带 `invite=<邀请码>`。 -- 静音和锁屏上的播放、暂停只管本机,锁屏上的「下一首」会切整个房间的歌;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 -- YouTube 的歌还不能在 App 里播放,会提示改用网页版。 -- 房间空闲或暂停时切到后台,系统可能会挂起 App,回到前台后自动重连。 +- 静音和锁屏上的播放、暂停只管本机,锁屏上的「下一首」和进度条会影响整个房间;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 +- YouTube 用官方的内嵌播放器,只在播放页打开时播放,不能在后台听。 +- 歌放完后,App 会在后台等 30 分钟,有人点歌就接着放。房间暂停时切到后台,系统会挂起 App,回到前台后自动重连并继续播放。 +- 左滑撤回待播的歌;房主和管理员长按拖动可以调整顺序。 +- 歌词的时间偏移和手动选的歌词只存在本机。 ## 开发 @@ -22,7 +24,7 @@ cd ios && xcodegen && open MusicGo.xcodeproj | 目录 | 内容 | |---|---| | `MusicGoKit/` | 接口、数据结构、链接解析、进度推算。Linux 上也能 `swift test` | -| `App/` | SwiftUI 界面、实时连接、播放。播放页和歌词改写自开源项目,见 [NOTICE](App/Player/NOTICE.md) | +| `App/` | SwiftUI 界面、实时连接、播放。播放页改写自开源项目,歌词用 MelismaKit 绘制,见 [NOTICE](App/Player/NOTICE.md) | | `UITests/` | 对着真实服务端走完整流程的界面测试 | | `scripts/test-server.sh` | 启动界面测试用的服务端,音源是 `testplugin/` 里的纯音 | diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index 0c660f9..a42c036 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -38,9 +38,17 @@ final class MusicGoUITests: XCTestCase { capture("4-player") app.buttons["show-lyrics"].tap() - let line = app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", "一起听歌")).firstMatch - XCTAssertTrue(line.waitForExistence(timeout: 10)) + // 歌词是一整块自绘的画面,读屏的值是正在唱的那一行。 + let lyrics = app.descendants(matching: .any)["lyrics"].firstMatch + XCTAssertTrue(lyrics.waitForExistence(timeout: 10)) + expectation(for: NSPredicate(format: "value CONTAINS %@", "一起听歌"), evaluatedWith: lyrics) + waitForExpectations(timeout: 10) capture("5-lyrics") + app.buttons["lyrics-options"].tap() + XCTAssertTrue(app.staticTexts["歌词时间:原样"].waitForExistence(timeout: 10)) + capture("6-lyrics-options") + app.buttons["完成"].tap() + XCTAssertTrue(app.staticTexts["歌词时间:原样"].waitForNonExistence(timeout: 10)) app.buttons["show-queue"].tap() XCTAssertTrue(app.staticTexts["待播 1 首"].waitForExistence(timeout: 10)) @@ -56,6 +64,29 @@ final class MusicGoUITests: XCTestCase { app.buttons["close-player"].tap() XCTAssertTrue(title.waitForNonExistence(timeout: 10)) + app.buttons["open-room-info"].tap() + XCTAssertTrue(app.staticTexts["邀请码"].waitForExistence(timeout: 10)) + capture("7-room-info") + app.buttons["房间设置"].tap() + let name = app.textFields["房间名称"] + XCTAssertTrue(name.waitForExistence(timeout: 10)) + name.tap() + name.typeText("2") + app.buttons["保存"].tap() + XCTAssertTrue(name.waitForNonExistence(timeout: 10)) + app.buttons["最近播放"].tap() + XCTAssertTrue(app.staticTexts["first 1"].waitForExistence(timeout: 10)) + app.navigationBars.buttons.firstMatch.tap() + app.buttons["完成"].tap() + + // 撤回一首待播的歌。 + order("third", in: app) + let queued = app.staticTexts["third 1"] + XCTAssertTrue(queued.waitForExistence(timeout: 10)) + queued.swipeLeft() + app.buttons["撤回"].tap() + XCTAssertTrue(queued.waitForNonExistence(timeout: 10)) + // 重新打开后仍是登录状态。 app.terminate() app.launch() @@ -74,6 +105,9 @@ final class MusicGoUITests: XCTestCase { XCTAssertTrue(result.waitForExistence(timeout: 10)) if query == "first" { capture("2-search") } result.tap() + expectation(for: NSPredicate(format: "value == %@", "已点"), evaluatedWith: result) + waitForExpectations(timeout: 10) + app.buttons["close-search"].tap() XCTAssertTrue(search.waitForNonExistence(timeout: 10)) } diff --git a/ios/project.yml b/ios/project.yml index 8f8a4b4..63ce5cb 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -13,6 +13,10 @@ settings: packages: MusicGoKit: path: MusicGoKit + # 歌词渲染。没有发布版本,固定到一个提交。 + MelismaKit: + url: https://github.com/kmgcc/melismakit-ios + revision: 045a0a264cb26c2301bb587044d47a17d1e39a98 targets: MusicGo: type: application @@ -22,6 +26,8 @@ targets: excludes: ['**/*.md'] dependencies: - package: MusicGoKit + - package: MelismaKit + products: [MelismaKit, MelismaKitSwiftUI] settings: base: PRODUCT_BUNDLE_IDENTIFIER: dev.luckybot.musicgo @@ -35,6 +41,8 @@ targets: CFBundleDevelopmentRegion: zh-Hans UILaunchScreen: {} UIBackgroundModes: [audio] + # 让歌词在支持的机型上用 120 Hz 滚动 + CADisableMinimumFrameDurationOnPhone: true UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait] UISupportedInterfaceOrientations~ipad: - UIInterfaceOrientationPortrait From c1e59e915954310f37b4cd72f01d72d7b38b361f Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:20:23 +0800 Subject: [PATCH 8/9] =?UTF-8?q?fix(ios):=20=E6=90=9C=E7=B4=A2=E6=97=B6?= =?UTF-8?q?=E4=BF=9D=E7=95=99=E3=80=8C=E5=AE=8C=E6=88=90=E3=80=8D=E6=8C=89?= =?UTF-8?q?=E9=92=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- ios/App/SearchView.swift | 2 ++ ios/UITests/MusicGoUITests.swift | 13 +++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/ios/App/SearchView.swift b/ios/App/SearchView.swift index f9ed4ce..60486e7 100644 --- a/ios/App/SearchView.swift +++ b/ios/App/SearchView.swift @@ -59,6 +59,8 @@ struct SearchView: View { .navigationBarTitleDisplayMode(.inline) .searchable( text: $query, placement: .navigationBarDrawer(displayMode: .always), prompt: "歌名、歌手,或歌曲链接") + // 搜索时也留着「完成」,不用先退出搜索。 + .searchPresentationToolbarBehavior(.avoidHidingContent) .autocorrectionDisabled() .textInputAutocapitalization(.never) .onSubmit(of: .search, submit) diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index a42c036..7faefc6 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -45,10 +45,11 @@ final class MusicGoUITests: XCTestCase { waitForExpectations(timeout: 10) capture("5-lyrics") app.buttons["lyrics-options"].tap() - XCTAssertTrue(app.staticTexts["歌词时间:原样"].waitForExistence(timeout: 10)) + let offset = text(containing: "歌词时间", in: app) + XCTAssertTrue(offset.waitForExistence(timeout: 10)) capture("6-lyrics-options") app.buttons["完成"].tap() - XCTAssertTrue(app.staticTexts["歌词时间:原样"].waitForNonExistence(timeout: 10)) + XCTAssertTrue(offset.waitForNonExistence(timeout: 10)) app.buttons["show-queue"].tap() XCTAssertTrue(app.staticTexts["待播 1 首"].waitForExistence(timeout: 10)) @@ -65,7 +66,7 @@ final class MusicGoUITests: XCTestCase { XCTAssertTrue(title.waitForNonExistence(timeout: 10)) app.buttons["open-room-info"].tap() - XCTAssertTrue(app.staticTexts["邀请码"].waitForExistence(timeout: 10)) + XCTAssertTrue(text(containing: "邀请码", in: app).waitForExistence(timeout: 10)) capture("7-room-info") app.buttons["房间设置"].tap() let name = app.textFields["房间名称"] @@ -76,7 +77,7 @@ final class MusicGoUITests: XCTestCase { XCTAssertTrue(name.waitForNonExistence(timeout: 10)) app.buttons["最近播放"].tap() XCTAssertTrue(app.staticTexts["first 1"].waitForExistence(timeout: 10)) - app.navigationBars.buttons.firstMatch.tap() + app.navigationBars["最近播放"].buttons.firstMatch.tap() app.buttons["完成"].tap() // 撤回一首待播的歌。 @@ -111,6 +112,10 @@ final class MusicGoUITests: XCTestCase { XCTAssertTrue(search.waitForNonExistence(timeout: 10)) } + private func text(containing part: String, in app: XCUIApplication) -> XCUIElement { + app.staticTexts.matching(NSPredicate(format: "label CONTAINS %@", part)).firstMatch + } + private func waitForPlayer(_ text: String, in app: XCUIApplication) { let state = app.staticTexts["player-state"] let done = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", text), object: state) From 2b679ba2b79236e484364fa1ec43c5fab1cdb9f4 Mon Sep 17 00:00:00 2001 From: aronnaxlin <87559395+aronnaxlin@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:33:11 +0800 Subject: [PATCH 9/9] =?UTF-8?q?test(ios):=20=E5=9C=A8=E6=95=B4=E8=A1=8C?= =?UTF-8?q?=E4=B8=8A=E5=B7=A6=E6=BB=91=E6=92=A4=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- ios/UITests/MusicGoUITests.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ios/UITests/MusicGoUITests.swift b/ios/UITests/MusicGoUITests.swift index 7faefc6..181264f 100644 --- a/ios/UITests/MusicGoUITests.swift +++ b/ios/UITests/MusicGoUITests.swift @@ -84,7 +84,8 @@ final class MusicGoUITests: XCTestCase { order("third", in: app) let queued = app.staticTexts["third 1"] XCTAssertTrue(queued.waitForExistence(timeout: 10)) - queued.swipeLeft() + // 歌名很短,要在整行上滑。 + app.cells.containing(NSPredicate(format: "label == %@", "third 1")).firstMatch.swipeLeft() app.buttons["撤回"].tap() XCTAssertTrue(queued.waitForNonExistence(timeout: 10))