PlatformAPI.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import Foundation
  2. struct PlatformAPIConfiguration: Sendable {
  3. let baseURL: URL
  4. let channel: String
  5. enum ConfigurationError: Error { case invalidURL, invalidChannel }
  6. init(baseURL: String, channel: String) throws {
  7. guard let url = ActivityURL.parse(baseURL), url.query == nil, url.fragment == nil,
  8. !url.absoluteString.contains("$(") else { throw ConfigurationError.invalidURL }
  9. let channel = channel.trimmingCharacters(in: .whitespacesAndNewlines)
  10. guard !channel.isEmpty, !channel.contains("$(") else { throw ConfigurationError.invalidChannel }
  11. self.baseURL = url
  12. self.channel = channel
  13. }
  14. static func fromBundle(_ bundle: Bundle = .main) -> Self? {
  15. guard let base = bundle.object(forInfoDictionaryKey: "PlatformAPIBaseURL") as? String,
  16. let channel = bundle.object(forInfoDictionaryKey: "PlatformChannel") as? String else { return nil }
  17. return try? Self(baseURL: base, channel: channel)
  18. }
  19. }
  20. struct PlatformRequestContext: Encodable, Sendable {
  21. static var deviceRegionCode: String? {
  22. if #available(iOS 16, macOS 13, *) { return Locale.current.region?.identifier }
  23. return Locale.current.regionCode
  24. }
  25. let channel: String
  26. let language: String
  27. let region: String?
  28. let timezone: String
  29. }
  30. enum ActivityURL {
  31. static func parse(_ input: String) -> URL? {
  32. var text = input.trimmingCharacters(in: .whitespacesAndNewlines)
  33. if (text.hasPrefix("\"") && text.hasSuffix("\"")) || (text.hasPrefix("“") && text.hasSuffix("”")) {
  34. text = String(text.dropFirst().dropLast()).trimmingCharacters(in: .whitespacesAndNewlines)
  35. }
  36. guard !text.isEmpty, !text.contains(where: \.isWhitespace),
  37. let parts = URLComponents(string: text), let scheme = parts.scheme?.lowercased(),
  38. ["https", "http"].contains(scheme), let host = parts.host, !host.isEmpty,
  39. parts.user == nil, parts.password == nil else { return nil }
  40. var normalized = parts
  41. normalized.scheme = scheme
  42. return normalized.url
  43. }
  44. }
  45. struct ActivityClosePolicy: Equatable {
  46. let isEnabled: Bool
  47. let delaySeconds: UInt64
  48. init(url: URL) {
  49. let items = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []
  50. let switches = items.filter { $0.name == "s" }
  51. let value = switches.count == 1 ? switches.first?.value.flatMap(Double.init) : nil
  52. isEnabled = value.map { $0.isFinite && $0 != 0 } ?? false
  53. let delays = items.filter { $0.name == "sec" }
  54. let requestedDelay = delays.count == 1 ? delays.first?.value.flatMap(UInt64.init) ?? 0 : 0
  55. delaySeconds = min(requestedDelay, 10)
  56. }
  57. }
  58. struct PlatformConfigurationResponse: Sendable {
  59. let surveySampling: SurveySampling
  60. var surveyURL: URL? = nil
  61. var privacyURL: URL? = nil
  62. }
  63. protocol PlatformRemoteFetching: Sendable {
  64. func fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse
  65. }
  66. struct PlatformAPIClient: PlatformRemoteFetching {
  67. enum APIError: Error { case invalidResponse }
  68. private struct Payload: Decodable {
  69. enum CodingKeys: String, CodingKey {
  70. case su
  71. case privacyURL = "privacyurl", sampling = "player_info_10"
  72. }
  73. let configuration: PlatformConfigurationResponse
  74. init(from decoder: Decoder) throws {
  75. let fields = try decoder.container(keyedBy: CodingKeys.self)
  76. let raw: String?
  77. if let text = try? fields.decode(String.self, forKey: .sampling) { raw = text }
  78. else if let number = try? fields.decode(Int.self, forKey: .sampling) { raw = String(number) }
  79. else if let number = try? fields.decode(Double.self, forKey: .sampling) { raw = String(number) }
  80. else { raw = nil }
  81. let surveyURL = (try? fields.decode(String.self, forKey: .su)).flatMap(ActivityURL.parse)
  82. let privacyURL = (try? fields.decode(String.self, forKey: .privacyURL)).flatMap(ActivityURL.parse)
  83. configuration = PlatformConfigurationResponse(surveySampling: SurveySampling(raw),
  84. surveyURL: surveyURL, privacyURL: privacyURL)
  85. }
  86. }
  87. let configuration: PlatformAPIConfiguration
  88. let transport: DataTransport
  89. init(configuration: PlatformAPIConfiguration, session: URLSession? = nil) {
  90. self.configuration = configuration
  91. transport = NetworkClient(session: session, allowedHTTPHosts: configuration.baseURL.scheme == "http" ? [configuration.baseURL.host!]: [])
  92. }
  93. func fetchConfiguration(context: PlatformRequestContext) async throws -> PlatformConfigurationResponse {
  94. let encoder = JSONEncoder()
  95. encoder.outputFormatting = [.sortedKeys]
  96. let encoded = try encoder.encode(context)
  97. let encrypted = try PlatformCrypto.encrypt(String(decoding: encoded, as: UTF8.self))
  98. struct RequestBody: Encodable { let payload: String }
  99. struct ResponseBody: Decodable { let data: String }
  100. let url = configuration.baseURL.appendingPathComponent("platform").appendingPathComponent("config")
  101. var request = URLRequest(url: url)
  102. request.httpMethod = "POST"
  103. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  104. request.setValue("application/json", forHTTPHeaderField: "Accept")
  105. request.httpBody = try JSONEncoder().encode(RequestBody(payload: encrypted))
  106. let data = try await transport.execute(request)
  107. guard let body = try? JSONDecoder().decode(ResponseBody.self, from: data) else {
  108. throw APIError.invalidResponse
  109. }
  110. let plaintext = try PlatformCrypto.decrypt(body.data)
  111. guard let payload = try? JSONDecoder().decode(Payload.self, from: Data(plaintext.utf8)) else { throw APIError.invalidResponse }
  112. return payload.configuration
  113. }
  114. }