Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
461 lines
17 KiB
Swift
461 lines
17 KiB
Swift
// WatchModel — the watch app's services and their wiring: the phone's
|
|
// AppServices + AppRoot bootstrap/control plane, cut down to what a watch does.
|
|
//
|
|
// - Sign-in: the phone's login, through WatchLink (no web view on watchOS).
|
|
// - Remote: RemoteService, the same Firebase tree every CrossSound app uses.
|
|
// The watch is a device in it like any other: it lists and drives the
|
|
// others, and they can drive it.
|
|
// - Player: the phone's QueueController + PlayerEngine (FairPlay included),
|
|
// playing to Bluetooth headphones, or the watch's own speaker. Every play
|
|
// first makes sure the watch has somewhere to send audio (WatchAudioRoute).
|
|
|
|
import CrossSoundKit
|
|
import Foundation
|
|
import Observation
|
|
import RedWhiteUI
|
|
import SwiftUI
|
|
|
|
@MainActor
|
|
@Observable
|
|
final class WatchModel {
|
|
enum Phase {
|
|
case loading
|
|
case signedOut
|
|
case ready
|
|
}
|
|
|
|
let auth: AuthStore
|
|
let api: SoundCloudAPI
|
|
let engine: PlayerEngine
|
|
let queue: QueueController
|
|
let remote: RemoteService
|
|
@ObservationIgnored private let nowPlaying = NowPlayingCenter()
|
|
|
|
private(set) var phase: Phase = .loading
|
|
private(set) var me: SCUser?
|
|
private(set) var appearance: RwAppearance
|
|
/// A short message for the bottom of the screen (a play that failed, no
|
|
/// headphones). Clears itself.
|
|
private(set) var notice: String?
|
|
/// Where the audio is going, for the player screen ("Speaker", "AirPods
|
|
/// Pro"); `routeIsFallback` = the speaker only while the app is open.
|
|
private(set) var route: String?
|
|
private(set) var routeIsFallback = false
|
|
|
|
@ObservationIgnored private var booted = false
|
|
/// CrossSound is frontmost (active, or inactive under a covered or dimmed
|
|
/// screen), where the speaker fallback can play. False in the background.
|
|
@ObservationIgnored private var isFrontmost = true
|
|
@ObservationIgnored private var noticeTask: Task<Void, Never>?
|
|
/// The phone's last theme, so a launch doesn't flash the default first.
|
|
private static let themeKey = "cs_watch_theme"
|
|
|
|
init() {
|
|
let auth = AuthStore()
|
|
let engine = PlayerEngine()
|
|
let api = SoundCloudAPI(auth: auth)
|
|
self.auth = auth
|
|
self.engine = engine
|
|
self.api = api
|
|
queue = QueueController(engine: engine, api: api)
|
|
remote = RemoteService(api: api)
|
|
appearance = Self.decodeTheme(UserDefaults.standard.string(forKey: Self.themeKey)) ?? RwAppearance()
|
|
}
|
|
|
|
// MARK: - Boot
|
|
|
|
func boot() async {
|
|
guard !booted else { return }
|
|
booted = true
|
|
await auth.load()
|
|
let link = WatchLink.shared
|
|
link.onCredentials = { [weak self] signedIn in
|
|
Task { await self?.credentialsChanged(signedIn: signedIn) }
|
|
}
|
|
// After load(), like the phone: started on an empty store, the link
|
|
// would tell the phone this watch has nothing (harmless, but noise).
|
|
await link.start(auth: auth)
|
|
await api.setHooks(
|
|
onSessionExpired: { [auth] in
|
|
// The phone re-captures its own session when SoundCloud drops it;
|
|
// a different one from there is worth one retry.
|
|
guard let fresh = await WatchLink.shared.requestCredentials(refresh: false) else {
|
|
return false
|
|
}
|
|
return await auth.adopt(fresh)
|
|
},
|
|
onAuthFailed: { [weak self] in
|
|
Task { @MainActor in self?.phase = .signedOut }
|
|
},
|
|
onV2SessionNeedsReauth: nil)
|
|
wireControls()
|
|
if queue.currentTrack == nil { queue.restorePersistedState() }
|
|
Task { await runPump() }
|
|
await signIn()
|
|
}
|
|
|
|
/// With the stored credentials, or the phone's when there are none yet.
|
|
/// [userInitiated] = the Sign in button, which also undoes a sign-out made
|
|
/// on this watch; without it (launch, a re-delivered login) a watch that
|
|
/// was signed out here stays signed out.
|
|
func signIn(userInitiated: Bool = false) async {
|
|
if userInitiated { WatchLink.shared.signedOutHere = false }
|
|
if WatchLink.shared.signedOutHere {
|
|
phase = .signedOut
|
|
return
|
|
}
|
|
if !(await auth.hasCredentials),
|
|
let fresh = await WatchLink.shared.requestCredentials(refresh: false)
|
|
{
|
|
await auth.adopt(fresh)
|
|
}
|
|
guard await auth.hasCredentials else {
|
|
// The phone answers from the background too (WatchLink.activateEarly),
|
|
// but it has to be in reach and signed in to CrossSound itself.
|
|
if userInitiated {
|
|
show("Couldn't get a login from your iPhone. Keep it nearby and signed in to CrossSound, then try again.")
|
|
}
|
|
phase = .signedOut
|
|
return
|
|
}
|
|
do {
|
|
let me = try await api.getMe()
|
|
self.me = me
|
|
// CrossSound Remote and its widgets find the account through this.
|
|
RemoteAppGroup.userId = me.id
|
|
CSLog.shared.log("watch", "signed in as \(me.username)")
|
|
Task { await remote.start(scUid: me.id) }
|
|
} catch {
|
|
CSLog.shared.log("watch", "getMe failed: \(error.localizedDescription)")
|
|
// Offline or a hiccup: the remote still knows its namespace from the
|
|
// phone, and the restored session stays playable.
|
|
if let uid = WatchLink.shared.phoneUserId {
|
|
RemoteAppGroup.userId = uid
|
|
Task { await remote.start(scUid: uid) }
|
|
}
|
|
}
|
|
phase = .ready
|
|
}
|
|
|
|
/// Sign out of CrossSound on this watch only: the iPhone stays signed in
|
|
/// (the watch can't sign it out). Sticks across launches (WatchLink.signedOutHere).
|
|
func signOut() async {
|
|
WatchLink.shared.signedOutHere = true
|
|
if queue.isPlaying { await queue.togglePlay() }
|
|
queue.persistNow()
|
|
engine.stop()
|
|
// Off the device list (marks this watch offline for the others).
|
|
await remote.stop()
|
|
await auth.clearAll()
|
|
me = nil
|
|
RemoteAppGroup.userId = nil
|
|
phase = .signedOut
|
|
CSLog.shared.log("watch", "signed out on this watch")
|
|
}
|
|
|
|
private func credentialsChanged(signedIn: Bool) async {
|
|
if signedIn {
|
|
if phase != .ready || me == nil { await signIn() }
|
|
return
|
|
}
|
|
engine.stop()
|
|
await remote.stop()
|
|
me = nil
|
|
RemoteAppGroup.userId = nil
|
|
phase = .signedOut
|
|
}
|
|
|
|
// MARK: - Theme
|
|
|
|
func applyTheme(_ json: String?) {
|
|
guard let value = Self.decodeTheme(json) else { return }
|
|
appearance = value
|
|
UserDefaults.standard.set(json, forKey: Self.themeKey)
|
|
RemoteAppGroup.themeJSON = json // the remote wears it too
|
|
}
|
|
|
|
/// The phone's JSON (AppearanceStore.encode). A theme font file never
|
|
/// crosses, so anything but the built-in families falls back to Raleway.
|
|
private static func decodeTheme(_ json: String?) -> RwAppearance? {
|
|
guard let json, let value = try? JSONDecoder().decode(RwAppearance.self, from: Data(json.utf8))
|
|
else { return nil }
|
|
return value.widgetSafe()
|
|
}
|
|
|
|
// MARK: - Playing on the watch
|
|
|
|
/// Play `tracks` from `index` on this watch.
|
|
func play(_ tracks: [SCTrack], at index: Int = 0, station: QueueController.PlayingStation? = nil)
|
|
async
|
|
{
|
|
guard tracks.indices.contains(index), await routeReady() else { return }
|
|
await queue.playTrack(tracks[index], newQueue: tracks, station: station)
|
|
}
|
|
|
|
func shuffle(_ tracks: [SCTrack]) async {
|
|
guard !tracks.isEmpty, await routeReady() else { return }
|
|
if !queue.shuffle { queue.toggleShuffle() }
|
|
await queue.playTrack(tracks[0], newQueue: tracks)
|
|
}
|
|
|
|
func togglePlay() async { await queue.togglePlay() } // onBeforeUserPlay asks for the route
|
|
|
|
func jump(to index: Int) async {
|
|
guard await routeReady() else { return }
|
|
await queue.playQueueIndex(index)
|
|
}
|
|
|
|
/// Take over what another device is playing — the phone's "Resume here"
|
|
/// (RemoteAdoption): its published queue, hydrated in order, from the same
|
|
/// song and second, then pause it there.
|
|
func playHere(from device: RemoteDevice) async {
|
|
let currentId = device.trackId
|
|
var ids = device.queue.compactMap(\.trackId)
|
|
if ids.isEmpty, let currentId, !currentId.isEmpty { ids = [currentId] }
|
|
guard !ids.isEmpty, await routeReady() else { return }
|
|
let byId = await api.getTracksByIds(ids)
|
|
let tracks = ids.compactMap { byId[$0] }
|
|
guard !tracks.isEmpty else {
|
|
show("Couldn't load what \(device.name) is playing")
|
|
return
|
|
}
|
|
var index = currentId.flatMap { id in tracks.firstIndex { $0.id == id } } ?? -1
|
|
if index < 0 { index = min(max(device.queueIndex, 0), tracks.count - 1) }
|
|
await queue.adoptSession(tracks: tracks, index: index, positionMs: device.positionMs)
|
|
await remote.sendCommand(to: device.id, cmd: "pause")
|
|
}
|
|
|
|
/// Somewhere to play, before anything starts: long-form first (headphones,
|
|
/// or the speaker on watches that play media there), else the speaker while
|
|
/// the app is open — said once, when it starts. False = nowhere at all.
|
|
private func routeReady() async -> Bool {
|
|
let wasOnSpeaker = WatchAudioRoute.onSpeakerFallback
|
|
guard await WatchAudioRoute.activate(allowSpeakerFallback: isFrontmost) else {
|
|
show(
|
|
isFrontmost
|
|
? "Couldn't start audio on this watch"
|
|
: "Open CrossSound to play on the watch speaker")
|
|
return false
|
|
}
|
|
if WatchAudioRoute.onSpeakerFallback, !wasOnSpeaker {
|
|
// Why long-form said no rides along: it's the difference between "pick
|
|
// the speaker in the picker" and a watch that can't.
|
|
let why = WatchAudioRoute.longFormRefusal.map { " (\($0))" } ?? ""
|
|
show("Playing on the watch speaker while CrossSound is open\(why)")
|
|
}
|
|
return true
|
|
}
|
|
|
|
// MARK: - Controlling another device
|
|
|
|
func send(_ cmd: String, to device: RemoteDevice, args: [String: Any]? = nil) {
|
|
Task { await remote.sendCommand(to: device.id, cmd: cmd, args: args) }
|
|
}
|
|
|
|
// MARK: - Notices
|
|
|
|
func show(_ message: String) {
|
|
noticeTask?.cancel()
|
|
withAnimation { notice = message }
|
|
noticeTask = Task {
|
|
try? await Task.sleep(for: .seconds(4))
|
|
guard !Task.isCancelled else { return }
|
|
withAnimation { notice = nil }
|
|
}
|
|
}
|
|
|
|
// MARK: - Lifecycle
|
|
|
|
func scenePhaseChanged(_ phase: ScenePhase) {
|
|
switch phase {
|
|
case .background:
|
|
isFrontmost = false
|
|
// Possibly the last chance before the watch suspends us.
|
|
queue.persistNow()
|
|
Task {
|
|
// The speaker fallback stops in the background (watchOS suspends
|
|
// it). Pause it ourselves so the app, the Now Playing widget and the
|
|
// other devices all show it paused where it stopped, rather than a
|
|
// dead "playing" — and let go of the fallback, so the widget's play
|
|
// button tries long-form (headphones) instead.
|
|
if WatchAudioRoute.onSpeakerFallback {
|
|
if queue.isPlaying { await queue.togglePlay() }
|
|
queue.persistNow()
|
|
WatchAudioRoute.reset()
|
|
}
|
|
// Long-form carries on in the background.
|
|
guard !queue.isPlaying else { return }
|
|
// Nothing playing: let go of the route, so the next play tries
|
|
// headphones (or the long-form speaker) again — and say this watch
|
|
// is going to sleep, or peers list it online until lastSeen goes stale.
|
|
WatchAudioRoute.reset()
|
|
await remote.stop()
|
|
}
|
|
case .active:
|
|
isFrontmost = true
|
|
if let uid = me?.id ?? WatchLink.shared.phoneUserId, !remote.started {
|
|
Task { await remote.start(scUid: uid) }
|
|
}
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
|
|
// MARK: - Control plane
|
|
|
|
private func wireControls() {
|
|
// Every not-playing → playing press (togglePlay) passes here first.
|
|
// True = consumed: there is nowhere to play.
|
|
queue.onBeforeUserPlay = { [weak self] in !(await self?.routeReady() ?? false) }
|
|
|
|
// The watch's Now Playing, the headphones' buttons.
|
|
nowPlaying.onCommand = { [weak self] command in
|
|
Task { @MainActor in await self?.run(command) }
|
|
}
|
|
|
|
remote.stateProvider = { [queue, engine] in
|
|
guard let track = queue.currentTrack else { return nil }
|
|
return RemoteNowPlaying(
|
|
trackId: track.id,
|
|
title: track.title,
|
|
artist: track.user.username,
|
|
artworkUrl: track.artworkUrl,
|
|
durationMs: engine.durationMs > 0 ? engine.durationMs : track.duration,
|
|
positionMs: queue.shownPositionMs,
|
|
isPlaying: queue.isPlaying,
|
|
isLiked: track.isLiked)
|
|
}
|
|
remote.queueProvider = { [queue] in
|
|
let q = queue.queue
|
|
let items = q.prefix(60).map { t in
|
|
RemoteQueueItem(
|
|
trackId: t.id, title: t.title, artist: t.user.username,
|
|
artworkUrl: t.artworkUrlSmall ?? t.artworkUrl)
|
|
}
|
|
return RemoteQueueSnapshot(index: queue.queueIndex, total: q.count, items: Array(items))
|
|
}
|
|
remote.onCommand = { [weak self] message in
|
|
Task { @MainActor in await self?.runRemote(message) }
|
|
}
|
|
}
|
|
|
|
private func run(_ command: RemoteCommand) async {
|
|
defer { remote.publishState(force: true) }
|
|
switch command {
|
|
case .play:
|
|
if !queue.isPlaying { await queue.togglePlay() }
|
|
case .pause:
|
|
if queue.isPlaying { await queue.togglePlay() }
|
|
case .toggle:
|
|
await queue.togglePlay()
|
|
case .next:
|
|
await queue.playNext()
|
|
case .prev:
|
|
await queue.playPrev()
|
|
case .like:
|
|
await queue.toggleLike()
|
|
case .seek(let ms):
|
|
queue.seek(toMs: ms)
|
|
}
|
|
}
|
|
|
|
/// A peer driving this watch — the phone's runRemoteCommand vocabulary.
|
|
/// play/pause are absolute, so a command replayed after a reconnect is
|
|
/// harmless.
|
|
private func runRemote(_ message: RemoteCommandMessage) async {
|
|
let args = message.args
|
|
CSLog.shared.log("remote", "command \(message.cmd) args=\(args)")
|
|
switch message.cmd {
|
|
case "play":
|
|
if !queue.isPlaying { await queue.togglePlay() }
|
|
case "pause":
|
|
if queue.isPlaying { await queue.togglePlay() }
|
|
case "next":
|
|
await queue.playNext()
|
|
case "prev":
|
|
await queue.playPrev()
|
|
case "like":
|
|
guard
|
|
RemoteService.likeCommandApplies(
|
|
args: args, currentTrackId: queue.currentTrack?.id,
|
|
isLiked: queue.currentTrack?.isLiked ?? false)
|
|
else { return }
|
|
await queue.toggleLike()
|
|
case "seek":
|
|
queue.seek(toMs: Self.int(args["ms"]) ?? 0)
|
|
case "jump":
|
|
let index = Self.int(args["index"]) ?? -1
|
|
if queue.queue.indices.contains(index) { await jump(to: index) }
|
|
case "removeAt":
|
|
queue.removeQueueAt(Self.int(args["index"]) ?? -1)
|
|
case "reorder":
|
|
queue.reorderQueue(from: Self.int(args["from"]) ?? -1, to: Self.int(args["to"]) ?? -1)
|
|
case "clearQueue":
|
|
queue.clearQueue()
|
|
case "enqueue":
|
|
let ids = (args["trackIds"] as? [Any])?.compactMap { raw -> String? in
|
|
(raw as? String) ?? (raw as? NSNumber)?.stringValue
|
|
} ?? []
|
|
guard !ids.isEmpty else { break }
|
|
// Enqueueing into an empty queue starts playing: route first.
|
|
if queue.currentTrack == nil, !(await routeReady()) { break }
|
|
let byId = await api.getTracksByIds(ids)
|
|
await queue.addTracksToQueue(ids.compactMap { byId[$0] })
|
|
default:
|
|
CSLog.shared.log("remote", "unknown command \(message.cmd) — ignored")
|
|
}
|
|
remote.publishState(force: true)
|
|
remote.publishQueue()
|
|
}
|
|
|
|
private static func int(_ value: Any?) -> Int? {
|
|
if let n = value as? NSNumber { return n.intValue }
|
|
if let s = value as? String { return Int(s) }
|
|
return nil
|
|
}
|
|
|
|
/// Once a second: the watch's Now Playing, and the remote's state while
|
|
/// playing (plus one frame on the pause edge, the phone's pump rule — a
|
|
/// paused device goes quiet on purpose). The queue publishes only on a
|
|
/// real change; its signature guard makes the call free otherwise.
|
|
private func runPump() async {
|
|
var wasPlaying = false
|
|
var lastTrackId: String?
|
|
var lastLiked: Bool?
|
|
var lastError: String?
|
|
while !Task.isCancelled {
|
|
let playing = queue.isPlaying
|
|
if let track = queue.currentTrack {
|
|
nowPlaying.update(
|
|
title: track.title,
|
|
artist: track.user.username,
|
|
isPlaying: playing,
|
|
positionMs: queue.shownPositionMs,
|
|
durationMs: engine.durationMs > 0 ? engine.durationMs : track.duration,
|
|
isLiked: track.isLiked,
|
|
artworkUrl: track.artworkUrl)
|
|
}
|
|
// A new song, or a like made here: out at once, paused or not, so the
|
|
// remotes' title and heart follow.
|
|
let trackChanged =
|
|
queue.currentTrack?.id != lastTrackId || queue.currentTrack?.isLiked != lastLiked
|
|
if playing || wasPlaying || trackChanged {
|
|
remote.publishState(force: !playing || trackChanged)
|
|
}
|
|
remote.publishQueue()
|
|
wasPlaying = playing
|
|
lastTrackId = queue.currentTrack?.id
|
|
lastLiked = queue.currentTrack?.isLiked
|
|
let output = WatchAudioRoute.outputName
|
|
if output != route { route = output }
|
|
if WatchAudioRoute.onSpeakerFallback != routeIsFallback {
|
|
routeIsFallback = WatchAudioRoute.onSpeakerFallback
|
|
}
|
|
// Each failure once (lastError stays set until the next play).
|
|
if let error = queue.lastError, error != lastError { show(error) }
|
|
lastError = queue.lastError
|
|
try? await Task.sleep(for: .seconds(1))
|
|
}
|
|
}
|
|
}
|