import Foundation import SwiftProtobuf /// Reading ipx without the page: the badge and CarPlay (#420), which has no web view. Signed in /// as the player is, by the credentials or else the cookies the web view left (CookieBridge). enum API { /// What ipx answers and reads in protobuf rather than JSON (#465, #469). The messages are /// `Sources/Wire`, generated from ipx's own `.proto` files by `scripts/proto.sh`. static let protobuf = "application/x-protobuf" private static let session: URLSession = { let cfg = URLSessionConfiguration.default cfg.httpCookieStorage = .shared cfg.timeoutIntervalForRequest = 20 return URLSession(configuration: cfg) }() /// The body of a 200, or nil: not signed in, no server, no connection. static func get(_ path: String, accept: String? = nil) async -> Data? { guard let (data, resp) = await fetch(path, accept: accept), resp.statusCode == 200 else { return nil } return data } /// A 200's body as message `M`, or nil. Nil too for an answer not in protobuf: a server from /// before #465 answers JSON whatever it is asked, and JSON can read as a message of nothing. static func get(_ type: M.Type, _ path: String) async -> M? { guard let (data, resp) = await fetch(path, accept: protobuf), resp.statusCode == 200, resp.value(forHTTPHeaderField: "Content-Type")?.hasPrefix(protobuf) == true else { return nil } return try? M(serializedBytes: data) } private static func fetch(_ path: String, accept: String?) async -> (Data, HTTPURLResponse)? { guard let url = Server.resolveForPlayer(path) else { return nil } var req = URLRequest(url: url) if let accept { req.setValue(accept, forHTTPHeaderField: "Accept") } Credentials.headers.forEach { req.setValue($1, forHTTPHeaderField: $0) } guard let (data, resp) = try? await session.data(for: req), let http = resp as? HTTPURLResponse else { return nil } return (data, http) } }