UserNotificationsManager.swift 16 KB

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