UserNotificationsManager.swift 14 KB

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