Still not broken: Next commit decides the fate

This commit is contained in:
Hariharan Mudaliar 2025-10-05 23:34:57 +05:30
commit dc45c50df4
17 changed files with 1028 additions and 608 deletions

View file

@ -0,0 +1,87 @@
//
// YouTubeMusicAuthentication.swift
// DynamicIsland
//
// Created by Alexander on 2025-09-14.
//
import Foundation
// MARK: - Authentication Manager
actor YouTubeMusicAuthManager {
private var accessToken: String?
private var authenticationTask: Task<String, Error>?
private let httpClient: YouTubeMusicHTTPClient
init(httpClient: YouTubeMusicHTTPClient) {
self.httpClient = httpClient
}
var currentToken: String? {
accessToken
}
func authenticate() async throws -> String {
// Return existing token if valid
if let token = accessToken {
return token
}
// Wait for ongoing authentication if in progress
if let task = authenticationTask {
return try await task.value
}
// Start new authentication
let task = Task<String, Error> {
do {
let token = try await httpClient.authenticate()
await setToken(token)
return token
} catch {
await clearAuthenticationTask()
throw error
}
}
authenticationTask = task
return try await task.value
}
func invalidateToken() async {
accessToken = nil
authenticationTask?.cancel()
authenticationTask = nil
}
private func setToken(_ token: String) async {
accessToken = token
authenticationTask = nil
}
private func clearAuthenticationTask() async {
authenticationTask = nil
}
}
// MARK: - Authentication State
enum AuthenticationState: Sendable {
case unauthenticated
case authenticating
case authenticated(String)
case failed(Error)
var isAuthenticated: Bool {
if case .authenticated = self {
return true
}
return false
}
var token: String? {
if case .authenticated(let token) = self {
return token
}
return nil
}
}

View file

@ -0,0 +1,424 @@
//
// YouTubeMusicController.swift
// DynamicIsland
//
// Created By Alexander on 2025-03-30.
// Modified by Pranav on 2025-06-16.
//
import Foundation
import Combine
import SwiftUI
final class YouTubeMusicController: MediaControllerProtocol {
// MARK: - Published Properties
@Published var playbackState = PlaybackState(
bundleIdentifier: YouTubeMusicConfiguration.default.bundleIdentifier
)
private var artworkFetchTask: Task<Void, Never>?
var playbackStatePublisher: AnyPublisher<PlaybackState, Never> {
$playbackState.eraseToAnyPublisher()
}
var isWorking: Bool {
isActive() && (updateTimer != nil || webSocketClient != nil)
}
// MARK: - Private Properties
private let configuration: YouTubeMusicConfiguration
private let httpClient: YouTubeMusicHTTPClient
private let authManager: YouTubeMusicAuthManager
private var webSocketClient: YouTubeMusicWebSocketClient?
private var updateTimer: Timer?
private var appStateObserver: Task<Void, Never>?
private var reconnectDelay: TimeInterval = 1.0
// MARK: - Initialization
init(configuration: YouTubeMusicConfiguration = .default) {
self.configuration = configuration
self.httpClient = YouTubeMusicHTTPClient(baseURL: configuration.baseURL)
self.authManager = YouTubeMusicAuthManager(httpClient: httpClient)
setupAppStateObserver()
Task {
await initializeIfAppActive()
}
}
// MARK: - MediaControllerProtocol Implementation
func play() async { await sendCommand(endpoint: "/play", method: "POST") }
func pause() async { await sendCommand(endpoint: "/pause", method: "POST") }
func togglePlay() async {
if !isActive() { launchApp() }
await sendCommand(endpoint: "/toggle-play", method: "POST")
}
func nextTrack() async { await sendCommand(endpoint: "/next", method: "POST") }
func previousTrack() async { await sendCommand(endpoint: "/previous", method: "POST") }
func seek(to time: Double) async {
let payload = ["seconds": time]
await sendCommand(endpoint: "/seek-to", method: "POST", body: payload)
}
func fetchShuffleState() async { await sendCommand(endpoint: "/shuffle", method: "GET", refresh: false) }
func fetchRepeatMode() async { await sendCommand(endpoint: "/repeat-mode", method: "GET", refresh: false) }
func toggleShuffle() async { await sendCommand(endpoint: "/shuffle", method: "POST") }
func toggleRepeat() async { await sendCommand(endpoint: "/switch-repeat", method: "POST") }
nonisolated func isActive() -> Bool {
NSWorkspace.shared.runningApplications.contains {
$0.bundleIdentifier == configuration.bundleIdentifier
}
}
func updatePlaybackInfo() async {
guard isActive() else {
resetPlaybackState()
return
}
do {
let token = try await authManager.authenticate()
let response = try await httpClient.getPlaybackInfo(token: token)
await updatePlaybackState(with: response)
} catch YouTubeMusicError.authenticationRequired {
await authManager.invalidateToken()
} catch {
print("[YouTubeMusicController] Failed to update playback info: \(error)")
}
}
// MARK: - Private Methods
private func setupAppStateObserver() {
appStateObserver = Task { [weak self] in
await withTaskGroup(of: Void.self) { group in
group.addTask {
let launchNotifications = NSWorkspace.shared.notificationCenter.notifications(
named: NSWorkspace.didLaunchApplicationNotification
)
for await notification in launchNotifications {
await self?.handleAppLaunched(notification)
}
}
group.addTask {
let terminateNotifications = NSWorkspace.shared.notificationCenter.notifications(
named: NSWorkspace.didTerminateApplicationNotification
)
for await notification in terminateNotifications {
await self?.handleAppTerminated(notification)
}
}
}
}
}
private func handleAppLaunched(_ notification: Notification) async {
guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.bundleIdentifier == configuration.bundleIdentifier else {
return
}
await initializeIfAppActive()
}
private func handleAppTerminated(_ notification: Notification) async {
guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
app.bundleIdentifier == configuration.bundleIdentifier else {
return
}
Task { @MainActor in
stopPeriodicUpdates()
appStateObserver?.cancel()
}
Task {
await webSocketClient?.disconnect()
webSocketClient = nil
}
resetPlaybackState()
}
private func initializeIfAppActive() async {
guard isActive() else { return }
do {
let token = try await authManager.authenticate()
await setupWebSocketIfPossible(token: token)
await startPeriodicUpdates()
await updatePlaybackInfo()
} catch {
print("[YouTubeMusicController] Failed to initialize: \(error)")
await scheduleReconnect()
}
}
private func setupWebSocketIfPossible(token: String) async {
guard let wsURL = WebSocketURLBuilder.buildURL(from: configuration.baseURL) else {
print("[YouTubeMusicController] Failed to build WebSocket URL")
return
}
let client = YouTubeMusicWebSocketClient(
onMessage: { [weak self] data in
await self?.handleWebSocketMessage(data)
},
onDisconnect: { [weak self] in
await self?.handleWebSocketDisconnect()
}
)
do {
try await client.connect(to: wsURL, with: token)
webSocketClient = client
stopPeriodicUpdates() // WebSocket will provide real-time updates
reconnectDelay = configuration.reconnectDelay.lowerBound
} catch {
print("[YouTubeMusicController] WebSocket connection failed: \(error)")
await scheduleReconnect()
}
}
private func handleWebSocketMessage(_ data: Data) async {
guard let message = WebSocketMessage(from: data) else {
if let response = try? JSONDecoder().decode(PlaybackResponse.self, from: data) {
await updatePlaybackState(with: response)
}
return
}
switch message.type {
case .playerInfo, .videoChanged, .playerStateChanged:
if let data = message.extractData(),
let response = PlaybackResponse.from(websocketData: data) {
await updatePlaybackState(with: response)
}
case .positionChanged:
guard let data = message.extractData() else { return }
var position: Double? = nil
if let pos = data["position"] as? Double {
position = pos
} else if let elapsed = data["elapsedSeconds"] as? Double {
position = elapsed
}
guard let newPosition = position else { return }
var copied = playbackState
copied.currentTime = newPosition
copied.lastUpdated = Date()
playbackState = copied
case .repeatChanged:
guard let data = message.extractData() else { return }
var copy = playbackState
if let repeatStr = data["repeat"] as? String {
switch repeatStr.uppercased() {
case "NONE": copy.repeatMode = .off
case "ALL": copy.repeatMode = .all
case "ONE": copy.repeatMode = .one
default: break
}
}
copy.lastUpdated = Date()
playbackState = copy
case .shuffleChanged:
guard let data = message.extractData() else { return }
var copy = playbackState
if let shuffle = data["shuffle"] as? Bool { copy.isShuffled = shuffle }
else if let shuffle = data["isShuffled"] as? Bool { copy.isShuffled = shuffle }
copy.lastUpdated = Date()
playbackState = copy
case .volumeChanged:
break
}
}
private func handleWebSocketDisconnect() async {
webSocketClient = nil
await startPeriodicUpdates() // Fallback to polling
await scheduleReconnect()
}
private func scheduleReconnect() async {
try? await Task.sleep(for: .seconds(reconnectDelay))
reconnectDelay = min(reconnectDelay * 2, configuration.reconnectDelay.upperBound)
if isActive() {
await initializeIfAppActive()
}
}
private func startPeriodicUpdates() async {
guard isActive() && webSocketClient == nil else { return }
stopPeriodicUpdates()
updateTimer = Timer.scheduledTimer(withTimeInterval: configuration.updateInterval, repeats: true) { [weak self] _ in
Task { @MainActor in
await self?.updatePlaybackInfo()
}
}
}
private func stopPeriodicUpdates() {
updateTimer?.invalidate()
updateTimer = nil
}
func pollPlaybackState() async {
if !isActive() {
return
}
await fetchRepeatMode()
await fetchShuffleState()
await updatePlaybackInfo()
}
private func sendCommand(
endpoint: String,
method: String = "POST",
body: (any Codable & Sendable)? = nil,
refresh: Bool = true
) async {
do {
let token = try await authManager.authenticate()
let data = try await httpClient.sendCommand(
endpoint: endpoint,
method: method,
body: body,
token: token
)
// Lightweight endpoint-specific parsing
if endpoint == "/shuffle" {
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let shuffleState = json["state"] as? Bool {
playbackState.isShuffled = shuffleState
} else {
playbackState.isShuffled = !playbackState.isShuffled
}
} else if endpoint == "/repeat-mode" {
if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let mode = json["mode"] as? String { updateRepeatMode(mode) }
}
} else if endpoint == "/switch-repeat" {
// Find next repeat mode
let nextMode: RepeatMode
switch playbackState.repeatMode {
case .off: nextMode = .all
case .all: nextMode = .one
case .one: nextMode = .off
}
playbackState.repeatMode = nextMode
} else if refresh && webSocketClient == nil {
try? await Task.sleep(for: .milliseconds(100))
await updatePlaybackInfo()
}
} catch YouTubeMusicError.authenticationRequired {
await authManager.invalidateToken()
} catch {
print("[YouTubeMusicController] Command failed: \(error)")
}
}
private func updatePlaybackState(with response: PlaybackResponse) async {
var newState = playbackState
newState.isPlaying = !response.isPaused
if let title = response.title {
newState.title = title
}
if let artist = response.artist {
newState.artist = artist
}
if let album = response.album {
newState.album = album
}
if let elapsed = response.elapsedSeconds {
newState.currentTime = elapsed
}
if let duration = response.songDuration {
newState.duration = duration
}
newState.lastUpdated = Date()
if let shuffled = response.isShuffled {
newState.isShuffled = shuffled
}
if let mode = response.repeatMode {
switch mode {
case 0: newState.repeatMode = .off
case 1: newState.repeatMode = .all
case 2: newState.repeatMode = .one
default: break
}
}
// Always update - removed comparison since PlaybackState doesn't conform to Equatable
playbackState = newState
artworkFetchTask?.cancel()
artworkFetchTask = nil
if let artworkURL = response.imageSrc,
let url = URL(string: artworkURL) {
artworkFetchTask = Task {
do {
let data = try await ImageService.shared.fetchImageData(from: url)
await MainActor.run { [weak self] in
self?.playbackState.artwork = data
}
} catch { /* ignore */ }
}
}
}
private func resetPlaybackState() {
playbackState = PlaybackState(
bundleIdentifier: configuration.bundleIdentifier,
isPlaying: false
)
}
private func launchApp() {
guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: configuration.bundleIdentifier) else {
return
}
NSWorkspace.shared.open(url)
}
private func updateRepeatMode(_ mode: String) {
var target: RepeatMode? = nil
switch mode {
case "NONE": target = .off
case "ALL": target = .all
case "ONE": target = .one
default: break
}
if let target, target != playbackState.repeatMode { playbackState.repeatMode = target }
}
}

View file

@ -0,0 +1,157 @@
//
// YouTubeMusicModels.swift
// DynamicIsland
//
// Created by Alexander on 2025-09-14.
//
import Foundation
// MARK: - Configuration
struct YouTubeMusicConfiguration: Sendable {
let baseURL: String
let bundleIdentifier: String
let reconnectDelay: ClosedRange<TimeInterval>
let updateInterval: TimeInterval
static let `default` = YouTubeMusicConfiguration(
baseURL: "http://localhost:26538",
bundleIdentifier: "com.github.th-ch.youtube-music",
reconnectDelay: 1...60,
updateInterval: 2.0
)
}
// MARK: - API Models
struct AuthResponse: Decodable, Sendable {
let accessToken: String
}
struct PlaybackResponse: Decodable, Sendable {
let isPaused: Bool
let title: String?
let artist: String?
let album: String?
let elapsedSeconds: Double?
let songDuration: Double?
let imageSrc: String?
let repeatMode: Int?
let isShuffled: Bool?
}
// MARK: - WebSocket Message Types
enum WebSocketMessageType: String, Sendable {
case playerInfo = "PLAYER_INFO"
case videoChanged = "VIDEO_CHANGED"
case playerStateChanged = "PLAYER_STATE_CHANGED"
case positionChanged = "POSITION_CHANGED"
case volumeChanged = "VOLUME_CHANGED"
case repeatChanged = "REPEAT_CHANGED"
case shuffleChanged = "SHUFFLE_CHANGED"
}
struct WebSocketMessage {
let type: WebSocketMessageType
let rawData: Data
private let parsedJSON: [String: Any]?
init?(from data: Data) {
let json = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])
guard let typeString = json?["type"] as? String,
let messageType = WebSocketMessageType(rawValue: typeString) else {
return nil
}
self.type = messageType
self.rawData = data
self.parsedJSON = json
}
func extractData() -> [String: Any]? {
parsedJSON
}
}
// MARK: - Extensions
extension PlaybackResponse {
static func from(websocketData: [String: Any]) -> PlaybackResponse? {
let songData = websocketData["song"] as? [String: Any]
let isPaused: Bool
if let paused = songData?["isPaused"] as? Bool {
isPaused = paused
} else if let playing = websocketData["isPlaying"] as? Bool {
isPaused = !playing
} else {
isPaused = true
}
let title = (songData?["title"] as? String) ??
(songData?["alternativeTitle"] as? String) ??
(websocketData["title"] as? String)
let artist = (songData?["artist"] as? String) ?? (websocketData["artist"] as? String)
let album = songData?["album"] as? String
let elapsed = extractDouble(from: songData, key: "elapsedSeconds") ??
extractDouble(from: websocketData, key: "position")
let duration = extractDouble(from: songData, key: "songDuration") ??
extractDouble(from: websocketData, key: "songDuration")
let imageSrc = (songData?["imageSrc"] as? String) ?? (websocketData["imageSrc"] as? String)
let isShuffled = (websocketData["shuffle"] as? Bool) ?? (songData?["isShuffled"] as? Bool)
var repeatModeInt: Int? = nil
if let repeatVal = websocketData["repeat"] as? String {
switch repeatVal.uppercased() {
case "NONE": repeatModeInt = 0
case "ALL": repeatModeInt = 1
case "ONE": repeatModeInt = 2
default: break
}
} else if let repeatStr = songData?["repeat"] as? String {
switch repeatStr.uppercased() {
case "NONE": repeatModeInt = 0
case "ALL": repeatModeInt = 1
case "ONE": repeatModeInt = 2
default: break
}
}
return PlaybackResponse(
isPaused: isPaused,
title: title,
artist: artist,
album: album,
elapsedSeconds: elapsed,
songDuration: duration,
imageSrc: imageSrc,
repeatMode: repeatModeInt,
isShuffled: isShuffled
)
}
func with(elapsedSeconds: Double) -> PlaybackResponse {
PlaybackResponse(
isPaused: isPaused,
title: title,
artist: artist,
album: album,
elapsedSeconds: elapsedSeconds,
songDuration: songDuration,
imageSrc: imageSrc,
repeatMode: repeatMode,
isShuffled: isShuffled
)
}
}
private func extractDouble(from dict: [String: Any]?, key: String) -> Double? {
guard let dict = dict else { return nil }
if let value = dict[key] as? Double {
return value
} else if let value = dict[key] as? Int {
return Double(value)
}
return nil
}

View file

@ -0,0 +1,225 @@
//
// YouTubeMusicNetworking.swift
// DynamicIsland
//
// Created by Alexander on 2025-09-14.
//
import Foundation
// MARK: - HTTP Client
final class YouTubeMusicHTTPClient: ObservableObject {
private let session: URLSession
private let baseURL: String
private static let decoder = JSONDecoder()
private static let encoder = JSONEncoder()
init(baseURL: String) {
self.baseURL = baseURL
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
config.timeoutIntervalForRequest = 5
config.timeoutIntervalForResource = 10
self.session = URLSession(configuration: config)
}
// MARK: - Authentication
func authenticate() async throws -> String {
guard let url = URL(string: "\(baseURL)/auth/DynamicIsland") else {
throw YouTubeMusicError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
let (data, response) = try await session.data(for: request)
try validateResponse(response)
let authResponse: AuthResponse = try Self.decoder.decode(AuthResponse.self, from: data)
return authResponse.accessToken
}
// MARK: - Playback Info
func getPlaybackInfo(token: String) async throws -> PlaybackResponse {
let data = try await sendCommand(
endpoint: "/song",
method: "GET",
token: token
)
return try Self.decoder.decode(PlaybackResponse.self, from: data)
}
// MARK: - Commands
func sendCommand(
endpoint: String,
method: String = "POST",
body: (any Codable & Sendable)? = nil,
token: String
) async throws -> Data {
let request = try createAuthenticatedRequest(
endpoint: "/api/v1\(endpoint)",
method: method,
body: body,
token: token
)
let (data, response) = try await session.data(for: request)
try validateResponse(response)
return data
}
// MARK: - Private Helpers
private func createAuthenticatedRequest(
endpoint: String,
method: String,
body: (any Codable & Sendable)? = nil,
token: String
) throws -> URLRequest {
guard let url = URL(string: "\(baseURL)\(endpoint)") else {
throw YouTubeMusicError.invalidURL
}
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
if let body = body {
request.httpBody = try Self.encoder.encode(body)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
return request
}
private func validateResponse(_ response: URLResponse) throws {
guard let httpResponse = response as? HTTPURLResponse else {
throw YouTubeMusicError.invalidResponse
}
switch httpResponse.statusCode {
case 200..<300:
break
case 401, 403:
throw YouTubeMusicError.authenticationRequired
default:
throw YouTubeMusicError.httpError(httpResponse.statusCode)
}
}
}
// MARK: - WebSocket Client
actor YouTubeMusicWebSocketClient {
private var task: URLSessionWebSocketTask?
private let session: URLSession
private let onMessage: @Sendable (Data) async -> Void
private let onDisconnect: @Sendable () async -> Void
var isConnected: Bool { task != nil }
init(
onMessage: @escaping @Sendable (Data) async -> Void,
onDisconnect: @escaping @Sendable () async -> Void,
session: URLSession = .shared
) {
self.onMessage = onMessage
self.onDisconnect = onDisconnect
self.session = session
}
func connect(to url: URL, with token: String) async throws {
await disconnect()
var request = URLRequest(url: url)
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let newTask = session.webSocketTask(with: request)
task = newTask
newTask.resume()
Task { await listenForMessages() }
}
func disconnect() async {
task?.cancel(with: .goingAway, reason: nil)
task = nil
}
private func listenForMessages() async {
guard let currentTask = task else { return }
while !Task.isCancelled && task != nil {
do {
let message = try await currentTask.receive()
let data: Data
switch message {
case .data(let d):
data = d
case .string(let s):
data = s.data(using: .utf8) ?? Data()
@unknown default:
continue
}
await onMessage(data)
} catch {
break
}
}
task = nil
await onDisconnect()
}
}
// MARK: - WebSocket URL Helper
struct WebSocketURLBuilder {
static func buildURL(from baseURL: String) -> URL? {
guard var components = URLComponents(string: baseURL) else { return nil }
switch components.scheme {
case "http":
components.scheme = "ws"
case "https":
components.scheme = "wss"
default:
break
}
components.path = "/api/v1/ws"
return components.url
}
}
// MARK: - Errors
enum YouTubeMusicError: Error, LocalizedError, Sendable {
case invalidURL
case invalidResponse
case httpError(Int)
case authenticationRequired
case webSocketNotConnected
case encodingFailed
case decodingFailed
var errorDescription: String? {
switch self {
case .invalidURL:
return "Invalid URL"
case .invalidResponse:
return "Invalid response"
case .httpError(let code):
return "HTTP error: \(code)"
case .authenticationRequired:
return "Authentication required"
case .webSocketNotConnected:
return "WebSocket not connected"
case .encodingFailed:
return "Failed to encode data"
case .decodingFailed:
return "Failed to decode data"
}
}
}