UserNotificationsManager.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. }
  11. final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, Injectable {
  12. private enum Identifier: String {
  13. case glucocoseNotification = "FreeAPS.glucoseNotification"
  14. }
  15. @Injected() private var settingsManager: SettingsManager!
  16. @Injected() private var broadcaster: Broadcaster!
  17. @Injected() private var glucoseStorage: GlucoseStorage!
  18. @Injected(as: FetchGlucoseManager.self) private var sourceInfoProvider: SourceInfoProvider!
  19. @Persisted(key: "UserNotificationsManager.snoozeUntilDate") private var snoozeUntilDate: Date = .distantPast
  20. private let center = UNUserNotificationCenter.current()
  21. init(resolver: Resolver) {
  22. super.init()
  23. center.delegate = self
  24. injectServices(resolver)
  25. broadcaster.register(GlucoseObserver.self, observer: self)
  26. requestNotificationPermissionsIfNeeded()
  27. sendGlucoseNotification()
  28. }
  29. private func addAppBadge(glucose: Int?) {
  30. guard let glucose = glucose, settingsManager.settings.glucoseBadge else {
  31. DispatchQueue.main.async {
  32. UIApplication.shared.applicationIconBadgeNumber = 0
  33. }
  34. return
  35. }
  36. let badge: Int
  37. if settingsManager.settings.units == .mmolL {
  38. badge = Int(round(Double((glucose * 10).asMmolL)))
  39. } else {
  40. badge = glucose
  41. }
  42. DispatchQueue.main.async {
  43. UIApplication.shared.applicationIconBadgeNumber = badge
  44. }
  45. }
  46. private func sendGlucoseNotification() {
  47. addAppBadge(glucose: nil)
  48. let glucose = glucoseStorage.recent()
  49. guard let lastGlucose = glucose.last, let glucoseValue = lastGlucose.glucose else { return }
  50. addAppBadge(glucose: lastGlucose.glucose)
  51. guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else {
  52. return
  53. }
  54. ensureCanSendNotification {
  55. var titles: [String] = []
  56. switch self.glucoseStorage.alarm {
  57. case .none:
  58. titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
  59. case .low:
  60. titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
  61. self.playSoundIfNeeded()
  62. case .high:
  63. titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
  64. self.playSoundIfNeeded()
  65. }
  66. if self.snoozeUntilDate > Date() {
  67. titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
  68. }
  69. let delta = glucose.count >= 2 ? glucoseValue - (glucose[glucose.count - 2].glucose ?? 0) : nil
  70. let body = self.glucoseText(glucoseValue: glucoseValue, delta: delta, direction: lastGlucose.direction) + self
  71. .infoBody()
  72. titles.append(body)
  73. let content = UNMutableNotificationContent()
  74. content.title = titles.joined(separator: " ")
  75. content.body = body
  76. self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
  77. }
  78. }
  79. private func glucoseText(glucoseValue: Int, delta: Int?, direction: BloodGlucose.Direction?) -> String {
  80. let units = settingsManager.settings.units
  81. let glucoseText = glucoseFormatter
  82. .string(from: Double(
  83. units == .mmolL ? glucoseValue
  84. .asMmolL : Decimal(glucoseValue)
  85. ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
  86. let directionText = direction?.symbol ?? "↔︎"
  87. let deltaText = delta
  88. .map {
  89. self.deltaFormatter
  90. .string(from: Double(
  91. units == .mmolL ? $0
  92. .asMmolL : Decimal($0)
  93. ) as NSNumber)!
  94. } ?? "--"
  95. return glucoseText + " " + directionText + " " + deltaText
  96. }
  97. private func infoBody() -> String {
  98. var body = ""
  99. if settingsManager.settings.addSourceInfoToGlucoseNotifications,
  100. let info = sourceInfoProvider.sourceInfo()
  101. {
  102. // NS ping
  103. if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
  104. body.append(
  105. "\n"
  106. + String(
  107. format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
  108. Int(ping * 1000)
  109. )
  110. )
  111. }
  112. // Transmitter battery
  113. if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
  114. body.append(
  115. "\n"
  116. + String(
  117. format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
  118. transmitterBattery
  119. )
  120. )
  121. }
  122. }
  123. return body
  124. }
  125. private func requestNotificationPermissionsIfNeeded() {
  126. center.getNotificationSettings { settings in
  127. debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
  128. if ![.authorized, .provisional].contains(settings.authorizationStatus) {
  129. self.requestNotificationPermissions()
  130. }
  131. }
  132. }
  133. private func requestNotificationPermissions() {
  134. debug(.service, "requestNotificationPermissions")
  135. center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
  136. if granted {
  137. debug(.service, "requestNotificationPermissions was granted")
  138. } else {
  139. warning(.service, "requestNotificationPermissions failed", error: error)
  140. }
  141. }
  142. }
  143. private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
  144. center.getNotificationSettings { settings in
  145. guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
  146. warning(.service, "ensureCanSendNotification failed, authorization denied")
  147. return
  148. }
  149. debug(.service, "Sending notification was allowed")
  150. completion()
  151. }
  152. }
  153. private func addRequest(identifier: Identifier, content: UNMutableNotificationContent, deleteOld: Bool = false) {
  154. let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: nil)
  155. if deleteOld {
  156. center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
  157. center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
  158. }
  159. center.add(request) { error in
  160. if let error = error {
  161. warning(.service, "Unable to addNotificationRequest", error: error)
  162. return
  163. }
  164. debug(.service, "Sending \(identifier) notification")
  165. }
  166. }
  167. private func playSoundIfNeeded() {
  168. guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
  169. playSound()
  170. }
  171. private let soundID: UInt32 = 1336
  172. private func playSound(times: Int = 3) {
  173. guard times > 0 else {
  174. return
  175. }
  176. AudioServicesPlaySystemSoundWithCompletion(soundID) {
  177. self.playSound(times: times - 1)
  178. }
  179. }
  180. private func stopSound() {
  181. AudioServicesDisposeSystemSoundID(soundID)
  182. }
  183. private var glucoseFormatter: NumberFormatter {
  184. let formatter = NumberFormatter()
  185. formatter.numberStyle = .decimal
  186. formatter.maximumFractionDigits = 0
  187. if settingsManager.settings.units == .mmolL {
  188. formatter.minimumFractionDigits = 1
  189. formatter.maximumFractionDigits = 1
  190. }
  191. formatter.roundingMode = .halfUp
  192. return formatter
  193. }
  194. private var deltaFormatter: NumberFormatter {
  195. let formatter = NumberFormatter()
  196. formatter.numberStyle = .decimal
  197. formatter.maximumFractionDigits = 2
  198. formatter.positivePrefix = "+"
  199. return formatter
  200. }
  201. }
  202. extension BaseUserNotificationsManager: GlucoseObserver {
  203. func glucoseDidUpdate(_: [BloodGlucose]) {
  204. sendGlucoseNotification()
  205. }
  206. }
  207. extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
  208. func userNotificationCenter(
  209. _: UNUserNotificationCenter,
  210. willPresent _: UNNotification,
  211. withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  212. ) {
  213. completionHandler([.banner, .badge, .sound])
  214. }
  215. }