LoopAPNSService.swift 29 KB

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