UserNotificationsManager.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else {
  157. return
  158. }
  159. ensureCanSendNotification {
  160. var titles: [String] = []
  161. var notificationAlarm = false
  162. switch self.glucoseStorage.alarm {
  163. case .none:
  164. titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
  165. case .low:
  166. titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
  167. notificationAlarm = true
  168. case .high:
  169. titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
  170. notificationAlarm = true
  171. }
  172. let delta = glucose.count >= 2 ? glucoseValue - (glucose[glucose.count - 2].glucose ?? 0) : nil
  173. let body = self.glucoseText(glucoseValue: glucoseValue, delta: delta, direction: lastGlucose.direction) + self
  174. .infoBody()
  175. if self.snoozeUntilDate > Date() {
  176. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  177. notificationAlarm = false
  178. } else {
  179. titles.append(body)
  180. let content = UNMutableNotificationContent()
  181. content.title = titles.joined(separator: " ")
  182. content.body = body
  183. if notificationAlarm {
  184. self.playSoundIfNeeded()
  185. content.sound = .default
  186. content.userInfo[NotificationAction.key] = NotificationAction.snooze.rawValue
  187. }
  188. self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
  189. }
  190. }
  191. }
  192. private func glucoseText(glucoseValue: Int, delta: Int?, direction: BloodGlucose.Direction?) -> String {
  193. let units = settingsManager.settings.units
  194. let glucoseText = glucoseFormatter
  195. .string(from: Double(
  196. units == .mmolL ? glucoseValue
  197. .asMmolL : Decimal(glucoseValue)
  198. ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
  199. let directionText = direction?.symbol ?? "↔︎"
  200. let deltaText = delta
  201. .map {
  202. self.deltaFormatter
  203. .string(from: Double(
  204. units == .mmolL ? $0
  205. .asMmolL : Decimal($0)
  206. ) as NSNumber)!
  207. } ?? "--"
  208. return glucoseText + " " + directionText + " " + deltaText
  209. }
  210. private func infoBody() -> String {
  211. var body = ""
  212. if settingsManager.settings.addSourceInfoToGlucoseNotifications,
  213. let info = sourceInfoProvider.sourceInfo()
  214. {
  215. // Description
  216. if let description = info[GlucoseSourceKey.description.rawValue] as? String {
  217. body.append("\n" + description)
  218. }
  219. // NS ping
  220. if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
  221. body.append(
  222. "\n"
  223. + String(
  224. format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
  225. Int(ping * 1000)
  226. )
  227. )
  228. }
  229. // Transmitter battery
  230. if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
  231. body.append(
  232. "\n"
  233. + String(
  234. format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
  235. "\(transmitterBattery)"
  236. )
  237. )
  238. }
  239. }
  240. return body
  241. }
  242. private func requestNotificationPermissionsIfNeeded() {
  243. center.getNotificationSettings { settings in
  244. debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
  245. if ![.authorized, .provisional].contains(settings.authorizationStatus) {
  246. self.requestNotificationPermissions()
  247. }
  248. }
  249. }
  250. private func requestNotificationPermissions() {
  251. debug(.service, "requestNotificationPermissions")
  252. center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
  253. if granted {
  254. debug(.service, "requestNotificationPermissions was granted")
  255. } else {
  256. warning(.service, "requestNotificationPermissions failed", error: error)
  257. }
  258. }
  259. }
  260. private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
  261. center.getNotificationSettings { settings in
  262. guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
  263. warning(.service, "ensureCanSendNotification failed, authorization denied")
  264. return
  265. }
  266. debug(.service, "Sending notification was allowed")
  267. completion()
  268. }
  269. }
  270. private func addRequest(
  271. identifier: Identifier,
  272. content: UNMutableNotificationContent,
  273. deleteOld: Bool = false,
  274. trigger: UNNotificationTrigger? = nil
  275. ) {
  276. let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
  277. if deleteOld {
  278. DispatchQueue.main.async {
  279. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  280. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  281. }
  282. }
  283. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  284. self.center.add(request) { error in
  285. if let error = error {
  286. warning(.service, "Unable to addNotificationRequest", error: error)
  287. return
  288. }
  289. debug(.service, "Sending \(identifier) notification")
  290. }
  291. }
  292. }
  293. private func playSoundIfNeeded() {
  294. guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
  295. Self.stopPlaying = false
  296. playSound()
  297. }
  298. static let soundID: UInt32 = 1336
  299. private static var stopPlaying = false
  300. private func playSound(times: Int = 1) {
  301. guard times > 0, !Self.stopPlaying else {
  302. return
  303. }
  304. AudioServicesPlaySystemSoundWithCompletion(Self.soundID) {
  305. self.playSound(times: times - 1)
  306. }
  307. }
  308. static func stopSound() {
  309. stopPlaying = true
  310. AudioServicesDisposeSystemSoundID(soundID)
  311. }
  312. private var glucoseFormatter: NumberFormatter {
  313. let formatter = NumberFormatter()
  314. formatter.numberStyle = .decimal
  315. formatter.maximumFractionDigits = 0
  316. if settingsManager.settings.units == .mmolL {
  317. formatter.minimumFractionDigits = 1
  318. formatter.maximumFractionDigits = 1
  319. }
  320. formatter.roundingMode = .halfUp
  321. return formatter
  322. }
  323. private var deltaFormatter: NumberFormatter {
  324. let formatter = NumberFormatter()
  325. formatter.numberStyle = .decimal
  326. formatter.maximumFractionDigits = 1
  327. formatter.positivePrefix = "+"
  328. return formatter
  329. }
  330. }
  331. extension BaseUserNotificationsManager: GlucoseObserver {
  332. func glucoseDidUpdate(_: [BloodGlucose]) {
  333. sendGlucoseNotification()
  334. }
  335. }
  336. extension BaseUserNotificationsManager: pumpNotificationObserver {
  337. func pumpNotification(alert: AlertEntry) {
  338. ensureCanSendNotification {
  339. let content = UNMutableNotificationContent()
  340. content.title = alert.contentTitle ?? "Unknown"
  341. content.body = alert.contentBody ?? "Unknown"
  342. content.sound = .default
  343. self.addRequest(
  344. identifier: .pumpNotification,
  345. content: content,
  346. deleteOld: true,
  347. trigger: nil
  348. )
  349. }
  350. }
  351. func pumpRemoveNotification() {
  352. let identifier: Identifier = .pumpNotification
  353. DispatchQueue.main.async {
  354. self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  355. self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  356. }
  357. }
  358. }
  359. extension BaseUserNotificationsManager: SuggestionObserver {
  360. func suggestionDidUpdate(_ suggestion: Suggestion) {
  361. guard let carndRequired = suggestion.carbsReq else { return }
  362. notifyCarbsRequired(Int(carndRequired))
  363. }
  364. }
  365. extension BaseUserNotificationsManager: BolusFailureObserver {
  366. func bolusDidFail() {
  367. notifyBolusFailure()
  368. }
  369. }
  370. extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
  371. func userNotificationCenter(
  372. _: UNUserNotificationCenter,
  373. willPresent _: UNNotification,
  374. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  375. ) {
  376. completionHandler([.banner, .badge, .sound])
  377. }
  378. func userNotificationCenter(
  379. _: UNUserNotificationCenter,
  380. didReceive response: UNNotificationResponse,
  381. withCompletionHandler completionHandler: @escaping () -> Void
  382. ) {
  383. defer { completionHandler() }
  384. guard let actionRaw = response.notification.request.content.userInfo[NotificationAction.key] as? String,
  385. let action = NotificationAction(rawValue: actionRaw)
  386. else { return }
  387. switch action {
  388. case .snooze:
  389. router.mainModalScreen.send(.snooze)
  390. }
  391. }
  392. }