UserNotificationsManager.swift 16 KB

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