| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524 |
- import AudioToolbox
- import CoreData
- import Foundation
- import LoopKit
- import SwiftUI
- import Swinject
- import UIKit
- import UserNotifications
- protocol UserNotificationsManager {}
- enum GlucoseSourceKey: String {
- case transmitterBattery
- case nightscoutPing
- case description
- }
- enum NotificationAction: String {
- static let key = "action"
- case snooze
- }
- protocol BolusFailureObserver {
- func bolusDidFail()
- }
- protocol pumpNotificationObserver {
- func pumpNotification(alert: AlertEntry)
- func pumpRemoveNotification()
- }
- final class BaseUserNotificationsManager: NSObject, UserNotificationsManager, Injectable {
- private enum Identifier: String {
- case glucocoseNotification = "FreeAPS.glucoseNotification"
- case carbsRequiredNotification = "FreeAPS.carbsRequiredNotification"
- case noLoopFirstNotification = "FreeAPS.noLoopFirstNotification"
- case noLoopSecondNotification = "FreeAPS.noLoopSecondNotification"
- case bolusFailedNotification = "FreeAPS.bolusFailedNotification"
- case pumpNotification = "FreeAPS.pumpNotification"
- }
- @Injected() private var settingsManager: SettingsManager!
- @Injected() private var broadcaster: Broadcaster!
- @Injected() private var glucoseStorage: GlucoseStorage!
- @Injected() private var apsManager: APSManager!
- @Injected() private var router: Router!
- @Injected(as: FetchGlucoseManager.self) private var sourceInfoProvider: SourceInfoProvider!
- @Persisted(key: "UserNotificationsManager.snoozeUntilDate") private var snoozeUntilDate: Date = .distantPast
- private let center = UNUserNotificationCenter.current()
- private var lifetime = Lifetime()
- private let viewContext = CoreDataStack.shared.persistentContainer.viewContext
- private let backgroundContext = CoreDataStack.shared.newTaskContext()
- private var coreDataObserver: CoreDataObserver?
- init(resolver: Resolver) {
- super.init()
- center.delegate = self
- injectServices(resolver)
- broadcaster.register(DeterminationObserver.self, observer: self)
- broadcaster.register(BolusFailureObserver.self, observer: self)
- broadcaster.register(pumpNotificationObserver.self, observer: self)
- requestNotificationPermissionsIfNeeded()
- Task {
- await sendGlucoseNotification()
- }
- registerHandlers()
- setupGlucoseNotification()
- subscribeOnLoop()
- }
- private func subscribeOnLoop() {
- apsManager.lastLoopDateSubject
- .sink { [weak self] date in
- self?.scheduleMissingLoopNotifiactions(date: date)
- }
- .store(in: &lifetime)
- }
- private func registerHandlers() {
- // Due to the Batch insert this only is used for observing Deletion of Glucose entries
- coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
- guard let self = self else { return }
- Task {
- await self.sendGlucoseNotification()
- }
- }
- }
- private func setupGlucoseNotification() {
- /// custom notification that is sent when a batch insert of glucose objects is done
- Foundation.NotificationCenter.default.addObserver(
- self,
- selector: #selector(handleBatchInsert),
- name: .didPerformBatchInsert,
- object: nil
- )
- }
- @objc private func handleBatchInsert() {
- Task {
- await sendGlucoseNotification()
- }
- }
- private func addAppBadge(glucose: Int?) {
- guard let glucose = glucose, settingsManager.settings.glucoseBadge else {
- DispatchQueue.main.async {
- UIApplication.shared.applicationIconBadgeNumber = 0
- }
- return
- }
- let badge: Int
- if settingsManager.settings.units == .mmolL {
- badge = Int(round(Double((glucose * 10).asMmolL)))
- } else {
- badge = glucose
- }
- DispatchQueue.main.async {
- UIApplication.shared.applicationIconBadgeNumber = badge
- }
- }
- private func notifyCarbsRequired(_ carbs: Int) {
- guard Decimal(carbs) >= settingsManager.settings.carbsRequiredThreshold,
- settingsManager.settings.showCarbsRequiredBadge else { return }
- ensureCanSendNotification {
- var titles: [String] = []
- let content = UNMutableNotificationContent()
- if self.snoozeUntilDate > Date() {
- titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
- } else {
- content.sound = .default
- self.playSoundIfNeeded()
- }
- titles.append(String(format: NSLocalizedString("Carbs required: %d g", comment: "Carbs required"), carbs))
- content.title = titles.joined(separator: " ")
- content.body = String(
- format: NSLocalizedString(
- "To prevent LOW required %d g of carbs",
- comment: "To prevent LOW required %d g of carbs"
- ),
- carbs
- )
- self.addRequest(identifier: .carbsRequiredNotification, content: content, deleteOld: true)
- }
- }
- private func scheduleMissingLoopNotifiactions(date _: Date) {
- ensureCanSendNotification {
- let title = NSLocalizedString("Trio Not Active", comment: "Trio Not Active")
- let body = NSLocalizedString("Last loop was more than %d min ago", comment: "Last loop was more than %d min ago")
- let firstInterval = 20 // min
- let secondInterval = 40 // min
- let firstContent = UNMutableNotificationContent()
- firstContent.title = title
- firstContent.body = String(format: body, firstInterval)
- firstContent.sound = .default
- let secondContent = UNMutableNotificationContent()
- secondContent.title = title
- secondContent.body = String(format: body, secondInterval)
- secondContent.sound = .default
- let firstTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(firstInterval), repeats: false)
- let secondTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60 * TimeInterval(secondInterval), repeats: false)
- self.addRequest(
- identifier: .noLoopFirstNotification,
- content: firstContent,
- deleteOld: true,
- trigger: firstTrigger
- )
- self.addRequest(
- identifier: .noLoopSecondNotification,
- content: secondContent,
- deleteOld: true,
- trigger: secondTrigger
- )
- }
- }
- private func notifyBolusFailure() {
- ensureCanSendNotification {
- let title = NSLocalizedString("Bolus failed", comment: "Bolus failed")
- let body = NSLocalizedString(
- "Bolus failed or inaccurate. Check pump history before repeating.",
- comment: "Bolus failed or inaccurate. Check pump history before repeating."
- )
- let content = UNMutableNotificationContent()
- content.title = title
- content.body = body
- content.sound = .default
- self.addRequest(
- identifier: .noLoopFirstNotification,
- content: content,
- deleteOld: true,
- trigger: nil
- )
- }
- }
- private func fetchGlucoseIDs() async -> [NSManagedObjectID] {
- let results = await CoreDataStack.shared.fetchEntitiesAsync(
- ofType: GlucoseStored.self,
- onContext: backgroundContext,
- predicate: NSPredicate.predicateFor20MinAgo,
- key: "date",
- ascending: false,
- fetchLimit: 3
- )
- guard let fetchedResults = results as? [GlucoseStored] else { return [] }
- return await backgroundContext.perform {
- return fetchedResults.map(\.objectID)
- }
- }
- @MainActor private func sendGlucoseNotification() async {
- do {
- addAppBadge(glucose: nil)
- let glucoseIDs = await fetchGlucoseIDs()
- let glucoseObjects = try glucoseIDs.compactMap { id in
- try viewContext.existingObject(with: id) as? GlucoseStored
- }
- guard let lastReading = glucoseObjects.first?.glucose,
- let secondLastReading = glucoseObjects.dropFirst().first?.glucose,
- let lastDirection = glucoseObjects.first?.directionEnum?.symbol else { return }
- addAppBadge(glucose: (glucoseObjects.first?.glucose).map { Int($0) })
- guard glucoseStorage.alarm != nil || settingsManager.settings.glucoseNotificationsAlways else { return }
- ensureCanSendNotification {
- var titles: [String] = []
- var notificationAlarm = false
- switch self.glucoseStorage.alarm {
- case .none:
- titles.append(NSLocalizedString("Glucose", comment: "Glucose"))
- case .low:
- titles.append(NSLocalizedString("LOWALERT!", comment: "LOWALERT!"))
- notificationAlarm = true
- case .high:
- titles.append(NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!"))
- notificationAlarm = true
- }
- let delta = glucoseObjects.count >= 2 ? lastReading - secondLastReading : nil
- let body = self.glucoseText(
- glucoseValue: Int(lastReading),
- delta: Int(delta ?? 0),
- direction: lastDirection
- ) + self.infoBody()
- if self.snoozeUntilDate > Date() {
- titles.append(NSLocalizedString("(Snoozed)", comment: "(Snoozed)"))
- notificationAlarm = false
- } else {
- titles.append(body)
- let content = UNMutableNotificationContent()
- content.title = titles.joined(separator: " ")
- content.body = body
- if notificationAlarm {
- self.playSoundIfNeeded()
- content.sound = .default
- content.userInfo[NotificationAction.key] = NotificationAction.snooze.rawValue
- }
- self.addRequest(identifier: .glucocoseNotification, content: content, deleteOld: true)
- }
- }
- } catch {
- debugPrint(
- "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to send glucose notification with error: \(error.localizedDescription)"
- )
- }
- }
- private func glucoseText(glucoseValue: Int, delta: Int?, direction: String?) -> String {
- let units = settingsManager.settings.units
- let glucoseText = glucoseFormatter
- .string(from: Double(
- units == .mmolL ? glucoseValue
- .asMmolL : Decimal(glucoseValue)
- ) as NSNumber)! + " " + NSLocalizedString(units.rawValue, comment: "units")
- let directionText = direction ?? "↔︎"
- let deltaText = delta
- .map {
- self.deltaFormatter
- .string(from: Double(
- units == .mmolL ? $0
- .asMmolL : Decimal($0)
- ) as NSNumber)!
- } ?? "--"
- return glucoseText + " " + directionText + " " + deltaText
- }
- private func infoBody() -> String {
- var body = ""
- if settingsManager.settings.addSourceInfoToGlucoseNotifications,
- let info = sourceInfoProvider.sourceInfo()
- {
- // Description
- if let description = info[GlucoseSourceKey.description.rawValue] as? String {
- body.append("\n" + description)
- }
- // NS ping
- if let ping = info[GlucoseSourceKey.nightscoutPing.rawValue] as? TimeInterval {
- body.append(
- "\n"
- + String(
- format: NSLocalizedString("Nightscout ping: %d ms", comment: "Nightscout ping"),
- Int(ping * 1000)
- )
- )
- }
- // Transmitter battery
- if let transmitterBattery = info[GlucoseSourceKey.transmitterBattery.rawValue] as? Int {
- body.append(
- "\n"
- + String(
- format: NSLocalizedString("Transmitter: %@%%", comment: "Transmitter: %@%%"),
- "\(transmitterBattery)"
- )
- )
- }
- }
- return body
- }
- private func requestNotificationPermissionsIfNeeded() {
- center.getNotificationSettings { settings in
- debug(.service, "UNUserNotificationCenter.authorizationStatus: \(String(describing: settings.authorizationStatus))")
- if ![.authorized, .provisional].contains(settings.authorizationStatus) {
- self.requestNotificationPermissions()
- }
- }
- }
- private func requestNotificationPermissions() {
- debug(.service, "requestNotificationPermissions")
- center.requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in
- if granted {
- debug(.service, "requestNotificationPermissions was granted")
- } else {
- warning(.service, "requestNotificationPermissions failed", error: error)
- }
- }
- }
- private func ensureCanSendNotification(_ completion: @escaping () -> Void) {
- center.getNotificationSettings { settings in
- guard settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional else {
- warning(.service, "ensureCanSendNotification failed, authorization denied")
- return
- }
- debug(.service, "Sending notification was allowed")
- completion()
- }
- }
- private func addRequest(
- identifier: Identifier,
- content: UNMutableNotificationContent,
- deleteOld: Bool = false,
- trigger: UNNotificationTrigger? = nil
- ) {
- let request = UNNotificationRequest(identifier: identifier.rawValue, content: content, trigger: trigger)
- if deleteOld {
- DispatchQueue.main.async {
- self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
- self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
- }
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
- self.center.add(request) { error in
- if let error = error {
- warning(.service, "Unable to addNotificationRequest", error: error)
- return
- }
- debug(.service, "Sending \(identifier) notification")
- }
- }
- }
- private func playSoundIfNeeded() {
- guard settingsManager.settings.useAlarmSound, snoozeUntilDate < Date() else { return }
- Self.stopPlaying = false
- playSound()
- }
- static let soundID: UInt32 = 1336
- private static var stopPlaying = false
- private func playSound(times: Int = 1) {
- guard times > 0, !Self.stopPlaying else {
- return
- }
- AudioServicesPlaySystemSoundWithCompletion(Self.soundID) {
- self.playSound(times: times - 1)
- }
- }
- static func stopSound() {
- stopPlaying = true
- AudioServicesDisposeSystemSoundID(soundID)
- }
- private var glucoseFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 0
- if settingsManager.settings.units == .mmolL {
- formatter.minimumFractionDigits = 1
- formatter.maximumFractionDigits = 1
- }
- formatter.roundingMode = .halfUp
- return formatter
- }
- private var deltaFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 1
- formatter.positivePrefix = "+"
- return formatter
- }
- }
- extension BaseUserNotificationsManager: pumpNotificationObserver {
- func pumpNotification(alert: AlertEntry) {
- ensureCanSendNotification {
- let content = UNMutableNotificationContent()
- content.title = alert.contentTitle ?? "Unknown"
- content.body = alert.contentBody ?? "Unknown"
- content.sound = .default
- self.addRequest(
- identifier: .pumpNotification,
- content: content,
- deleteOld: true,
- trigger: nil
- )
- }
- }
- func pumpRemoveNotification() {
- let identifier: Identifier = .pumpNotification
- DispatchQueue.main.async {
- self.center.removeDeliveredNotifications(withIdentifiers: [identifier.rawValue])
- self.center.removePendingNotificationRequests(withIdentifiers: [identifier.rawValue])
- }
- }
- }
- extension BaseUserNotificationsManager: DeterminationObserver {
- func determinationDidUpdate(_ determination: Determination) {
- guard let carndRequired = determination.carbsReq else { return }
- notifyCarbsRequired(Int(carndRequired))
- }
- }
- extension BaseUserNotificationsManager: BolusFailureObserver {
- func bolusDidFail() {
- notifyBolusFailure()
- }
- }
- extension BaseUserNotificationsManager: UNUserNotificationCenterDelegate {
- func userNotificationCenter(
- _: UNUserNotificationCenter,
- willPresent _: UNNotification,
- withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
- ) {
- completionHandler([.banner, .badge, .sound])
- }
- func userNotificationCenter(
- _: UNUserNotificationCenter,
- didReceive response: UNNotificationResponse,
- withCompletionHandler completionHandler: @escaping () -> Void
- ) {
- defer { completionHandler() }
- guard let actionRaw = response.notification.request.content.userInfo[NotificationAction.key] as? String,
- let action = NotificationAction(rawValue: actionRaw)
- else { return }
- switch action {
- case .snooze:
- router.mainModalScreen.send(.snooze)
- }
- }
- }
|