Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / SocialTransport.swift
| 1 | import Foundation |
| 2 | |
| 3 | struct SocialRequestError: LocalizedError { |
| 4 | let errorDescription: String? |
| 5 | let uncertain: Bool |
| 6 | let statusCode: Int? |
| 7 | let providerCode: String? |
| 8 | |
| 9 | init(_ message: String, uncertain: Bool = false, statusCode: Int? = nil, providerCode: String? = nil) { |
| 10 | errorDescription = message |
| 11 | self.uncertain = uncertain |
| 12 | self.statusCode = statusCode |
| 13 | self.providerCode = providerCode |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | @MainActor |
| 18 | struct SocialTransport { |
| 19 | typealias Send = @MainActor (URLRequest) async throws -> (Data, HTTPURLResponse) |
| 20 | private let send: Send |
| 21 | |
| 22 | init(send: @escaping Send = live) { self.send = send } |
| 23 | |
| 24 | func request(_ url: URL, token: String? = nil, method: String = "GET", |
| 25 | json: [String: Any]? = nil, body: Data? = nil, headers: [String: String] = [:], |
| 26 | publishes: Bool = false, expectsJSON: Bool = true, timeout: TimeInterval = 45, acceptsArray: Bool = false) async throws -> (value: [String: Any], response: HTTPURLResponse) { |
| 27 | guard url.scheme == "https", url.user == nil, url.password == nil else { |
| 28 | throw SocialRequestError("Invalid social service address.") |
| 29 | } |
| 30 | var request = URLRequest(url: url, timeoutInterval: timeout) |
| 31 | request.httpMethod = method |
| 32 | if let token { request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") } |
| 33 | if let json { |
| 34 | request.httpBody = try JSONSerialization.data(withJSONObject: json) |
| 35 | request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 36 | } else { |
| 37 | request.httpBody = body |
| 38 | } |
| 39 | for (key, value) in headers { request.setValue(value, forHTTPHeaderField: key) } |
| 40 | |
| 41 | let data: Data |
| 42 | let response: HTTPURLResponse |
| 43 | do { (data, response) = try await send(request) } |
| 44 | catch { |
| 45 | throw SocialRequestError(publishes ? "The connection ended during publishing. Check the account before trying again." |
| 46 | : "Couldn’t reach the social service.", uncertain: publishes) |
| 47 | } |
| 48 | guard (200...299).contains(response.statusCode) else { |
| 49 | let uncertain = publishes && (response.statusCode >= 500 || [408, 409, 425].contains(response.statusCode)) |
| 50 | let message = switch response.statusCode { |
| 51 | case 401, 403: "The account or requested permission was declined. Check Connections." |
| 52 | case 429: "The platform reached a rate limit. Wait before retrying." |
| 53 | default: "The social service returned HTTP \(response.statusCode)." |
| 54 | } |
| 55 | let body = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] |
| 56 | let providerCode = (body?["error"] as? [String: Any])?["code"] as? String |
| 57 | throw SocialRequestError(message, uncertain: uncertain, statusCode: response.statusCode, providerCode: providerCode) |
| 58 | } |
| 59 | if data.isEmpty || !expectsJSON { return ([:], response) } |
| 60 | let decoded = try? JSONSerialization.jsonObject(with: data) |
| 61 | if acceptsArray, let list = decoded as? [Any] { return (["items": list], response) } |
| 62 | guard let value = decoded as? [String: Any] else { |
| 63 | throw SocialRequestError("The service returned an unreadable response.", uncertain: publishes) |
| 64 | } |
| 65 | return (value, response) |
| 66 | } |
| 67 | |
| 68 | func form(_ url: URL, token: String? = nil, values: [String: String], headers: [String: String] = [:], |
| 69 | publishes: Bool = false) async throws -> (value: [String: Any], response: HTTPURLResponse) { |
| 70 | let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") |
| 71 | let fields = values.sorted { $0.key < $1.key }.map { pair in |
| 72 | let name = pair.key.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| 73 | let value = pair.value.addingPercentEncoding(withAllowedCharacters: allowed) ?? "" |
| 74 | return name + "=" + value |
| 75 | }.joined(separator: "&") |
| 76 | var headers = headers |
| 77 | headers["Content-Type"] = "application/x-www-form-urlencoded" |
| 78 | return try await request(url, token: token, method: "POST", body: Data(fields.utf8), headers: headers, publishes: publishes) |
| 79 | } |
| 80 | |
| 81 | private static func live(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { |
| 82 | let config = URLSessionConfiguration.ephemeral |
| 83 | config.timeoutIntervalForResource = max(60, request.timeoutInterval) |
| 84 | let session = URLSession(configuration: config, delegate: NoHTTPRedirects(), delegateQueue: nil) |
| 85 | defer { session.invalidateAndCancel() } |
| 86 | let (bytes, raw) = try await session.bytes(for: request) |
| 87 | guard let response = raw as? HTTPURLResponse, response.expectedContentLength <= 4_194_304 else { |
| 88 | throw SocialRequestError("The service returned an invalid response.") |
| 89 | } |
| 90 | var data = Data() |
| 91 | for try await byte in bytes { |
| 92 | guard data.count < 4_194_304 else { throw SocialRequestError("The service response is too large.") } |
| 93 | data.append(byte) |
| 94 | } |
| 95 | return (data, response) |
| 96 | } |
| 97 | } |