Files
DockDoor/CrossSoundClient.swift
2026-09-17 22:14:07 -07:00

430 lines
15 KiB
Swift

import AppKit
import DockDoorWidgetSDK
import SwiftUI
// MARK: - Model types
/// One track in the current CrossSound queue.
struct CrossSoundTrack: Identifiable {
let id: Int
let index: Int
let title: String
let artist: String
}
/// What tapping a row in the panel does. Each case maps to one endpoint of the
/// CrossSound local API.
enum CrossSoundPlayAction {
case playlist(Int)
case url(String)
case queueIndex(Int)
}
/// A row in the Playlists / Discover / Queue lists.
struct CrossSoundBrowseRow: Identifiable {
let id: String
let title: String
let subtitle: String
let action: CrossSoundPlayAction
}
/// Snapshot of `GET /state`. Every field is optional on the wire: CrossSound
/// answers `{}` until something has played.
struct CrossSoundNowPlaying {
var title = ""
var artist = ""
var artworkURL = ""
var isPlaying = false
var isLiked = false
var shuffle = false
var repeatMode = "none"
var position: Double = 0
var elapsedText = "0:00"
var durationText = "0:00"
var queue: [CrossSoundTrack] = []
var queueIndex = 0
var hasTrack: Bool { !title.isEmpty || !artist.isEmpty }
/// Duration in seconds, parsed back out of the formatted string CrossSound
/// sends (`m:ss` or `h:mm:ss`) — the payload carries no numeric duration.
var durationSeconds: Double {
let parts = durationText.split(separator: ":").compactMap { Double($0) }
switch parts.count {
case 2: return parts[0] * 60 + parts[1]
case 3: return parts[0] * 3600 + parts[1] * 60 + parts[2]
default: return 0
}
}
}
/// Progress of a list fetch, so the panel can show a spinner or a reason.
enum CrossSoundLoad: Equatable {
case idle
case loading
case loaded
case failed(String)
}
// MARK: - Client
/// Polls the CrossSound loopback API and posts commands to it.
///
/// Polling is driven by `TimelineView` ticks from the views (see `tick`), not by
/// a `Timer`, so nothing runs while the widget is off screen. The dock view and
/// the panel share one instance and the same throttle.
@Observable
final class CrossSoundClient {
/// Ports the CrossSound bridges listen on: Stream Deck first, Game Bar second.
private static let defaultPorts = [52124, 8963]
private let widgetId: String
private let session: URLSession
var nowPlaying = CrossSoundNowPlaying()
var isConnected = false
var artwork: NSImage?
var playlists: [CrossSoundBrowseRow] = []
var discover: [CrossSoundBrowseRow] = []
var playlistsLoad: CrossSoundLoad = .idle
var discoverLoad: CrossSoundLoad = .idle
private var baseURL: URL?
private var lastPoll = Date.distantPast
private var pollInFlight = false
private var artworkKey = ""
init(widgetId: String) {
self.widgetId = widgetId
let config = URLSessionConfiguration.ephemeral
config.timeoutIntervalForRequest = 3
config.waitsForConnectivity = false
session = URLSession(configuration: config)
}
/// Ports to try: an explicit one from settings, else both known bridges.
private var candidatePorts: [Int] {
let manual = WidgetDefaults.string(key: "port", widgetId: widgetId)
.trimmingCharacters(in: .whitespaces)
if let port = Int(manual), port > 0, port < 65536 { return [port] }
return CrossSoundClient.defaultPorts
}
// MARK: Polling
/// Refresh the now-playing state, at most once per `minimumInterval`.
func tick(minimumInterval: TimeInterval) {
guard !pollInFlight, Date().timeIntervalSince(lastPoll) >= minimumInterval else { return }
lastPoll = Date()
pollInFlight = true
fetchState()
}
private func fetchState() {
resolveBase { [weak self] base in
guard let self = self else { return }
guard let base = base else {
self.pollInFlight = false
self.handleDisconnect()
return
}
self.get("state", base: base) { [weak self] json in
guard let self = self else { return }
self.pollInFlight = false
guard let dict = json as? [String: Any] else {
self.handleDisconnect()
return
}
self.isConnected = true
self.nowPlaying = CrossSoundClient.parseState(dict)
self.refreshArtwork(base: base)
}
}
}
/// Drop everything cached, so the next tick re-probes for the app.
private func handleDisconnect() {
isConnected = false
baseURL = nil
artwork = nil
artworkKey = ""
nowPlaying = CrossSoundNowPlaying()
playlists = []
discover = []
playlistsLoad = .idle
discoverLoad = .idle
}
/// Find the port CrossSound answers on, remembering it once found.
private func resolveBase(_ completion: @escaping (URL?) -> Void) {
if let base = baseURL {
completion(base)
return
}
probe(ports: candidatePorts, completion: completion)
}
/// Ping each candidate port in turn and keep the first that answers.
private func probe(ports: [Int], completion: @escaping (URL?) -> Void) {
var remaining = ports
guard let port = remaining.first else {
DispatchQueue.main.async { completion(nil) }
return
}
remaining.removeFirst()
guard let base = URL(string: "http://127.0.0.1:\(port)") else {
probe(ports: remaining, completion: completion)
return
}
var request = URLRequest(url: base.appendingPathComponent("ping"))
request.timeoutInterval = 1.5
session.dataTask(with: request) { [weak self] _, response, _ in
guard let self = self else {
DispatchQueue.main.async { completion(nil) }
return
}
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
self.probe(ports: remaining, completion: completion)
return
}
DispatchQueue.main.async {
self.baseURL = base
completion(base)
}
}.resume()
}
// MARK: Artwork
/// `GET /artwork` proxies the cover of the current track through CrossSound,
/// so the widget itself never reaches the internet. Re-fetched only when the
/// track changes.
private func refreshArtwork(base: URL) {
let key = "\(nowPlaying.title)|\(nowPlaying.artist)"
guard nowPlaying.hasTrack, !nowPlaying.artworkURL.isEmpty else {
artwork = nil
artworkKey = ""
return
}
guard key != artworkKey else { return }
artworkKey = key
var request = URLRequest(url: base.appendingPathComponent("artwork"))
request.timeoutInterval = 4
session.dataTask(with: request) { [weak self] data, response, _ in
var image: NSImage?
if (response as? HTTPURLResponse)?.statusCode == 200, let data = data {
image = NSImage(data: data)
}
DispatchQueue.main.async {
guard let self = self, self.artworkKey == key else { return }
self.artwork = image
}
}.resume()
}
// MARK: Commands
func playPause() {
// Flip locally so the dock reacts to the click, not to the next poll.
nowPlaying.isPlaying.toggle()
post("playpause")
}
func next() { post("next") }
func previous() { post("previous") }
func toggleLike() {
nowPlaying.isLiked.toggle()
post("like")
}
func toggleShuffle() {
nowPlaying.shuffle.toggle()
post("shuffle")
}
func cycleRepeat() { post("repeat") }
func seek(to seconds: Double) {
post("seek", body: ["seconds": max(0, seconds)])
}
func perform(_ action: CrossSoundPlayAction) {
switch action {
case let .playlist(id):
post("play-playlist", body: ["id": id])
case let .url(link):
post("play", body: ["url": link])
case let .queueIndex(index):
post("play-index", body: ["index": index])
}
}
private func post(_ path: String, body: [String: Any]? = nil) {
resolveBase { [weak self] base in
guard let self = self, let base = base else { return }
var request = URLRequest(url: base.appendingPathComponent(path))
request.httpMethod = "POST"
if let body = body {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
self.session.dataTask(with: request) { [weak self] _, _, _ in
// Let the next tick pick up the real state immediately.
DispatchQueue.main.async { self?.lastPoll = .distantPast }
}.resume()
}
}
// MARK: Lists
func loadPlaylists(force: Bool = false) {
if !force, playlistsLoad == .loading || playlistsLoad == .loaded { return }
playlistsLoad = .loading
resolveBase { [weak self] base in
guard let self = self else { return }
guard let base = base else {
self.playlistsLoad = .failed("CrossSound is not running")
return
}
self.get("playlists", base: base) { [weak self] json in
guard let self = self else { return }
guard let json = json else {
self.playlistsLoad = .failed("Sign in to CrossSound first")
return
}
self.playlists = CrossSoundClient.parsePlaylists(json)
self.playlistsLoad = self.playlists.isEmpty ? .failed("No playlists") : .loaded
}
}
}
func loadDiscover(force: Bool = false) {
if !force, discoverLoad == .loading || discoverLoad == .loaded { return }
discoverLoad = .loading
resolveBase { [weak self] base in
guard let self = self else { return }
guard let base = base else {
self.discoverLoad = .failed("CrossSound is not running")
return
}
self.get("discover/mixed", base: base) { [weak self] json in
guard let self = self else { return }
guard let json = json else {
self.discoverLoad = .failed("Sign in to CrossSound first")
return
}
self.discover = CrossSoundClient.parseDiscover(json)
self.discoverLoad = self.discover.isEmpty ? .failed("Nothing in Discover") : .loaded
}
}
}
/// GET a path and hand back the decoded JSON, or `nil` on any failure.
private func get(_ path: String, base: URL, completion: @escaping (Any?) -> Void) {
var request = URLRequest(url: base.appendingPathComponent(path))
request.timeoutInterval = 4
session.dataTask(with: request) { data, response, _ in
var json: Any?
if (response as? HTTPURLResponse)?.statusCode == 200, let data = data {
json = try? JSONSerialization.jsonObject(with: data)
}
DispatchQueue.main.async { completion(json) }
}.resume()
}
// MARK: Parsing
//
// The SoundCloud shapes behind these endpoints are loose (arrays vs a
// `collection` envelope, fields missing on re-uploads), so these read
// defensively out of dictionaries rather than through Codable.
private static func parseState(_ dict: [String: Any]) -> CrossSoundNowPlaying {
var state = CrossSoundNowPlaying()
state.title = dict["title"] as? String ?? ""
state.artist = dict["artist"] as? String ?? ""
state.artworkURL = dict["artwork"] as? String ?? ""
state.isPlaying = dict["isPlaying"] as? Bool ?? false
state.isLiked = dict["isLiked"] as? Bool ?? false
state.shuffle = dict["shuffle"] as? Bool ?? false
state.repeatMode = dict["repeat"] as? String ?? "none"
state.position = number(dict["position"])
state.elapsedText = dict["currentTimeStr"] as? String ?? "0:00"
state.durationText = dict["durationStr"] as? String ?? "0:00"
state.queueIndex = Int(number(dict["queueIndex"]))
let rawQueue = dict["queue"] as? [[String: Any]] ?? []
state.queue = rawQueue.enumerated().map { pair in
CrossSoundTrack(
id: Int(number(pair.element["id"])),
index: pair.offset,
title: pair.element["title"] as? String ?? "Unknown track",
artist: pair.element["artist"] as? String ?? ""
)
}
return state
}
private static func parsePlaylists(_ json: Any) -> [CrossSoundBrowseRow] {
collection(json).compactMap { item in
let id = Int(number(item["id"]))
guard id > 0 else { return nil }
let count = Int(number(item["track_count"]))
let owner = (item["user"] as? [String: Any])?["username"] as? String ?? ""
var subtitle = count == 1 ? "1 track" : "\(count) tracks"
if !owner.isEmpty { subtitle += " · \(owner)" }
return CrossSoundBrowseRow(
id: "playlist-\(id)",
title: item["title"] as? String ?? "Untitled playlist",
subtitle: subtitle,
action: .playlist(id)
)
}
}
/// `/discover/mixed` is a list of shelves, each with its own `items`
/// collection. Flattened into rows tagged with their shelf name. Rows play
/// through `/play` by permalink, the same way the CrossSound Discover
/// shelves do it.
private static func parseDiscover(_ json: Any) -> [CrossSoundBrowseRow] {
var rows: [CrossSoundBrowseRow] = []
for shelf in collection(json) {
let shelfTitle = shelf["title"] as? String ?? "Discover"
for item in collection(shelf["items"]) {
let link = (item["permalink_url"] as? String) ?? (item["urn"] as? String) ?? ""
guard !link.isEmpty else { continue }
let title = item["title"] as? String
?? (item["track"] as? [String: Any])?["title"] as? String
?? "Untitled"
rows.append(CrossSoundBrowseRow(
id: "discover-\(rows.count)-\(link)",
title: title,
subtitle: shelfTitle,
action: .url(link)
))
}
}
return rows
}
/// Unwraps either a bare array or a `{ collection: [...] }` envelope.
private static func collection(_ json: Any?) -> [[String: Any]] {
if let array = json as? [[String: Any]] { return array }
if let dict = json as? [String: Any], let array = dict["collection"] as? [[String: Any]] {
return array
}
return []
}
/// Numbers arrive as `Int`, `Double` or numeric strings depending on the route.
private static func number(_ value: Any?) -> Double {
if let double = value as? Double { return double }
if let int = value as? Int { return Double(int) }
if let string = value as? String, let double = Double(string) { return double }
return 0
}
}