LoopAPNSService.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. // LoopFollow
  2. // LoopAPNSService.swift
  3. import CryptoKit
  4. import Foundation
  5. import HealthKit
  6. import SwiftJWT
  7. class LoopAPNSService {
  8. private let storage = Storage.shared
  9. enum LoopAPNSError: Error, LocalizedError {
  10. case invalidConfiguration
  11. case jwtError
  12. case networkError
  13. case invalidResponse
  14. case noDeviceToken
  15. case noBundleIdentifier
  16. case unauthorized
  17. case deviceTokenNotConfigured
  18. case bundleIdentifierNotConfigured
  19. case rateLimited
  20. var errorDescription: String? {
  21. switch self {
  22. case .invalidConfiguration:
  23. return "Loop APNS Configuration not valid"
  24. case .jwtError:
  25. return "Failed generating JWT token, check APNS Key ID, APNS Key and Team ID"
  26. case .networkError:
  27. return "Network error occurred"
  28. case .invalidResponse:
  29. return "Invalid response from server"
  30. case .noDeviceToken:
  31. return "No device token found in profile"
  32. case .noBundleIdentifier:
  33. return "No bundle identifier found in profile"
  34. case .unauthorized:
  35. return "Unauthorized - check your API secret"
  36. case .deviceTokenNotConfigured:
  37. return "Device token not configured"
  38. case .bundleIdentifierNotConfigured:
  39. return "Bundle identifier not configured"
  40. case .rateLimited:
  41. return "Too many requests - please wait a few minutes before trying again"
  42. }
  43. }
  44. }
  45. /// Validates the Loop APNS setup by checking all required fields
  46. /// - Returns: True if setup is valid, false otherwise
  47. func validateSetup() -> Bool {
  48. let hasKeyId = !storage.keyId.value.isEmpty
  49. let hasAPNSKey = !storage.apnsKey.value.isEmpty
  50. let hasQrCode = !storage.loopAPNSQrCodeURL.value.isEmpty
  51. let hasDeviceToken = !Storage.shared.deviceToken.value.isEmpty
  52. let hasBundleIdentifier = !Storage.shared.bundleId.value.isEmpty
  53. // For initial setup, we don't require device token and bundle identifier
  54. // These will be fetched when the user clicks "Refresh Device Token"
  55. let hasBasicSetup = hasKeyId && hasAPNSKey && hasQrCode
  56. // For full validation (after device token is fetched), check everything
  57. let hasFullSetup = hasBasicSetup && hasDeviceToken && hasBundleIdentifier
  58. return hasFullSetup
  59. }
  60. /// Sends carbs via APNS push notification
  61. /// - Parameters:
  62. /// - payload: The carbs payload to send
  63. /// - completion: Completion handler with success status and error message
  64. func sendCarbsViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
  65. guard validateSetup() else {
  66. let errorMessage = "Loop APNS Configuration not valid"
  67. LogManager.shared.log(category: .apns, message: errorMessage)
  68. completion(false, errorMessage)
  69. return
  70. }
  71. let deviceToken = Storage.shared.deviceToken.value
  72. let bundleIdentifier = Storage.shared.bundleId.value
  73. let keyId = storage.keyId.value
  74. let apnsKey = storage.apnsKey.value
  75. // Create APNS notification payload (matching Loop's expected format)
  76. let now = Date()
  77. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  78. // Create the complete notification payload (matching Nightscout's exact format)
  79. // Based on Nightscout's loop.js implementation
  80. let carbsAmount = payload.carbsAmount ?? 0.0
  81. let absorptionTime = payload.absorptionTime ?? 3.0
  82. let startTime = payload.consumedDate ?? now
  83. let finalPayload = [
  84. "carbs-entry": carbsAmount,
  85. "absorption-time": absorptionTime,
  86. "otp": String(payload.otp),
  87. "remote-address": "LoopFollow",
  88. "notes": "Sent via LoopFollow APNS",
  89. "entered-by": "LoopFollow",
  90. "sent-at": formatDateForAPNS(now),
  91. "expiration": formatDateForAPNS(expiration),
  92. "start-time": formatDateForAPNS(startTime),
  93. "alert": "Remote Carbs Entry: \(String(format: "%.1f", carbsAmount)) grams\nAbsorption Time: \(String(format: "%.1f", absorptionTime)) hours",
  94. ] as [String: Any]
  95. // Log carbs entry attempt
  96. LogManager.shared.log(category: .apns, message: "Sending carbs: \(String(format: "%.1f", carbsAmount))g, absorption: \(String(format: "%.1f", absorptionTime))h")
  97. sendAPNSNotification(
  98. deviceToken: deviceToken,
  99. bundleIdentifier: bundleIdentifier,
  100. keyId: keyId,
  101. apnsKey: apnsKey,
  102. payload: finalPayload,
  103. completion: completion
  104. )
  105. }
  106. /// Sends bolus via APNS push notification
  107. /// - Parameters:
  108. /// - payload: The bolus payload to send
  109. /// - completion: Completion handler with success status and error message
  110. func sendBolusViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
  111. guard validateSetup() else {
  112. let errorMessage = "Loop APNS Configuration not valid"
  113. LogManager.shared.log(category: .apns, message: errorMessage)
  114. completion(false, errorMessage)
  115. return
  116. }
  117. let deviceToken = Storage.shared.deviceToken.value
  118. let bundleIdentifier = Storage.shared.bundleId.value
  119. let keyId = storage.keyId.value
  120. let apnsKey = storage.apnsKey.value
  121. // Create APNS notification payload (matching Loop's expected format)
  122. let now = Date()
  123. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  124. // Create the complete notification payload (matching Nightscout's exact format)
  125. // Based on Nightscout's loop.js implementation
  126. let bolusAmount = payload.bolusAmount ?? 0.0
  127. let finalPayload = [
  128. "bolus-entry": bolusAmount,
  129. "otp": String(payload.otp),
  130. "remote-address": "LoopFollow",
  131. "notes": "Sent via LoopFollow APNS",
  132. "entered-by": "LoopFollow",
  133. "sent-at": formatDateForAPNS(now),
  134. "expiration": formatDateForAPNS(expiration),
  135. "alert": "Remote Bolus Entry: \(String(format: "%.2f", bolusAmount)) U",
  136. ] as [String: Any]
  137. // Log bolus entry attempt
  138. LogManager.shared.log(category: .apns, message: "Sending bolus: \(String(format: "%.2f", bolusAmount))U")
  139. sendAPNSNotification(
  140. deviceToken: deviceToken,
  141. bundleIdentifier: bundleIdentifier,
  142. keyId: keyId,
  143. apnsKey: apnsKey,
  144. payload: finalPayload,
  145. completion: completion
  146. )
  147. }
  148. /// Validates APNS credentials similar to PushNotificationManager
  149. /// - Returns: Array of validation error messages, or nil if valid
  150. private func validateCredentials() -> [String]? {
  151. var errors = [String]()
  152. let keyId = storage.keyId.value
  153. let teamId = Storage.shared.teamId.value ?? ""
  154. let apnsKey = storage.apnsKey.value
  155. // Validate keyId (should be 10 alphanumeric characters)
  156. let keyIdPattern = "^[A-Z0-9]{10}$"
  157. if !matchesRegex(keyId, pattern: keyIdPattern) {
  158. errors.append("APNS Key ID (\(keyId)) must be 10 uppercase alphanumeric characters.")
  159. }
  160. // Validate teamId (should be 10 alphanumeric characters)
  161. let teamIdPattern = "^[A-Z0-9]{10}$"
  162. if !matchesRegex(teamId, pattern: teamIdPattern) {
  163. errors.append("Team ID (\(teamId)) must be 10 uppercase alphanumeric characters.")
  164. }
  165. // Validate apnsKey (should contain the BEGIN and END PRIVATE KEY markers)
  166. if !apnsKey.contains("-----BEGIN PRIVATE KEY-----") || !apnsKey.contains("-----END PRIVATE KEY-----") {
  167. errors.append("APNS Key must be a valid PEM-formatted private key.")
  168. } else {
  169. // Validate that the key data between the markers is valid Base64
  170. if let keyData = extractKeyData(from: apnsKey) {
  171. if Data(base64Encoded: keyData) == nil {
  172. errors.append("APNS Key contains invalid Base64 key data.")
  173. }
  174. } else {
  175. errors.append("APNS Key has invalid formatting.")
  176. }
  177. }
  178. return errors.isEmpty ? nil : errors
  179. }
  180. /// Helper method to match regex patterns
  181. /// - Parameters:
  182. /// - text: Text to match
  183. /// - pattern: Regex pattern
  184. /// - Returns: True if pattern matches
  185. private func matchesRegex(_ text: String, pattern: String) -> Bool {
  186. let regex = try? NSRegularExpression(pattern: pattern)
  187. let range = NSRange(location: 0, length: text.utf16.count)
  188. return regex?.firstMatch(in: text, options: [], range: range) != nil
  189. }
  190. /// Provides simple environment guidance for APNS configuration
  191. /// - Returns: String with simple guidance to try opposite setting
  192. private func getEnvironmentGuidance() -> String {
  193. let currentSetting = storage.productionEnvironment.value ? "ON" : "OFF"
  194. let trySetting = storage.productionEnvironment.value ? "OFF" : "ON"
  195. return "Try changing Production Environment from \(currentSetting) to \(trySetting) in your Loop APNS settings."
  196. }
  197. /// Sends an APNS notification
  198. /// - Parameters:
  199. /// - deviceToken: The device token to send to
  200. /// - bundleIdentifier: The bundle identifier
  201. /// - keyId: The APNS key ID
  202. /// - apnsKey: The APNS key
  203. /// - payload: The notification payload
  204. /// - completion: Completion handler with success status and error message
  205. private func sendAPNSNotification(
  206. deviceToken: String,
  207. bundleIdentifier: String,
  208. keyId: String,
  209. apnsKey: String,
  210. payload: [String: Any],
  211. completion: @escaping (Bool, String?) -> Void
  212. ) {
  213. // Validate credentials first
  214. if let validationErrors = validateCredentials() {
  215. let errorMessage = "Credential validation failed: \(validationErrors.joined(separator: ", "))"
  216. LogManager.shared.log(category: .apns, message: errorMessage)
  217. completion(false, errorMessage)
  218. return
  219. }
  220. // Create JWT token for APNS authentication
  221. guard let jwt = JWTManager.shared.getOrGenerateJWT(keyId: keyId, teamId: Storage.shared.teamId.value ?? "", apnsKey: apnsKey) else {
  222. let errorMessage = "Failed to generate JWT, please check that the APNS Key ID, APNS Key and Team ID are correct."
  223. LogManager.shared.log(category: .apns, message: errorMessage)
  224. completion(false, errorMessage)
  225. return
  226. }
  227. // Determine APNS environment
  228. let isProduction = storage.productionEnvironment.value
  229. let apnsURL = isProduction ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"
  230. guard let requestURL = URL(string: "\(apnsURL)/3/device/\(deviceToken)") else {
  231. let errorMessage = "Failed to construct APNs URL"
  232. LogManager.shared.log(category: .apns, message: errorMessage)
  233. completion(false, errorMessage)
  234. return
  235. }
  236. var request = URLRequest(url: requestURL)
  237. request.httpMethod = "POST"
  238. request.setValue("application/json", forHTTPHeaderField: "content-type")
  239. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  240. request.setValue(bundleIdentifier, forHTTPHeaderField: "apns-topic")
  241. request.setValue("alert", forHTTPHeaderField: "apns-push-type")
  242. request.setValue("10", forHTTPHeaderField: "apns-priority") // High priority
  243. // Validate bundle identifier format
  244. if !bundleIdentifier.contains(".") {
  245. LogManager.shared.log(category: .apns, message: "Warning: Bundle identifier may be in wrong format: \(bundleIdentifier)")
  246. }
  247. // Create the proper APNS payload structure (matching @parse/node-apn format)
  248. var apnsPayload: [String: Any] = [
  249. "aps": [
  250. "alert": payload["alert"] as? String ?? "",
  251. "content-available": 1,
  252. "interruption-level": "time-sensitive",
  253. ],
  254. ]
  255. // Add all the custom payload fields (excluding APNS-specific fields)
  256. for (key, value) in payload {
  257. if key != "alert", key != "content-available", key != "interruption-level" {
  258. apnsPayload[key] = value
  259. }
  260. }
  261. // Remove nil values to clean up the payload
  262. let cleanPayload = apnsPayload.compactMapValues { $0 }
  263. do {
  264. let jsonData = try JSONSerialization.data(withJSONObject: cleanPayload)
  265. request.httpBody = jsonData
  266. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  267. if let error = error {
  268. let errorMessage = "Failed to send push notification: \(error.localizedDescription)"
  269. LogManager.shared.log(category: .apns, message: errorMessage)
  270. completion(false, errorMessage)
  271. return
  272. }
  273. if let httpResponse = response as? HTTPURLResponse {
  274. var responseBodyMessage = ""
  275. if let data = data, let responseBody = String(data: data, encoding: .utf8) {
  276. if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  277. let reason = json["reason"] as? String
  278. {
  279. responseBodyMessage = reason
  280. }
  281. }
  282. switch httpResponse.statusCode {
  283. case 200:
  284. LogManager.shared.log(category: .apns, message: "APNS notification sent successfully")
  285. completion(true, nil)
  286. case 400:
  287. let environmentGuidance = self.getEnvironmentGuidance()
  288. let errorMessage = "Bad request. The request was invalid or malformed. \(responseBodyMessage)\n\n\(environmentGuidance)"
  289. LogManager.shared.log(category: .apns, message: "APNS error 400: \(responseBodyMessage) - Check device token and environment settings")
  290. completion(false, errorMessage)
  291. case 403:
  292. let errorMessage = "Authentication error. Check your certificate or authentication token. \(responseBodyMessage)"
  293. LogManager.shared.log(category: .apns, message: "APNS error 403: \(responseBodyMessage) - Check APNS key permissions for bundle ID")
  294. completion(false, errorMessage)
  295. case 404:
  296. let errorMessage = "Invalid request: The :path value was incorrect. \(responseBodyMessage)"
  297. LogManager.shared.log(category: .apns, message: "APNS error 404: \(responseBodyMessage)")
  298. completion(false, errorMessage)
  299. case 405:
  300. let errorMessage = "Invalid request: Only POST requests are supported. \(responseBodyMessage)"
  301. LogManager.shared.log(category: .apns, message: "APNS error 405: \(responseBodyMessage)")
  302. completion(false, errorMessage)
  303. case 410:
  304. let errorMessage = "The device token is no longer active for the topic. \(responseBodyMessage)"
  305. LogManager.shared.log(category: .apns, message: "APNS error 410: Device token is invalid or expired")
  306. completion(false, errorMessage)
  307. case 413:
  308. let errorMessage = "Payload too large. The notification payload exceeded the size limit. \(responseBodyMessage)"
  309. LogManager.shared.log(category: .apns, message: "APNS error 413: \(responseBodyMessage)")
  310. completion(false, errorMessage)
  311. case 429:
  312. let errorMessage = "Too many requests. \(responseBodyMessage)"
  313. LogManager.shared.log(category: .apns, message: "APNS error 429: Rate limited - wait before retrying")
  314. completion(false, errorMessage)
  315. case 500:
  316. let errorMessage = "Internal server error at APNs. \(responseBodyMessage)"
  317. LogManager.shared.log(category: .apns, message: "APNS error 500: \(responseBodyMessage)")
  318. completion(false, errorMessage)
  319. case 503:
  320. let errorMessage = "Service unavailable. The server is temporarily unavailable. Try again later. \(responseBodyMessage)"
  321. LogManager.shared.log(category: .apns, message: "APNS error 503: \(responseBodyMessage)")
  322. completion(false, errorMessage)
  323. default:
  324. let errorMessage = "Unexpected status code: \(httpResponse.statusCode). \(responseBodyMessage)"
  325. LogManager.shared.log(category: .apns, message: "APNS error \(httpResponse.statusCode): \(responseBodyMessage)")
  326. completion(false, errorMessage)
  327. }
  328. } else {
  329. let errorMessage = "Failed to get a valid HTTP response."
  330. LogManager.shared.log(category: .apns, message: errorMessage)
  331. completion(false, errorMessage)
  332. }
  333. }
  334. task.resume()
  335. } catch {
  336. let errorMessage = "Failed to serialize APNS payload: \(error.localizedDescription)"
  337. LogManager.shared.log(category: .apns, message: errorMessage)
  338. completion(false, errorMessage)
  339. }
  340. }
  341. /// Validates and fixes APNS key format if needed
  342. /// - Parameter key: The APNS key to validate and fix
  343. /// - Returns: The fixed APNS key
  344. func validateAndFixAPNSKey(_ key: String) -> String {
  345. // Normalize: replace all literal \n with real newlines
  346. var fixedKey = key.replacingOccurrences(of: "\\n", with: "\n")
  347. // Strip leading/trailing quotes
  348. fixedKey = fixedKey.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
  349. // Check if the key has proper line breaks
  350. if !fixedKey.contains("\n") {
  351. LogManager.shared.log(category: .apns, message: "APNS Key missing line breaks, attempting to fix format")
  352. // Try to add line breaks if the key is all on one line
  353. if fixedKey.contains("-----BEGIN PRIVATE KEY-----") && fixedKey.contains("-----END PRIVATE KEY-----") {
  354. // Find the positions of the headers
  355. if let beginRange = fixedKey.range(of: "-----BEGIN PRIVATE KEY-----"),
  356. let endRange = fixedKey.range(of: "-----END PRIVATE KEY-----")
  357. {
  358. let beginIndex = fixedKey.index(beginRange.upperBound, offsetBy: 0)
  359. let endIndex = endRange.lowerBound
  360. if beginIndex < endIndex {
  361. let header = String(fixedKey[..<beginIndex])
  362. let keyData = String(fixedKey[beginIndex ..< endIndex])
  363. let footer = String(fixedKey[endIndex...])
  364. // Clean up the key data - remove any whitespace and split into 64-character lines
  365. let cleanKeyData = keyData.replacingOccurrences(of: " ", with: "")
  366. .replacingOccurrences(of: "\t", with: "")
  367. .replacingOccurrences(of: "\n", with: "")
  368. .replacingOccurrences(of: "\r", with: "")
  369. // Validate the key data length (should be 44 characters for P-256)
  370. LogManager.shared.log(category: .apns, message: "Key data validation - Length: \(cleanKeyData.count) characters")
  371. if cleanKeyData.count != 44 {
  372. LogManager.shared.log(category: .apns, message: "WARNING: Key data length is \(cleanKeyData.count), expected 44 for P-256 private key")
  373. }
  374. // Validate base64 format
  375. if Data(base64Encoded: cleanKeyData) == nil {
  376. LogManager.shared.log(category: .apns, message: "WARNING: Key data is not valid base64")
  377. }
  378. // Split into 64-character lines (standard PEM format)
  379. var formattedKeyData = ""
  380. var currentLine = ""
  381. for char in cleanKeyData {
  382. currentLine.append(char)
  383. if currentLine.count == 64 {
  384. formattedKeyData += currentLine + "\n"
  385. currentLine = ""
  386. }
  387. }
  388. // Add any remaining characters
  389. if !currentLine.isEmpty {
  390. formattedKeyData += currentLine
  391. }
  392. fixedKey = "\(header)\n\(formattedKeyData)\n\(footer)"
  393. LogManager.shared.log(category: .apns, message: "APNS Key format fixed - added proper line breaks")
  394. LogManager.shared.log(category: .apns, message: "Key data length: \(cleanKeyData.count) characters")
  395. LogManager.shared.log(category: .apns, message: "Formatted key lines: \(formattedKeyData.components(separatedBy: "\n").count)")
  396. }
  397. }
  398. }
  399. } else {
  400. // Key already has line breaks, but let's ensure proper formatting
  401. let lines = fixedKey.components(separatedBy: .newlines)
  402. var cleanedLines: [String] = []
  403. for line in lines {
  404. let cleanedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
  405. if !cleanedLine.isEmpty {
  406. cleanedLines.append(cleanedLine)
  407. }
  408. }
  409. // Reconstruct with proper formatting
  410. if cleanedLines.count > 2 {
  411. let header = cleanedLines[0]
  412. let footer = cleanedLines[cleanedLines.count - 1]
  413. let keyLines = Array(cleanedLines[1 ..< (cleanedLines.count - 1)])
  414. // Combine all key data lines and validate
  415. let combinedKeyData = keyLines.joined()
  416. LogManager.shared.log(category: .apns, message: "Combined key data length: \(combinedKeyData.count) characters")
  417. // Validate the key data length (should be 44 characters for P-256)
  418. if combinedKeyData.count != 44 {
  419. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data length is \(combinedKeyData.count), expected 44 for P-256 private key")
  420. }
  421. // Validate base64 format
  422. if Data(base64Encoded: combinedKeyData) == nil {
  423. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data is not valid base64")
  424. }
  425. // Ensure key lines are properly formatted (64 characters each)
  426. var formattedKeyLines: [String] = []
  427. var currentLine = ""
  428. for line in keyLines {
  429. let cleanLine = line.replacingOccurrences(of: " ", with: "")
  430. .replacingOccurrences(of: "\t", with: "")
  431. for char in cleanLine {
  432. currentLine.append(char)
  433. if currentLine.count == 64 {
  434. formattedKeyLines.append(currentLine)
  435. currentLine = ""
  436. }
  437. }
  438. }
  439. // Add any remaining characters
  440. if !currentLine.isEmpty {
  441. formattedKeyLines.append(currentLine)
  442. }
  443. fixedKey = "\(header)\n\(formattedKeyLines.joined(separator: "\n"))\n\(footer)"
  444. LogManager.shared.log(category: .apns, message: "APNS Key reformatted - cleaned up existing line breaks")
  445. }
  446. }
  447. return fixedKey
  448. }
  449. /// Extracts key data from PEM format
  450. /// - Parameter pemString: The PEM formatted private key
  451. /// - Returns: The extracted key data string
  452. private func extractKeyData(from pemString: String) -> String? {
  453. let lines = pemString.components(separatedBy: "\n")
  454. guard let startIndex = lines.firstIndex(of: "-----BEGIN PRIVATE KEY-----"),
  455. let endIndex = lines.firstIndex(of: "-----END PRIVATE KEY-----"),
  456. startIndex < endIndex
  457. else {
  458. return nil
  459. }
  460. let keyLines = lines[(startIndex + 1) ..< endIndex]
  461. return keyLines.joined()
  462. }
  463. // MARK: - Date Formatting Helper
  464. /// Creates a properly formatted ISO8601 date string with milliseconds (matching Nightscout's format)
  465. /// - Parameter date: The date to format
  466. /// - Returns: Formatted date string like "2022-12-24T21:34:02.090Z"
  467. private func formatDateForAPNS(_ date: Date) -> String {
  468. let dateFormatter = ISO8601DateFormatter()
  469. dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  470. return dateFormatter.string(from: date)
  471. }
  472. // MARK: - Override Methods
  473. func sendOverrideNotification(presetName: String, duration: TimeInterval? = nil, completion: @escaping (Bool, String?) -> Void) {
  474. let deviceToken = Storage.shared.deviceToken.value
  475. guard !deviceToken.isEmpty else {
  476. let errorMessage = "Device token not configured"
  477. LogManager.shared.log(category: .apns, message: errorMessage)
  478. completion(false, errorMessage)
  479. return
  480. }
  481. let bundleIdentifier = Storage.shared.bundleId.value
  482. guard !bundleIdentifier.isEmpty else {
  483. let errorMessage = "Bundle identifier not configured"
  484. LogManager.shared.log(category: .apns, message: errorMessage)
  485. completion(false, errorMessage)
  486. return
  487. }
  488. // Create APNS notification payload (matching Loop's expected format)
  489. let now = Date()
  490. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  491. // Create alert text (matching Nightscout's format)
  492. var alertText = "\(presetName) Temporary Override"
  493. if let duration = duration, duration > 0 {
  494. let hours = Int(duration / 3600)
  495. let minutes = Int((duration.truncatingRemainder(dividingBy: 3600)) / 60)
  496. if hours > 0 {
  497. alertText += " (\(hours)h \(minutes)m)"
  498. } else {
  499. alertText += " (\(minutes)m)"
  500. }
  501. }
  502. var payload: [String: Any] = [
  503. "override-name": presetName,
  504. "remote-address": "LoopFollow",
  505. "entered-by": "LoopFollow",
  506. "sent-at": formatDateForAPNS(now),
  507. "expiration": formatDateForAPNS(expiration),
  508. "alert": alertText,
  509. ]
  510. if let duration = duration, duration > 0 {
  511. payload["override-duration-minutes"] = Int(duration / 60)
  512. }
  513. // Send the notification using the existing APNS infrastructure
  514. sendAPNSNotification(
  515. deviceToken: deviceToken,
  516. bundleIdentifier: bundleIdentifier,
  517. keyId: storage.keyId.value,
  518. apnsKey: storage.apnsKey.value,
  519. payload: payload,
  520. completion: completion
  521. )
  522. }
  523. func sendCancelOverrideNotification(completion: @escaping (Bool, String?) -> Void) {
  524. let deviceToken = Storage.shared.deviceToken.value
  525. guard !deviceToken.isEmpty else {
  526. let errorMessage = "Device token not configured"
  527. LogManager.shared.log(category: .apns, message: errorMessage)
  528. completion(false, errorMessage)
  529. return
  530. }
  531. let bundleIdentifier = Storage.shared.bundleId.value
  532. guard !bundleIdentifier.isEmpty else {
  533. let errorMessage = "Bundle identifier not configured"
  534. LogManager.shared.log(category: .apns, message: errorMessage)
  535. completion(false, errorMessage)
  536. return
  537. }
  538. // Create APNS notification payload (matching Loop's expected format)
  539. let now = Date()
  540. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  541. let payload: [String: Any] = [
  542. "cancel-temporary-override": "true",
  543. "remote-address": "LoopFollow",
  544. "entered-by": "LoopFollow",
  545. "sent-at": formatDateForAPNS(now),
  546. "expiration": formatDateForAPNS(expiration),
  547. "alert": "Cancel Temporary Override",
  548. ]
  549. // Send the notification using the existing APNS infrastructure
  550. sendAPNSNotification(
  551. deviceToken: deviceToken,
  552. bundleIdentifier: bundleIdentifier,
  553. keyId: storage.keyId.value,
  554. apnsKey: storage.apnsKey.value,
  555. payload: payload,
  556. completion: completion
  557. )
  558. }
  559. }