LoopAPNSService.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 environment-specific guidance for APNS configuration
  191. /// - Returns: String with guidance based on build configuration
  192. private func getEnvironmentGuidance() -> String {
  193. #if DEBUG
  194. let buildType = "Xcode"
  195. let recommendedEnvironment = "Development"
  196. let environmentSetting = "Production Environment: OFF"
  197. #else
  198. let buildType = "Browser/TestFlight"
  199. let recommendedEnvironment = "Production"
  200. let environmentSetting = "Production Environment: ON"
  201. #endif
  202. let currentEnvironment = storage.productionEnvironment.value ? "Production" : "Development"
  203. return """
  204. Environment Configuration Help:
  205. Build Type: \(buildType)
  206. Current Setting: \(currentEnvironment)
  207. Recommended Setting: \(recommendedEnvironment)
  208. Please check your Loop Remote control settings:
  209. • If you built with Xcode: Set "\(environmentSetting)"
  210. • If you built with Browser/TestFlight: Set "Production Environment: ON"
  211. """
  212. }
  213. /// Sends an APNS notification
  214. /// - Parameters:
  215. /// - deviceToken: The device token to send to
  216. /// - bundleIdentifier: The bundle identifier
  217. /// - keyId: The APNS key ID
  218. /// - apnsKey: The APNS key
  219. /// - payload: The notification payload
  220. /// - completion: Completion handler with success status and error message
  221. private func sendAPNSNotification(
  222. deviceToken: String,
  223. bundleIdentifier: String,
  224. keyId: String,
  225. apnsKey: String,
  226. payload: [String: Any],
  227. completion: @escaping (Bool, String?) -> Void
  228. ) {
  229. // Validate credentials first
  230. if let validationErrors = validateCredentials() {
  231. let errorMessage = "Credential validation failed: \(validationErrors.joined(separator: ", "))"
  232. LogManager.shared.log(category: .apns, message: errorMessage)
  233. completion(false, errorMessage)
  234. return
  235. }
  236. // Create JWT token for APNS authentication
  237. guard let jwt = JWTManager.shared.getOrGenerateJWT(keyId: keyId, teamId: Storage.shared.teamId.value ?? "", apnsKey: apnsKey) else {
  238. let errorMessage = "Failed to generate JWT, please check that the APNS Key ID, APNS Key and Team ID are correct."
  239. LogManager.shared.log(category: .apns, message: errorMessage)
  240. completion(false, errorMessage)
  241. return
  242. }
  243. // Determine APNS environment
  244. let isProduction = storage.productionEnvironment.value
  245. let apnsURL = isProduction ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"
  246. guard let requestURL = URL(string: "\(apnsURL)/3/device/\(deviceToken)") else {
  247. let errorMessage = "Failed to construct APNs URL"
  248. LogManager.shared.log(category: .apns, message: errorMessage)
  249. completion(false, errorMessage)
  250. return
  251. }
  252. var request = URLRequest(url: requestURL)
  253. request.httpMethod = "POST"
  254. request.setValue("application/json", forHTTPHeaderField: "content-type")
  255. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  256. request.setValue(bundleIdentifier, forHTTPHeaderField: "apns-topic")
  257. request.setValue("alert", forHTTPHeaderField: "apns-push-type")
  258. request.setValue("10", forHTTPHeaderField: "apns-priority") // High priority
  259. // Validate bundle identifier format
  260. if !bundleIdentifier.contains(".") {
  261. LogManager.shared.log(category: .apns, message: "Warning: Bundle identifier may be in wrong format: \(bundleIdentifier)")
  262. }
  263. // Create the proper APNS payload structure (matching @parse/node-apn format)
  264. var apnsPayload: [String: Any] = [
  265. "aps": [
  266. "alert": payload["alert"] as? String ?? "",
  267. "content-available": 1,
  268. "interruption-level": "time-sensitive",
  269. ],
  270. ]
  271. // Add all the custom payload fields (excluding APNS-specific fields)
  272. for (key, value) in payload {
  273. if key != "alert", key != "content-available", key != "interruption-level" {
  274. apnsPayload[key] = value
  275. }
  276. }
  277. // Remove nil values to clean up the payload
  278. let cleanPayload = apnsPayload.compactMapValues { $0 }
  279. do {
  280. let jsonData = try JSONSerialization.data(withJSONObject: cleanPayload)
  281. request.httpBody = jsonData
  282. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  283. if let error = error {
  284. let errorMessage = "Failed to send push notification: \(error.localizedDescription)"
  285. LogManager.shared.log(category: .apns, message: errorMessage)
  286. completion(false, errorMessage)
  287. return
  288. }
  289. if let httpResponse = response as? HTTPURLResponse {
  290. var responseBodyMessage = ""
  291. if let data = data, let responseBody = String(data: data, encoding: .utf8) {
  292. if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  293. let reason = json["reason"] as? String
  294. {
  295. responseBodyMessage = reason
  296. }
  297. }
  298. switch httpResponse.statusCode {
  299. case 200:
  300. LogManager.shared.log(category: .apns, message: "APNS notification sent successfully")
  301. completion(true, nil)
  302. case 400:
  303. let environmentGuidance = self.getEnvironmentGuidance()
  304. let errorMessage = "Bad request. The request was invalid or malformed. \(responseBodyMessage)\n\n\(environmentGuidance)"
  305. LogManager.shared.log(category: .apns, message: "APNS error 400: \(responseBodyMessage) - Check device token and environment settings")
  306. completion(false, errorMessage)
  307. case 403:
  308. let errorMessage = "Authentication error. Check your certificate or authentication token. \(responseBodyMessage)"
  309. LogManager.shared.log(category: .apns, message: "APNS error 403: \(responseBodyMessage) - Check APNS key permissions for bundle ID")
  310. completion(false, errorMessage)
  311. case 404:
  312. let errorMessage = "Invalid request: The :path value was incorrect. \(responseBodyMessage)"
  313. LogManager.shared.log(category: .apns, message: "APNS error 404: \(responseBodyMessage)")
  314. completion(false, errorMessage)
  315. case 405:
  316. let errorMessage = "Invalid request: Only POST requests are supported. \(responseBodyMessage)"
  317. LogManager.shared.log(category: .apns, message: "APNS error 405: \(responseBodyMessage)")
  318. completion(false, errorMessage)
  319. case 410:
  320. let errorMessage = "The device token is no longer active for the topic. \(responseBodyMessage)"
  321. LogManager.shared.log(category: .apns, message: "APNS error 410: Device token is invalid or expired")
  322. completion(false, errorMessage)
  323. case 413:
  324. let errorMessage = "Payload too large. The notification payload exceeded the size limit. \(responseBodyMessage)"
  325. LogManager.shared.log(category: .apns, message: "APNS error 413: \(responseBodyMessage)")
  326. completion(false, errorMessage)
  327. case 429:
  328. let errorMessage = "Too many requests. \(responseBodyMessage)"
  329. LogManager.shared.log(category: .apns, message: "APNS error 429: Rate limited - wait before retrying")
  330. completion(false, errorMessage)
  331. case 500:
  332. let errorMessage = "Internal server error at APNs. \(responseBodyMessage)"
  333. LogManager.shared.log(category: .apns, message: "APNS error 500: \(responseBodyMessage)")
  334. completion(false, errorMessage)
  335. case 503:
  336. let errorMessage = "Service unavailable. The server is temporarily unavailable. Try again later. \(responseBodyMessage)"
  337. LogManager.shared.log(category: .apns, message: "APNS error 503: \(responseBodyMessage)")
  338. completion(false, errorMessage)
  339. default:
  340. let errorMessage = "Unexpected status code: \(httpResponse.statusCode). \(responseBodyMessage)"
  341. LogManager.shared.log(category: .apns, message: "APNS error \(httpResponse.statusCode): \(responseBodyMessage)")
  342. completion(false, errorMessage)
  343. }
  344. } else {
  345. let errorMessage = "Failed to get a valid HTTP response."
  346. LogManager.shared.log(category: .apns, message: errorMessage)
  347. completion(false, errorMessage)
  348. }
  349. }
  350. task.resume()
  351. } catch {
  352. let errorMessage = "Failed to serialize APNS payload: \(error.localizedDescription)"
  353. LogManager.shared.log(category: .apns, message: errorMessage)
  354. completion(false, errorMessage)
  355. }
  356. }
  357. /// Validates and fixes APNS key format if needed
  358. /// - Parameter key: The APNS key to validate and fix
  359. /// - Returns: The fixed APNS key
  360. func validateAndFixAPNSKey(_ key: String) -> String {
  361. // Normalize: replace all literal \n with real newlines
  362. var fixedKey = key.replacingOccurrences(of: "\\n", with: "\n")
  363. // Strip leading/trailing quotes
  364. fixedKey = fixedKey.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
  365. // Check if the key has proper line breaks
  366. if !fixedKey.contains("\n") {
  367. LogManager.shared.log(category: .apns, message: "APNS Key missing line breaks, attempting to fix format")
  368. // Try to add line breaks if the key is all on one line
  369. if fixedKey.contains("-----BEGIN PRIVATE KEY-----") && fixedKey.contains("-----END PRIVATE KEY-----") {
  370. // Find the positions of the headers
  371. if let beginRange = fixedKey.range(of: "-----BEGIN PRIVATE KEY-----"),
  372. let endRange = fixedKey.range(of: "-----END PRIVATE KEY-----")
  373. {
  374. let beginIndex = fixedKey.index(beginRange.upperBound, offsetBy: 0)
  375. let endIndex = endRange.lowerBound
  376. if beginIndex < endIndex {
  377. let header = String(fixedKey[..<beginIndex])
  378. let keyData = String(fixedKey[beginIndex ..< endIndex])
  379. let footer = String(fixedKey[endIndex...])
  380. // Clean up the key data - remove any whitespace and split into 64-character lines
  381. let cleanKeyData = keyData.replacingOccurrences(of: " ", with: "")
  382. .replacingOccurrences(of: "\t", with: "")
  383. .replacingOccurrences(of: "\n", with: "")
  384. .replacingOccurrences(of: "\r", with: "")
  385. // Validate the key data length (should be 44 characters for P-256)
  386. LogManager.shared.log(category: .apns, message: "Key data validation - Length: \(cleanKeyData.count) characters")
  387. if cleanKeyData.count != 44 {
  388. LogManager.shared.log(category: .apns, message: "WARNING: Key data length is \(cleanKeyData.count), expected 44 for P-256 private key")
  389. }
  390. // Validate base64 format
  391. if Data(base64Encoded: cleanKeyData) == nil {
  392. LogManager.shared.log(category: .apns, message: "WARNING: Key data is not valid base64")
  393. }
  394. // Split into 64-character lines (standard PEM format)
  395. var formattedKeyData = ""
  396. var currentLine = ""
  397. for char in cleanKeyData {
  398. currentLine.append(char)
  399. if currentLine.count == 64 {
  400. formattedKeyData += currentLine + "\n"
  401. currentLine = ""
  402. }
  403. }
  404. // Add any remaining characters
  405. if !currentLine.isEmpty {
  406. formattedKeyData += currentLine
  407. }
  408. fixedKey = "\(header)\n\(formattedKeyData)\n\(footer)"
  409. LogManager.shared.log(category: .apns, message: "APNS Key format fixed - added proper line breaks")
  410. LogManager.shared.log(category: .apns, message: "Key data length: \(cleanKeyData.count) characters")
  411. LogManager.shared.log(category: .apns, message: "Formatted key lines: \(formattedKeyData.components(separatedBy: "\n").count)")
  412. }
  413. }
  414. }
  415. } else {
  416. // Key already has line breaks, but let's ensure proper formatting
  417. let lines = fixedKey.components(separatedBy: .newlines)
  418. var cleanedLines: [String] = []
  419. for line in lines {
  420. let cleanedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
  421. if !cleanedLine.isEmpty {
  422. cleanedLines.append(cleanedLine)
  423. }
  424. }
  425. // Reconstruct with proper formatting
  426. if cleanedLines.count > 2 {
  427. let header = cleanedLines[0]
  428. let footer = cleanedLines[cleanedLines.count - 1]
  429. let keyLines = Array(cleanedLines[1 ..< (cleanedLines.count - 1)])
  430. // Combine all key data lines and validate
  431. let combinedKeyData = keyLines.joined()
  432. LogManager.shared.log(category: .apns, message: "Combined key data length: \(combinedKeyData.count) characters")
  433. // Validate the key data length (should be 44 characters for P-256)
  434. if combinedKeyData.count != 44 {
  435. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data length is \(combinedKeyData.count), expected 44 for P-256 private key")
  436. }
  437. // Validate base64 format
  438. if Data(base64Encoded: combinedKeyData) == nil {
  439. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data is not valid base64")
  440. }
  441. // Ensure key lines are properly formatted (64 characters each)
  442. var formattedKeyLines: [String] = []
  443. var currentLine = ""
  444. for line in keyLines {
  445. let cleanLine = line.replacingOccurrences(of: " ", with: "")
  446. .replacingOccurrences(of: "\t", with: "")
  447. for char in cleanLine {
  448. currentLine.append(char)
  449. if currentLine.count == 64 {
  450. formattedKeyLines.append(currentLine)
  451. currentLine = ""
  452. }
  453. }
  454. }
  455. // Add any remaining characters
  456. if !currentLine.isEmpty {
  457. formattedKeyLines.append(currentLine)
  458. }
  459. fixedKey = "\(header)\n\(formattedKeyLines.joined(separator: "\n"))\n\(footer)"
  460. LogManager.shared.log(category: .apns, message: "APNS Key reformatted - cleaned up existing line breaks")
  461. }
  462. }
  463. return fixedKey
  464. }
  465. /// Extracts key data from PEM format
  466. /// - Parameter pemString: The PEM formatted private key
  467. /// - Returns: The extracted key data string
  468. private func extractKeyData(from pemString: String) -> String? {
  469. let lines = pemString.components(separatedBy: "\n")
  470. guard let startIndex = lines.firstIndex(of: "-----BEGIN PRIVATE KEY-----"),
  471. let endIndex = lines.firstIndex(of: "-----END PRIVATE KEY-----"),
  472. startIndex < endIndex
  473. else {
  474. return nil
  475. }
  476. let keyLines = lines[(startIndex + 1) ..< endIndex]
  477. return keyLines.joined()
  478. }
  479. // MARK: - Date Formatting Helper
  480. /// Creates a properly formatted ISO8601 date string with milliseconds (matching Nightscout's format)
  481. /// - Parameter date: The date to format
  482. /// - Returns: Formatted date string like "2022-12-24T21:34:02.090Z"
  483. private func formatDateForAPNS(_ date: Date) -> String {
  484. let dateFormatter = ISO8601DateFormatter()
  485. dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  486. return dateFormatter.string(from: date)
  487. }
  488. // MARK: - Override Methods
  489. func sendOverrideNotification(presetName: String, duration: TimeInterval? = nil, completion: @escaping (Bool, String?) -> Void) {
  490. let deviceToken = Storage.shared.deviceToken.value
  491. guard !deviceToken.isEmpty else {
  492. let errorMessage = "Device token not configured"
  493. LogManager.shared.log(category: .apns, message: errorMessage)
  494. completion(false, errorMessage)
  495. return
  496. }
  497. let bundleIdentifier = Storage.shared.bundleId.value
  498. guard !bundleIdentifier.isEmpty else {
  499. let errorMessage = "Bundle identifier not configured"
  500. LogManager.shared.log(category: .apns, message: errorMessage)
  501. completion(false, errorMessage)
  502. return
  503. }
  504. // Create APNS notification payload (matching Loop's expected format)
  505. let now = Date()
  506. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  507. // Create alert text (matching Nightscout's format)
  508. var alertText = "\(presetName) Temporary Override"
  509. if let duration = duration, duration > 0 {
  510. let hours = Int(duration / 3600)
  511. let minutes = Int((duration.truncatingRemainder(dividingBy: 3600)) / 60)
  512. if hours > 0 {
  513. alertText += " (\(hours)h \(minutes)m)"
  514. } else {
  515. alertText += " (\(minutes)m)"
  516. }
  517. }
  518. var payload: [String: Any] = [
  519. "override-name": presetName,
  520. "remote-address": "LoopFollow",
  521. "entered-by": "LoopFollow",
  522. "sent-at": formatDateForAPNS(now),
  523. "expiration": formatDateForAPNS(expiration),
  524. "alert": alertText,
  525. ]
  526. if let duration = duration, duration > 0 {
  527. payload["override-duration-minutes"] = Int(duration / 60)
  528. }
  529. // Send the notification using the existing APNS infrastructure
  530. sendAPNSNotification(
  531. deviceToken: deviceToken,
  532. bundleIdentifier: bundleIdentifier,
  533. keyId: storage.keyId.value,
  534. apnsKey: storage.apnsKey.value,
  535. payload: payload,
  536. completion: completion
  537. )
  538. }
  539. func sendCancelOverrideNotification(completion: @escaping (Bool, String?) -> Void) {
  540. let deviceToken = Storage.shared.deviceToken.value
  541. guard !deviceToken.isEmpty else {
  542. let errorMessage = "Device token not configured"
  543. LogManager.shared.log(category: .apns, message: errorMessage)
  544. completion(false, errorMessage)
  545. return
  546. }
  547. let bundleIdentifier = Storage.shared.bundleId.value
  548. guard !bundleIdentifier.isEmpty else {
  549. let errorMessage = "Bundle identifier not configured"
  550. LogManager.shared.log(category: .apns, message: errorMessage)
  551. completion(false, errorMessage)
  552. return
  553. }
  554. // Create APNS notification payload (matching Loop's expected format)
  555. let now = Date()
  556. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  557. let payload: [String: Any] = [
  558. "cancel-temporary-override": "true",
  559. "remote-address": "LoopFollow",
  560. "entered-by": "LoopFollow",
  561. "sent-at": formatDateForAPNS(now),
  562. "expiration": formatDateForAPNS(expiration),
  563. "alert": "Cancel Temporary Override",
  564. ]
  565. // Send the notification using the existing APNS infrastructure
  566. sendAPNSNotification(
  567. deviceToken: deviceToken,
  568. bundleIdentifier: bundleIdentifier,
  569. keyId: storage.keyId.value,
  570. apnsKey: storage.apnsKey.value,
  571. payload: payload,
  572. completion: completion
  573. )
  574. }
  575. }