PushNotificationManager.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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(carbs: HKQuantity, protein: HKQuantity, fat: HKQuantity, completion: @escaping (Bool, String?) -> Void) {
  89. let carbsValue = Int(carbs.doubleValue(for: .gram()))
  90. let proteinValue = Int(protein.doubleValue(for: .gram()))
  91. let fatValue = Int(fat.doubleValue(for: .gram()))
  92. let message = PushMessage(
  93. user: user,
  94. commandType: .meal,
  95. carbs: carbsValue,
  96. protein: proteinValue,
  97. fat: fatValue,
  98. sharedSecret: sharedSecret,
  99. timestamp: Date().timeIntervalSince1970
  100. )
  101. sendPushNotification(message: message, completion: completion)
  102. }
  103. private func sendPushNotification(message: PushMessage, completion: @escaping (Bool, String?) -> Void) {
  104. print("Push message to send: \(message)")
  105. var missingFields = [String]()
  106. if sharedSecret.isEmpty { missingFields.append("sharedSecret") }
  107. if apnsKey.isEmpty { missingFields.append("token") }
  108. if keyId.isEmpty { missingFields.append("keyId") }
  109. if user.isEmpty { missingFields.append("user") }
  110. if !missingFields.isEmpty {
  111. let errorMessage = "Missing required fields, check your remote settings: \(missingFields.joined(separator: ", "))"
  112. print(errorMessage)
  113. completion(false, errorMessage)
  114. return
  115. }
  116. if deviceToken.isEmpty { missingFields.append("deviceToken") }
  117. if bundleId.isEmpty { missingFields.append("bundleId") }
  118. if teamId.isEmpty { missingFields.append("teamId") }
  119. if !missingFields.isEmpty {
  120. let errorMessage = "Missing required data, verify that you are using the latest version of Trio: \(missingFields.joined(separator: ", "))"
  121. print(errorMessage)
  122. completion(false, errorMessage)
  123. return
  124. }
  125. guard let url = constructAPNsURL() else {
  126. let errorMessage = "Failed to construct APNs URL"
  127. print(errorMessage)
  128. completion(false, errorMessage)
  129. return
  130. }
  131. guard let jwt = getOrGenerateJWT() else {
  132. let errorMessage = "Failed to generate JWT, please check that the token is correct."
  133. print(errorMessage)
  134. completion(false, errorMessage)
  135. return
  136. }
  137. var request = URLRequest(url: url)
  138. request.httpMethod = "POST"
  139. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  140. request.setValue("application/json", forHTTPHeaderField: "content-type")
  141. request.setValue("10", forHTTPHeaderField: "apns-priority")
  142. request.setValue("0", forHTTPHeaderField: "apns-expiration")
  143. request.setValue(bundleId, forHTTPHeaderField: "apns-topic")
  144. request.setValue("background", forHTTPHeaderField: "apns-push-type")
  145. do {
  146. let jsonData = try JSONEncoder().encode(message)
  147. request.httpBody = jsonData
  148. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  149. if let error = error {
  150. let errorMessage = "Failed to send push notification: \(error.localizedDescription)"
  151. print(errorMessage)
  152. completion(false, errorMessage)
  153. return
  154. }
  155. if let httpResponse = response as? HTTPURLResponse {
  156. print("Push notification sent.")
  157. print("Status code: \(httpResponse.statusCode)")
  158. print("Response headers:")
  159. for (key, value) in httpResponse.allHeaderFields {
  160. print("\(key): \(value)")
  161. }
  162. var responseBodyMessage = ""
  163. if let data = data, let responseBody = String(data: data, encoding: .utf8) {
  164. print("Response body: \(responseBody)")
  165. if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  166. let reason = json["reason"] as? String {
  167. responseBodyMessage = reason
  168. }
  169. } else {
  170. print("No response body")
  171. }
  172. switch httpResponse.statusCode {
  173. case 200:
  174. completion(true, nil)
  175. case 400:
  176. completion(false, "Bad request. The request was invalid or malformed. \(responseBodyMessage)")
  177. case 403:
  178. completion(false, "Authentication error. Check your certificate or authentication token. \(responseBodyMessage)")
  179. case 404:
  180. completion(false, "Invalid request: The :path value was incorrect. \(responseBodyMessage)")
  181. case 405:
  182. completion(false, "Invalid request: Only POST requests are supported. \(responseBodyMessage)")
  183. case 410:
  184. completion(false, "The device token is no longer active for the topic. \(responseBodyMessage)")
  185. case 413:
  186. completion(false, "Payload too large. The notification payload exceeded the size limit. \(responseBodyMessage)")
  187. case 429:
  188. completion(false, "Too many requests. \(responseBodyMessage)")
  189. case 500:
  190. completion(false, "Internal server error at APNs. \(responseBodyMessage)")
  191. case 503:
  192. completion(false, "Service unavailable. The server is temporarily unavailable. Try again later. \(responseBodyMessage)")
  193. default:
  194. completion(false, "Unexpected status code: \(httpResponse.statusCode). \(responseBodyMessage)")
  195. }
  196. } else {
  197. completion(false, "Failed to get a valid HTTP response.")
  198. }
  199. }
  200. task.resume()
  201. } catch {
  202. let errorMessage = "Failed to encode push message: \(error.localizedDescription)"
  203. print(errorMessage)
  204. completion(false, errorMessage)
  205. }
  206. }
  207. private func constructAPNsURL() -> URL? {
  208. let host = productionEnvironment ? "api.push.apple.com" : "api.sandbox.push.apple.com"
  209. let urlString = "https://\(host)/3/device/\(deviceToken)"
  210. return URL(string: urlString)
  211. }
  212. private func getOrGenerateJWT() -> String? {
  213. if let cachedJWT = Storage.shared.cachedJWT.value, let expirationDate = Storage.shared.jwtExpirationDate.value {
  214. if Date() < expirationDate {
  215. return cachedJWT
  216. }
  217. }
  218. let header = Header(kid: keyId)
  219. let claims = APNsJWTClaims(iss: teamId, iat: Date())
  220. var jwt = JWT(header: header, claims: claims)
  221. do {
  222. let privateKey = Data(apnsKey.utf8)
  223. let jwtSigner = JWTSigner.es256(privateKey: privateKey)
  224. let signedJWT = try jwt.sign(using: jwtSigner)
  225. Storage.shared.cachedJWT.value = signedJWT
  226. Storage.shared.jwtExpirationDate.value = Date().addingTimeInterval(3600)
  227. return signedJWT
  228. } catch {
  229. print("Failed to sign JWT: \(error.localizedDescription)")
  230. return nil
  231. }
  232. }
  233. }