| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- import Foundation
- struct PlatformAPIConfiguration: Sendable {
- let baseURL: URL
- let channel: String
- 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 PlatformConfigurationResponse: Sendable {
- let surveySampling: SurveySampling
- var surveyURL: URL? = nil
- var privacyURL: URL? = nil
- }
- protocol PlatformRemoteFetching: Sendable {
- func fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse
- }
- struct PlatformAPIClient: PlatformRemoteFetching {
- enum APIError: Error { case invalidResponse }
- private struct Payload: Decodable {
- enum CodingKeys: String, CodingKey {
- case su
- case privacyURL = "privacyurl", sampling = "player_info_10"
- }
- let configuration: PlatformConfigurationResponse
- init(from decoder: Decoder) throws {
- let fields = try decoder.container(keyedBy: CodingKeys.self)
- let raw: String?
- if let text = try? fields.decode(String.self, forKey: .sampling) { raw = text }
- else if let number = try? fields.decode(Int.self, forKey: .sampling) { raw = String(number) }
- else if let number = try? fields.decode(Double.self, forKey: .sampling) { raw = String(number) }
- else { raw = nil }
- let surveyURL = (try? fields.decode(String.self, forKey: .su)).flatMap(ActivityURL.parse)
- let privacyURL = (try? fields.decode(String.self, forKey: .privacyURL)).flatMap(ActivityURL.parse)
- configuration = PlatformConfigurationResponse(surveySampling: SurveySampling(raw),
- surveyURL: surveyURL, privacyURL: privacyURL)
- }
- }
- 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 fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse {
- let encoder = JSONEncoder()
- encoder.outputFormatting = [.sortedKeys]
- let encoded = try encoder.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 }
- let url = configuration.baseURL.appendingPathComponent("platform").appendingPathComponent("config")
- var request = URLRequest(url: url)
- 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)
- guard let payload = try? JSONDecoder().decode(Payload.self, from: Data(plaintext.utf8)) else { throw APIError.invalidResponse }
- return payload.configuration
- }
- }
|