diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml new file mode 100644 index 0000000..f3c4399 --- /dev/null +++ b/.github/workflows/ios.yml @@ -0,0 +1,76 @@ +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: 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: | + xcodebuild test-without-building \ + -project ios/MusicGo.xcodeproj -scheme MusicGo -destination "id=$DEVICE" \ + -resultBundlePath "$RUNNER_TEMP/result.xcresult" + - name: 取出截图 + if: always() && steps.ui.outcome != 'skipped' + 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..d964ef6 100644 --- a/.gitignore +++ b/.gitignore @@ -35,3 +35,9 @@ filter-allow.txt .DS_Store .idea/ .vscode/ + +# iOS:Xcode 工程由 ios/project.yml 生成 +/ios/*.xcodeproj/ +/ios/App/Info.plist +.build/ +/ios/build/ 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/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 469ad24..6ee4aaf 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) | +| [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/CredentialStore.swift b/ios/App/CredentialStore.swift new file mode 100644 index 0000000..2008318 --- /dev/null +++ b/ios/App/CredentialStore.swift @@ -0,0 +1,37 @@ +import Foundation +import MusicGoKit +import Security + +/// 进入链接里有令牌,所以存钥匙串,且不随备份换到别的设备。 +enum CredentialStore { + private static var 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..7fad1a2 --- /dev/null +++ b/ios/App/LoginView.swift @@ -0,0 +1,62 @@ +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 { + onLogin(try await EntryLink(text).enter()) + } 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/Player/Artwork.swift b/ios/App/Player/Artwork.swift new file mode 100644 index 0000000..4eda109 --- /dev/null +++ b/ios/App/Player/Artwork.swift @@ -0,0 +1,92 @@ +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.45, brightness: 0.23 + Double($0 / 3) * 0.05) + } + + func load(_ url: URL?) async { + var loaded: UIImage? + if let url { loaded = await Self.fetch(url) } + guard !Task.isCancelled else { return } + withAnimation(.smooth(duration: 0.6)) { + image = loaded + colors = loaded.flatMap(Self.colors) ?? Self.fallback + } + } + + /// 原图可能有几千像素,先在后台缩小,显示时才不会卡。 + 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 + 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/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/MarqueeText.swift b/ios/App/Player/MarqueeText.swift new file mode 100644 index 0000000..3df9bb4 --- /dev/null +++ b/ios/App/Player/MarqueeText.swift @@ -0,0 +1,64 @@ +// 改写自 AppleMusicStylePlayer 的 MarqueeText.swift +// Copyright (c) 2025 Alexey Vorobyov,MIT 许可,全文见本目录的 NOTICE.md。 + +import SwiftUI + +/// 一行放不下时来回滚动的文字。 +struct MarqueeText: View { + let text: String + + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var textWidth: CGFloat = 0 + @State private var viewWidth: CGFloat = 0 + @State private var isMoving = false + + private static let fade: CGFloat = 24 + private static let spacing: CGFloat = 60 + + init(_ text: String) { + self.text = text + } + + private var overflows: Bool { textWidth > 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..4e7ab01 --- /dev/null +++ b/ios/App/Player/MiniPlayer.swift @@ -0,0 +1,95 @@ +// 布局改写自 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 onExpand: () -> Void + + var body: some View { + HStack(spacing: 12) { + Button(action: onExpand) { + HStack(spacing: 12) { + 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) + } + .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 + case .video: "打开播放页观看" + 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 .video: "视频只在播放页打开时播放" + 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..7891991 --- /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 | + +主要改动: + +- 数据和操作换成 MusicGo 的房间状态;进度条接上房间跳转,松手才生效。 +- 展开和收起改用系统的缩放转场,背景改用 `MeshGradient`,不再依赖 Kingfisher 和 Metal。 + +改写后的文件按 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 + +```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..15681e4 --- /dev/null +++ b/ios/App/Player/PlayerView.swift @@ -0,0 +1,253 @@ +// 布局改写自 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 + + private enum Panel { + case artwork, lyrics, queue + } + + @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 { + 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() } + } + .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 narrow(_ room: Room, _ entry: QueueEntry) -> some View { + VStack(spacing: 0) { + 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) + } + + 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, + 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(room) + } + } + + private func info(_ room: Room, _ entry: QueueEntry, showsThumbnail: Bool) -> some View { + HStack(spacing: 12) { + 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.requester(entry.requestedBy, onBehalfOf: entry.onBehalfOf))") + .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 func footer(_ room: Room) -> some View { + HStack { + panelButton(.lyrics, "歌词", "quote.bubble") + Text(status(room)) + .font(.caption) + .foregroundStyle(.white.opacity(0.65)) + .multilineTextAlignment(.center) + .frame(maxWidth: .infinity) + .accessibilityIdentifier("player-state") + panelButton(.queue, "待播", "list.bullet") + } + } + + 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 } + } + .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 { + 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()) + } + } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .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/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 new file mode 100644 index 0000000..79dd27e --- /dev/null +++ b/ios/App/RoomPlayer.swift @@ -0,0 +1,396 @@ +import AVFoundation +import MediaPlayer +import MusicGoKit +import Observation +import UIKit + +/// 在本机播放房间里正在放的歌,跟着房间的进度走。 +@MainActor @Observable +final class RoomPlayer { + enum State: Equatable { + case idle, loading, playing, paused, off + /// 由播放页里的 YouTube 播放器播放。 + case video + case unsupported + case failed(String) + } + + private(set) var state = State.idle + /// 本机是否出声。不影响房间里的其他人。 + var isListening = true { + 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() + @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 + /// 别的 App 或来电占用了声音。 + @ObservationIgnored private var isInterrupted = false + @ObservationIgnored private var cover: UIImage? + @ObservationIgnored private var alignedAt = Date.distantPast + @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 + } + + /// 耳朵实际听到的进度。没有在出声时为 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() + 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 { + tries = 0 + load() + } else if jumped { + align() + } + update() + if changedEntry || jumped { updateNowPlaying() } + } + + func stop() { + ticker?.cancel() + ticker = nil + observers.forEach(NotificationCenter.default.removeObserver) + observers = [] + 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() { + 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 refusal = error as? APIError + // 刚好切歌了,新的状态马上就到。 + guard refusal?.code != "stale_entry" else { return } + failed(error, retry: refusal?.isRefusal != true) + } + } + } + + private func failed(_ error: Error?, retry: Bool) { + if retry, tries < Self.maxTries { + load() + 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) + 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 } + state = next + updateNowPlaying() + } + + /// 没有声音时,后台的 App 几秒后就会被挂起,接不上下一首。 + /// 换歌、加载和等人点歌时放一段无声音频,让 App 继续运行。 + private func keepAwakeBetweenSongs() { + 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 + } + } + + /// 「打断已结束」的通知不一定会来。回到 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 entry.track.youTubeID == nil ? .unsupported : .video } + 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 { + guard takeSession() else { return .paused } + 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 } + silence?.numberOfLoops = -1 + 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 + // 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?.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 + 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?.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 + Task { @MainActor in self?.isListening = false } + return .success + } + remote.nextTrackCommand.addTarget { @Sendable [weak self] _ in + Task { @MainActor in self?.onNext?() } + return .success + } + } + + private func play() { + isListening = true + onPlay?() + } + + private func updateNowPlaying() { + let center = MPNowPlayingInfoCenter.default() + guard let playback, let track = playback.entry?.track, track.isStreamable else { + center.nowPlayingInfo = isAwaitingSong ? [MPMediaItemPropertyTitle: "等人点下一首"] : 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 + 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 new file mode 100644 index 0000000..5e01229 --- /dev/null +++ b/ios/App/RoomSession.swift @@ -0,0 +1,236 @@ +import Foundation +import MusicGoKit +import Observation + +/// 一个房间的连接和状态。服务端是唯一事实来源,这里只保留它最近一次给的快照。 +@MainActor @Observable +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() + private(set) var isLive = false + /// 凭据失效或被移出房间,不再重连。 + private(set) var endedReason: String? + /// 给用户看的一次性提示。 + 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) + player = RoomPlayer(client: client) + player.onNext = { [weak self] in + 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() { + guard connection == nil else { return } + connection = Task { await run() } + } + + 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() } + } + + 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 + 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))" } + } + } + } + + @discardableResult + func perform(_ action: () async throws -> Void) async -> Bool { + do { + try await action() + return true + } catch { + notice = error.localizedDescription + return false + } + } + + // MARK: 连接 + + private func run() async { + var delay = 1.0 + while !Task.isCancelled { + do { + // 连上过再断开的(如从后台回来),马上重连。 + try await connectOnce { delay = 0.2 } + } catch let error as APIError where error.endsSession { + endedReason = error.localizedDescription + 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) + } + } + + /// 连到断开为止。 + private func connectOnce(onLive: () -> Void) async throws { + 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(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 { + 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 + } + lastMessage = Date() + 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 } + let oldCover = self.room?.playback.entry?.track.cover + self.room = room + 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 new file mode 100644 index 0000000..ee8ec6e --- /dev/null +++ b/ios/App/RoomView.swift @@ -0,0 +1,91 @@ +import MusicGoKit +import SwiftUI + +struct RoomView: View { + let session: RoomSession + let onLeave: () -> Void + + @Environment(\.scenePhase) private var scenePhase + @State private var isSearching = false + @State private var isPlayerOpen = false + @State private var isShowingInfo = false + @Namespace private var transition + + private var current: QueueEntry? { session.endedReason == nil ? session.room?.playback.entry : nil } + + var body: some View { + 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 { + queue(room) + } else { + ProgressView("正在连接…") + } + } + .navigationTitle(session.room?.name ?? "MusicGo") + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button("房间", systemImage: "person.2") { isShowingInfo = true } + .accessibilityIdentifier("open-room-info") + } + ToolbarItem(placement: .topBarTrailing) { + Button("点歌", systemImage: "plus") { isSearching = true } + .disabled(session.room == nil || session.endedReason != nil) + .accessibilityIdentifier("open-search") + } + } + .safeAreaInset(edge: .bottom) { + if let current { + MiniPlayer(session: session, entry: current) { isPlayerOpen = true } + .matchedTransitionSource(id: "player", in: transition) + .padding(.horizontal, 12) + .padding(.bottom, 6) + .frame(maxWidth: 560) + } + } + } + .sheet(isPresented: $isSearching) { SearchView(session: session) } + .sheet(isPresented: $isShowingInfo) { RoomInfoView(session: session, onLeave: onLeave) } + .fullScreenCover(isPresented: $isPlayerOpen) { + PlayerView(session: session) + .navigationTransition(.zoom(sourceID: "player", in: transition)) + } + .noticeAlert(session, isActive: !isPlayerOpen && !isShowingInfo && !isSearching) + .task { session.start() } + .onChange(of: scenePhase) { _, phase in + if phase == .active { session.wake() } + } + } + + private func queue(_ room: Room) -> some View { + List { + Section { + QueueRows(session: session, room: room) + } header: { + HStack { + Text("待播 \(room.queue.count) 首") + Spacer() + Label( + session.isLive ? "\(room.online.count) 人在听" : "正在重新连接…", + systemImage: session.isLive ? "person.2.fill" : "wifi.exclamationmark") + } + } + } + .listStyle(.plain) + .overlay { + if room.queue.isEmpty { + ContentUnavailableView( + room.playback.entry == nil ? "现在没有在放歌" : "后面还没有歌", systemImage: "music.note.list", + description: Text("点右上角的 + 点一首")) + } + } + } +} diff --git a/ios/App/SearchView.swift b/ios/App/SearchView.swift new file mode 100644 index 0000000..60486e7 --- /dev/null +++ b/ios/App/SearchView.swift @@ -0,0 +1,142 @@ +import MusicGoKit +import SwiftUI + +/// 搜歌名,或粘贴歌曲链接。点完留在这里,可以接着点。 +struct SearchView: View { + let session: RoomSession + /// 打开时先搜这个。 + var initialQuery = "" + var initialSource: String? + + @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 ordered: Set = [] + @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 limitText { + Text(limitText).font(.footnote).foregroundStyle(.secondary) + } + if let problem { + Label(problem, systemImage: "exclamationmark.triangle").foregroundStyle(.red) + } + ForEach(results) { track in + let isQueued = isQueued(track) + Button { order(track) } label: { + HStack { + TrackRow(track: track, detail: "") + Image(systemName: isQueued ? "checkmark.circle.fill" : "plus.circle").foregroundStyle(.tint) + } + } + .tint(.primary) + .disabled(isQueued || isFull) + .accessibilityValue(isQueued ? "已点" : "") + .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: "歌名、歌手,或歌曲链接") + // 搜索时也留着「完成」,不用先退出搜索。 + .searchPresentationToolbarBehavior(.avoidHidingContent) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .onSubmit(of: .search, submit) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("完成") { dismiss() }.accessibilityIdentifier("close-search") + } + } + .task { + do { + sources = try await client.sources() + source = sources.first { $0.id == initialSource }?.id ?? sources.first?.id ?? "" + if !initialQuery.isEmpty { + query = initialQuery + submit() + } + } catch { + problem = error.localizedDescription + } + } + } + } + + 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 { [client] in try await client.resolve(url: text) } then: { + results = [$0] + searched = text + } + } else { + let source = source + run { [client] in 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..ef7d23d --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/APIClient.swift @@ -0,0 +1,308 @@ +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 + /// 限流时,多少秒后可以再试。 + 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 + } + let detail = try? JSON.decoder.decode(Body.self, from: body).error + self.status = status + code = detail?.code ?? "internal" + message = detail?.message ?? "服务器返回了错误(HTTP \(status))" + retryAfter = detail?.details?.retryAfterSeconds + limit = detail?.details?.limit + } + + public var errorDescription: String? { + switch code { + 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) } +} + +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 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] + } + 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 + } + + public func lyrics(_ entryID: String) async throws -> Lyrics { + 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]) + } + + @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 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]) + } + + public func voteSkip(_ entryID: String) async throws -> VoteResult { + 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 + } + try await change("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", [:]) } + + /// 时长未知的歌,服务端靠客户端上报播完来切歌。 + 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: 房间管理 + + 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)" } + + private struct Ignored: Decodable {} + + private func act(_ action: String, _ body: [String: String]) async throws { + 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 { + try await send(request(path, query: query)) + } + + 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 = 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) + } + + func request(_ path: String, query: [String: String] = [:]) -> URLRequest { + var parts = URLComponents(url: link.server, resolvingAgainstBaseURL: false)! + parts.path = path + if !query.isEmpty { + parts.setQuery(query) + } + 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) + } +} + +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 new file mode 100644 index 0000000..2357708 --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/EntryLink.swift @@ -0,0 +1,78 @@ +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 + + 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 + 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 = 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 new file mode 100644 index 0000000..85f2abf --- /dev/null +++ b/ios/MusicGoKit/Sources/MusicGoKit/Lyrics.swift @@ -0,0 +1,138 @@ +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 source: String + public let lines: [LyricLine] + + public var isSynced: Bool { lines.contains { $0.atMs > 0 } } + + public var sourceName: String { + switch source { + case "netease": "网易云音乐" + case "qq": "QQ 音乐" + case "lrclib": "LRCLIB" + default: source + } + } +} + +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 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] + + /// 逐字时间,拼起来正好是 `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 { + 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 { + 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 { + 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 encoder: JSONEncoder { + let e = JSONEncoder() + e.keyEncodingStrategy = .convertToSnakeCase + return e + } + + 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..fca0570 --- /dev/null +++ b/ios/MusicGoKit/Tests/MusicGoKitTests/MusicGoKitTests.swift @@ -0,0 +1,199 @@ +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 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.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,"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_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"}, + "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_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 { + 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 == "不是房间成员") + 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) + } + + @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") + } +} + +@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 wordsCoverTheWholeLine() throws { + let lyrics = try JSON.decoder.decode(Lyrics.self, from: Data(Self.found.utf8)) + #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 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) + } +} diff --git a/ios/README.md b/ios/README.md new file mode 100644 index 0000000..f29b5ee --- /dev/null +++ b/ios/README.md @@ -0,0 +1,31 @@ +# MusicGo iOS 客户端 + +功能与网页版相同:一起听、点歌、调整队列、逐字歌词、投票切歌、管理成员和房间设置。需要 iOS 18 或更高版本。 + +## 使用 + +粘贴房间的进入链接(`https://musicgo.example.com/rooms/<房间>#token=<令牌>`)即可。服务器地址来自链接,令牌存在钥匙串。还不是成员时,链接里可以带 `invite=<邀请码>`。 + +- 静音和锁屏上的播放、暂停只管本机,锁屏上的「下一首」和进度条会影响整个房间;房间的暂停、切歌按[权限](../docs/api.md#权限矩阵)生效。 +- YouTube 用官方的内嵌播放器,只在播放页打开时播放,不能在后台听。 +- 歌放完后,App 会在后台等 30 分钟,有人点歌就接着放。房间暂停时切到后台,系统会挂起 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 界面、实时连接、播放。播放页改写自开源项目,歌词用 MelismaKit 绘制,见 [NOTICE](App/Player/NOTICE.md) | +| `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..181264f --- /dev/null +++ b/ios/UITests/MusicGoUITests.swift @@ -0,0 +1,133 @@ +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.tap() + field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: 12) + link + "\n") + + 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("4-player") + + app.buttons["show-lyrics"].tap() + // 歌词是一整块自绘的画面,读屏的值是正在唱的那一行。 + 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() + let offset = text(containing: "歌词时间", in: app) + XCTAssertTrue(offset.waitForExistence(timeout: 10)) + capture("6-lyrics-options") + app.buttons["完成"].tap() + XCTAssertTrue(offset.waitForNonExistence(timeout: 10)) + app.buttons["show-queue"].tap() + XCTAssertTrue(app.staticTexts["待播 1 首"].waitForExistence(timeout: 10)) + + 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.buttons["close-player"].tap() + XCTAssertTrue(title.waitForNonExistence(timeout: 10)) + + app.buttons["open-room-info"].tap() + XCTAssertTrue(text(containing: "邀请码", in: app).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)) + // 歌名很短,要在整行上滑。 + app.cells.containing(NSPredicate(format: "label == %@", "third 1")).firstMatch.swipeLeft() + app.buttons["撤回"].tap() + XCTAssertTrue(queued.waitForNonExistence(timeout: 10)) + + // 重新打开后仍是登录状态。 + app.terminate() + app.launch() + XCTAssertTrue(mini.waitForExistence(timeout: 20)) + mini.tap() + 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() + expectation(for: NSPredicate(format: "value == %@", "已点"), evaluatedWith: result) + waitForExpectations(timeout: 10) + app.buttons["close-search"].tap() + 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) + 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..63ce5cb --- /dev/null +++ b/ios/project.yml @@ -0,0 +1,70 @@ +# 用 XcodeGen 生成 MusicGo.xcodeproj(不进仓库):cd ios && xcodegen +name: MusicGo +options: + bundleIdPrefix: dev.luckybot + deploymentTarget: + iOS: "18.0" + createIntermediateGroups: true +settings: + base: + SWIFT_VERSION: "6.0" + MARKETING_VERSION: "0.1.0" + CURRENT_PROJECT_VERSION: "1" +packages: + MusicGoKit: + path: MusicGoKit + # 歌词渲染。没有发布版本,固定到一个提交。 + MelismaKit: + url: https://github.com/kmgcc/melismakit-ios + revision: 045a0a264cb26c2301bb587044d47a17d1e39a98 +targets: + MusicGo: + type: application + platform: iOS + sources: + - path: App + excludes: ['**/*.md'] + dependencies: + - package: MusicGoKit + - package: MelismaKit + products: [MelismaKit, MelismaKitSwiftUI] + 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] + # 让歌词在支持的机型上用 120 Hz 滚动 + CADisableMinimumFrameDurationOnPhone: true + 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..5609c72 --- /dev/null +++ b/ios/testplugin/index.js @@ -0,0 +1,30 @@ +// 只给 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' } +} + +// 每 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 } +} 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" +}