diff --git a/LoopFollow/Application/AppDelegate.swift b/LoopFollow/Application/AppDelegate.swift index 66b06478d..7583268ae 100644 --- a/LoopFollow/Application/AppDelegate.swift +++ b/LoopFollow/Application/AppDelegate.swift @@ -323,6 +323,13 @@ extension AppDelegate: UNUserNotificationCenterDelegate { return } + // Loop's and Trio's replies to remote commands stay in Notification Center to be read later. + // Alarms are handled on screen, and a listed alarm's snooze action would act on the current alarm. + if content.userInfo["command_status"] != nil { + completionHandler([.banner, .list, .sound, .badge]) + return + } + completionHandler([.banner, .sound, .badge]) } } diff --git a/LoopFollow/Controllers/Nightscout/Treatments.swift b/LoopFollow/Controllers/Nightscout/Treatments.swift index 9774eff1b..d1f5516cc 100644 --- a/LoopFollow/Controllers/Nightscout/Treatments.swift +++ b/LoopFollow/Controllers/Nightscout/Treatments.swift @@ -37,6 +37,52 @@ extension MainViewController { return rawDate.flatMap(NightscoutUtils.parseDate) } + /// The greatest 24-hex-digit `_id` among the entries. Nightscout `_id`s are Mongo ObjectIds, which sort by server insert time + /// (first 8 hex digits, seconds); ids dated more than 5 minutes after `now` are skipped. + static func knownThroughID(_ entries: [[String: AnyObject]], now: Date = Date()) -> String? { + let latest = now.addingTimeInterval(5 * 60).timeIntervalSince1970 + return entries + .compactMap { $0["_id"] as? String } + .filter { $0.count == 24 && $0.allSatisfy { $0.isASCII && $0.isHexDigit } } + .filter { UInt32($0.prefix(8), radix: 16).map { TimeInterval($0) <= latest } ?? false } + .map { $0.lowercased() } + .max() + } + + /// The Nightscout site and hub a treatments download reads from; the marker is cleared when any of them changes. + struct TreatmentsSite: Equatable { + let url: String + let token: String + let hubURL: String + var hubMode = false + var deviceKey = "" + + static var current: TreatmentsSite { + TreatmentsSite( + url: Storage.shared.url.value, + token: Storage.shared.token.value, + hubURL: Storage.shared.hubURL.value, + hubMode: HubClient.shared.isHubMode, + deviceKey: HubClient.shared.deviceKey.value + ) + } + } + + /// Stores the marker of a download that started at `site`, provided the site is still `current` and treatments are still downloaded. + static func storeKnownThroughID( + _ entries: [[String: AnyObject]], + fetchedFrom site: TreatmentsSite, + current: TreatmentsSite = .current, + downloadsTreatments: Bool = Storage.shared.downloadTreatments.value, + now: Date = Date() + ) { + guard site == current, downloadsTreatments else { + LogManager.shared.log(category: .nightscout, message: "Treatments marker skipped: the site or the treatment download changed during the download") + return + } + Observable.shared.treatmentsKnownThroughID.value = knownThroughID(entries, now: now) + } + // NS Treatments Web Call // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides func WebLoadNSTreatments() { @@ -50,12 +96,13 @@ extension MainViewController { "find[created_at][$lte]": endTimeString, "count": "\(estimatedCount)", ] + let site = TreatmentsSite.current NightscoutUtils.executeDynamicRequest(eventType: .treatments, parameters: parameters, hubPart: .treatments) { (result: Result) in switch result { case let .success(data): if let entries = data as? [[String: AnyObject]] { DispatchQueue.main.async { - self.updateTreatments(entries: entries) + self.updateTreatments(entries: entries, site: site) } } else { LogManager.shared.log(category: .nightscout, message: "WebLoadNSTreatments, Unexpected data structure") @@ -67,7 +114,8 @@ extension MainViewController { } // Process and split out treatments to individual tasks - func updateTreatments(entries: [[String: AnyObject]]) { + func updateTreatments(entries: [[String: AnyObject]], site: TreatmentsSite) { + Self.storeKnownThroughID(entries, fetchedFrom: site) let uniqueEntries = Self.deduplicatedTreatmentEntries(entries) var tempBasal: [[String: AnyObject]] = [] diff --git a/LoopFollow/Remote/LoopAPNS/LoopAPNSBolusView.swift b/LoopFollow/Remote/LoopAPNS/LoopAPNSBolusView.swift index 59260eb55..24bfe1783 100644 --- a/LoopFollow/Remote/LoopAPNS/LoopAPNSBolusView.swift +++ b/LoopFollow/Remote/LoopAPNS/LoopAPNSBolusView.swift @@ -22,6 +22,8 @@ struct LoopAPNSBolusView: View { @State private var otpTimeRemaining: Int? = nil @State private var showOldCalculationWarning = false @State private var showTOTPWarning = false + /// The treatments marker as the user sees it on this screen. + @State private var origin = RemoteCommandOrigin.phoneScreenAppeared() private let otpPeriod: TimeInterval = 30 private var otpTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() @@ -202,6 +204,7 @@ struct LoopAPNSBolusView: View { .navigationBarTitleDisplayMode(.inline) } + .remoteCommandOrigin($origin) .onAppear { // Validate APNS setup let apnsService = LoopAPNSService() @@ -400,7 +403,7 @@ struct LoopAPNSBolusView: View { ) let apnsService = LoopAPNSService() - apnsService.sendBolusViaAPNS(payload: payload) { success, errorMessage in + apnsService.sendBolusViaAPNS(payload: payload, origin: origin) { success, errorMessage in DispatchQueue.main.async { self.isLoading = false if success { diff --git a/LoopFollow/Remote/LoopAPNS/LoopAPNSCarbsView.swift b/LoopFollow/Remote/LoopAPNS/LoopAPNSCarbsView.swift index 2e8cac6f7..a2972a1f4 100644 --- a/LoopFollow/Remote/LoopAPNS/LoopAPNSCarbsView.swift +++ b/LoopFollow/Remote/LoopAPNS/LoopAPNSCarbsView.swift @@ -23,6 +23,8 @@ struct LoopAPNSCarbsView: View { @State private var alertType: AlertType = .success @State private var otpTimeRemaining: Int? = nil @State private var showTOTPWarning = false + /// The treatments marker as the user sees it on this screen. + @State private var origin = RemoteCommandOrigin.phoneScreenAppeared() private let otpPeriod: TimeInterval = 30 private let timeAdjustmentStepMinutes = 5 private let maxPastHours = 12 @@ -405,6 +407,7 @@ struct LoopAPNSCarbsView: View { normalizeAbsorptionTime() } } + .remoteCommandOrigin($origin) .onAppear { // Validate APNS setup let apnsService = LoopAPNSService() @@ -565,7 +568,7 @@ struct LoopAPNSCarbsView: View { ) let apnsService = LoopAPNSService() - apnsService.sendCarbsViaAPNS(payload: payload) { success, errorMessage in + apnsService.sendCarbsViaAPNS(payload: payload, origin: origin) { success, errorMessage in DispatchQueue.main.async { self.isLoading = false if success { diff --git a/LoopFollow/Remote/LoopAPNS/LoopAPNSService.swift b/LoopFollow/Remote/LoopAPNS/LoopAPNSService.swift index d586d165a..1bd9b47e8 100644 --- a/LoopFollow/Remote/LoopAPNS/LoopAPNSService.swift +++ b/LoopFollow/Remote/LoopAPNS/LoopAPNSService.swift @@ -238,8 +238,8 @@ class LoopAPNSService { /// - Parameters: /// - payload: The carbs payload to send /// - completion: Completion handler with success status and error message - func sendCarbsViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) { - var finalPayload = LoopAPNSCommands.carbsCommandPayload(payload) + func sendCarbsViaAPNS(payload: LoopAPNSPayload, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) { + var finalPayload = LoopAPNSCommands.carbsCommandPayload(payload, knownThroughID: origin.knownThroughID) if let encryptedReturnInfo = encryptedReturnNotification(otp: payload.otp) { finalPayload["encrypted_return_notification"] = encryptedReturnInfo } @@ -251,8 +251,8 @@ class LoopAPNSService { /// - Parameters: /// - payload: The bolus payload to send /// - completion: Completion handler with success status and error message - func sendBolusViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) { - var finalPayload = LoopAPNSCommands.bolusCommandPayload(payload) + func sendBolusViaAPNS(payload: LoopAPNSPayload, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) { + var finalPayload = LoopAPNSCommands.bolusCommandPayload(payload, knownThroughID: origin.knownThroughID) if let encryptedReturnInfo = encryptedReturnNotification(otp: payload.otp) { finalPayload["encrypted_return_notification"] = encryptedReturnInfo } diff --git a/LoopFollow/Remote/RemoteCommandOrigin.swift b/LoopFollow/Remote/RemoteCommandOrigin.swift new file mode 100644 index 000000000..ae07d690a --- /dev/null +++ b/LoopFollow/Remote/RemoteCommandOrigin.swift @@ -0,0 +1,66 @@ +// LoopFollow +// RemoteCommandOrigin.swift + +import Foundation +import SwiftUI +import UIKit + +/// Where a bolus or carb command was entered. +enum RemoteCommandOrigin: Equatable { + /// Entered on a command screen of the phone; `screenOpenedWith` is the treatments marker when that screen appeared, + /// read from `site`. + case phone(screenOpenedWith: String?, site: MainViewController.TreatmentsSite) + /// Relayed from Apple Watch, which may show older data than the phone. + case watch + + /// A phone command screen that is appearing now: it keeps the treatments marker the user sees while deciding. + static func phoneScreenAppeared() -> RemoteCommandOrigin { + .phone(screenOpenedWith: Observable.shared.treatmentsKnownThroughID.value, site: .current) + } + + /// The treatments marker the command carries. + var knownThroughID: String? { + knownThroughID(current: Observable.shared.treatmentsKnownThroughID.value, currentSite: .current) + } + + /// The older of the marker when the screen appeared and `current`, or whichever of them exists. The marker from + /// when the screen appeared counts only while its site is `currentSite`. Watch commands carry none. + func knownThroughID(current: String?, currentSite: MainViewController.TreatmentsSite) -> String? { + switch self { + case let .phone(screenOpenedWith, site): + let opened = site == currentSite ? screenOpenedWith : nil + return [opened, current].compactMap { $0 }.min() + case .watch: + return nil + } + } +} + +extension View { + /// Keeps `origin` at the treatments marker the user sees on this phone command screen: the marker when the screen + /// appears, and after a return to the foreground the marker of the first treatments download that follows. + func remoteCommandOrigin(_ origin: Binding) -> some View { + modifier(RemoteCommandOriginTracker(origin: origin)) + } +} + +private struct RemoteCommandOriginTracker: ViewModifier { + @Binding var origin: RemoteCommandOrigin + @State private var awaitsDownload = false + + func body(content: Content) -> some View { + content + .onAppear { + origin = .phoneScreenAppeared() + } + .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in + origin = .phoneScreenAppeared() + awaitsDownload = true + } + .onReceive(Observable.shared.treatmentsKnownThroughID.$value.dropFirst()) { marker in + guard awaitsDownload, let marker else { return } + origin = .phone(screenOpenedWith: marker, site: .current) + awaitsDownload = false + } + } +} diff --git a/LoopFollow/Remote/TRC/BolusView.swift b/LoopFollow/Remote/TRC/BolusView.swift index c0be6e408..719686eca 100644 --- a/LoopFollow/Remote/TRC/BolusView.swift +++ b/LoopFollow/Remote/TRC/BolusView.swift @@ -20,6 +20,8 @@ struct BolusView: View { @State private var alertMessage: String? = nil @State private var isLoading = false @State private var statusMessage: String? = nil + /// The treatments marker as the user sees it on this screen. + @State private var origin = RemoteCommandOrigin.phoneScreenAppeared() private let pushNotificationManager = PushNotificationManager() @@ -141,6 +143,7 @@ struct BolusView: View { .navigationTitle("Bolus") .navigationBarTitleDisplayMode(.inline) } + .remoteCommandOrigin($origin) .onAppear { quickPickBoluses.refresh( stepIncrement: stepU, @@ -312,7 +315,7 @@ struct BolusView: View { private func sendBolus() { isLoading = true - pushNotificationManager.sendBolusPushNotification(bolusAmount: bolusAmount) { success, errorMessage in + pushNotificationManager.sendBolusPushNotification(bolusAmount: bolusAmount, origin: origin) { success, errorMessage in DispatchQueue.main.async { isLoading = false if success { diff --git a/LoopFollow/Remote/TRC/MealView.swift b/LoopFollow/Remote/TRC/MealView.swift index 9d9ed0e7e..d40ab6d9f 100644 --- a/LoopFollow/Remote/TRC/MealView.swift +++ b/LoopFollow/Remote/TRC/MealView.swift @@ -35,6 +35,8 @@ struct MealView: View { @State private var selectedTime: Date? = nil @State private var isScheduling: Bool = false @State private var showFatProteinOrderBanner = false + /// The treatments marker as the user sees it on this screen. + @State private var origin = RemoteCommandOrigin.phoneScreenAppeared() enum AlertType { case confirmMeal @@ -187,6 +189,7 @@ struct MealView: View { .navigationTitle("Meal") .navigationBarTitleDisplayMode(.inline) } + .remoteCommandOrigin($origin) .onAppear { selectedTime = nil isScheduling = false @@ -318,7 +321,8 @@ struct MealView: View { protein: protein, fat: fat, bolusAmount: bolusAmount, - scheduledTime: scheduledDate + scheduledTime: scheduledDate, + origin: origin ) { success, errorMessage in DispatchQueue.main.async { isLoading = false diff --git a/LoopFollow/Remote/TRC/PushNotificationManager.swift b/LoopFollow/Remote/TRC/PushNotificationManager.swift index 027c9fbab..ceb073f82 100644 --- a/LoopFollow/Remote/TRC/PushNotificationManager.swift +++ b/LoopFollow/Remote/TRC/PushNotificationManager.swift @@ -54,13 +54,12 @@ class PushNotificationManager { sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following(.override, completion)) } - func sendBolusPushNotification(bolusAmount: HKQuantity, completion: @escaping (Bool, String?) -> Void) { + func sendBolusPushNotification(bolusAmount: HKQuantity, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) { let bolusAmountDecimal = Decimal(bolusAmount.doubleValue(for: .internationalUnit())) - let payload = CommandPayload( + let payload = Self.bolusPayload( user: user, - commandType: .bolus, - timestamp: Date().timeIntervalSince1970, bolusAmount: bolusAmountDecimal, + knownThroughID: origin.knownThroughID, returnNotification: ReturnNotificationInfo.loopFollow() ) sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following(.bolus(units: bolusAmount.doubleValue(for: .internationalUnit())), completion)) @@ -96,6 +95,7 @@ class PushNotificationManager { fat: HKQuantity, bolusAmount: HKQuantity, scheduledTime: Date?, + origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void ) { func convertToOptionalInt(_ quantity: HKQuantity) -> Int? { @@ -116,15 +116,14 @@ class PushNotificationManager { completion(false, "No nutrient data provided. At least one of carbs, fat, or protein must be greater than 0.") return } - let payload = CommandPayload( + let payload = Self.mealPayload( user: user, - commandType: .meal, - timestamp: Date().timeIntervalSince1970, bolusAmount: bolusAmountValue, carbs: carbsValue, protein: proteinValue, fat: fatValue, scheduledTime: scheduledTimeInterval, + knownThroughID: origin.knownThroughID, returnNotification: ReturnNotificationInfo.loopFollow() ) sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following( @@ -133,6 +132,54 @@ class PushNotificationManager { )) } + /// A bolus command with a command id of its own, so Trio enacts it at most once. + static func bolusPayload( + user: String, + bolusAmount: Decimal, + knownThroughID: String?, + returnNotification: ReturnNotificationInfo?, + now: Date = Date(), + commandID: String = UUID().uuidString + ) -> CommandPayload { + CommandPayload( + user: user, + commandType: .bolus, + timestamp: now.timeIntervalSince1970, + bolusAmount: bolusAmount, + commandID: commandID, + knownThroughID: knownThroughID, + returnNotification: returnNotification + ) + } + + /// A meal command with a command id of its own, so Trio enacts it at most once. + static func mealPayload( + user: String, + bolusAmount: Decimal?, + carbs: Int?, + protein: Int?, + fat: Int?, + scheduledTime: TimeInterval?, + knownThroughID: String?, + returnNotification: ReturnNotificationInfo?, + now: Date = Date(), + commandID: String = UUID().uuidString + ) -> CommandPayload { + CommandPayload( + user: user, + commandType: .meal, + timestamp: now.timeIntervalSince1970, + bolusAmount: bolusAmount, + carbs: carbs, + protein: protein, + fat: fat, + scheduledTime: scheduledTime, + commandID: commandID, + knownThroughID: knownThroughID, + returnNotification: returnNotification + ) + } + /// Trio confirms edit/delete through a return notification, so LoopFollow's own APNs credentials are required. func sendDeleteMealPushNotification(mealID: String, commandID: String, completion: @escaping (Bool, String?) -> Void) { guard let returnNotification = ReturnNotificationInfo.loopFollow() else { diff --git a/LoopFollow/Storage/Observable.swift b/LoopFollow/Storage/Observable.swift index 8d2de84b0..ac32f8bab 100644 --- a/LoopFollow/Storage/Observable.swift +++ b/LoopFollow/Storage/Observable.swift @@ -59,6 +59,9 @@ class Observable { var lastSentTOTP = ObservableValue(default: nil) + /// Greatest Nightscout `_id` in the latest treatments download; nil until one has loaded. + var treatmentsKnownThroughID = ObservableValue(default: nil) + var loopFollowDeviceToken = ObservableValue(default: "") /// Saved profiles from the latest Loop or Trio profile upload; nil until one is loaded. diff --git a/LoopFollow/ViewControllers/MainViewController.swift b/LoopFollow/ViewControllers/MainViewController.swift index 1df99a134..7570d7268 100644 --- a/LoopFollow/ViewControllers/MainViewController.swift +++ b/LoopFollow/ViewControllers/MainViewController.swift @@ -340,6 +340,19 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { } .store(in: &cancellables) + // The treatments marker belongs to the site it was read from, and to a treatment download that is on. + Publishers.MergeMany( + Storage.shared.url.$value.removeDuplicates().dropFirst().map { _ in () }.eraseToAnyPublisher(), + Storage.shared.token.$value.removeDuplicates().dropFirst().map { _ in () }.eraseToAnyPublisher(), + Storage.shared.hubURL.$value.removeDuplicates().dropFirst().map { _ in () }.eraseToAnyPublisher(), + HubClient.shared.deviceKey.$value.removeDuplicates().dropFirst().map { _ in () }.eraseToAnyPublisher(), + Storage.shared.backgroundRefreshType.$value.removeDuplicates().dropFirst().map { _ in () }.eraseToAnyPublisher(), + Storage.shared.downloadTreatments.$value.removeDuplicates().dropFirst().filter { !$0 }.map { _ in () }.eraseToAnyPublisher() + ) + .receive(on: DispatchQueue.main) + .sink { Observable.shared.treatmentsKnownThroughID.value = nil } + .store(in: &cancellables) + // ShareClient captures the credentials at init, so it's rebuilt on any change. Publishers.MergeMany( Storage.shared.shareUserName.$value.map { _ in () }.eraseToAnyPublisher(), diff --git a/LoopFollow/Watch/WatchCommandHandler.swift b/LoopFollow/Watch/WatchCommandHandler.swift index 238e1d964..f4fb6ad03 100644 --- a/LoopFollow/Watch/WatchCommandHandler.swift +++ b/LoopFollow/Watch/WatchCommandHandler.swift @@ -90,7 +90,7 @@ final class WatchCommandHandler { case let .bolus(units): guard service.validateSetup() else { return finish(false, loopSetupIncomplete) } guard let otp = loopOTP(finish: finish) else { return } - service.sendBolusViaAPNS(payload: LoopAPNSPayload(type: .bolus, bolusAmount: units, otp: otp)) { success, error in + service.sendBolusViaAPNS(payload: LoopAPNSPayload(type: .bolus, bolusAmount: units, otp: otp), origin: .watch) { success, error in DispatchQueue.main.async { if success { TOTPService.shared.markTOTPAsUsed(qrCodeURL: Storage.shared.loopAPNSQrCodeURL.value) @@ -110,7 +110,7 @@ final class WatchCommandHandler { consumedDate: consumedAt.dateUsingCurrentSeconds(), otp: otp ) - service.sendCarbsViaAPNS(payload: payload) { success, error in + service.sendCarbsViaAPNS(payload: payload, origin: .watch) { success, error in DispatchQueue.main.async { if success { TOTPService.shared.markTOTPAsUsed(qrCodeURL: Storage.shared.loopAPNSQrCodeURL.value) @@ -165,7 +165,7 @@ final class WatchCommandHandler { switch action { case let .bolus(units): - manager.sendBolusPushNotification(bolusAmount: HKQuantity(unit: .internationalUnit(), doubleValue: units)) { success, error in + manager.sendBolusPushNotification(bolusAmount: HKQuantity(unit: .internationalUnit(), doubleValue: units), origin: .watch) { success, error in if success { DispatchQueue.main.async { QuickPickBolusesManager.shared.recordBolus(units: units) } } @@ -178,7 +178,8 @@ final class WatchCommandHandler { protein: HKQuantity(unit: .gram(), doubleValue: protein), fat: HKQuantity(unit: .gram(), doubleValue: fat), bolusAmount: HKQuantity(unit: .internationalUnit(), doubleValue: bolus), - scheduledTime: WatchCommand.trioScheduledTime(consumedAt) + scheduledTime: WatchCommand.trioScheduledTime(consumedAt), + origin: .watch ) { success, error in if success, carbs > 0 { DispatchQueue.main.async { diff --git a/LoopFollowWatch/DirectCommandSender.swift b/LoopFollowWatch/DirectCommandSender.swift index b2320524f..ae9542cba 100644 --- a/LoopFollowWatch/DirectCommandSender.swift +++ b/LoopFollowWatch/DirectCommandSender.swift @@ -52,8 +52,10 @@ enum DirectCommandSender { switch action { case let .bolus(units): payload.bolusAmount = Decimal(units) + payload.commandID = UUID().uuidString case let .meal(carbs, fat, protein, bolus, consumedAt): payload.commandType = .meal + payload.commandID = UUID().uuidString payload.carbs = carbs > 0 ? Int(carbs) : nil payload.fat = fat > 0 ? Int(fat) : nil payload.protein = protein > 0 ? Int(protein) : nil diff --git a/RemoteShared/LoopAPNSCommands.swift b/RemoteShared/LoopAPNSCommands.swift index d5fe4e20d..94dfca9f1 100644 --- a/RemoteShared/LoopAPNSCommands.swift +++ b/RemoteShared/LoopAPNSCommands.swift @@ -5,37 +5,49 @@ import Foundation /// Loop remote command payloads, matching Nightscout's loop.js format. enum LoopAPNSCommands { + /// How long Loop may accept a bolus or carb command after it is sent. + static let treatmentCommandLifetime: TimeInterval = 12 * 60 + /// Fields every Loop remote command carries. - static func commandHeader(otp: String, alert: String, now: Date) -> [String: Any] { + static func commandHeader(otp: String, alert: String, now: Date, lifetime: TimeInterval = 5 * 60) -> [String: Any] { [ "otp": otp, "remote-address": "LoopFollow", "notes": "Sent via LoopFollow APNS", "entered-by": "LoopFollow", "sent-at": formatDateForAPNS(now), - "expiration": formatDateForAPNS(now.addingTimeInterval(5 * 60)), + "expiration": formatDateForAPNS(now.addingTimeInterval(lifetime)), "alert": alert, ] } - static func carbsCommandPayload(_ payload: LoopAPNSPayload, now: Date = Date()) -> [String: Any] { + /// `knownThroughID` is the newest Nightscout treatment `_id` the sender had seen; Loop rejects the command when newer insulin or carbs exist. + static func carbsCommandPayload(_ payload: LoopAPNSPayload, knownThroughID: String? = nil, now: Date = Date()) -> [String: Any] { let carbsAmount = payload.carbsAmount ?? 0.0 let absorptionTime = payload.absorptionTime ?? 3.0 var fields = commandHeader( otp: payload.otp, alert: "Remote Carbs Entry: \(String(format: "%.1f", carbsAmount)) grams\nAbsorption Time: \(String(format: "%.1f", absorptionTime)) hours", - now: now + now: now, + lifetime: treatmentCommandLifetime ) fields["carbs-entry"] = carbsAmount fields["absorption-time"] = absorptionTime fields["start-time"] = formatDateForAPNS(payload.consumedDate ?? now) + fields["known-through-id"] = knownThroughID return fields } - static func bolusCommandPayload(_ payload: LoopAPNSPayload, now: Date = Date()) -> [String: Any] { + static func bolusCommandPayload(_ payload: LoopAPNSPayload, knownThroughID: String? = nil, now: Date = Date()) -> [String: Any] { let bolusAmount = payload.bolusAmount ?? 0.0 - var fields = commandHeader(otp: payload.otp, alert: "Remote Bolus Entry: \(String(format: "%.2f", bolusAmount)) U", now: now) + var fields = commandHeader( + otp: payload.otp, + alert: "Remote Bolus Entry: \(String(format: "%.2f", bolusAmount)) U", + now: now, + lifetime: treatmentCommandLifetime + ) fields["bolus-entry"] = bolusAmount + fields["known-through-id"] = knownThroughID return fields } diff --git a/RemoteShared/PushMessage.swift b/RemoteShared/PushMessage.swift index 3025f3caf..a5c2ffea2 100644 --- a/RemoteShared/PushMessage.swift +++ b/RemoteShared/PushMessage.swift @@ -45,6 +45,8 @@ struct CommandPayload: Encodable { var scheduledTime: TimeInterval? var commandID: String? var mealID: String? + /// Newest Nightscout treatment `_id` the sender had seen; Trio rejects bolus and meal commands when newer insulin or carbs exist. + var knownThroughID: String? var profileName: String? var originalProfileName: String? var baseFingerprint: String? @@ -73,6 +75,7 @@ struct CommandPayload: Encodable { case scheduledTime = "scheduled_time" case commandID = "command_id" case mealID = "meal_id" + case knownThroughID = "known_through_id" case profileName = "profile_name" case originalProfileName = "original_profile_name" case baseFingerprint = "base_fingerprint" diff --git a/Tests/LoopAPNSCommandPayloadTests.swift b/Tests/LoopAPNSCommandPayloadTests.swift index 2040bb127..67b088e89 100644 --- a/Tests/LoopAPNSCommandPayloadTests.swift +++ b/Tests/LoopAPNSCommandPayloadTests.swift @@ -21,7 +21,7 @@ struct LoopAPNSCommandPayloadTests { #expect(json["entered-by"] as? String == "LoopFollow") #expect(json["notes"] as? String == "Sent via LoopFollow APNS") #expect(json["sent-at"] as? String == "2023-11-14T22:13:20.000Z") - #expect(json["expiration"] as? String == "2023-11-14T22:18:20.000Z") + #expect(json["expiration"] as? String == "2023-11-14T22:25:20.000Z") #expect(json["start-time"] as? String == "2023-11-14T22:03:20.000Z") #expect(json["alert"] as? String == "Remote Carbs Entry: 30.0 grams\nAbsorption Time: 3.0 hours") } @@ -32,6 +32,25 @@ struct LoopAPNSCommandPayloadTests { #expect(Set(json.keys) == headerKeys.union(["bolus-entry"])) #expect(json["bolus-entry"] as? Double == 1.25) #expect(json["alert"] as? String == "Remote Bolus Entry: 1.25 U") + #expect(json["expiration"] as? String == "2023-11-14T22:25:20.000Z") + } + + @Test("bolus and carbs carry the known-through id when set") + func knownThroughID() { + let marker = "6566a3c0a1b2c3d4e5f60718" + let bolus = LoopAPNSCommands.bolusCommandPayload(LoopAPNSPayload(type: .bolus, bolusAmount: 1, otp: "123456"), knownThroughID: marker, now: now) + let carbs = LoopAPNSCommands.carbsCommandPayload(LoopAPNSPayload(type: .carbs, carbsAmount: 20, otp: "123456"), knownThroughID: marker, now: now) + #expect(bolus["known-through-id"] as? String == marker) + #expect(carbs["known-through-id"] as? String == marker) + + let body = try? JSONSerialization.jsonObject(with: LoopAPNSCommands.apnsBody(bolus)) as? [String: Any] + #expect(body?["known-through-id"] as? String == marker) + } + + @Test("other commands keep the five minute expiration") + func otherCommandsExpiration() { + let json = LoopAPNSCommands.carbsDeleteCommandPayload(syncIdentifier: "SYNC-1", otp: "123456", now: now) + #expect(json["expiration"] as? String == "2023-11-14T22:18:20.000Z") } @Test("carbs delete addresses the entry by sync identifier") diff --git a/Tests/NightscoutTreatmentDeduplicationTests.swift b/Tests/NightscoutTreatmentDeduplicationTests.swift index 4c7696bda..1143f80ff 100644 --- a/Tests/NightscoutTreatmentDeduplicationTests.swift +++ b/Tests/NightscoutTreatmentDeduplicationTests.swift @@ -5,6 +5,7 @@ import Foundation @testable import LoopFollow import Testing +@Suite(.serialized) struct NightscoutTreatmentDeduplicationTests { private typealias Entry = [String: AnyObject] @@ -47,6 +48,143 @@ struct NightscoutTreatmentDeduplicationTests { #expect(deduplicatedIDs([sensor, sensorDuplicate]) == ["sensor"]) } + @Test("known-through id is the greatest valid _id over all entries") + func knownThroughID() { + let entries: [Entry] = [ + entry("6566a3c0a1b2c3d4e5f60718", eventType: "Temp Basal"), + entry("6566a3c0a1b2c3d4e5f60719", eventType: "Note"), + entry("6566a3c0a1b2c3d4e5f60719", eventType: "Note"), + entry("6566a3c0a1b2c3d4e5f6071"), + entry("ffffffffffffffffffffffffff"), + entry("zz66a3c0a1b2c3d4e5f60718"), + entry("NA"), + ] + #expect(MainViewController.knownThroughID(entries) == "6566a3c0a1b2c3d4e5f60719") + #expect(MainViewController.knownThroughID([entry("NA"), entry("")]) == nil) + #expect(MainViewController.knownThroughID([]) == nil) + } + + @Test("known-through id skips ids dated more than 5 minutes ahead") + func knownThroughIDSkipsFutureIDs() { + let now = Date(timeIntervalSince1970: 0x6566_A3C0) + let entries: [Entry] = [ + entry("6566a3c0a1b2c3d4e5f60718"), + entry("6566a4eca1b2c3d4e5f60718"), + entry("6566a4eda1b2c3d4e5f60718"), + entry("ffffffffa1b2c3d4e5f60718"), + ] + #expect(MainViewController.knownThroughID(entries, now: now) == "6566a4eca1b2c3d4e5f60718") + #expect(MainViewController.knownThroughID([entry("6566a4eda1b2c3d4e5f60718")], now: now) == nil) + } + + @Test("a download stores its marker only while its site is current") + func knownThroughIDBelongsToItsSite() { + let marker = Observable.shared.treatmentsKnownThroughID + let saved = marker.value + defer { marker.value = saved } + let site = MainViewController.TreatmentsSite(url: "https://a.example", token: "token-a", hubURL: "") + let entries = [entry("6566a3c0a1b2c3d4e5f60718")] + let now = Date(timeIntervalSince1970: 0x6566_A3C0) + + marker.value = nil + MainViewController.storeKnownThroughID(entries, fetchedFrom: site, current: site, now: now) + #expect(marker.value == "6566a3c0a1b2c3d4e5f60718") + + let changes = [ + MainViewController.TreatmentsSite(url: "https://b.example", token: "token-a", hubURL: ""), + MainViewController.TreatmentsSite(url: "https://a.example", token: "token-b", hubURL: ""), + MainViewController.TreatmentsSite(url: "https://a.example", token: "token-a", hubURL: "https://hub.example"), + ] + for current in changes { + marker.value = nil + MainViewController.storeKnownThroughID(entries, fetchedFrom: site, current: current, now: now) + #expect(marker.value == nil) + } + } + + @Test("a download stores no marker after hub mode, the device key or the treatment download changes") + func knownThroughIDBelongsToHubAndDownload() { + let marker = Observable.shared.treatmentsKnownThroughID + let saved = marker.value + defer { marker.value = saved } + let site = MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "https://hub.example", hubMode: true, deviceKey: "key-a") + let entries = [entry("6566a3c0a1b2c3d4e5f60718")] + let now = Date(timeIntervalSince1970: 0x6566_A3C0) + + let changes = [ + MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "https://hub.example", hubMode: false, deviceKey: "key-a"), + MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "https://hub.example", hubMode: true, deviceKey: "key-b"), + ] + for current in changes { + marker.value = nil + MainViewController.storeKnownThroughID(entries, fetchedFrom: site, current: current, now: now) + #expect(marker.value == nil) + } + + marker.value = nil + MainViewController.storeKnownThroughID(entries, fetchedFrom: site, current: site, downloadsTreatments: false, now: now) + #expect(marker.value == nil) + } + + @Test("a phone command carries the marker from when its screen appeared") + func originMarkerFromScreenAppearance() { + let marker = Observable.shared.treatmentsKnownThroughID + let saved = marker.value + defer { marker.value = saved } + let seen = "6566a3c0a1b2c3d4e5f60718" + let otherCaregiversBolus = "6566a3dea1b2c3d4e5f60718" + + marker.value = seen + let origin = RemoteCommandOrigin.phoneScreenAppeared() + marker.value = otherCaregiversBolus + #expect(origin.knownThroughID == seen) + } + + @Test("a phone command carries the older marker, or whichever one exists") + func originMarkerOlderOrEither() { + let site = MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "") + let seen = "6566a3c0a1b2c3d4e5f60718" + let origin = RemoteCommandOrigin.phone(screenOpenedWith: seen, site: site) + + #expect(origin.knownThroughID(current: "6566a3dea1b2c3d4e5f60718", currentSite: site) == seen) + #expect(origin.knownThroughID(current: "6566a3a0a1b2c3d4e5f60718", currentSite: site) == "6566a3a0a1b2c3d4e5f60718") + #expect(origin.knownThroughID(current: nil, currentSite: site) == seen) + #expect(RemoteCommandOrigin.phone(screenOpenedWith: nil, site: site).knownThroughID(current: seen, currentSite: site) == seen) + #expect(RemoteCommandOrigin.phone(screenOpenedWith: nil, site: site).knownThroughID(current: nil, currentSite: site) == nil) + } + + @Test("a phone command drops the marker from when its screen appeared once the site changed") + func originMarkerBelongsToItsSite() { + let site = MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "") + let origin = RemoteCommandOrigin.phone(screenOpenedWith: "6566a3c0a1b2c3d4e5f60718", site: site) + let changes = [ + MainViewController.TreatmentsSite(url: "https://b.example", token: "t", hubURL: ""), + MainViewController.TreatmentsSite(url: "https://a.example", token: "u", hubURL: ""), + MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "https://hub.example"), + MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "", hubMode: true), + MainViewController.TreatmentsSite(url: "https://a.example", token: "t", hubURL: "", deviceKey: "key-b"), + ] + for current in changes { + #expect(origin.knownThroughID(current: nil, currentSite: current) == nil) + #expect(origin.knownThroughID(current: "6566a3dea1b2c3d4e5f60718", currentSite: current) == "6566a3dea1b2c3d4e5f60718") + } + } + + @Test("commands relayed from the watch carry no marker") + func originMarker() { + let marker = Observable.shared.treatmentsKnownThroughID + let saved = marker.value + defer { marker.value = saved } + marker.value = "6566a3c0a1b2c3d4e5f60718" + #expect(RemoteCommandOrigin.watch.knownThroughID == nil) + + let relayed = LoopAPNSCommands.bolusCommandPayload( + LoopAPNSPayload(type: .bolus, bolusAmount: 1, otp: "123456"), + knownThroughID: RemoteCommandOrigin.watch.knownThroughID + ) + #expect(relayed.keys.contains("known-through-id") == false) + } + private func deduplicatedIDs(_ entries: [Entry]) -> [String] { MainViewController.deduplicatedTreatmentEntries(entries).compactMap { $0["_id"] as? String } } diff --git a/Tests/TRCMealCommandPayloadTests.swift b/Tests/TRCMealCommandPayloadTests.swift index 34f21c484..5b9f86940 100644 --- a/Tests/TRCMealCommandPayloadTests.swift +++ b/Tests/TRCMealCommandPayloadTests.swift @@ -53,6 +53,47 @@ struct TRCMealCommandPayloadTests { #expect(json["bolus_amount"] == nil) } + @Test("known_through_id is sent when set and omitted when nil") + func knownThroughID() throws { + let marker = "6566a3c0a1b2c3d4e5f60718" + let bolus = try encode(CommandPayload(user: "u", commandType: .bolus, timestamp: 0, bolusAmount: 1, knownThroughID: marker)) + let meal = try encode(CommandPayload(user: "u", commandType: .meal, timestamp: 0, carbs: 10, knownThroughID: marker)) + let unknown = try encode(CommandPayload(user: "u", commandType: .bolus, timestamp: 0, bolusAmount: 1)) + #expect(bolus["known_through_id"] as? String == marker) + #expect(meal["known_through_id"] as? String == marker) + #expect(unknown.keys.contains("known_through_id") == false) + } + + @Test("bolus and meal commands carry a fresh command id and the marker") + func bolusAndMealCommandIDs() throws { + let marker = "6566a3c0a1b2c3d4e5f60718" + let now = Date(timeIntervalSince1970: 1_700_000_000) + func bolus() throws -> [String: Any] { + try encode(PushNotificationManager.bolusPayload(user: "u", bolusAmount: 1, knownThroughID: marker, returnNotification: nil, now: now)) + } + func meal() throws -> [String: Any] { + try encode(PushNotificationManager.mealPayload( + user: "u", bolusAmount: 1, carbs: 10, protein: nil, fat: nil, scheduledTime: nil, + knownThroughID: marker, returnNotification: nil, now: now + )) + } + let ids = try [bolus(), bolus(), meal(), meal()].map { try #require($0["command_id"] as? String) } + #expect(Set(ids).count == 4) + #expect(ids.allSatisfy { UUID(uuidString: $0) != nil }) + + let first = try bolus() + #expect(first["command_type"] as? String == "bolus") + #expect(first["known_through_id"] as? String == marker) + #expect(first["timestamp"] as? Double == 1_700_000_000) + let second = try meal() + #expect(second["command_type"] as? String == "meal") + #expect(second["known_through_id"] as? String == marker) + #expect(PushNotificationManager.mealPayload( + user: "u", bolusAmount: nil, carbs: 10, protein: nil, fat: nil, scheduledTime: nil, + knownThroughID: nil, returnNotification: nil + ).apnsCollapseID == "meal") + } + @Test("collapse id is the command id for meal mutations only") func collapseID() { let edit = CommandPayload(user: "u", commandType: .editMeal, timestamp: 0, commandID: "CMD", mealID: "M")