HeartbeatsPayload.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. #if SWIFT_PACKAGE
  16. import GoogleUtilities_NSData
  17. #else
  18. import GoogleUtilities
  19. #endif // SWIFT_PACKAGE
  20. /// A type that provides a string representation for use in an HTTP header.
  21. public protocol HTTPHeaderRepresentable {
  22. func headerValue() -> String
  23. }
  24. /// A value type representing a payload of heartbeat data intended for sending in network requests.
  25. ///
  26. /// This type's structure is optimized for type-safe encoding into a HTTP payload format.
  27. /// The current encoding format for the payload's current version is:
  28. ///
  29. /// {
  30. /// "version": 2,
  31. /// "heartbeats": [
  32. /// {
  33. /// "agent": "dummy_agent_1",
  34. /// "dates": ["2021-11-01", "2021-11-02"]
  35. /// },
  36. /// {
  37. /// "agent": "dummy_agent_2",
  38. /// "dates": ["2021-11-03"]
  39. /// }
  40. /// ]
  41. /// }
  42. ///
  43. public struct HeartbeatsPayload: Codable {
  44. /// The version of the payload. See go/firebase-apple-heartbeats for details regarding current version.
  45. static let version: Int = 2
  46. /// A payload component composed of a user agent and array of dates (heartbeats).
  47. struct UserAgentPayload: Codable {
  48. /// An anonymous agent string.
  49. let agent: String
  50. /// An array of dates where each date represents a "heartbeat".
  51. let dates: [Date]
  52. }
  53. /// An array of user agent payloads.
  54. let userAgentPayloads: [UserAgentPayload]
  55. /// The version of the payload structure.
  56. let version: Int
  57. /// Alternative keys for properties so encoding follows platform-wide payload structure.
  58. enum CodingKeys: String, CodingKey {
  59. case userAgentPayloads = "heartbeats"
  60. case version
  61. }
  62. /// Designated initializer.
  63. /// - Parameters:
  64. /// - userAgentPayloads: An array of payloads containing heartbeat data corresponding to a
  65. /// given user agent.
  66. /// - version: A version of the payload. Defaults to the static default.
  67. init(userAgentPayloads: [UserAgentPayload] = [], version: Int = version) {
  68. self.userAgentPayloads = userAgentPayloads
  69. self.version = version
  70. }
  71. /// A Boolean value indicating whether the payload is empty.
  72. public var isEmpty: Bool {
  73. userAgentPayloads.isEmpty
  74. }
  75. }
  76. // MARK: - HTTPHeaderRepresentable
  77. extension HeartbeatsPayload: HTTPHeaderRepresentable {
  78. /// Returns a processed payload string intended for use in a HTTP header.
  79. /// - Returns: A string value from the heartbeats payload.
  80. public func headerValue() -> String {
  81. let encoder = JSONEncoder()
  82. encoder.dateEncodingStrategy = .formatted(Self.dateFormatter)
  83. guard let data = try? encoder.encode(self) else {
  84. // If encoding fails, fall back to encoding with an empty payload.
  85. return Self.emptyPayload.headerValue()
  86. }
  87. do {
  88. let gzippedData = try data.zipped()
  89. return gzippedData.base64URLEncodedString()
  90. } catch {
  91. // If gzipping fails, fall back to encoding with base64URL.
  92. return data.base64URLEncodedString()
  93. }
  94. }
  95. }
  96. // MARK: - Static Defaults
  97. extension HeartbeatsPayload {
  98. /// Convenience instance that represents an empty payload.
  99. static let emptyPayload = HeartbeatsPayload()
  100. /// A default date formatter that uses `YYYY-MM-dd` format.
  101. public static let dateFormatter: DateFormatter = {
  102. let formatter = DateFormatter()
  103. formatter.dateFormat = "YYYY-MM-dd"
  104. formatter.locale = Locale(identifier: "en_US_POSIX")
  105. formatter.timeZone = TimeZone(secondsFromGMT: 0)
  106. return formatter
  107. }()
  108. }
  109. // MARK: - Equatable
  110. extension HeartbeatsPayload: Equatable {}
  111. extension HeartbeatsPayload.UserAgentPayload: Equatable {}
  112. // MARK: - Data
  113. public extension Data {
  114. /// Returns a Base-64 URL-safe encoded string.
  115. ///
  116. /// - parameter options: The options to use for the encoding. Default value is `[]`.
  117. /// - returns: The Base-64 URL-safe encoded string.
  118. func base64URLEncodedString(options: Data.Base64EncodingOptions = []) -> String {
  119. base64EncodedString()
  120. .replacingOccurrences(of: "/", with: "_")
  121. .replacingOccurrences(of: "+", with: "-")
  122. .replacingOccurrences(of: "=", with: "")
  123. }
  124. /// Initialize a `Data` from a Base-64 URL encoded String using the given options.
  125. ///
  126. /// Returns nil when the input is not recognized as valid Base-64.
  127. /// - parameter base64URLString: The string to parse.
  128. /// - parameter options: Encoding options. Default value is `[]`.
  129. init?(base64URLEncoded base64URLString: String, options: Data.Base64DecodingOptions = []) {
  130. var base64Encoded = base64URLString
  131. .replacingOccurrences(of: "_", with: "/")
  132. .replacingOccurrences(of: "-", with: "+")
  133. // Pad the string with "=" signs until the string's length is a multiple of 4.
  134. while !base64Encoded.count.isMultiple(of: 4) {
  135. base64Encoded.append("=")
  136. }
  137. self.init(base64Encoded: base64Encoded, options: options)
  138. }
  139. /// Returns the compressed data.
  140. /// - Returns: The compressed data.
  141. /// - Throws: An error if compression failed.
  142. func zipped() throws -> Data {
  143. try NSData.gul_data(byGzippingData: self)
  144. }
  145. /// Returns the uncompressed data.
  146. /// - Returns: The decompressed data.
  147. /// - Throws: An error if decompression failed.
  148. func unzipped() throws -> Data {
  149. try NSData.gul_data(byInflatingGzippedData: self)
  150. }
  151. }