UserNotificationsManager.swift 17 KB

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