PushNotificationManager.swift 10.0 KB

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