PushNotificationManager.swift 9.2 KB

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