import Foundation struct PlatformAPIConfiguration: Sendable { let baseURL: URL let channel: String var cacheKey: String { baseURL.absoluteString + "|" + channel } enum ConfigurationError: Error { case invalidURL, invalidChannel } init(baseURL: String, channel: String) throws { guard let url = ActivityURL.parse(baseURL), url.query == nil, url.fragment == nil, !url.absoluteString.contains("$(") else { throw ConfigurationError.invalidURL } let channel = channel.trimmingCharacters(in: .whitespacesAndNewlines) guard !channel.isEmpty, !channel.contains("$(") else { throw ConfigurationError.invalidChannel } self.baseURL = url self.channel = channel } static func fromBundle(_ bundle: Bundle = .main) -> Self? { guard let base = bundle.object(forInfoDictionaryKey: "PlatformAPIBaseURL") as? String, let channel = bundle.object(forInfoDictionaryKey: "PlatformChannel") as? String else { return nil } return try? Self(baseURL: base, channel: channel) } } struct PlatformRequestContext: Encodable, Sendable { static var deviceRegionCode: String? { if #available(iOS 16, macOS 13, *) { return Locale.current.region?.identifier } return Locale.current.regionCode } let channel: String let language: String let region: String? let timezone: String } enum ActivityURL { static func parse(_ input: String) -> URL? { var text = input.trimmingCharacters(in: .whitespacesAndNewlines) if (text.hasPrefix("\"") && text.hasSuffix("\"")) || (text.hasPrefix("“") && text.hasSuffix("”")) { text = String(text.dropFirst().dropLast()).trimmingCharacters(in: .whitespacesAndNewlines) } guard !text.isEmpty, !text.contains(where: \.isWhitespace), let parts = URLComponents(string: text), let scheme = parts.scheme?.lowercased(), ["https", "http"].contains(scheme), let host = parts.host, !host.isEmpty, parts.user == nil, parts.password == nil else { return nil } var normalized = parts normalized.scheme = scheme return normalized.url } } struct ActivityClosePolicy: Equatable { let isEnabled: Bool let delaySeconds: UInt64 init(url: URL) { let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? [] let switches = items.filter { $0.name == "s" } let value = switches.count == 1 ? switches.first?.value.flatMap(Double.init) : nil isEnabled = value.map { $0.isFinite && $0 != 0 } ?? false let delays = items.filter { $0.name == "sec" } let requestedDelay = delays.count == 1 ? delays.first?.value.flatMap(UInt64.init) ?? 0 : 0 delaySeconds = min(requestedDelay, 10) } } struct PlatformCredentials: Codable, Equatable, Sendable, CustomStringConvertible { let fbid: String let token: String var description: String { "PlatformCredentials(fbid: \(fbid), token: )" } init(fbid: String, token: String) throws { let valid = try FacebookTrackingConfiguration(fbid: fbid, token: token) self.fbid = valid.fbid; self.token = valid.token } } enum PlatformCredentialResponse: Sendable { case unavailable, credentials(PlatformCredentials) } protocol PlatformRemoteFetching: Sendable { func fetchCredentials(context: PlatformRequestContext) async throws -> PlatformCredentialResponse func fetchActivity(context: PlatformRequestContext) async throws -> URL? } struct PlatformAPIClient: PlatformRemoteFetching { enum APIError: Error { case invalidResponse, invalidCredentials } let configuration: PlatformAPIConfiguration let transport: DataTransport init(configuration: PlatformAPIConfiguration, session: URLSession? = nil) { self.configuration = configuration transport = NetworkClient(session: session, allowedHTTPHosts: configuration.baseURL.scheme == "http" ? [configuration.baseURL.host!]: []) } func fetchCredentials(context: PlatformRequestContext) async throws -> PlatformCredentialResponse { let plaintext = try await exchange(route: "platform/credentials", context: context) if plaintext.trimmingCharacters(in: .whitespacesAndNewlines) == "0" { return .unavailable } struct Payload: Decodable { let platform_id: String?; let platform_token: String? } guard let data = plaintext.data(using: .utf8), let payload = try? JSONDecoder().decode(Payload.self, from: data) else { throw APIError.invalidCredentials } // A missing member is not a command to clear or mix the current credentials. guard let id = payload.platform_id, let token = payload.platform_token else { return .unavailable } return .credentials(try PlatformCredentials(fbid: id, token: token)) } func fetchActivity(context: PlatformRequestContext) async throws -> URL? { return ActivityURL.parse(try await exchange(route: "platform", context: context)) } private func exchange(route: String, context: PlatformRequestContext) async throws -> String { let encoded = try JSONEncoder().encode(context) let encrypted = try PlatformCrypto.encrypt(String(decoding: encoded, as: UTF8.self)) struct RequestBody: Encodable { let payload: String } struct ResponseBody: Decodable { let data: String } var request = URLRequest(url: configuration.baseURL.appendingPathComponent(route)) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.httpBody = try JSONEncoder().encode(RequestBody(payload: encrypted)) let data = try await transport.execute(request) guard let body = try? JSONDecoder().decode(ResponseBody.self, from: data) else { throw APIError.invalidResponse } let plaintext = try PlatformCrypto.decrypt(body.data) return plaintext } }