UserNotificationsManager.swift 16 KB

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