UserNotificationsManager.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. import AudioToolbox
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import SwiftUI
  6. import Swinject
  7. import UIKit
  8. import UserNotifications
  9. protocol UserNotificationsManager {}
  10. enum GlucoseSourceKey: String {
  11. case transmitterBattery
  12. case nightscoutPing
  13. case description
  14. }
  15. enum NotificationAction: String {
  16. static let key = "action"
  17. case snooze
  18. }
  19. protocol BolusFailureObserver {
  20. func bolusDidFail()
  21. }
  22. protocol pumpNotificationObserver {
  23. func pumpNotification(alert: AlertEntry)
  24. func pumpRemoveNotification()
  25. }
  26. final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, Injectable {
  27. private enum Identifier: String {
  28. case glucocoseNotification = "FreeAPS.glucoseNotification"
  29. case carbsRequiredNotification = "FreeAPS.carbsRequiredNotification"
  30. case noLoopFirstNotification = "FreeAPS.noLoopFirstNotification"
  31. case noLoopSecondNotification = "FreeAPS.noLoopSecondNotification"
  32. case bolusFailedNotification = "FreeAPS.bolusFailedNotification"
  33. case pumpNotification = "FreeAPS.pumpNotification"
  34. }
  35. @Injected() private var settingsManager: SettingsManager!
  36. @Injected() private var broadcaster: Broadcaster!
  37. @Injected() private var glucoseStorage: GlucoseStorage!
  38. @Injected() private var apsManager: APSManager!
  39. @Injected() private var router: Router!
  40. @Injected(as: FetchGlucoseManager.self) private var sourceInfoProvider: SourceInfoProvider!
  41. @Persisted(key: "UserNotificationsManager.snoozeUntilDate") private var snoozeUntilDate: Date = .distantPast
  42. private let center = UNUserNotificationCenter.current()
  43. private var lifetime = Lifetime()
  44. private let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  45. private let backgroundContext = CoreDataStack.shared.newTaskContext()
  46. private var coreDataObserver: CoreDataObserver?
  47. init(resolver: Resolver) {
  48. super.init()
  49. center.delegate = self
  50. injectServices(resolver)
  51. broadcaster.register(DeterminationObserver.self, observer: self)
  52. broadcaster.register(BolusFailureObserver.self, observer: self)
  53. broadcaster.register(pumpNotificationObserver.self, observer: self)
  54. requestNotificationPermissionsIfNeeded()
  55. Task {
  56. await sendGlucoseNotification()
  57. }
  58. registerHandlers()
  59. setupGlucoseNotification()
  60. subscribeOnLoop()
  61. }
  62. private func subscribeOnLoop() {
  63. apsManager.lastLoopDateSubject
  64. .sink { [weak self] date in
  65. self?.scheduleMissingLoopNotifiactions(date: date)
  66. }
  67. .store(in: &lifetime)
  68. }
  69. private func registerHandlers() {
  70. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  71. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  72. guard let self = self else { return }
  73. Task {
  74. await self.sendGlucoseNotification()
  75. }
  76. }
  77. }
  78. private func setupGlucoseNotification() {
  79. /// custom notification that is sent when a batch insert of glucose objects is done
  80. Foundation.NotificationCenter.default.addObserver(
  81. self,
  82. selector: #selector(handleBatchInsert),
  83. name: .didPerformBatchInsert,
  84. object: nil
  85. )
  86. }
  87. @objc private func handleBatchInsert() {
  88. Task {
  89. await sendGlucoseNotification()
  90. }
  91. }
  92. private func addAppBadge(glucose: Int?) {
  93. guard let glucose = glucose, settingsManager.settings.glucoseBadge else {
  94. DispatchQueue.main.async {
  95. UIApplication.shared.applicationIconBadgeNumber = 0
  96. }
  97. return
  98. }
  99. let badge: Int
  100. if settingsManager.settings.units == .mmolL {
  101. badge = Int(round(Double((glucose * 10).asMmolL)))
  102. } else {
  103. badge = glucose
  104. }
  105. DispatchQueue.main.async {
  106. UIApplication.shared.applicationIconBadgeNumber = badge
  107. }
  108. }
  109. private func notifyCarbsRequired(_ carbs: Int) {
  110. guard Decimal(carbs) >= settingsManager.settings.carbsRequiredThreshold else { return }
  111. ensureCanSendNotification {
  112. var titles: [String] = []
  113. let content = UNMutableNotificationContent()
  114. if self.snoozeUntilDate > Date() {
  115. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  116. } else {
  117. content.sound = .default
  118. self.playSoundIfNeeded()
  119. }
  120. titles.append(String(format: NSLocalizedString("Carbs required: %d g", comment: "Carbs required"), carbs))
  121. content.title = titles.joined(separator: " ")
  122. content.body = String(
  123. format: NSLocalizedString(
  124. "To prevent LOW required %d g of carbs",
  125. comment: "To prevent LOW required %d g of carbs"
  126. ),
  127. carbs
  128. )
  129. self.addRequest(identifier: .carbsRequiredNotification, content: content, deleteOld: true)
  130. }
  131. }
  132. private func scheduleMissingLoopNotifiactions(date _: Date) {
  133. ensureCanSendNotification {
  134. let title = NSLocalizedString("Trio Not Active", comment: "Trio Not Active")
  135. let body = NSLocalizedString("Last loop was more than %d min ago", comment: "Last loop was more than %d min ago")
  136. let firstInterval = 20 // min
  137. let secondInterval = 40 // min
  138. let firstContent = UNMutableNotificationContent()
  139. firstContent.title = title
  140. firstContent.body = String(format: body, firstInterval)
  141. firstContent.sound = .default
  142. let secondContent = UNMutableNotificationContent()
  143. secondContent.title = title
  144. secondContent.body = String(format: body, secondInterval)
  145. secondContent.sound = .default
  146. let firstTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(firstInterval), repeats: false)
  147. let secondTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(secondInterval), repeats: false)
  148. self.addRequest(
  149. identifier: .noLoopFirstNotification,
  150. content: firstContent,
  151. deleteOld: true,
  152. trigger: firstTrigger
  153. )
  154. self.addRequest(
  155. identifier: .noLoopSecondNotification,
  156. content: secondContent,
  157. deleteOld: true,
  158. trigger: secondTrigger
  159. )
  160. }
  161. }
  162. private func notifyBolusFailure() {
  163. ensureCanSendNotification {
  164. let title = NSLocalizedString("Bolus failed", comment: "Bolus failed")
  165. let body = NSLocalizedString(
  166. "Bolus failed or inaccurate. Check pump history before repeating.",
  167. comment: "Bolus failed or inaccurate. Check pump history before repeating."
  168. )
  169. let content = UNMutableNotificationContent()
  170. content.title = title
  171. content.body = body
  172. content.sound = .default
  173. self.addRequest(
  174. identifier: .noLoopFirstNotification,
  175. content: content,
  176. deleteOld: true,
  177. trigger: nil
  178. )
  179. }
  180. }
  181. private func fetchGlucoseIDs() async -> [NSManagedObjectID] {
  182. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  183. ofType: GlucoseStored.self,
  184. onContext: backgroundContext,
  185. predicate: NSPredicate.predicateFor20MinAgo,
  186. key: "date",
  187. ascending: false,
  188. fetchLimit: 3
  189. )
  190. return await backgroundContext.perform {
  191. return results.map(\.objectID)
  192. }
  193. }
  194. @MainActor private func sendGlucoseNotification() async {
  195. do {
  196. addAppBadge(glucose: nil)
  197. let glucoseIDs = await fetchGlucoseIDs()
  198. let glucoseObjects = try glucoseIDs.compactMap { id in
  199. try viewContext.existingObject(with: id) as? GlucoseStored
  200. }
  201. guard let lastReading = glucoseObjects.first?.glucose,
  202. let secondLastReading = glucoseObjects.dropFirst().first?.glucose,
  203. let lastDirection = glucoseObjects.first?.directionEnum?.symbol else { return }
  204. addAppBadge(glucose: (glucoseObjects.first?.glucose).map { Int($0) })
  205. guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else { return }
  206. ensureCanSendNotification {
  207. var titles: [String] = []
  208. var notificationAlarm = false
  209. switch self.glucoseStorage.alarm {
  210. case .none:
  211. titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
  212. case .low:
  213. titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
  214. notificationAlarm = true
  215. case .high:
  216. titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
  217. notificationAlarm = true
  218. }
  219. let delta = glucoseObjects.count >= 2 ? lastReading - secondLastReading : nil
  220. let body = self.glucoseText(
  221. glucoseValue: Int(lastReading),
  222. delta: Int(delta ?? 0),
  223. direction: lastDirection
  224. ) + self.infoBody()
  225. if self.snoozeUntilDate > Date() {
  226. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  227. notificationAlarm = false
  228. } else {
  229. titles.append(body)
  230. let content = UNMutableNotificationContent()
  231. content.title = titles.joined(separator: " ")
  232. content.body = body
  233. if notificationAlarm {
  234. self.playSoundIfNeeded()
  235. content.sound = .default
  236. content.userInfo[NotificationAction.key] = NotificationAction.snooze.rawValue
  237. }
  238. self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
  239. }
  240. }
  241. } catch {
  242. debugPrint(
  243. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to send glucose notification with error: \(error.localizedDescription)"
  244. )
  245. }
  246. }
  247. private func glucoseText(glucoseValue: Int, delta: Int?, direction: String?) -> String {
  248. let units = settingsManager.settings.units
  249. let glucoseText = glucoseFormatter
  250. .string(from: Double(
  251. units == .mmolL ? glucoseValue
  252. .asMmolL : Decimal(glucoseValue)
  253. ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
  254. let directionText = direction ?? "↔︎"
  255. let deltaText = delta
  256. .map {
  257. self.deltaFormatter
  258. .string(from: Double(
  259. units == .mmolL ? $0
  260. .asMmolL : Decimal($0)
  261. ) as NSNumber)!
  262. } ?? "--"
  263. return glucoseText + " " + directionText + " " + deltaText
  264. }
  265. private func infoBody() -> String {
  266. var body = ""
  267. if settingsManager.settings.addSourceInfoToGlucoseNotifications,
  268. let info = sourceInfoProvider.sourceInfo()
  269. {
  270. // Description
  271. if let description = info[GlucoseSourceKey.description.rawValue] as? String {
  272. body.append("\n" + description)
  273. }
  274. // NS ping
  275. if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
  276. body.append(
  277. "\n"
  278. + String(
  279. format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
  280. Int(ping * 1000)
  281. )
  282. )
  283. }
  284. // Transmitter battery
  285. if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
  286. body.append(
  287. "\n"
  288. + String(
  289. format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
  290. "\(transmitterBattery)"
  291. )
  292. )
  293. }
  294. }
  295. return body
  296. }
  297. private func requestNotificationPermissionsIfNeeded() {
  298. center.getNotificationSettings { settings in
  299. debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
  300. if ![.authorized, .provisional].contains(settings.authorizationStatus) {
  301. self.requestNotificationPermissions()
  302. }
  303. }
  304. }
  305. private func requestNotificationPermissions() {
  306. debug(.service, "requestNotificationPermissions")
  307. center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
  308. if granted {
  309. debug(.service, "requestNotificationPermissions was granted")
  310. } else {
  311. warning(.service, "requestNotificationPermissions failed", error: error)
  312. }
  313. }
  314. }
  315. private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
  316. center.getNotificationSettings { settings in
  317. guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
  318. warning(.service, "ensureCanSendNotification failed, authorization denied")
  319. return
  320. }
  321. debug(.service, "Sending notification was allowed")
  322. completion()
  323. }
  324. }
  325. private func addRequest(
  326. identifier: Identifier,
  327. content: UNMutableNotificationContent,
  328. deleteOld: Bool = false,
  329. trigger: UNNotificationTrigger? = nil
  330. ) {
  331. let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
  332. if deleteOld {
  333. DispatchQueue.main.async {
  334. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  335. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  336. }
  337. }
  338. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  339. self.center.add(request) { error in
  340. if let error = error {
  341. warning(.service, "Unable to addNotificationRequest", error: error)
  342. return
  343. }
  344. debug(.service, "Sending \(identifier) notification")
  345. }
  346. }
  347. }
  348. private func playSoundIfNeeded() {
  349. guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
  350. Self.stopPlaying = false
  351. playSound()
  352. }
  353. static let soundID: UInt32 = 1336
  354. private static var stopPlaying = false
  355. private func playSound(times: Int = 1) {
  356. guard times > 0, !Self.stopPlaying else {
  357. return
  358. }
  359. AudioServicesPlaySystemSoundWithCompletion(Self.soundID) {
  360. self.playSound(times: times - 1)
  361. }
  362. }
  363. static func stopSound() {
  364. stopPlaying = true
  365. AudioServicesDisposeSystemSoundID(soundID)
  366. }
  367. private var glucoseFormatter: NumberFormatter {
  368. let formatter = NumberFormatter()
  369. formatter.numberStyle = .decimal
  370. formatter.maximumFractionDigits = 0
  371. if settingsManager.settings.units == .mmolL {
  372. formatter.minimumFractionDigits = 1
  373. formatter.maximumFractionDigits = 1
  374. }
  375. formatter.roundingMode = .halfUp
  376. return formatter
  377. }
  378. private var deltaFormatter: NumberFormatter {
  379. let formatter = NumberFormatter()
  380. formatter.numberStyle = .decimal
  381. formatter.maximumFractionDigits = 1
  382. formatter.positivePrefix = "+"
  383. return formatter
  384. }
  385. }
  386. extension BaseUserNotificationsManager: pumpNotificationObserver {
  387. func pumpNotification(alert: AlertEntry) {
  388. ensureCanSendNotification {
  389. let content = UNMutableNotificationContent()
  390. content.title = alert.contentTitle ?? "Unknown"
  391. content.body = alert.contentBody ?? "Unknown"
  392. content.sound = .default
  393. self.addRequest(
  394. identifier: .pumpNotification,
  395. content: content,
  396. deleteOld: true,
  397. trigger: nil
  398. )
  399. }
  400. }
  401. func pumpRemoveNotification() {
  402. let identifier: Identifier = .pumpNotification
  403. DispatchQueue.main.async {
  404. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  405. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  406. }
  407. }
  408. }
  409. extension BaseUserNotificationsManager: DeterminationObserver {
  410. func determinationDidUpdate(_ determination: Determination) {
  411. guard let carndRequired = determination.carbsReq else { return }
  412. notifyCarbsRequired(Int(carndRequired))
  413. }
  414. }
  415. extension BaseUserNotificationsManager: BolusFailureObserver {
  416. func bolusDidFail() {
  417. notifyBolusFailure()
  418. }
  419. }
  420. extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
  421. func userNotificationCenter(
  422. _: UNUserNotificationCenter,
  423. willPresent _: UNNotification,
  424. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  425. ) {
  426. completionHandler([.banner, .badge, .sound])
  427. }
  428. func userNotificationCenter(
  429. _: UNUserNotificationCenter,
  430. didReceive response: UNNotificationResponse,
  431. withCompletionHandler completionHandler: @escaping () -> Void
  432. ) {
  433. defer { completionHandler() }
  434. guard let actionRaw = response.notification.request.content.userInfo[NotificationAction.key] as? String,
  435. let action = NotificationAction(rawValue: actionRaw)
  436. else { return }
  437. switch action {
  438. case .snooze:
  439. router.mainModalScreen.send(.snooze)
  440. }
  441. }
  442. }