Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
324 lines
10 KiB
Swift
324 lines
10 KiB
Swift
// CrossSound Remote — a remote control for the CrossSound devices on your
|
|
// account, and nothing else: pick a device, see what it's playing, drive it.
|
|
//
|
|
// It plays nothing and is never a device itself (RemoteService's controller-
|
|
// only mode: it listens to the devices and sends commands, and writes nothing
|
|
// of its own). The account comes from CrossSound on this watch — just the
|
|
// SoundCloud uid the remote tree is keyed by — and so does the theme
|
|
// (RemoteAppGroup). The widgets in Widget/ read the device list it leaves
|
|
// there.
|
|
|
|
import CrossSoundKit
|
|
import RedWhiteUI
|
|
import SwiftUI
|
|
import WidgetKit
|
|
|
|
@main
|
|
struct CrossSoundRemoteApp: App {
|
|
@State private var model = RemoteModel()
|
|
@Environment(\.scenePhase) private var scenePhase
|
|
|
|
var body: some Scene {
|
|
WindowGroup {
|
|
RemoteRoot()
|
|
.crossSoundWatchLook()
|
|
.rwTheme(model.appearance)
|
|
.environment(model)
|
|
// A widget tap lands on the device it shows.
|
|
.onOpenURL { model.open($0) }
|
|
}
|
|
.onChange(of: scenePhase, initial: true) { _, phase in model.scenePhaseChanged(phase) }
|
|
}
|
|
}
|
|
|
|
// MARK: - Model
|
|
|
|
@MainActor
|
|
@Observable
|
|
final class RemoteModel {
|
|
/// Controller-only. RemoteService wants an API for adoption reach-through,
|
|
/// which a remote never does; this one is never signed in or called.
|
|
let remote = RemoteService(api: SoundCloudAPI(auth: AuthStore()))
|
|
private(set) var userId: String?
|
|
private(set) var appearance: RwAppearance
|
|
/// The device the screen drives, remembered between launches.
|
|
var selectedId: String? {
|
|
didSet { UserDefaults.standard.set(selectedId, forKey: Self.kSelected) }
|
|
}
|
|
|
|
@ObservationIgnored private var widgetUpdate: Task<Void, Never>?
|
|
@ObservationIgnored private var lastDeviceSet = ""
|
|
private static let kSelected = "remote_selected_device"
|
|
|
|
init() {
|
|
appearance = Self.theme()
|
|
userId = RemoteAppGroup.userId
|
|
selectedId = UserDefaults.standard.string(forKey: Self.kSelected)
|
|
remote.onDevices = { [weak self] devices in self?.devicesChanged(devices) }
|
|
}
|
|
|
|
/// The chosen device; when there's none (or it's gone), the one playing,
|
|
/// else the first online.
|
|
var shown: RemoteDevice? {
|
|
let devices = remote.devices
|
|
if let selectedId, let device = devices.first(where: { $0.id == selectedId }) {
|
|
return device
|
|
}
|
|
return devices.first { $0.online && $0.isPlaying } ?? devices.first(where: \.online)
|
|
}
|
|
|
|
func send(_ cmd: String, to device: RemoteDevice, args: [String: Any]? = nil) {
|
|
Task { await remote.sendCommand(to: device.id, cmd: cmd, args: args) }
|
|
}
|
|
|
|
/// `csremote://device/<id>` from a widget.
|
|
func open(_ url: URL) {
|
|
guard url.scheme == "csremote", url.host == "device", let id = url.pathComponents.last,
|
|
id != "/"
|
|
else { return }
|
|
selectedId = id
|
|
}
|
|
|
|
func scenePhaseChanged(_ phase: ScenePhase) {
|
|
switch phase {
|
|
case .active:
|
|
// Re-read every time: CrossSound may have signed in (or the phone's
|
|
// theme changed) while the remote was closed.
|
|
appearance = Self.theme()
|
|
userId = RemoteAppGroup.userId
|
|
if let userId, !remote.started {
|
|
Task { await remote.start(scUid: userId, controllerOnly: true) }
|
|
}
|
|
case .background:
|
|
// Nothing to say on the way out (a controller writes nothing); just
|
|
// close the stream.
|
|
Task { await remote.stop() }
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
|
|
/// Every devices snapshot (~2s while something plays). The widgets get the
|
|
/// list a few seconds later, in one go: the gallery's choices when the set
|
|
/// of devices changed, and a redraw.
|
|
private func devicesChanged(_ devices: [RemoteDevice]) {
|
|
widgetUpdate?.cancel()
|
|
widgetUpdate = Task {
|
|
try? await Task.sleep(for: .seconds(3))
|
|
guard !Task.isCancelled else { return }
|
|
RemoteAppGroup.saveDevices(devices)
|
|
let set = devices.map { "\($0.id)=\($0.name)" }.joined(separator: ",")
|
|
if set != lastDeviceSet {
|
|
lastDeviceSet = set
|
|
WidgetCenter.shared.invalidateConfigurationRecommendations()
|
|
}
|
|
WidgetCenter.shared.reloadAllTimelines()
|
|
}
|
|
}
|
|
|
|
private static func theme() -> RwAppearance {
|
|
guard let json = RemoteAppGroup.themeJSON,
|
|
let value = try? JSONDecoder().decode(RwAppearance.self, from: Data(json.utf8))
|
|
else { return RwAppearance() }
|
|
return value.widgetSafe()
|
|
}
|
|
}
|
|
|
|
// MARK: - Screens
|
|
|
|
enum RemoteRoute: Hashable {
|
|
case picker
|
|
}
|
|
|
|
struct RemoteRoot: View {
|
|
@Environment(RemoteModel.self) private var model
|
|
@Environment(\.rw) private var p
|
|
|
|
var body: some View {
|
|
NavigationStack {
|
|
Group {
|
|
if model.userId == nil {
|
|
SetupScreen()
|
|
} else {
|
|
ControlScreen()
|
|
}
|
|
}
|
|
.navigationDestination(for: RemoteRoute.self) { _ in
|
|
DevicePickerScreen()
|
|
.containerBackground(p.bg.color, for: .navigation)
|
|
.toolbarForegroundStyle(p.red.color, for: .navigationBar)
|
|
}
|
|
.containerBackground(p.bg.color, for: .navigation)
|
|
.toolbarForegroundStyle(p.red.color, for: .navigationBar)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The chosen device and its controls.
|
|
struct ControlScreen: View {
|
|
@Environment(RemoteModel.self) private var model
|
|
|
|
var body: some View {
|
|
let device = model.shown
|
|
ScrollView {
|
|
VStack(spacing: 8) {
|
|
NavigationLink(value: RemoteRoute.picker) {
|
|
PickerButton(device: device, connecting: !model.remote.dbConnected)
|
|
}
|
|
|
|
if let device {
|
|
nowPlaying(device)
|
|
}
|
|
}
|
|
.padding(.horizontal, 4)
|
|
}
|
|
.navigationTitle("Remote")
|
|
}
|
|
|
|
@ViewBuilder
|
|
private func nowPlaying(_ device: RemoteDevice) -> some View {
|
|
if let title = device.title, !title.isEmpty {
|
|
HStack(alignment: .top, spacing: 8) {
|
|
Artwork(url: device.artworkUrl, size: 52)
|
|
VStack(alignment: .leading, spacing: 2) {
|
|
Text(title).rw(.titleSmall).lineLimit(3)
|
|
Text(device.artist ?? "").rw(.labelMedium).lineLimit(1)
|
|
}
|
|
Spacer(minLength: 0)
|
|
}
|
|
TimelineView(.periodic(from: .now, by: 1)) { context in
|
|
ProgressLine(positionMs: device.position(at: context.date), durationMs: device.durationMs)
|
|
}
|
|
} else {
|
|
Text("Nothing playing").rw(.titleSmall).padding(.vertical, 8)
|
|
}
|
|
|
|
TransportRow(
|
|
isPlaying: device.isPlaying,
|
|
enabled: device.online,
|
|
liked: device.isLiked,
|
|
onPrev: { model.send("prev", to: device) },
|
|
onToggle: { model.send(device.isPlaying ? "pause" : "play", to: device) },
|
|
onNext: { model.send("next", to: device) },
|
|
onLike: { model.send("like", to: device, args: device.likeArgs) })
|
|
|
|
if !device.queue.isEmpty {
|
|
SectionLabel(
|
|
device.queueTotal > device.queue.count
|
|
? "Up next · \(device.queue.count) of \(device.queueTotal)" : "Up next")
|
|
ForEach(Array(device.queue.enumerated()), id: \.offset) { index, item in
|
|
Button {
|
|
model.send("jump", to: device, args: ["index": index])
|
|
} label: {
|
|
TrackRow(
|
|
title: item.title, artist: item.artist, artworkUrl: item.artworkUrl,
|
|
isCurrent: index == device.queueIndex)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The device picker's button: which device, and that it changes.
|
|
struct PickerButton: View {
|
|
let device: RemoteDevice?
|
|
let connecting: Bool
|
|
|
|
var body: some View {
|
|
HStack(spacing: 8) {
|
|
Image(systemName: device.map { DeviceRow.icon($0.platform) } ?? "dot.radiowaves.left.and.right")
|
|
.font(.system(size: 17, weight: .semibold))
|
|
.frame(width: 24)
|
|
VStack(alignment: .leading, spacing: 1) {
|
|
Text(device?.name ?? (connecting ? "Connecting…" : "No devices online"))
|
|
.rw(.titleSmall)
|
|
.lineLimit(1)
|
|
Text(device.map { $0.online ? "Online" : "Offline" } ?? "Choose a device")
|
|
.rw(.labelSmall)
|
|
}
|
|
Spacer(minLength: 0)
|
|
Image(systemName: "chevron.up.chevron.down")
|
|
.font(.system(size: 12, weight: .semibold))
|
|
}
|
|
.padding(6)
|
|
.rwBorder(.accent, width: 2)
|
|
.contentShape(Rectangle())
|
|
.accessibilityLabel(device.map { "Controlling \($0.name). Choose a device." } ?? "Choose a device")
|
|
}
|
|
}
|
|
|
|
/// Every device on the account; the one being driven is checked.
|
|
struct DevicePickerScreen: View {
|
|
@Environment(RemoteModel.self) private var model
|
|
@Environment(\.dismiss) private var dismiss
|
|
|
|
var body: some View {
|
|
let devices = model.remote.devices
|
|
let online = devices.filter(\.online)
|
|
let offline = devices.filter { !$0.online }
|
|
ScrollView {
|
|
LazyVStack(alignment: .leading, spacing: 2) {
|
|
if devices.isEmpty {
|
|
Text("No CrossSound devices yet. Open CrossSound on a phone, Mac or computer.")
|
|
.rw(.labelMedium)
|
|
.padding(.top, 8)
|
|
}
|
|
if !online.isEmpty {
|
|
SectionLabel("Online")
|
|
ForEach(online) { row($0) }
|
|
}
|
|
if !offline.isEmpty {
|
|
SectionLabel("Offline")
|
|
ForEach(offline) { row($0) }
|
|
}
|
|
}
|
|
.padding(.horizontal, 4)
|
|
}
|
|
.navigationTitle("Devices")
|
|
}
|
|
|
|
private func row(_ device: RemoteDevice) -> some View {
|
|
Button {
|
|
model.selectedId = device.id
|
|
dismiss()
|
|
} label: {
|
|
HStack(spacing: 0) {
|
|
DeviceRow(device: device)
|
|
if device.id == model.shown?.id {
|
|
Image(systemName: "checkmark")
|
|
.font(.system(size: 13, weight: .bold))
|
|
.padding(.trailing, 6)
|
|
.accessibilityLabel("Selected")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// No account yet: the remote borrows CrossSound's.
|
|
struct SetupScreen: View {
|
|
@Environment(RemoteModel.self) private var model
|
|
|
|
var body: some View {
|
|
ScrollView {
|
|
VStack(spacing: 10) {
|
|
Image(systemName: "applewatch")
|
|
.font(.system(size: 30, weight: .semibold))
|
|
Text("Open CrossSound on this watch")
|
|
.rw(.titleMedium)
|
|
.multilineTextAlignment(.center)
|
|
Text("The remote uses the account CrossSound is signed in with. Open it once, then come back.")
|
|
.rw(.labelMedium)
|
|
.multilineTextAlignment(.center)
|
|
Button {
|
|
model.scenePhaseChanged(.active)
|
|
} label: {
|
|
Text("Try again").rw(.titleSmall)
|
|
}
|
|
}
|
|
.padding(.horizontal, 6)
|
|
}
|
|
.navigationTitle("Remote")
|
|
}
|
|
}
|