LoopAPNSService.swift 32 KB

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