LoopAPNSService.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. /// - Parameter payload: The carbs payload to send
  62. /// - Returns: True if successful, false otherwise
  63. func sendCarbsViaAPNS(payload: LoopAPNSPayload) async throws -> Bool {
  64. guard validateSetup() else {
  65. throw LoopAPNSError.invalidConfiguration
  66. }
  67. let deviceToken = Storage.shared.deviceToken.value
  68. let bundleIdentifier = Storage.shared.bundleId.value
  69. let keyId = storage.keyId.value
  70. let apnsKey = storage.apnsKey.value
  71. // Create APNS notification payload (matching Loop's expected format)
  72. let now = Date()
  73. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  74. // Create the complete notification payload (matching Nightscout's exact format)
  75. // Based on Nightscout's loop.js implementation
  76. let carbsAmount = payload.carbsAmount ?? 0.0
  77. let absorptionTime = payload.absorptionTime ?? 3.0
  78. let startTime = payload.consumedDate ?? now
  79. let finalPayload = [
  80. "carbs-entry": carbsAmount,
  81. "absorption-time": absorptionTime,
  82. "otp": String(payload.otp),
  83. "remote-address": "LoopFollow",
  84. "notes": "Sent via LoopFollow APNS",
  85. "entered-by": "LoopFollow",
  86. "sent-at": formatDateForAPNS(now),
  87. "expiration": formatDateForAPNS(expiration),
  88. "start-time": formatDateForAPNS(startTime),
  89. "alert": "Remote Carbs Entry: \(String(format: "%.1f", carbsAmount)) grams\nAbsorption Time: \(String(format: "%.1f", absorptionTime)) hours",
  90. ] as [String: Any]
  91. // Log the exact carbs amount for debugging precision issues
  92. LogManager.shared.log(category: .apns, message: "Carbs amount - Raw: \(payload.carbsAmount ?? 0.0), Formatted: \(String(format: "%.1f", carbsAmount)), JSON: \(carbsAmount)")
  93. LogManager.shared.log(category: .apns, message: "Absorption time - Raw: \(payload.absorptionTime ?? 3.0), Formatted: \(String(format: "%.1f", absorptionTime)), JSON: \(absorptionTime)")
  94. // Log the final payload for debugging
  95. if let payloadData = try? JSONSerialization.data(withJSONObject: finalPayload),
  96. let payloadString = String(data: payloadData, encoding: .utf8)
  97. {
  98. LogManager.shared.log(category: .apns, message: "Final payload being sent: \(payloadString)")
  99. }
  100. return try await sendAPNSNotification(
  101. deviceToken: deviceToken,
  102. bundleIdentifier: bundleIdentifier,
  103. keyId: keyId,
  104. apnsKey: apnsKey,
  105. payload: finalPayload
  106. )
  107. }
  108. /// Sends bolus via APNS push notification
  109. /// - Parameter payload: The bolus payload to send
  110. /// - Returns: True if successful, false otherwise
  111. func sendBolusViaAPNS(payload: LoopAPNSPayload) async throws -> Bool {
  112. guard validateSetup() else {
  113. throw LoopAPNSError.invalidConfiguration
  114. }
  115. let deviceToken = Storage.shared.deviceToken.value
  116. let bundleIdentifier = Storage.shared.bundleId.value
  117. let keyId = storage.keyId.value
  118. let apnsKey = storage.apnsKey.value
  119. // Create APNS notification payload (matching Loop's expected format)
  120. let now = Date()
  121. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  122. // Create the complete notification payload (matching Nightscout's exact format)
  123. // Based on Nightscout's loop.js implementation
  124. let bolusAmount = payload.bolusAmount ?? 0.0
  125. let finalPayload = [
  126. "bolus-entry": bolusAmount,
  127. "otp": String(payload.otp),
  128. "remote-address": "LoopFollow",
  129. "notes": "Sent via LoopFollow APNS",
  130. "entered-by": "LoopFollow",
  131. "sent-at": formatDateForAPNS(now),
  132. "expiration": formatDateForAPNS(expiration),
  133. "alert": "Remote Bolus Entry: \(String(format: "%.2f", bolusAmount)) U",
  134. ] as [String: Any]
  135. // Log the exact bolus amount for debugging precision issues
  136. LogManager.shared.log(category: .apns, message: "Bolus amount - Raw: \(payload.bolusAmount ?? 0.0), Formatted: \(String(format: "%.2f", bolusAmount)), JSON: \(bolusAmount)")
  137. // Log the final payload for debugging
  138. if let payloadData = try? JSONSerialization.data(withJSONObject: finalPayload),
  139. let payloadString = String(data: payloadData, encoding: .utf8)
  140. {
  141. LogManager.shared.log(category: .apns, message: "Final payload being sent: \(payloadString)")
  142. }
  143. return try await sendAPNSNotification(
  144. deviceToken: deviceToken,
  145. bundleIdentifier: bundleIdentifier,
  146. keyId: keyId,
  147. apnsKey: apnsKey,
  148. payload: finalPayload
  149. )
  150. }
  151. /// Sends an APNS notification
  152. /// - Parameters:
  153. /// - deviceToken: The device token to send to
  154. /// - bundleIdentifier: The bundle identifier
  155. /// - keyId: The APNS key ID
  156. /// - apnsKey: The APNS key
  157. /// - payload: The notification payload
  158. /// - Returns: True if successful, false otherwise
  159. private func sendAPNSNotification(
  160. deviceToken: String,
  161. bundleIdentifier: String,
  162. keyId: String,
  163. apnsKey: String,
  164. payload: [String: Any]
  165. ) async throws -> Bool {
  166. // Create JWT token for APNS authentication
  167. guard let jwt = JWTManager.shared.getOrGenerateJWT(keyId: keyId, teamId: Storage.shared.teamId.value ?? "", apnsKey: apnsKey) else {
  168. LogManager.shared.log(category: .apns, message: "Failed to create JWT using JWTManager. Check APNS credentials.")
  169. throw LoopAPNSError.jwtError
  170. }
  171. // Determine APNS environment
  172. let isProduction = storage.productionEnvironment.value
  173. let apnsURL = isProduction ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"
  174. let requestURL = URL(string: "\(apnsURL)/3/device/\(deviceToken)")!
  175. var request = URLRequest(url: requestURL)
  176. request.httpMethod = "POST"
  177. request.setValue("application/json", forHTTPHeaderField: "content-type")
  178. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  179. request.setValue(bundleIdentifier, forHTTPHeaderField: "apns-topic")
  180. request.setValue("alert", forHTTPHeaderField: "apns-push-type")
  181. request.setValue("10", forHTTPHeaderField: "apns-priority") // High priority
  182. // Log request details for debugging
  183. LogManager.shared.log(category: .apns, message: "APNS Request URL: \(requestURL)")
  184. LogManager.shared.log(category: .apns, message: "APNS Request Headers - Authorization: Bearer \(jwt.prefix(50))..., Topic: \(bundleIdentifier)")
  185. // Validate bundle identifier format
  186. if !bundleIdentifier.contains(".") {
  187. LogManager.shared.log(category: .apns, message: "Warning: Bundle identifier may be in wrong format: \(bundleIdentifier)")
  188. }
  189. // Validate device token format (should be 64 hex characters)
  190. let deviceTokenLength = deviceToken.count
  191. let isHexToken = deviceToken.range(of: "^[0-9A-Fa-f]{64}$", options: .regularExpression) != nil
  192. LogManager.shared.log(category: .apns, message: "Device token validation - Length: \(deviceTokenLength), Is hex: \(isHexToken)")
  193. // Create the proper APNS payload structure (matching @parse/node-apn format)
  194. var apnsPayload: [String: Any] = [
  195. "aps": [
  196. "alert": payload["alert"] as? String ?? "",
  197. "content-available": 1,
  198. "interruption-level": "time-sensitive",
  199. ],
  200. ]
  201. // Add all the custom payload fields (excluding APNS-specific fields)
  202. for (key, value) in payload {
  203. if key != "alert" && key != "content-available" && key != "interruption-level" {
  204. apnsPayload[key] = value
  205. }
  206. }
  207. // Remove nil values to clean up the payload
  208. let cleanPayload = apnsPayload.compactMapValues { $0 }
  209. let jsonData: Data
  210. do {
  211. jsonData = try JSONSerialization.data(withJSONObject: cleanPayload)
  212. LogManager.shared.log(category: .apns, message: "APNS payload serialized successfully, size: \(jsonData.count) bytes")
  213. // Log the actual payload being sent
  214. if let payloadString = String(data: jsonData, encoding: .utf8) {
  215. LogManager.shared.log(category: .apns, message: "APNS payload being sent: \(payloadString)")
  216. }
  217. } catch {
  218. LogManager.shared.log(category: .apns, message: "Failed to serialize APNS payload: \(error.localizedDescription)")
  219. throw LoopAPNSError.invalidConfiguration
  220. }
  221. request.httpBody = jsonData
  222. do {
  223. let (data, response) = try await URLSession.shared.data(for: request)
  224. if let httpResponse = response as? HTTPURLResponse {
  225. switch httpResponse.statusCode {
  226. case 200:
  227. LogManager.shared.log(category: .apns, message: "APNS notification sent successfully")
  228. return true
  229. case 400:
  230. let errorResponse = String(data: data, encoding: .utf8) ?? "Unknown error"
  231. LogManager.shared.log(category: .apns, message: "APNS error 400: \(errorResponse)")
  232. LogManager.shared.log(category: .apns, message: "BadDeviceToken error - this usually means:")
  233. LogManager.shared.log(category: .apns, message: "1. Device token is expired or invalid")
  234. LogManager.shared.log(category: .apns, message: "2. Device token is from different environment (dev vs prod)")
  235. LogManager.shared.log(category: .apns, message: "3. Device token is not registered for this bundle identifier")
  236. LogManager.shared.log(category: .apns, message: "Troubleshooting steps:")
  237. LogManager.shared.log(category: .apns, message: "1. Refresh device token from Loop app")
  238. LogManager.shared.log(category: .apns, message: "2. Check if Loop app is using same environment (dev/prod)")
  239. LogManager.shared.log(category: .apns, message: "3. Verify device token is for bundle ID: \(bundleIdentifier)")
  240. LogManager.shared.log(category: .apns, message: "4. Check if device token is from production environment")
  241. LogManager.shared.log(category: .apns, message: "Current environment: \(storage.productionEnvironment.value ? "Production" : "Development")")
  242. throw LoopAPNSError.invalidResponse
  243. case 403:
  244. let errorResponse = String(data: data, encoding: .utf8) ?? "Unknown error"
  245. LogManager.shared.log(category: .apns, message: "APNS error 403: Forbidden - \(errorResponse)")
  246. LogManager.shared.log(category: .apns, message: "This usually means the APNS key doesn't have permissions for this bundle ID")
  247. LogManager.shared.log(category: .apns, message: "Troubleshooting steps:")
  248. LogManager.shared.log(category: .apns, message: "1. Check that APNS key \(keyId) has 'Apple Push Notifications service (APNs)' capability enabled")
  249. LogManager.shared.log(category: .apns, message: "2. Check that bundle ID \(bundleIdentifier) has 'Push Notifications' capability enabled")
  250. LogManager.shared.log(category: .apns, message: "3. Verify the APNS key is associated with the bundle ID in Apple Developer account")
  251. throw LoopAPNSError.unauthorized
  252. case 410:
  253. LogManager.shared.log(category: .apns, message: "APNS error 410: Device token is invalid or expired")
  254. throw LoopAPNSError.noDeviceToken
  255. case 429:
  256. let errorResponse = String(data: data, encoding: .utf8) ?? "Unknown error"
  257. LogManager.shared.log(category: .apns, message: "APNS error 429: Too Many Requests - \(errorResponse)")
  258. LogManager.shared.log(category: .apns, message: "Rate limiting error - Apple is throttling APNS requests")
  259. LogManager.shared.log(category: .apns, message: "Troubleshooting steps:")
  260. LogManager.shared.log(category: .apns, message: "1. Wait a few minutes before trying again")
  261. LogManager.shared.log(category: .apns, message: "2. Check if you're sending too many notifications too quickly")
  262. LogManager.shared.log(category: .apns, message: "3. Consider implementing exponential backoff")
  263. throw LoopAPNSError.rateLimited
  264. default:
  265. let errorResponse = String(data: data, encoding: .utf8) ?? "Unknown error"
  266. LogManager.shared.log(category: .apns, message: "APNS error \(httpResponse.statusCode): \(errorResponse)")
  267. throw LoopAPNSError.networkError
  268. }
  269. } else {
  270. throw LoopAPNSError.networkError
  271. }
  272. } catch {
  273. LogManager.shared.log(category: .apns, message: "APNS request failed: \(error.localizedDescription)")
  274. throw LoopAPNSError.networkError
  275. }
  276. }
  277. /// Validates and fixes APNS key format if needed
  278. /// - Parameter key: The APNS key to validate and fix
  279. /// - Returns: The fixed APNS key
  280. func validateAndFixAPNSKey(_ key: String) -> String {
  281. // Normalize: replace all literal \n with real newlines
  282. var fixedKey = key.replacingOccurrences(of: "\\n", with: "\n")
  283. // Strip leading/trailing quotes
  284. fixedKey = fixedKey.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
  285. // Check if the key has proper line breaks
  286. if !fixedKey.contains("\n") {
  287. LogManager.shared.log(category: .apns, message: "APNS Key missing line breaks, attempting to fix format")
  288. // Try to add line breaks if the key is all on one line
  289. if fixedKey.contains("-----BEGIN PRIVATE KEY-----") && fixedKey.contains("-----END PRIVATE KEY-----") {
  290. // Find the positions of the headers
  291. if let beginRange = fixedKey.range(of: "-----BEGIN PRIVATE KEY-----"),
  292. let endRange = fixedKey.range(of: "-----END PRIVATE KEY-----")
  293. {
  294. let beginIndex = fixedKey.index(beginRange.upperBound, offsetBy: 0)
  295. let endIndex = endRange.lowerBound
  296. if beginIndex < endIndex {
  297. let header = String(fixedKey[..<beginIndex])
  298. let keyData = String(fixedKey[beginIndex ..< endIndex])
  299. let footer = String(fixedKey[endIndex...])
  300. // Clean up the key data - remove any whitespace and split into 64-character lines
  301. let cleanKeyData = keyData.replacingOccurrences(of: " ", with: "")
  302. .replacingOccurrences(of: "\t", with: "")
  303. .replacingOccurrences(of: "\n", with: "")
  304. .replacingOccurrences(of: "\r", with: "")
  305. // Validate the key data length (should be 44 characters for P-256)
  306. LogManager.shared.log(category: .apns, message: "Key data validation - Length: \(cleanKeyData.count) characters")
  307. if cleanKeyData.count != 44 {
  308. LogManager.shared.log(category: .apns, message: "WARNING: Key data length is \(cleanKeyData.count), expected 44 for P-256 private key")
  309. }
  310. // Validate base64 format
  311. if Data(base64Encoded: cleanKeyData) == nil {
  312. LogManager.shared.log(category: .apns, message: "WARNING: Key data is not valid base64")
  313. }
  314. // Split into 64-character lines (standard PEM format)
  315. var formattedKeyData = ""
  316. var currentLine = ""
  317. for char in cleanKeyData {
  318. currentLine.append(char)
  319. if currentLine.count == 64 {
  320. formattedKeyData += currentLine + "\n"
  321. currentLine = ""
  322. }
  323. }
  324. // Add any remaining characters
  325. if !currentLine.isEmpty {
  326. formattedKeyData += currentLine
  327. }
  328. fixedKey = "\(header)\n\(formattedKeyData)\n\(footer)"
  329. LogManager.shared.log(category: .apns, message: "APNS Key format fixed - added proper line breaks")
  330. LogManager.shared.log(category: .apns, message: "Key data length: \(cleanKeyData.count) characters")
  331. LogManager.shared.log(category: .apns, message: "Formatted key lines: \(formattedKeyData.components(separatedBy: "\n").count)")
  332. }
  333. }
  334. }
  335. } else {
  336. // Key already has line breaks, but let's ensure proper formatting
  337. let lines = fixedKey.components(separatedBy: .newlines)
  338. var cleanedLines: [String] = []
  339. for line in lines {
  340. let cleanedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
  341. if !cleanedLine.isEmpty {
  342. cleanedLines.append(cleanedLine)
  343. }
  344. }
  345. // Reconstruct with proper formatting
  346. if cleanedLines.count > 2 {
  347. let header = cleanedLines[0]
  348. let footer = cleanedLines[cleanedLines.count - 1]
  349. let keyLines = Array(cleanedLines[1 ..< (cleanedLines.count - 1)])
  350. // Combine all key data lines and validate
  351. let combinedKeyData = keyLines.joined()
  352. LogManager.shared.log(category: .apns, message: "Combined key data length: \(combinedKeyData.count) characters")
  353. // Validate the key data length (should be 44 characters for P-256)
  354. if combinedKeyData.count != 44 {
  355. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data length is \(combinedKeyData.count), expected 44 for P-256 private key")
  356. }
  357. // Validate base64 format
  358. if Data(base64Encoded: combinedKeyData) == nil {
  359. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data is not valid base64")
  360. }
  361. // Ensure key lines are properly formatted (64 characters each)
  362. var formattedKeyLines: [String] = []
  363. var currentLine = ""
  364. for line in keyLines {
  365. let cleanLine = line.replacingOccurrences(of: " ", with: "")
  366. .replacingOccurrences(of: "\t", with: "")
  367. for char in cleanLine {
  368. currentLine.append(char)
  369. if currentLine.count == 64 {
  370. formattedKeyLines.append(currentLine)
  371. currentLine = ""
  372. }
  373. }
  374. }
  375. // Add any remaining characters
  376. if !currentLine.isEmpty {
  377. formattedKeyLines.append(currentLine)
  378. }
  379. fixedKey = "\(header)\n\(formattedKeyLines.joined(separator: "\n"))\n\(footer)"
  380. LogManager.shared.log(category: .apns, message: "APNS Key reformatted - cleaned up existing line breaks")
  381. }
  382. }
  383. return fixedKey
  384. }
  385. /// Extracts key data from PEM format
  386. /// - Parameter pemString: The PEM formatted private key
  387. /// - Returns: The extracted key data string
  388. private func extractKeyData(from pemString: String) -> String? {
  389. let lines = pemString.components(separatedBy: "\n")
  390. guard let startIndex = lines.firstIndex(of: "-----BEGIN PRIVATE KEY-----"),
  391. let endIndex = lines.firstIndex(of: "-----END PRIVATE KEY-----"),
  392. startIndex < endIndex
  393. else {
  394. return nil
  395. }
  396. let keyLines = lines[(startIndex + 1) ..< endIndex]
  397. return keyLines.joined()
  398. }
  399. // MARK: - Date Formatting Helper
  400. /// Creates a properly formatted ISO8601 date string with milliseconds (matching Nightscout's format)
  401. /// - Parameter date: The date to format
  402. /// - Returns: Formatted date string like "2022-12-24T21:34:02.090Z"
  403. private func formatDateForAPNS(_ date: Date) -> String {
  404. let dateFormatter = ISO8601DateFormatter()
  405. dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  406. return dateFormatter.string(from: date)
  407. }
  408. // MARK: - Override Methods
  409. func sendOverrideNotification(presetName: String, duration: TimeInterval? = nil) async throws {
  410. let deviceToken = Storage.shared.deviceToken.value
  411. guard !deviceToken.isEmpty else {
  412. throw LoopAPNSError.deviceTokenNotConfigured
  413. }
  414. let bundleIdentifier = Storage.shared.bundleId.value
  415. guard !bundleIdentifier.isEmpty else {
  416. throw LoopAPNSError.bundleIdentifierNotConfigured
  417. }
  418. // Create APNS notification payload (matching Loop's expected format)
  419. let now = Date()
  420. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  421. // Create alert text (matching Nightscout's format)
  422. var alertText = "\(presetName) Temporary Override"
  423. if let duration = duration, duration > 0 {
  424. let hours = Int(duration / 3600)
  425. let minutes = Int((duration.truncatingRemainder(dividingBy: 3600)) / 60)
  426. if hours > 0 {
  427. alertText += " (\(hours)h \(minutes)m)"
  428. } else {
  429. alertText += " (\(minutes)m)"
  430. }
  431. }
  432. var payload: [String: Any] = [
  433. "override-name": presetName,
  434. "remote-address": "LoopFollow",
  435. "entered-by": "LoopFollow",
  436. "sent-at": formatDateForAPNS(now),
  437. "expiration": formatDateForAPNS(expiration),
  438. "alert": alertText,
  439. ]
  440. if let duration = duration, duration > 0 {
  441. payload["override-duration-minutes"] = Int(duration / 60)
  442. }
  443. // Send the notification using the existing APNS infrastructure
  444. try await sendAPNSNotification(
  445. deviceToken: deviceToken,
  446. bundleIdentifier: bundleIdentifier,
  447. keyId: storage.keyId.value,
  448. apnsKey: storage.apnsKey.value,
  449. payload: payload
  450. )
  451. }
  452. func sendCancelOverrideNotification() async throws {
  453. let deviceToken = Storage.shared.deviceToken.value
  454. guard !deviceToken.isEmpty else {
  455. throw LoopAPNSError.deviceTokenNotConfigured
  456. }
  457. let bundleIdentifier = Storage.shared.bundleId.value
  458. guard !bundleIdentifier.isEmpty else {
  459. throw LoopAPNSError.bundleIdentifierNotConfigured
  460. }
  461. // Create APNS notification payload (matching Loop's expected format)
  462. let now = Date()
  463. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  464. let payload: [String: Any] = [
  465. "cancel-temporary-override": "true",
  466. "remote-address": "LoopFollow",
  467. "entered-by": "LoopFollow",
  468. "sent-at": formatDateForAPNS(now),
  469. "expiration": formatDateForAPNS(expiration),
  470. "alert": "Cancel Temporary Override",
  471. ]
  472. // Send the notification using the existing APNS infrastructure
  473. try await sendAPNSNotification(
  474. deviceToken: deviceToken,
  475. bundleIdentifier: bundleIdentifier,
  476. keyId: storage.keyId.value,
  477. apnsKey: storage.apnsKey.value,
  478. payload: payload
  479. )
  480. }
  481. }