UserNotificationsManager.swift 19 KB

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