UserNotificationsManager.swift 13 KB

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