UserNotificationsManager.swift 8.6 KB

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