UserNotificationsManager.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  191. return await backgroundContext.perform {
  192. return fetchedResults.map(\.objectID)
  193. }
  194. }
  195. @MainActor private func sendGlucoseNotification() async {
  196. do {
  197. addAppBadge(glucose: nil)
  198. let glucoseIDs = await fetchGlucoseIDs()
  199. let glucoseObjects = try glucoseIDs.compactMap { id in
  200. try viewContext.existingObject(with: id) as? GlucoseStored
  201. }
  202. guard let lastReading = glucoseObjects.first?.glucose,
  203. let secondLastReading = glucoseObjects.dropFirst().first?.glucose,
  204. let lastDirection = glucoseObjects.first?.directionEnum?.symbol else { return }
  205. addAppBadge(glucose: (glucoseObjects.first?.glucose).map { Int($0) })
  206. guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else { return }
  207. ensureCanSendNotification {
  208. var titles: [String] = []
  209. var notificationAlarm = false
  210. switch self.glucoseStorage.alarm {
  211. case .none:
  212. titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
  213. case .low:
  214. titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
  215. notificationAlarm = true
  216. case .high:
  217. titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
  218. notificationAlarm = true
  219. }
  220. let delta = glucoseObjects.count >= 2 ? lastReading - secondLastReading : nil
  221. let body = self.glucoseText(
  222. glucoseValue: Int(lastReading),
  223. delta: Int(delta ?? 0),
  224. direction: lastDirection
  225. ) + self.infoBody()
  226. if self.snoozeUntilDate > Date() {
  227. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  228. notificationAlarm = false
  229. } else {
  230. titles.append(body)
  231. let content = UNMutableNotificationContent()
  232. content.title = titles.joined(separator: " ")
  233. content.body = body
  234. if notificationAlarm {
  235. self.playSoundIfNeeded()
  236. content.sound = .default
  237. content.userInfo[NotificationAction.key] = NotificationAction.snooze.rawValue
  238. }
  239. self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
  240. }
  241. }
  242. } catch {
  243. debugPrint(
  244. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to send glucose notification with error: \(error.localizedDescription)"
  245. )
  246. }
  247. }
  248. private func glucoseText(glucoseValue: Int, delta: Int?, direction: String?) -> String {
  249. let units = settingsManager.settings.units
  250. let glucoseText = glucoseFormatter
  251. .string(from: Double(
  252. units == .mmolL ? glucoseValue
  253. .asMmolL : Decimal(glucoseValue)
  254. ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
  255. let directionText = direction ?? "↔︎"
  256. let deltaText = delta
  257. .map {
  258. self.deltaFormatter
  259. .string(from: Double(
  260. units == .mmolL ? $0
  261. .asMmolL : Decimal($0)
  262. ) as NSNumber)!
  263. } ?? "--"
  264. return glucoseText + " " + directionText + " " + deltaText
  265. }
  266. private func infoBody() -> String {
  267. var body = ""
  268. if settingsManager.settings.addSourceInfoToGlucoseNotifications,
  269. let info = sourceInfoProvider.sourceInfo()
  270. {
  271. // Description
  272. if let description = info[GlucoseSourceKey.description.rawValue] as? String {
  273. body.append("\n" + description)
  274. }
  275. // NS ping
  276. if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
  277. body.append(
  278. "\n"
  279. + String(
  280. format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
  281. Int(ping * 1000)
  282. )
  283. )
  284. }
  285. // Transmitter battery
  286. if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
  287. body.append(
  288. "\n"
  289. + String(
  290. format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
  291. "\(transmitterBattery)"
  292. )
  293. )
  294. }
  295. }
  296. return body
  297. }
  298. private func requestNotificationPermissionsIfNeeded() {
  299. center.getNotificationSettings { settings in
  300. debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
  301. if ![.authorized, .provisional].contains(settings.authorizationStatus) {
  302. self.requestNotificationPermissions()
  303. }
  304. }
  305. }
  306. private func requestNotificationPermissions() {
  307. debug(.service, "requestNotificationPermissions")
  308. center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
  309. if granted {
  310. debug(.service, "requestNotificationPermissions was granted")
  311. } else {
  312. warning(.service, "requestNotificationPermissions failed", error: error)
  313. }
  314. }
  315. }
  316. private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
  317. center.getNotificationSettings { settings in
  318. guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
  319. warning(.service, "ensureCanSendNotification failed, authorization denied")
  320. return
  321. }
  322. debug(.service, "Sending notification was allowed")
  323. completion()
  324. }
  325. }
  326. private func addRequest(
  327. identifier: Identifier,
  328. content: UNMutableNotificationContent,
  329. deleteOld: Bool = false,
  330. trigger: UNNotificationTrigger? = nil
  331. ) {
  332. let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
  333. if deleteOld {
  334. DispatchQueue.main.async {
  335. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  336. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  337. }
  338. }
  339. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  340. self.center.add(request) { error in
  341. if let error = error {
  342. warning(.service, "Unable to addNotificationRequest", error: error)
  343. return
  344. }
  345. debug(.service, "Sending \(identifier) notification")
  346. }
  347. }
  348. }
  349. private func playSoundIfNeeded() {
  350. guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
  351. Self.stopPlaying = false
  352. playSound()
  353. }
  354. static let soundID: UInt32 = 1336
  355. private static var stopPlaying = false
  356. private func playSound(times: Int = 1) {
  357. guard times > 0, !Self.stopPlaying else {
  358. return
  359. }
  360. AudioServicesPlaySystemSoundWithCompletion(Self.soundID) {
  361. self.playSound(times: times - 1)
  362. }
  363. }
  364. static func stopSound() {
  365. stopPlaying = true
  366. AudioServicesDisposeSystemSoundID(soundID)
  367. }
  368. private var glucoseFormatter: NumberFormatter {
  369. let formatter = NumberFormatter()
  370. formatter.numberStyle = .decimal
  371. formatter.maximumFractionDigits = 0
  372. if settingsManager.settings.units == .mmolL {
  373. formatter.minimumFractionDigits = 1
  374. formatter.maximumFractionDigits = 1
  375. }
  376. formatter.roundingMode = .halfUp
  377. return formatter
  378. }
  379. private var deltaFormatter: NumberFormatter {
  380. let formatter = NumberFormatter()
  381. formatter.numberStyle = .decimal
  382. formatter.maximumFractionDigits = 1
  383. formatter.positivePrefix = "+"
  384. return formatter
  385. }
  386. }
  387. extension BaseUserNotificationsManager: pumpNotificationObserver {
  388. func pumpNotification(alert: AlertEntry) {
  389. ensureCanSendNotification {
  390. let content = UNMutableNotificationContent()
  391. content.title = alert.contentTitle ?? "Unknown"
  392. content.body = alert.contentBody ?? "Unknown"
  393. content.sound = .default
  394. self.addRequest(
  395. identifier: .pumpNotification,
  396. content: content,
  397. deleteOld: true,
  398. trigger: nil
  399. )
  400. }
  401. }
  402. func pumpRemoveNotification() {
  403. let identifier: Identifier = .pumpNotification
  404. DispatchQueue.main.async {
  405. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  406. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  407. }
  408. }
  409. }
  410. extension BaseUserNotificationsManager: DeterminationObserver {
  411. func determinationDidUpdate(_ determination: Determination) {
  412. guard let carndRequired = determination.carbsReq else { return }
  413. notifyCarbsRequired(Int(carndRequired))
  414. }
  415. }
  416. extension BaseUserNotificationsManager: BolusFailureObserver {
  417. func bolusDidFail() {
  418. notifyBolusFailure()
  419. }
  420. }
  421. extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
  422. func userNotificationCenter(
  423. _: UNUserNotificationCenter,
  424. willPresent _: UNNotification,
  425. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  426. ) {
  427. completionHandler([.banner, .badge, .sound])
  428. }
  429. func userNotificationCenter(
  430. _: UNUserNotificationCenter,
  431. didReceive response: UNNotificationResponse,
  432. withCompletionHandler completionHandler: @escaping () -> Void
  433. ) {
  434. defer { completionHandler() }
  435. guard let actionRaw = response.notification.request.content.userInfo[NotificationAction.key] as? String,
  436. let action = NotificationAction(rawValue: actionRaw)
  437. else { return }
  438. switch action {
  439. case .snooze:
  440. router.mainModalScreen.send(.snooze)
  441. }
  442. }
  443. }