UserNotificationsManager.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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,
  111. settingsManager.settings.showCarbsRequiredBadge else { return }
  112. ensureCanSendNotification {
  113. var titles: [String] = []
  114. let content = UNMutableNotificationContent()
  115. if self.snoozeUntilDate > Date() {
  116. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  117. } else {
  118. content.sound = .default
  119. self.playSoundIfNeeded()
  120. }
  121. titles.append(String(format: NSLocalizedString("Carbs required: %d g", comment: "Carbs required"), carbs))
  122. content.title = titles.joined(separator: " ")
  123. content.body = String(
  124. format: NSLocalizedString(
  125. "To prevent LOW required %d g of carbs",
  126. comment: "To prevent LOW required %d g of carbs"
  127. ),
  128. carbs
  129. )
  130. self.addRequest(identifier: .carbsRequiredNotification, content: content, deleteOld: true)
  131. }
  132. }
  133. private func scheduleMissingLoopNotifiactions(date _: Date) {
  134. ensureCanSendNotification {
  135. let title = NSLocalizedString("Trio Not Active", comment: "Trio Not Active")
  136. let body = NSLocalizedString("Last loop was more than %d min ago", comment: "Last loop was more than %d min ago")
  137. let firstInterval = 20 // min
  138. let secondInterval = 40 // min
  139. let firstContent = UNMutableNotificationContent()
  140. firstContent.title = title
  141. firstContent.body = String(format: body, firstInterval)
  142. firstContent.sound = .default
  143. let secondContent = UNMutableNotificationContent()
  144. secondContent.title = title
  145. secondContent.body = String(format: body, secondInterval)
  146. secondContent.sound = .default
  147. let firstTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(firstInterval), repeats: false)
  148. let secondTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(secondInterval), repeats: false)
  149. self.addRequest(
  150. identifier: .noLoopFirstNotification,
  151. content: firstContent,
  152. deleteOld: true,
  153. trigger: firstTrigger
  154. )
  155. self.addRequest(
  156. identifier: .noLoopSecondNotification,
  157. content: secondContent,
  158. deleteOld: true,
  159. trigger: secondTrigger
  160. )
  161. }
  162. }
  163. private func notifyBolusFailure() {
  164. ensureCanSendNotification {
  165. let title = NSLocalizedString("Bolus failed", comment: "Bolus failed")
  166. let body = NSLocalizedString(
  167. "Bolus failed or inaccurate. Check pump history before repeating.",
  168. comment: "Bolus failed or inaccurate. Check pump history before repeating."
  169. )
  170. let content = UNMutableNotificationContent()
  171. content.title = title
  172. content.body = body
  173. content.sound = .default
  174. self.addRequest(
  175. identifier: .noLoopFirstNotification,
  176. content: content,
  177. deleteOld: true,
  178. trigger: nil
  179. )
  180. }
  181. }
  182. private func fetchGlucoseIDs() async -> [NSManagedObjectID] {
  183. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  184. ofType: GlucoseStored.self,
  185. onContext: backgroundContext,
  186. predicate: NSPredicate.predicateFor20MinAgo,
  187. key: "date",
  188. ascending: false,
  189. fetchLimit: 3
  190. )
  191. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  192. return await backgroundContext.perform {
  193. return fetchedResults.map(\.objectID)
  194. }
  195. }
  196. @MainActor private func sendGlucoseNotification() async {
  197. do {
  198. addAppBadge(glucose: nil)
  199. let glucoseIDs = await fetchGlucoseIDs()
  200. let glucoseObjects = try glucoseIDs.compactMap { id in
  201. try viewContext.existingObject(with: id) as? GlucoseStored
  202. }
  203. guard let lastReading = glucoseObjects.first?.glucose,
  204. let secondLastReading = glucoseObjects.dropFirst().first?.glucose,
  205. let lastDirection = glucoseObjects.first?.directionEnum?.symbol else { return }
  206. addAppBadge(glucose: (glucoseObjects.first?.glucose).map { Int($0) })
  207. guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else { return }
  208. ensureCanSendNotification {
  209. var titles: [String] = []
  210. var notificationAlarm = false
  211. switch self.glucoseStorage.alarm {
  212. case .none:
  213. titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
  214. case .low:
  215. titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
  216. notificationAlarm = true
  217. case .high:
  218. titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
  219. notificationAlarm = true
  220. }
  221. let delta = glucoseObjects.count >= 2 ? lastReading - secondLastReading : nil
  222. let body = self.glucoseText(
  223. glucoseValue: Int(lastReading),
  224. delta: Int(delta ?? 0),
  225. direction: lastDirection
  226. ) + self.infoBody()
  227. if self.snoozeUntilDate > Date() {
  228. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  229. notificationAlarm = false
  230. } else {
  231. titles.append(body)
  232. let content = UNMutableNotificationContent()
  233. content.title = titles.joined(separator: " ")
  234. content.body = body
  235. if notificationAlarm {
  236. self.playSoundIfNeeded()
  237. content.sound = .default
  238. content.userInfo[NotificationAction.key] = NotificationAction.snooze.rawValue
  239. }
  240. self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
  241. }
  242. }
  243. } catch {
  244. debugPrint(
  245. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to send glucose notification with error: \(error.localizedDescription)"
  246. )
  247. }
  248. }
  249. private func glucoseText(glucoseValue: Int, delta: Int?, direction: String?) -> String {
  250. let units = settingsManager.settings.units
  251. let glucoseText = glucoseFormatter
  252. .string(from: Double(
  253. units == .mmolL ? glucoseValue
  254. .asMmolL : Decimal(glucoseValue)
  255. ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
  256. let directionText = direction ?? "↔︎"
  257. let deltaText = delta
  258. .map {
  259. self.deltaFormatter
  260. .string(from: Double(
  261. units == .mmolL ? $0
  262. .asMmolL : Decimal($0)
  263. ) as NSNumber)!
  264. } ?? "--"
  265. return glucoseText + " " + directionText + " " + deltaText
  266. }
  267. private func infoBody() -> String {
  268. var body = ""
  269. if settingsManager.settings.addSourceInfoToGlucoseNotifications,
  270. let info = sourceInfoProvider.sourceInfo()
  271. {
  272. // Description
  273. if let description = info[GlucoseSourceKey.description.rawValue] as? String {
  274. body.append("\n" + description)
  275. }
  276. // NS ping
  277. if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
  278. body.append(
  279. "\n"
  280. + String(
  281. format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
  282. Int(ping * 1000)
  283. )
  284. )
  285. }
  286. // Transmitter battery
  287. if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
  288. body.append(
  289. "\n"
  290. + String(
  291. format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
  292. "\(transmitterBattery)"
  293. )
  294. )
  295. }
  296. }
  297. return body
  298. }
  299. private func requestNotificationPermissionsIfNeeded() {
  300. center.getNotificationSettings { settings in
  301. debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
  302. if ![.authorized, .provisional].contains(settings.authorizationStatus) {
  303. self.requestNotificationPermissions()
  304. }
  305. }
  306. }
  307. private func requestNotificationPermissions() {
  308. debug(.service, "requestNotificationPermissions")
  309. center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
  310. if granted {
  311. debug(.service, "requestNotificationPermissions was granted")
  312. } else {
  313. warning(.service, "requestNotificationPermissions failed", error: error)
  314. }
  315. }
  316. }
  317. private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
  318. center.getNotificationSettings { settings in
  319. guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
  320. warning(.service, "ensureCanSendNotification failed, authorization denied")
  321. return
  322. }
  323. debug(.service, "Sending notification was allowed")
  324. completion()
  325. }
  326. }
  327. private func addRequest(
  328. identifier: Identifier,
  329. content: UNMutableNotificationContent,
  330. deleteOld: Bool = false,
  331. trigger: UNNotificationTrigger? = nil
  332. ) {
  333. let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
  334. if deleteOld {
  335. DispatchQueue.main.async {
  336. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  337. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  338. }
  339. }
  340. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  341. self.center.add(request) { error in
  342. if let error = error {
  343. warning(.service, "Unable to addNotificationRequest", error: error)
  344. return
  345. }
  346. debug(.service, "Sending \(identifier) notification")
  347. }
  348. }
  349. }
  350. private func playSoundIfNeeded() {
  351. guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
  352. Self.stopPlaying = false
  353. playSound()
  354. }
  355. static let soundID: UInt32 = 1336
  356. private static var stopPlaying = false
  357. private func playSound(times: Int = 1) {
  358. guard times > 0, !Self.stopPlaying else {
  359. return
  360. }
  361. AudioServicesPlaySystemSoundWithCompletion(Self.soundID) {
  362. self.playSound(times: times - 1)
  363. }
  364. }
  365. static func stopSound() {
  366. stopPlaying = true
  367. AudioServicesDisposeSystemSoundID(soundID)
  368. }
  369. private var glucoseFormatter: NumberFormatter {
  370. let formatter = NumberFormatter()
  371. formatter.numberStyle = .decimal
  372. formatter.maximumFractionDigits = 0
  373. if settingsManager.settings.units == .mmolL {
  374. formatter.minimumFractionDigits = 1
  375. formatter.maximumFractionDigits = 1
  376. }
  377. formatter.roundingMode = .halfUp
  378. return formatter
  379. }
  380. private var deltaFormatter: NumberFormatter {
  381. let formatter = NumberFormatter()
  382. formatter.numberStyle = .decimal
  383. formatter.maximumFractionDigits = 1
  384. formatter.positivePrefix = "+"
  385. return formatter
  386. }
  387. }
  388. extension BaseUserNotificationsManager: pumpNotificationObserver {
  389. func pumpNotification(alert: AlertEntry) {
  390. ensureCanSendNotification {
  391. let content = UNMutableNotificationContent()
  392. content.title = alert.contentTitle ?? "Unknown"
  393. content.body = alert.contentBody ?? "Unknown"
  394. content.sound = .default
  395. self.addRequest(
  396. identifier: .pumpNotification,
  397. content: content,
  398. deleteOld: true,
  399. trigger: nil
  400. )
  401. }
  402. }
  403. func pumpRemoveNotification() {
  404. let identifier: Identifier = .pumpNotification
  405. DispatchQueue.main.async {
  406. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  407. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  408. }
  409. }
  410. }
  411. extension BaseUserNotificationsManager: DeterminationObserver {
  412. func determinationDidUpdate(_ determination: Determination) {
  413. guard let carndRequired = determination.carbsReq else { return }
  414. notifyCarbsRequired(Int(carndRequired))
  415. }
  416. }
  417. extension BaseUserNotificationsManager: BolusFailureObserver {
  418. func bolusDidFail() {
  419. notifyBolusFailure()
  420. }
  421. }
  422. extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
  423. func userNotificationCenter(
  424. _: UNUserNotificationCenter,
  425. willPresent _: UNNotification,
  426. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  427. ) {
  428. completionHandler([.banner, .badge, .sound])
  429. }
  430. func userNotificationCenter(
  431. _: UNUserNotificationCenter,
  432. didReceive response: UNNotificationResponse,
  433. withCompletionHandler completionHandler: @escaping () -> Void
  434. ) {
  435. defer { completionHandler() }
  436. guard let actionRaw = response.notification.request.content.userInfo[NotificationAction.key] as? String,
  437. let action = NotificationAction(rawValue: actionRaw)
  438. else { return }
  439. switch action {
  440. case .snooze:
  441. router.mainModalScreen.send(.snooze)
  442. }
  443. }
  444. }