Repository Public
1import Foundation23/// HTTPS and WebSocket to the SP Message server. The session cookie lives in the app's own cookie4/// storage (HttpOnly, never exposed to the engine script).5final class Net: NSObject, URLSessionWebSocketDelegate {6 private lazy var session: URLSession = {7 let c = URLSessionConfiguration.default8 c.httpCookieStorage = .shared9 c.httpShouldSetCookies = true10 c.requestCachePolicy = .reloadIgnoringLocalCacheData11 c.urlCache = nil12 c.timeoutIntervalForRequest = 4013 return URLSession(configuration: c, delegate: self, delegateQueue: nil)14 }()15 private var socket: URLSessionWebSocketTask?16 private var ping: Timer?17 var onSocket: ((String, String?) -> Void)?18 private var origin: String { Config.base.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")) }1920 func request(_ method: String, _ path: String, json: String? = nil, bytes: Data? = nil) async -> (Int, Data) {21 guard let url = URL(string: origin + path) else { return (0, Data()) }22 var r = URLRequest(url: url)23 r.httpMethod = method24 r.setValue(origin, forHTTPHeaderField: "Origin")25 r.setValue("1", forHTTPHeaderField: "x-spm")26 r.setValue("SPMessage-Apple/1.0", forHTTPHeaderField: "User-Agent")27 if let json { r.httpBody = Data(json.utf8); r.setValue("application/json", forHTTPHeaderField: "Content-Type") }28 if let bytes { r.httpBody = bytes; r.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") }29 do {30 let (d, resp) = try await session.data(for: r)31 return ((resp as? HTTPURLResponse)?.statusCode ?? 0, d)32 } catch { return (0, Data()) }33 }3435 func json(_ method: String, _ path: String, _ body: [String: Any]? = nil) async throws -> [String: Any] {36 let payload = try body.map { String(data: try JSONSerialization.data(withJSONObject: $0), encoding: .utf8)! }37 let (status, data) = await request(method, path, json: payload ?? (method == "GET" ? nil : "{}"))38 let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]39 guard (200..<300).contains(status) else {40 throw APIError(status: status, code: obj["error"] as? String ?? "error", message: obj["message"] as? String ?? (status == 0 ? "Network unavailable" : "Error \(status)"))41 }42 return obj43 }4445 func openSocket() {46 closeSocket()47 var comps = URLComponents(url: Config.base, resolvingAgainstBaseURL: false)!48 comps.scheme = comps.scheme == "https" ? "wss" : "ws"49 comps.path = "/ws"50 var r = URLRequest(url: comps.url!)51 r.setValue(origin, forHTTPHeaderField: "Origin")52 if let cookies = HTTPCookieStorage.shared.cookies(for: Config.base), !cookies.isEmpty {53 r.setValue(cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; "), forHTTPHeaderField: "Cookie")54 }55 let task = session.webSocketTask(with: r)56 socket = task57 task.resume()58 receive(task)59 DispatchQueue.main.async {60 self.ping?.invalidate()61 self.ping = Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { [weak self] _ in self?.send("{\"t\":\"ping\"}") }62 }63 }64 private func receive(_ task: URLSessionWebSocketTask) {65 task.receive { [weak self] result in66 guard let self, task === self.socket else { return }67 switch result {68 case .success(.string(let s)): self.onSocket?("message", s); self.receive(task)69 case .success: self.receive(task)70 case .failure: self.socket = nil; self.onSocket?("close", nil)71 }72 }73 }74 func send(_ text: String) { socket?.send(.string(text)) { _ in } }75 func closeSocket() {76 let s = socket77 socket = nil78 s?.cancel(with: .goingAway, reason: nil)79 }80 func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {81 if webSocketTask === socket { onSocket?("open", nil) }82 }83 func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {84 if webSocketTask === socket { socket = nil; onSocket?("close", nil) }85 }86 func clearCookies() {87 for c in HTTPCookieStorage.shared.cookies(for: Config.base) ?? [] { HTTPCookieStorage.shared.deleteCookie(c) }88 }89}9091struct APIError: LocalizedError {92 let status: Int93 let code: String94 let message: String95 var errorDescription: String? { message }96}97