ActivityBridge.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import Foundation
  2. import CoreFoundation
  3. /// The page-facing API is window.iosapp.postMessage(action, JSON.stringify(params)).
  4. enum ActivityBridgeScript {
  5. static let handlerName = "iosapp"
  6. static let source = source(privacyURL: nil)
  7. static func source(privacyURL: URL?) -> String {
  8. let value = try! JSONSerialization.data(withJSONObject: privacyURL?.absoluteString ?? "", options: [.fragmentsAllowed])
  9. let encoded = String(decoding: value, as: UTF8.self)
  10. return """
  11. (() => {
  12. const bridge = Object.freeze({
  13. privacyURL: \(encoded),
  14. postMessage(action, params) {
  15. window.webkit.messageHandlers.iosapp.postMessage({action, params: params ?? '{}'});
  16. }
  17. });
  18. Object.defineProperty(window, 'iosapp', {value: bridge, configurable: true});
  19. })();
  20. """
  21. }
  22. }
  23. enum ActivityBridgeCommand: Equatable {
  24. case close(SurveySubmission?)
  25. case openWindow(URL)
  26. case facebook(FacebookEvent)
  27. enum DecodeError: String, Error {
  28. case invalidMessage, missingAction, missingParams, oversizedParams, invalidJSON
  29. case invalidURL, unsupportedAction, invalidValue, invalidCurrency
  30. }
  31. static func parse(_ body: Any) -> Self? { try? decode(body) }
  32. static func decode(_ body: Any) throws -> Self {
  33. guard let message = body as? [String: Any] else { throw DecodeError.invalidMessage }
  34. guard let action = message["action"] as? String else { throw DecodeError.missingAction }
  35. let params: [String: Any]
  36. if let json = message["params"] as? String {
  37. guard json.utf8.count <= 16_384 else { throw DecodeError.oversizedParams }
  38. guard let data = json.data(using: .utf8),
  39. let decoded = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw DecodeError.invalidJSON }
  40. params = decoded
  41. } else if let object = message["params"] as? [String: Any] {
  42. params = object
  43. } else { throw DecodeError.missingParams }
  44. if action == "close" {
  45. if let submitted = params["submitted"] {
  46. guard let flag = submitted as? NSNumber, CFGetTypeID(flag) == CFBooleanGetTypeID() else { throw DecodeError.invalidMessage }
  47. }
  48. if params["submitted"] as? Bool == true {
  49. guard let answers = params["answers"] as? [NSNumber], answers.count == 4,
  50. answers.allSatisfy({ CFGetTypeID($0) != CFBooleanGetTypeID() && [1.0, 2.0].contains($0.doubleValue) }),
  51. let feedback = params["feedback"] as? String, feedback.count <= 2000 else { throw DecodeError.invalidMessage }
  52. return .close(SurveySubmission(answers: answers.map(\.intValue), feedback: feedback))
  53. }
  54. return .close(nil)
  55. }
  56. if action == "openWindow" {
  57. guard let raw = params["url"] as? String, let url = ActivityURL.parse(raw) else { throw DecodeError.invalidURL }
  58. return .openWindow(url)
  59. }
  60. do {
  61. let event = try FacebookEvent(action: action, params: params)
  62. return .facebook(event)
  63. }
  64. catch FacebookEvent.ValidationError.unsupportedAction { throw DecodeError.unsupportedAction }
  65. catch FacebookEvent.ValidationError.invalidCurrency { throw DecodeError.invalidCurrency }
  66. catch { throw DecodeError.invalidValue }
  67. }
  68. }
  69. @MainActor final class ActivityBridge {
  70. enum Result: Equatable { case ignored, closed, externalURLRequested, facebook(FacebookTracking.LogResult) }
  71. private let pageURL: URL
  72. private let close: (SurveySubmission?) -> Void
  73. private let openExternalURL: (URL) -> Void
  74. private let tracking: FacebookTracking
  75. init(pageURL: URL, tracking: FacebookTracking, close: @escaping (SurveySubmission?) -> Void = { _ in }, openExternalURL: @escaping (URL) -> Void) {
  76. self.pageURL = pageURL; self.tracking = tracking; self.openExternalURL = openExternalURL
  77. self.close = close
  78. }
  79. @discardableResult func receive(_ body: Any, from sourceURL: URL?, isMainFrame: Bool) -> Result {
  80. guard isMainFrame, let sourceURL, Self.sameOrigin(pageURL, sourceURL),
  81. let command = ActivityBridgeCommand.parse(body) else { return .ignored }
  82. switch command {
  83. case .close(let submission):
  84. close(submission)
  85. return .closed
  86. case .openWindow(let url):
  87. openExternalURL(url)
  88. return .externalURLRequested
  89. case .facebook(let event):
  90. let result = tracking.logFBEvent(action: event.action.rawValue, params: event.parameters)
  91. return .facebook(result)
  92. }
  93. }
  94. private static func sameOrigin(_ lhs: URL, _ rhs: URL) -> Bool {
  95. func port(_ url: URL) -> Int { url.port ?? (url.scheme?.lowercased() == "https" ? 443 : 80) }
  96. return lhs.scheme?.lowercased() == rhs.scheme?.lowercased()
  97. && lhs.host?.lowercased() == rhs.host?.lowercased() && port(lhs) == port(rhs)
  98. }
  99. }