PlatformAPI.swift 5.9 KB

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