PushNotificationManager.swift 14 KB

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