UserNotificationsManager.swift 15 KB

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