PushNotificationManager.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. // LoopFollow
  2. // PushNotificationManager.swift
  3. // Created by Jonas Björkert.
  4. import Foundation
  5. import HealthKit
  6. import SwiftJWT
  7. struct APNsJWTClaims: Claims {
  8. let iss: String
  9. let iat: Date
  10. }
  11. class PushNotificationManager {
  12. private var deviceToken: String
  13. private var sharedSecret: String
  14. private var productionEnvironment: Bool
  15. private var apnsKey: String
  16. private var teamId: String
  17. private var keyId: String
  18. private var user: String
  19. private var bundleId: String
  20. init() {
  21. deviceToken = Storage.shared.deviceToken.value
  22. sharedSecret = Storage.shared.sharedSecret.value
  23. productionEnvironment = Storage.shared.productionEnvironment.value
  24. apnsKey = Storage.shared.apnsKey.value
  25. teamId = Storage.shared.teamId.value ?? ""
  26. keyId = Storage.shared.keyId.value
  27. user = Storage.shared.user.value
  28. bundleId = Storage.shared.bundleId.value
  29. }
  30. func sendOverridePushNotification(override: ProfileManager.TrioOverride, completion: @escaping (Bool, String?) -> Void) {
  31. let message = PushMessage(
  32. user: user,
  33. commandType: .startOverride,
  34. sharedSecret: sharedSecret,
  35. timestamp: Date().timeIntervalSince1970,
  36. overrideName: override.name
  37. )
  38. sendPushNotification(message: message, completion: completion)
  39. }
  40. func sendCancelOverridePushNotification(completion: @escaping (Bool, String?) -> Void) {
  41. let message = PushMessage(
  42. user: user,
  43. commandType: .cancelOverride,
  44. sharedSecret: sharedSecret,
  45. timestamp: Date().timeIntervalSince1970,
  46. overrideName: nil
  47. )
  48. sendPushNotification(message: message, completion: completion)
  49. }
  50. func sendBolusPushNotification(bolusAmount: HKQuantity, completion: @escaping (Bool, String?) -> Void) {
  51. let bolusAmount = Decimal(bolusAmount.doubleValue(for: .internationalUnit()))
  52. let message = PushMessage(
  53. user: user,
  54. commandType: .bolus,
  55. bolusAmount: bolusAmount,
  56. sharedSecret: sharedSecret,
  57. timestamp: Date().timeIntervalSince1970
  58. )
  59. sendPushNotification(message: message, completion: completion)
  60. }
  61. func sendTempTargetPushNotification(target: HKQuantity, duration: HKQuantity, completion: @escaping (Bool, String?) -> Void) {
  62. let targetValue = Int(target.doubleValue(for: HKUnit.milligramsPerDeciliter))
  63. let durationValue = Int(duration.doubleValue(for: HKUnit.minute()))
  64. let message = PushMessage(
  65. user: user,
  66. commandType: .tempTarget,
  67. bolusAmount: nil,
  68. target: targetValue,
  69. duration: durationValue,
  70. sharedSecret: sharedSecret,
  71. timestamp: Date().timeIntervalSince1970
  72. )
  73. sendPushNotification(message: message, completion: completion)
  74. }
  75. func sendCancelTempTargetPushNotification(completion: @escaping (Bool, String?) -> Void) {
  76. let message = PushMessage(
  77. user: user,
  78. commandType: .cancelTempTarget,
  79. sharedSecret: sharedSecret,
  80. timestamp: Date().timeIntervalSince1970
  81. )
  82. sendPushNotification(message: message, completion: completion)
  83. }
  84. func sendMealPushNotification(
  85. carbs: HKQuantity,
  86. protein: HKQuantity,
  87. fat: HKQuantity,
  88. bolusAmount: HKQuantity,
  89. scheduledTime: Date?,
  90. completion: @escaping (Bool, String?) -> Void
  91. ) {
  92. func convertToOptionalInt(_ quantity: HKQuantity) -> Int? {
  93. let valueInGrams = quantity.doubleValue(for: .gram())
  94. return valueInGrams > 0 ? Int(valueInGrams) : nil
  95. }
  96. func convertToOptionalDecimal(_ quantity: HKQuantity?) -> Decimal? {
  97. guard let quantity = quantity else { return nil }
  98. let value = quantity.doubleValue(for: .internationalUnit())
  99. return value > 0 ? Decimal(value) : nil
  100. }
  101. let carbsValue = convertToOptionalInt(carbs)
  102. let proteinValue = convertToOptionalInt(protein)
  103. let fatValue = convertToOptionalInt(fat)
  104. let scheduledTimeInterval: TimeInterval? = scheduledTime?.timeIntervalSince1970
  105. let bolusAmountValue = convertToOptionalDecimal(bolusAmount)
  106. guard carbsValue != nil || proteinValue != nil || fatValue != nil else {
  107. completion(false, "No nutrient data provided. At least one of carbs, fat, or protein must be greater than 0.")
  108. return
  109. }
  110. let message = PushMessage(
  111. user: user,
  112. commandType: .meal,
  113. bolusAmount: bolusAmountValue,
  114. carbs: carbsValue,
  115. protein: proteinValue,
  116. fat: fatValue,
  117. sharedSecret: sharedSecret,
  118. timestamp: Date().timeIntervalSince1970,
  119. scheduledTime: scheduledTimeInterval
  120. )
  121. sendPushNotification(message: message, completion: completion)
  122. }
  123. private func validateCredentials() -> [String]? {
  124. var errors = [String]()
  125. // Validate keyId (should be 10 alphanumeric characters)
  126. let keyIdPattern = "^[A-Z0-9]{10}$"
  127. if !matchesRegex(keyId, pattern: keyIdPattern) {
  128. errors.append("APNS Key ID (\(keyId)) must be 10 uppercase alphanumeric characters.")
  129. }
  130. // Validate teamId (should be 10 alphanumeric characters)
  131. let teamIdPattern = "^[A-Z0-9]{10}$"
  132. if !matchesRegex(teamId, pattern: teamIdPattern) {
  133. errors.append("Team ID (\(teamId)) must be 10 uppercase alphanumeric characters.")
  134. }
  135. // Validate apnsKey (should contain the BEGIN and END PRIVATE KEY markers)
  136. if !apnsKey.contains("-----BEGIN PRIVATE KEY-----") || !apnsKey.contains("-----END PRIVATE KEY-----") {
  137. errors.append("APNS Key must be a valid PEM-formatted private key.")
  138. } else {
  139. // Validate that the key data between the markers is valid Base64
  140. if let keyData = extractKeyData(from: apnsKey) {
  141. if Data(base64Encoded: keyData) == nil {
  142. errors.append("APNS Key contains invalid Base64 key data.")
  143. }
  144. } else {
  145. errors.append("APNS Key has invalid formatting.")
  146. }
  147. }
  148. return errors.isEmpty ? nil : errors
  149. }
  150. private func matchesRegex(_ text: String, pattern: String) -> Bool {
  151. let regex = try? NSRegularExpression(pattern: pattern)
  152. let range = NSRange(location: 0, length: text.utf16.count)
  153. return regex?.firstMatch(in: text, options: [], range: range) != nil
  154. }
  155. private func extractKeyData(from pemString: String) -> String? {
  156. let lines = pemString.components(separatedBy: "\n")
  157. guard let startIndex = lines.firstIndex(of: "-----BEGIN PRIVATE KEY-----"),
  158. let endIndex = lines.firstIndex(of: "-----END PRIVATE KEY-----"),
  159. startIndex < endIndex
  160. else {
  161. return nil
  162. }
  163. let keyLines = lines[(startIndex + 1) ..< endIndex]
  164. return keyLines.joined()
  165. }
  166. private func sendPushNotification(message: PushMessage, completion: @escaping (Bool, String?) -> Void) {
  167. print("Push message to send: \(message)")
  168. var missingFields = [String]()
  169. if sharedSecret.isEmpty { missingFields.append("sharedSecret") }
  170. if apnsKey.isEmpty { missingFields.append("token") }
  171. if keyId.isEmpty { missingFields.append("keyId") }
  172. if user.isEmpty { missingFields.append("user") }
  173. if !missingFields.isEmpty {
  174. let errorMessage = "Missing required fields, check your remote settings: \(missingFields.joined(separator: ", "))"
  175. LogManager.shared.log(category: .apns, message: errorMessage)
  176. completion(false, errorMessage)
  177. return
  178. }
  179. if deviceToken.isEmpty { missingFields.append("deviceToken") }
  180. if bundleId.isEmpty { missingFields.append("bundleId") }
  181. if teamId.isEmpty { missingFields.append("teamId") }
  182. if !missingFields.isEmpty {
  183. let errorMessage = "Missing required data, verify that you are using the latest version of Trio: \(missingFields.joined(separator: ", "))"
  184. LogManager.shared.log(category: .apns, message: errorMessage)
  185. completion(false, errorMessage)
  186. return
  187. }
  188. if let validationErrors = validateCredentials() {
  189. let errorMessage = "Credential validation failed: \(validationErrors.joined(separator: ", "))"
  190. LogManager.shared.log(category: .apns, message: errorMessage)
  191. completion(false, errorMessage)
  192. return
  193. }
  194. guard let url = constructAPNsURL() else {
  195. let errorMessage = "Failed to construct APNs URL"
  196. LogManager.shared.log(category: .apns, message: errorMessage)
  197. completion(false, errorMessage)
  198. return
  199. }
  200. guard let jwt = getOrGenerateJWT() else {
  201. let errorMessage = "Failed to generate JWT, please check that the token is correct."
  202. LogManager.shared.log(category: .apns, message: errorMessage)
  203. completion(false, errorMessage)
  204. return
  205. }
  206. var request = URLRequest(url: url)
  207. request.httpMethod = "POST"
  208. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  209. request.setValue("application/json", forHTTPHeaderField: "content-type")
  210. request.setValue("10", forHTTPHeaderField: "apns-priority")
  211. request.setValue("0", forHTTPHeaderField: "apns-expiration")
  212. request.setValue(bundleId, forHTTPHeaderField: "apns-topic")
  213. request.setValue("background", forHTTPHeaderField: "apns-push-type")
  214. do {
  215. let jsonData = try JSONEncoder().encode(message)
  216. request.httpBody = jsonData
  217. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  218. if let error = error {
  219. let errorMessage = "Failed to send push notification: \(error.localizedDescription)"
  220. LogManager.shared.log(category: .apns, message: errorMessage)
  221. completion(false, errorMessage)
  222. return
  223. }
  224. if let httpResponse = response as? HTTPURLResponse {
  225. print("Push notification sent.")
  226. print("Status code: \(httpResponse.statusCode)")
  227. print("Response headers:")
  228. for (key, value) in httpResponse.allHeaderFields {
  229. print("\(key): \(value)")
  230. }
  231. var responseBodyMessage = ""
  232. if let data = data, let responseBody = String(data: data, encoding: .utf8) {
  233. print("Response body: \(responseBody)")
  234. if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  235. let reason = json["reason"] as? String
  236. {
  237. responseBodyMessage = reason
  238. }
  239. } else {
  240. print("No response body")
  241. }
  242. switch httpResponse.statusCode {
  243. case 200:
  244. completion(true, nil)
  245. case 400:
  246. completion(false, "Bad request. The request was invalid or malformed. \(responseBodyMessage)")
  247. case 403:
  248. completion(false, "Authentication error. Check your certificate or authentication token. \(responseBodyMessage)")
  249. case 404:
  250. completion(false, "Invalid request: The :path value was incorrect. \(responseBodyMessage)")
  251. case 405:
  252. completion(false, "Invalid request: Only POST requests are supported. \(responseBodyMessage)")
  253. case 410:
  254. completion(false, "The device token is no longer active for the topic. \(responseBodyMessage)")
  255. case 413:
  256. completion(false, "Payload too large. The notification payload exceeded the size limit. \(responseBodyMessage)")
  257. case 429:
  258. completion(false, "Too many requests. \(responseBodyMessage)")
  259. case 500:
  260. completion(false, "Internal server error at APNs. \(responseBodyMessage)")
  261. case 503:
  262. completion(false, "Service unavailable. The server is temporarily unavailable. Try again later. \(responseBodyMessage)")
  263. default:
  264. completion(false, "Unexpected status code: \(httpResponse.statusCode). \(responseBodyMessage)")
  265. }
  266. } else {
  267. completion(false, "Failed to get a valid HTTP response.")
  268. }
  269. }
  270. task.resume()
  271. } catch {
  272. let errorMessage = "Failed to encode push message: \(error.localizedDescription)"
  273. print(errorMessage)
  274. completion(false, errorMessage)
  275. }
  276. }
  277. private func constructAPNsURL() -> URL? {
  278. let host = productionEnvironment ? "api.push.apple.com" : "api.sandbox.push.apple.com"
  279. let urlString = "https://\(host)/3/device/\(deviceToken)"
  280. return URL(string: urlString)
  281. }
  282. private func getOrGenerateJWT() -> String? {
  283. if let cachedJWT = Storage.shared.cachedJWT.value, let expirationDate = Storage.shared.jwtExpirationDate.value {
  284. if Date() < expirationDate {
  285. return cachedJWT
  286. }
  287. }
  288. let header = Header(kid: keyId)
  289. let claims = APNsJWTClaims(iss: teamId, iat: Date())
  290. var jwt = JWT(header: header, claims: claims)
  291. do {
  292. let privateKey = Data(apnsKey.utf8)
  293. let jwtSigner = JWTSigner.es256(privateKey: privateKey)
  294. let signedJWT = try jwt.sign(using: jwtSigner)
  295. Storage.shared.cachedJWT.value = signedJWT
  296. Storage.shared.jwtExpirationDate.value = Date().addingTimeInterval(3600)
  297. return signedJWT
  298. } catch {
  299. print("Failed to sign JWT: \(error.localizedDescription)")
  300. return nil
  301. }
  302. }
  303. }