diff --git a/Normal.xcodeproj/project.pbxproj b/Normal.xcodeproj/project.pbxproj index 78335c1..08d1336 100644 --- a/Normal.xcodeproj/project.pbxproj +++ b/Normal.xcodeproj/project.pbxproj @@ -844,6 +844,7 @@ INFOPLIST_FILE = Normal/Info.plist; INFOPLIST_KEY_NFCReaderUsageDescription = "Normal uses NFC to scan tags so you can lock and unlock your blocked apps."; INFOPLIST_KEY_NSCameraUsageDescription = "Normal uses the camera to scan QR codes so you can lock and unlock your blocked apps."; + INFOPLIST_KEY_NSLocationAlwaysAndWhenInUseUsageDescription = "Normal checks your location in the background only when a shortcut unblocks apps with a Location key."; INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Normal uses your location only when you create or verify a Location key."; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; @@ -882,6 +883,7 @@ INFOPLIST_FILE = Normal/Info.plist; INFOPLIST_KEY_NFCReaderUsageDescription = "Normal uses NFC to scan tags so you can lock and unlock your blocked apps."; INFOPLIST_KEY_NSCameraUsageDescription = "Normal uses the camera to scan QR codes so you can lock and unlock your blocked apps."; + INFOPLIST_KEY_NSLocationAlwaysAndWhenInUseUsageDescription = "Normal checks your location in the background only when a shortcut unblocks apps with a Location key."; INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Normal uses your location only when you create or verify a Location key."; INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; diff --git a/Normal/Intents/AppUnblockIntentPerformer.swift b/Normal/Intents/AppUnblockIntentPerformer.swift index 62d7680..29fa2ad 100644 --- a/Normal/Intents/AppUnblockIntentPerformer.swift +++ b/Normal/Intents/AppUnblockIntentPerformer.swift @@ -5,13 +5,17 @@ import SwiftData final class AppUnblockIntentPerformer: UnblockIntentPerforming { private let intents: IntentContext private let unlockInbox: UnlockRequestInbox + private let locationVerifier: BackgroundLocationVerifier + private let syncsExternalSurfaces: Bool private let logger = Logger(subsystem: "com.normalengineering.normal", category: "Intents") init( container: ModelContainer, screenTimeService: any ScreenTimeProviding, timedUnblockService: TimedUnblockService, - unlockInbox: UnlockRequestInbox + unlockInbox: UnlockRequestInbox, + locationVerifier: BackgroundLocationVerifier, + syncsExternalSurfaces: Bool = true ) { intents = IntentContext( container: container, @@ -19,6 +23,8 @@ final class AppUnblockIntentPerformer: UnblockIntentPerforming { timedUnblockService: timedUnblockService ) self.unlockInbox = unlockInbox + self.locationVerifier = locationVerifier + self.syncsExternalSurfaces = syncsExternalSurfaces } convenience init(container: ModelContainer, services: AppServices) { @@ -26,35 +32,104 @@ final class AppUnblockIntentPerformer: UnblockIntentPerforming { container: container, screenTimeService: services.screenTime, timedUnblockService: services.timedUnblock, - unlockInbox: services.unlockInbox + unlockInbox: services.unlockInbox, + locationVerifier: BackgroundLocationVerifier(provider: LocationService.shared) ) } - func unblock(_ request: UnblockRequest) throws -> UnblockOutcome { + func unblock(_ request: UnblockRequest) async throws -> UnblockOutcome { logger.info("Unblock intent: \(request.groupID == nil ? "all" : "group", privacy: .public)") - let settings = try intents.validatedSettings(requiringGlobalKey: false) - intents.timedUnblockService.refresh(screenTimeService: intents.screenTimeService) - let target = try intents.target(groupID: request.groupID, settings: settings) - let status = intents.screenTimeService.blockStatus(of: target, settings: settings) - guard target.canUnblock(status: status, timedUnblockService: intents.timedUnblockService) else { - return status == .none ? .alreadyUnblocked(name: target.name) : .timedUnblockRunning(name: target.name) + let settings: Settings + switch try readiness(for: request) { + case let .settled(outcome): + return outcome + case let .ready(readySettings, _): + settings = readySettings + } + + let keys = try Key.scoped(intents.keys(), toGroup: request.groupID) + guard keyType(for: request, keys: keys, settings: settings) == .location, + settings.unblockLength(for: request.duration) != nil + else { return .continueInApp(.checkKey) } + let radiusKind = Key.existingLocationKind(in: keys) ?? .unblock + + let location = await locationVerifier.check(keys: keys) + try Task.checkCancellation() + switch location { + case .verified: + break + case .outOfRange: + throw UnblockIntentError.notAtLocation(radiusKind) + case .needsAlways: + return .continueInApp(.backgroundLocationOff) + case .needsPrecise: + return .continueInApp(.preciseLocationOff) + case .inconclusive: + return .continueInApp(.noLocationFix) + case .noLocationKey: + return .continueInApp(.checkKey) + } + + switch try readiness(for: request) { + case let .settled(outcome): + return outcome + case let .ready(settings, target): + guard let length = settings.unblockLength(for: request.duration) else { return .continueInApp(.checkKey) } + return try start(target, for: length, settings: settings) } - return .continueInApp } func continueInApp(_ request: UnblockRequest) { unlockInbox.post(UnblockRequest( groupID: request.groupID, duration: request.duration, - keyType: keyType(for: request) + keyType: keyType( + for: request, + keys: Key.scoped((try? intents.keys()) ?? [], toGroup: request.groupID), + settings: intents.settings() + ) )) } - private func keyType(for request: UnblockRequest) -> KeyType? { - let keys = Key.scoped((try? intents.keys()) ?? [], toGroup: request.groupID) - return KeySelectLogic.shortcutKeyType( + private enum Readiness { + case ready(Settings, UnblockTarget) + case settled(UnblockOutcome) + } + + private func readiness(for request: UnblockRequest) throws -> Readiness { + let settings = try intents.validatedSettings(requiringGlobalKey: false) + intents.timedUnblockService.refresh(screenTimeService: intents.screenTimeService) + let target = try intents.target(groupID: request.groupID, settings: settings) + let status = intents.screenTimeService.blockStatus(of: target, settings: settings) + guard target.canUnblock(status: status, timedUnblockService: intents.timedUnblockService) else { + return .settled(status == .none ? .alreadyUnblocked(name: target.name) : .timedUnblockRunning(name: target.name)) + } + return .ready(settings, target) + } + + private func start(_ target: UnblockTarget, for length: UnblockLength, settings: Settings) throws -> UnblockOutcome { + do { + try BlockActions.unblock( + target, + for: length, + settings: settings, + screenTimeService: intents.screenTimeService, + timedUnblockService: intents.timedUnblockService + ) + } catch { + logger.error("Unblock intent failed to start: \(error.localizedDescription, privacy: .public)") + throw UnblockIntentError.unblockFailed + } + if syncsExternalSurfaces { + intents.syncExternalSurfaces(settings: settings) + } + return .unblocked(name: target.name, length: length) + } + + private func keyType(for request: UnblockRequest, keys: [Key], settings: Settings?) -> KeyType? { + KeySelectLogic.shortcutKeyType( requested: request.keyType, - defaultKeyType: intents.settings()?.defaultKeyType, + defaultKeyType: settings?.defaultKeyType, availableKeyTypes: KeyType.selectable(registered: keys.map(\.type)) ) } diff --git a/Normal/Intents/UnblockIntents.swift b/Normal/Intents/UnblockIntents.swift index f3979b2..52d1a27 100644 --- a/Normal/Intents/UnblockIntents.swift +++ b/Normal/Intents/UnblockIntents.swift @@ -12,22 +12,53 @@ nonisolated extension UnblockRequest { } enum UnblockOutcome: Equatable, Sendable { + case unblocked(name: String, length: UnblockLength) case alreadyUnblocked(name: String) case timedUnblockRunning(name: String) - case continueInApp + case continueInApp(HandOffReason) +} + +enum HandOffReason: Equatable, Sendable { + case checkKey + case backgroundLocationOff + case preciseLocationOff + case noLocationFix + + var prompt: LocalizedStringResource { + switch self { + case .checkKey: "Open Normal to check your key?" + case .backgroundLocationOff: "Background Location is off. Open Normal to check your location?" + case .preciseLocationOff: "Precise Location is off. Open Normal to check your location?" + case .noLocationFix: "Couldn't confirm your location. Open Normal to check it?" + } + } + + var notice: LocalizedStringResource? { + switch self { + case .checkKey: nil + case .backgroundLocationOff: "Background Location is off, so Normal will check your location." + case .preciseLocationOff: "Precise Location is off, so Normal will check your location." + case .noLocationFix: "Couldn't confirm your location, so Normal will check it." + } + } } protocol UnblockIntentPerforming: Sendable { - @MainActor func unblock(_ request: UnblockRequest) throws -> UnblockOutcome + @MainActor func unblock(_ request: UnblockRequest) async throws -> UnblockOutcome @MainActor func continueInApp(_ request: UnblockRequest) } enum UnblockIntentError: Error, Equatable, CustomLocalizedStringResourceConvertible { case openNormal + case notAtLocation(LocationRadiusKind) + case unblockFailed var localizedStringResource: LocalizedStringResource { switch self { case .openNormal: "Open Normal to unblock." + case .notAtLocation(.unblock): "You're outside your unblock radius." + case .notAtLocation(.block): "You're inside your block radius." + case .unblockFailed: "Couldn't start the unblock. Open Normal and try again." } } } @@ -35,7 +66,7 @@ enum UnblockIntentError: Error, Equatable, CustomLocalizedStringResourceConverti struct UnblockAllIntent: LiveActivityIntent { static let title: LocalizedStringResource = "Unblock All Apps" static let description = IntentDescription( - "Opens Normal to check your key, then unblocks the apps and websites selected in Normal. With no Key Type or Unblock Duration, Normal uses your defaults." + "Unblocks the apps and websites selected in Normal after checking your key. NFC Tag and QR Code / Barcode keys open Normal to scan. A Location key is checked without opening Normal when Background Location is on and a duration is set. With no Key Type or Unblock Duration, Normal uses your defaults." ) @Parameter(title: "Key Type") @@ -60,13 +91,14 @@ struct UnblockAllIntent: LiveActivityIntent { func perform() async throws -> some IntentResult & ProvidesDialog & OpensIntent { let request = UnblockRequest(group: nil, keyType: keyType, duration: duration) switch try await performer.unblock(request) { - case .alreadyUnblocked: - return .result(dialog: "All selected apps are already unblocked.") + case .unblocked, .alreadyUnblocked: + return .result(dialog: "").withoutDialog case .timedUnblockRunning: return .result(dialog: "A timed unblock is already running for all apps.") - case .continueInApp: + case let .continueInApp(reason): return try await continueInApp( request, + reason: reason, performer: performer, fallback: OpenUnblockIntent(group: nil, keyType: keyType, duration: duration) ) @@ -77,7 +109,7 @@ struct UnblockAllIntent: LiveActivityIntent { struct UnblockGroupIntent: LiveActivityIntent { static let title: LocalizedStringResource = "Unblock Group" static let description = IntentDescription( - "Opens Normal to check your key, then unblocks one of your Normal groups. With no Key Type or Unblock Duration, Normal uses your defaults." + "Unblocks one of your Normal groups after checking your key. NFC Tag and QR Code / Barcode keys open Normal to scan. A Location key is checked without opening Normal when Background Location is on and a duration is set. With no Key Type or Unblock Duration, Normal uses your defaults." ) @Parameter(title: "Group", requestValueDialog: "Which group should Normal unblock?") @@ -105,13 +137,14 @@ struct UnblockGroupIntent: LiveActivityIntent { func perform() async throws -> some IntentResult & ProvidesDialog & OpensIntent { let request = UnblockRequest(group: group, keyType: keyType, duration: duration) switch try await performer.unblock(request) { - case let .alreadyUnblocked(name): - return .result(dialog: "\(name) is already unblocked.") + case .unblocked, .alreadyUnblocked: + return .result(dialog: "").withoutDialog case let .timedUnblockRunning(name): return .result(dialog: "A timed unblock is already running for \(name).") - case .continueInApp: + case let .continueInApp(reason): return try await continueInApp( request, + reason: reason, performer: performer, fallback: OpenUnblockIntent(group: group, keyType: keyType, duration: duration) ) @@ -163,6 +196,7 @@ struct OpenUnblockIntent: AppIntent { private extension AppIntent { func continueInApp( _ request: UnblockRequest, + reason: HandOffReason, performer: any UnblockIntentPerforming, fallback: OpenUnblockIntent ) async throws -> IntentResultContainer { @@ -172,13 +206,16 @@ private extension AppIntent { performer.continueInApp(request) throw UnblockIntentError.openNormal } - try await continueInForeground("Open Normal to check your key?", alwaysConfirm: false) + try await continueInForeground(IntentDialog(reason.prompt), alwaysConfirm: false) } performer.continueInApp(request) return .result(dialog: "").withoutDialog } if #available(iOS 18.2, *) { - return .result(opensIntent: fallback, dialog: "").withoutDialog + guard let notice = reason.notice else { + return .result(opensIntent: fallback, dialog: "").withoutDialog + } + return .result(opensIntent: fallback, dialog: IntentDialog(notice)) } performer.continueInApp(request) throw UnblockIntentError.openNormal diff --git a/Normal/Models/LocationZones.swift b/Normal/Models/LocationZones.swift new file mode 100644 index 0000000..27cddf6 --- /dev/null +++ b/Normal/Models/LocationZones.swift @@ -0,0 +1,47 @@ +import CoreLocation + +enum LocationFit: Equatable { + case satisfied + case unsatisfied(margin: CLLocationDistance) + case uncertain +} + +struct LocationZones { + struct Circle { + let center: CLLocation + let radius: CLLocationDistance + } + + let kind: LocationRadiusKind + let circles: [Circle] + + init?(keys: [Key]) { + let locationKeys = Key.locationKeys(in: keys) + guard let kind = locationKeys.first?.radiusKind else { return nil } + let circles = locationKeys.compactMap { key -> Circle? in + guard let latitude = key.latitude, let longitude = key.longitude, let radius = key.radiusMeters else { return nil } + return Circle(center: CLLocation(latitude: latitude, longitude: longitude), radius: radius) + } + guard !circles.isEmpty else { return nil } + self.kind = kind + self.circles = circles + } + + func fit(_ location: CLLocation) -> LocationFit { + guard let nearestEdge = circles.map({ location.distance(from: $0.center) - $0.radius }).min() else { + return .uncertain + } + let accuracy = max(location.horizontalAccuracy, 0) + let surelyInside = nearestEdge + accuracy <= 0 + let surelyOutside = nearestEdge - accuracy > 0 + switch kind { + case .unblock: + if surelyInside { return .satisfied } + if surelyOutside { return .unsatisfied(margin: nearestEdge - accuracy) } + case .block: + if surelyOutside { return .satisfied } + if surelyInside { return .unsatisfied(margin: -(nearestEdge + accuracy)) } + } + return .uncertain + } +} diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index d252685..1534282 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -56,10 +56,6 @@ "comment" : "A dialog message that indicates a group is already blocked.", "isCommentAutoGenerated" : true }, - "%@ is already unblocked." : { - "comment" : "A localized string that can be used in a dialog. The argument is the name of the group.", - "isCommentAutoGenerated" : true - }, "%@ is your default duration. Deleting it sets Default Duration to None. You can choose a new default anytime." : { "comment" : "A confirmation alert that lets the user delete a timed unblock duration. The argument is the name of the duration.", "isCommentAutoGenerated" : true @@ -329,10 +325,6 @@ "comment" : "Text displayed in a dialog when all selected apps are already blocked.", "isCommentAutoGenerated" : true }, - "All selected apps are already unblocked." : { - "comment" : "Text displayed in a dialog when all apps are already unblocked.", - "isCommentAutoGenerated" : true - }, "Almost any NFC tag works. AirTags, Amiibo, and even Credit Cards have NFC chips you can use." : { "comment" : "Feature description for using an NFC tag as a key.", "isCommentAutoGenerated" : true @@ -414,6 +406,18 @@ "comment" : "Short label for a usage limit state when the limit is not yet reached.", "isCommentAutoGenerated" : true }, + "Background Location" : { + "comment" : "A button that opens the user's device settings.", + "isCommentAutoGenerated" : true + }, + "Background Location is off, so Normal will check your location." : { + "comment" : "Notice displayed in a notification when Background Location is off.", + "isCommentAutoGenerated" : true + }, + "Background Location is off. Open Normal to check your location?" : { + "comment" : "Text displayed in a notification when the user is in a location that requires background location access.", + "isCommentAutoGenerated" : true + }, "Block" : { "comment" : "A button to block access to a family member's account.", "isCommentAutoGenerated" : true @@ -558,6 +562,18 @@ "comment" : "A button that copies the callback log to the clipboard.", "isCommentAutoGenerated" : true }, + "Couldn't confirm your location, so Normal will check it." : { + "comment" : "Text displayed in a notification when a timed unblock is already running for all apps.", + "isCommentAutoGenerated" : true + }, + "Couldn't confirm your location. Open Normal to check it?" : { + "comment" : "Text displayed in a notification when a timed unblock is already running for all apps.", + "isCommentAutoGenerated" : true + }, + "Couldn't start the unblock. Open Normal and try again." : { + "comment" : "Error when unblocking an app fails.", + "isCommentAutoGenerated" : true + }, "Create a schedule to automatically block or unblock apps at set times." : { "comment" : "A footer message in the Schedules view that instructs the user on how to create schedules.", "isCommentAutoGenerated" : true @@ -955,10 +971,6 @@ "comment" : "The title of the view.", "isCommentAutoGenerated" : true }, - "Location keys still require you to unblock selected apps/groups by opening the Normal app and unblocking. Your NFC and QR keys will still work from anywhere!" : { - "comment" : "A note explaining that NFC and QR keys can be used from anywhere, even if the user has blocked certain apps or groups.", - "isCommentAutoGenerated" : true - }, "Location permission needed" : { "comment" : "A label indicating that location permission is needed.", "isCommentAutoGenerated" : true @@ -1091,6 +1103,10 @@ "comment" : "A note in the onboarding finish view that describes the security of the app.", "isCommentAutoGenerated" : true }, + "Normal checks a location key when you unblock. With Background Location on in Settings, a shortcut can check it without opening Normal. Your NFC and QR keys work from anywhere!" : { + "comment" : "A note that describes how a location key works.", + "isCommentAutoGenerated" : true + }, "Normal identifies an NFC tag by its unique ID, not by the data stored inside it." : { "comment" : "A description of how NFC tags are handled by the app.", "isCommentAutoGenerated" : true @@ -1110,6 +1126,10 @@ "comment" : "Error message when Screen Time access is not authorized.", "isCommentAutoGenerated" : true }, + "Normal only checks your location at the moment you unblock. With Background Location on in Settings, a shortcut can unblock without opening Normal." : { + "comment" : "Text describing the behavior of a location key when unblocking.", + "isCommentAutoGenerated" : true + }, "Normal only reads the tag's unique ID, never the data on it. That means only the tag you register can unblock your apps, and your privacy stays protected." : { }, @@ -1174,12 +1194,8 @@ "comment" : "A button to open the device settings.", "isCommentAutoGenerated" : true }, - "Opens Normal to check your key, then unblocks one of your Normal groups. With no Key Type or Unblock Duration, Normal uses your defaults." : { - "comment" : "Description of the UnblockGroupIntent intent.", - "isCommentAutoGenerated" : true - }, - "Opens Normal to check your key, then unblocks the apps and websites selected in Normal. With no Key Type or Unblock Duration, Normal uses your defaults." : { - "comment" : "Description of the unblock intent.", + "Opens Settings" : { + "comment" : "A hint that describes the action of opening the app's settings.", "isCommentAutoGenerated" : true }, "Option A: Ask a trusted friend" : { @@ -1241,6 +1257,14 @@ "comment" : "A text instruction to point the user's camera at a QR code or barcode.", "isCommentAutoGenerated" : true }, + "Precise Location is off, so Normal will check your location." : { + "comment" : "Text displayed in a notification when Precise Location is off.", + "isCommentAutoGenerated" : true + }, + "Precise Location is off. Open Normal to check your location?" : { + "comment" : "Text displayed in a notification when Precise Location is off.", + "isCommentAutoGenerated" : true + }, "Prevent App Deletion" : { "comment" : "A toggle that allows the user to enable or disable preventing apps from being uninstalled from their device.", "isCommentAutoGenerated" : true @@ -1543,10 +1567,6 @@ "comment" : "Text describing the requirement to unblock all apps to make changes to apps, keys, groups, or schedules.", "isCommentAutoGenerated" : true }, - "To use a location key, open Normal and unblock. Normal only checks your location at that moment, never in the background." : { - "comment" : "Text displayed in a card that describes how to use a location key.", - "isCommentAutoGenerated" : true - }, "Too many items selected." : { "comment" : "A warning message displayed when a user has selected too many items to be blocked.", "isCommentAutoGenerated" : true @@ -1633,6 +1653,10 @@ "comment" : "Text displayed in a card that shows a location key with a description of the unblock radius.", "isCommentAutoGenerated" : true }, + "Unblock when you arrive somewhere" : { + "comment" : "A step in the process of unblocking apps when arriving at a location.", + "isCommentAutoGenerated" : true + }, "Unblock with an NFC tag" : { "comment" : "A heading for the NFC tag unblocking process.", "isCommentAutoGenerated" : true @@ -1641,6 +1665,14 @@ "comment" : "A section header that lists unblocking-related settings.", "isCommentAutoGenerated" : true }, + "Unblocks one of your Normal groups after checking your key. NFC Tag and QR Code / Barcode keys open Normal to scan. A Location key is checked without opening Normal when Background Location is on and a duration is set. With no Key Type or Unblock Duration, Normal uses your defaults." : { + "comment" : "Description of the UnblockGroupIntent intent.", + "isCommentAutoGenerated" : true + }, + "Unblocks the apps and websites selected in Normal after checking your key. NFC Tag and QR Code / Barcode keys open Normal to scan. A Location key is checked without opening Normal when Background Location is on and a duration is set. With no Key Type or Unblock Duration, Normal uses your defaults." : { + "comment" : "Description of the UnblockAllIntent intent.", + "isCommentAutoGenerated" : true + }, "Until Manually Re-Blocked" : { "comment" : "A label for a section in the timed unblock sheet that indicates the option to unblock indefinitely.", "isCommentAutoGenerated" : true @@ -1659,6 +1691,9 @@ }, "Updating your app selection will affect the functionality of your groups. After updating selection please update your groups to ensure consistency." : { + }, + "Use a radius of 100 m or more so a background reading can confirm where you are" : { + }, "Use a tag with a fixed unique ID; AirTags, Amiibo, most Credit Cards and most everyday NFC tags work well. Or use a QR code/barcode or Location as a key instead." : { "comment" : "A description of NFC tags that can be used as a key.", @@ -1742,8 +1777,8 @@ "Yes, it shouldn't cost anything to use your phone less." : { }, - "Yes. Normal adds Unblock All Apps and Unblock Group to the Shortcuts app. Your key is still checked, so Normal opens to scan it." : { - "comment" : "A description of how users can unblock apps using shortcuts.", + "Yes. Normal adds Unblock All Apps and Unblock Group to the Shortcuts app. Your key is still checked." : { + "comment" : "A response to the FAQ question \"Can I use the Unblock feature with Shortcuts?\"", "isCommentAutoGenerated" : true }, "Yes. There are two ways to close the Settings bypass. Pick the one that fits how strict you want to be." : { @@ -1792,6 +1827,14 @@ "comment" : "A title for the onboarding finish view.", "isCommentAutoGenerated" : true }, + "You're inside your block radius." : { + "comment" : "Text displayed in a notification when the user is inside their block radius.", + "isCommentAutoGenerated" : true + }, + "You're outside your unblock radius." : { + "comment" : "Text displayed when the user is outside their unblock radius.", + "isCommentAutoGenerated" : true + }, "You're welcome" : { "comment" : "The text on a button that says \"You're welcome\" and is used in an alert.", "isCommentAutoGenerated" : true diff --git a/Normal/Services/Keys/BackgroundLocationVerifier.swift b/Normal/Services/Keys/BackgroundLocationVerifier.swift new file mode 100644 index 0000000..9100297 --- /dev/null +++ b/Normal/Services/Keys/BackgroundLocationVerifier.swift @@ -0,0 +1,96 @@ +import CoreLocation +import Foundation + +enum BackgroundLocationCheck: Equatable { + case verified + case outOfRange + case inconclusive + case needsAlways + case needsPrecise + case noLocationKey +} + +@MainActor +struct BackgroundLocationVerifier { + static let policy = LocationFixPolicy(maxAccuracy: 100) + static let maxTravelSpeed: CLLocationSpeed = 35 + + let provider: any LocationProviding + var deadline: Duration = .seconds(15) + var pollInterval: Duration = .seconds(2) + var now: () -> Date = { .now } + + static func isOutOfReach(_ margin: CLLocationDistance, within remaining: Duration) -> Bool { + margin > maxTravelSpeed * (remaining / .seconds(1)) + } + + func check(keys: [Key]) async -> BackgroundLocationCheck { + guard let zones = LocationZones(keys: keys) else { return .noLocationKey } + guard provider.authorizationStatus == .authorizedAlways else { return .needsAlways } + guard provider.accuracyAuthorization == .fullAccuracy else { return .needsPrecise } + + let clock = ContinuousClock() + let end = clock.now.advanced(by: deadline) + var result = BackgroundLocationCheck.inconclusive + while !Task.isCancelled { + let remaining = clock.now.duration(to: end) + guard remaining > .zero else { break } + if let fix = await freshFix(within: remaining), Self.policy.accepts(fix, now: now()) { + switch zones.fit(fix) { + case .satisfied: + return .verified + case let .unsatisfied(margin): + if Self.isOutOfReach(margin, within: clock.now.duration(to: end)) { + return .outOfRange + } + result = .outOfRange + case .uncertain: + result = .inconclusive + } + } + let wait = min(pollInterval, clock.now.duration(to: end)) + guard wait > .zero else { break } + try? await Task.sleep(for: wait) + } + return result + } + + private func freshFix(within limit: Duration) async -> CLLocation? { + let gate = FixGate() + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + gate.wait(continuation) + let timeout = Task { @MainActor in + try? await Task.sleep(for: limit) + gate.finish(with: nil) + } + Task { @MainActor in + gate.finish(with: try? await provider.currentLocation()) + timeout.cancel() + } + } + } onCancel: { + Task { @MainActor in gate.finish(with: nil) } + } + } +} + +@MainActor +private final class FixGate { + private var continuation: CheckedContinuation? + private var isFinished = false + + func wait(_ continuation: CheckedContinuation) { + if isFinished { + continuation.resume(returning: nil) + } else { + self.continuation = continuation + } + } + + func finish(with fix: CLLocation?) { + isFinished = true + continuation?.resume(returning: fix) + continuation = nil + } +} diff --git a/Normal/Services/LocationService.swift b/Normal/Services/LocationService.swift index 2675671..6347b84 100644 --- a/Normal/Services/LocationService.swift +++ b/Normal/Services/LocationService.swift @@ -29,6 +29,7 @@ enum LocationKeyError: Error, Equatable { @MainActor protocol LocationProviding: AnyObject { var authorizationStatus: CLAuthorizationStatus { get } + var accuracyAuthorization: CLAccuracyAuthorization { get } var cachedLocation: CLLocation? { get } var recentLocation: CLLocation? { get } func currentLocation() async throws -> CLLocation @@ -43,9 +44,26 @@ final class LocationService: NSObject, LocationProviding { if UITestSupport.isActive { return .authorizedWhenInUse } + _ = authorizationRevision return manager.authorizationStatus } + var accuracyAuthorization: CLAccuracyAuthorization { + if UITestSupport.isActive { + return .fullAccuracy + } + _ = authorizationRevision + return manager.accuracyAuthorization + } + + var canRequestAlways: Bool { + switch authorizationStatus { + case .notDetermined: true + case .authorizedWhenInUse: !UserDefaults.standard.bool(forKey: Self.alwaysRequestedKey) + default: false + } + } + var cachedLocation: CLLocation? { if UITestSupport.isActive { return CLLocation(latitude: 37.33182, longitude: -122.03118) @@ -63,7 +81,11 @@ final class LocationService: NSObject, LocationProviding { return lastFix.location } + private static let alwaysRequestedKey = "locationAlwaysRequested_v1" + private let manager = CLLocationManager() + private var authorizationRevision = 0 + private var upgradesToAlways = false private var lastFix: (location: CLLocation, receivedAt: ContinuousClock.Instant)? private var locationContinuations: [CheckedContinuation] = [] private var authContinuations: [CheckedContinuation] = [] @@ -74,6 +96,16 @@ final class LocationService: NSObject, LocationProviding { manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters } + func requestAlwaysAuthorization() { + guard manager.authorizationStatus != .notDetermined else { + upgradesToAlways = true + manager.requestWhenInUseAuthorization() + return + } + UserDefaults.standard.set(true, forKey: Self.alwaysRequestedKey) + manager.requestAlwaysAuthorization() + } + func currentLocation() async throws -> CLLocation { if UITestSupport.isActive { return CLLocation(latitude: 37.33182, longitude: -122.03118) @@ -114,7 +146,14 @@ final class LocationService: NSObject, LocationProviding { } private func flushAuth(_ status: CLAuthorizationStatus) { + authorizationRevision += 1 guard status != .notDetermined else { return } + if upgradesToAlways { + upgradesToAlways = false + if status == .authorizedWhenInUse { + requestAlwaysAuthorization() + } + } let pending = authContinuations authContinuations.removeAll() for c in pending { diff --git a/Normal/Views/Key/KeyFormSheetSetupSection.swift b/Normal/Views/Key/KeyFormSheetSetupSection.swift index 5d76137..d078d64 100644 --- a/Normal/Views/Key/KeyFormSheetSetupSection.swift +++ b/Normal/Views/Key/KeyFormSheetSetupSection.swift @@ -105,7 +105,7 @@ struct KeyFormSheetSetupSection: View { HStack(alignment: .top, spacing: DS.Spacing.sm) { Image(systemName: "info.circle.fill") .foregroundStyle(.blue) - Text("Location keys still require you to unblock selected apps/groups by opening the Normal app and unblocking. Your NFC and QR keys will still work from anywhere!") + Text("Normal checks a location key when you unblock. With Background Location on in Settings, a shortcut can check it without opening Normal. Your NFC and QR keys work from anywhere!") .font(.caption) .foregroundStyle(.secondary) } diff --git a/Normal/Views/Key/KeyTypeExamplesView.swift b/Normal/Views/Key/KeyTypeExamplesView.swift index 43c7d17..632738e 100644 --- a/Normal/Views/Key/KeyTypeExamplesView.swift +++ b/Normal/Views/Key/KeyTypeExamplesView.swift @@ -45,7 +45,7 @@ struct KeyTypeExamplesView: View { cardTitle("Location examples", systemImage: KeyType.location.icon) FeatureRow(systemImage: "location.circle.fill", text: "Unblock radius: your key only works inside the areas you choose, like your office or the gym.", tint: LocationRadiusKind.unblock.zoneColor) FeatureRow(systemImage: "location.slash.circle.fill", text: "Block radius: your key only works outside the areas you choose, like home or school, so you can't unblock while you're there.", tint: LocationRadiusKind.block.zoneColor) - FeatureRow(systemImage: "iphone", text: "To use a location key, open Normal and unblock. Normal only checks your location at that moment, never in the background.") + FeatureRow(systemImage: "iphone", text: "Normal only checks your location at the moment you unblock. With Background Location on in Settings, a shortcut can unblock without opening Normal.") } } diff --git a/Normal/Views/Settings/BackgroundLocationRow.swift b/Normal/Views/Settings/BackgroundLocationRow.swift new file mode 100644 index 0000000..62cc7d8 --- /dev/null +++ b/Normal/Views/Settings/BackgroundLocationRow.swift @@ -0,0 +1,43 @@ +import SwiftUI +import UIKit + +struct BackgroundLocationRow: View { + @Environment(LocationService.self) private var locationService + + private var status: String? { + if locationService.authorizationStatus != .authorizedAlways { + return "Off" + } + if locationService.accuracyAuthorization != .fullAccuracy { + return "Precise Off" + } + return nil + } + + private var opensSettings: Bool { + locationService.authorizationStatus == .authorizedAlways || !locationService.canRequestAlways + } + + var body: some View { + if let status { + Button(action: allow) { + LabeledContent("Background Location", value: status) + } + .accessibilityHint(opensSettings ? "Opens Settings" : "") + .accessibilityIdentifier("settings.backgroundLocation") + } else { + LabeledContent("Background Location", value: "On") + .accessibilityIdentifier("settings.backgroundLocation") + } + } + + private func allow() { + if opensSettings { + if let url = URL(string: UIApplication.openSettingsURLString) { + UIApplication.shared.open(url) + } + } else { + locationService.requestAlwaysAuthorization() + } + } +} diff --git a/Normal/Views/Settings/FAQ/FAQAnswers.swift b/Normal/Views/Settings/FAQ/FAQAnswers.swift index 50c4c68..5259f18 100644 --- a/Normal/Views/Settings/FAQ/FAQAnswers.swift +++ b/Normal/Views/Settings/FAQ/FAQAnswers.swift @@ -170,7 +170,16 @@ enum FAQAnswer { static let shortcutsUnblock = AnyView( VStack(alignment: .leading, spacing: DS.Spacing.md) { - Text("Yes. Normal adds Unblock All Apps and Unblock Group to the Shortcuts app. Your key is still checked, so Normal opens to scan it.") + Text("Yes. Normal adds Unblock All Apps and Unblock Group to the Shortcuts app. Your key is still checked.") + VStack(alignment: .leading, spacing: DS.Spacing.xs) { + Text("Unblock when you arrive somewhere").fontWeight(.medium).foregroundStyle(.primary) + NumberedRow(number: 1, text: "Add a Location key in the Keys tab") + NumberedRow(number: 2, text: "In Settings, tap Background Location and choose Always") + NumberedRow(number: 3, text: "In Shortcuts, add an Arrive automation and set it to run without asking") + NumberedRow(number: 4, text: "Add Unblock All Apps, set Key Type to Location and choose an Unblock Duration") + BulletRow(text: "Keep the Arrive area inside your key's radius, or the check fails on arrival") + BulletRow(text: "Use a radius of 100 m or more so a background reading can confirm where you are") + } VStack(alignment: .leading, spacing: DS.Spacing.xs) { Text("Unblock with an NFC tag").fontWeight(.medium).foregroundStyle(.primary) NumberedRow(number: 1, text: "In Shortcuts, add an NFC automation and scan your tag") diff --git a/Normal/Views/Settings/GeneralSettingsView.swift b/Normal/Views/Settings/GeneralSettingsView.swift index 2f676b2..854000d 100644 --- a/Normal/Views/Settings/GeneralSettingsView.swift +++ b/Normal/Views/Settings/GeneralSettingsView.swift @@ -81,6 +81,10 @@ struct GeneralSettingsView: View { } } + if availableKeyTypes.contains(.location) { + BackgroundLocationRow() + } + Toggle( "Live Activity", isOn: Bindable(settings).showTimedUnblockLiveActivity diff --git a/NormalTests/Models/LocationZonesTests.swift b/NormalTests/Models/LocationZonesTests.swift new file mode 100644 index 0000000..c584f63 --- /dev/null +++ b/NormalTests/Models/LocationZonesTests.swift @@ -0,0 +1,61 @@ +import CoreLocation +@testable import Normal +import Testing + +struct LocationZonesTests { + private static let center = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) + + private func zone(kind: LocationRadiusKind, radius: Double = 200) -> Key { + Key(name: "Zone", latitude: Self.center.latitude, longitude: Self.center.longitude, radiusMeters: radius, radiusKind: kind) + } + + private func fix(metersNorth: Double, accuracy: CLLocationAccuracy = 10) -> CLLocation { + let latitude = Self.center.latitude + metersNorth / 111_320 + return CLLocation( + coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: Self.center.longitude), + altitude: 0, + horizontalAccuracy: accuracy, + verticalAccuracy: 10, + timestamp: .now + ) + } + + private func fit(_ zone: Key, _ location: CLLocation) -> LocationFit? { + LocationZones(keys: [zone])?.fit(location) + } + + @Test func insideAnUnblockZoneIsSatisfied() { + #expect(fit(zone(kind: .unblock), fix(metersNorth: 50)) == .satisfied) + } + + @Test func nearTheUnblockEdgeIsUncertain() { + #expect(fit(zone(kind: .unblock), fix(metersNorth: 180, accuracy: 50)) == .uncertain) + } + + @Test func outsideAnUnblockZoneIsUnsatisfied() { + guard case let .unsatisfied(margin) = fit(zone(kind: .unblock), fix(metersNorth: 400)) else { + Issue.record("Expected unsatisfied") + return + } + #expect(abs(margin - 190) < 2) + } + + @Test func outsideABlockZoneIsSatisfied() { + #expect(fit(zone(kind: .block), fix(metersNorth: 400)) == .satisfied) + } + + @Test func nearTheBlockEdgeIsUncertain() { + #expect(fit(zone(kind: .block, radius: 50), fix(metersNorth: 60, accuracy: 65)) == .uncertain) + } + + @Test func insideABlockZoneIsUnsatisfied() { + guard case .unsatisfied = fit(zone(kind: .block), fix(metersNorth: 20)) else { + Issue.record("Expected unsatisfied") + return + } + } + + @Test func noLocationKeysHasNoZones() { + #expect(LocationZones(keys: [Key(name: "QR", type: .qr, rawValue: "x")]) == nil) + } +} diff --git a/NormalTests/Services/AppUnblockIntentPerformerTests.swift b/NormalTests/Services/AppUnblockIntentPerformerTests.swift index 4b2c8b5..7efc3e4 100644 --- a/NormalTests/Services/AppUnblockIntentPerformerTests.swift +++ b/NormalTests/Services/AppUnblockIntentPerformerTests.swift @@ -1,3 +1,5 @@ +import CoreLocation +import DeviceActivity import FamilyControls import Foundation @testable import Normal @@ -11,9 +13,10 @@ struct AppUnblockIntentPerformerTests { private let activity = FakeDeviceActivityCenter() private let store = FakeSharedStore() private let inbox = UnlockRequestInbox() + private let location: FakeLocationProvider private let clock = TestClock() private let timedUnblock: TimedUnblockService - private let performer: AppUnblockIntentPerformer + private let now = Date() private final class TestClock { var now = Date() @@ -28,11 +31,40 @@ struct AppUnblockIntentPerformerTests { clock: { clock.now }, onExpiration: {} ) - performer = AppUnblockIntentPerformer( + location = FakeLocationProvider( + outcome: .location(Self.fix(latitude: 37.3349, longitude: -122.0090, at: now)), + authorizationStatus: .authorizedAlways + ) + } + + private static func fix(latitude: Double, longitude: Double, at timestamp: Date) -> CLLocation { + CLLocation( + coordinate: CLLocationCoordinate2D(latitude: latitude, longitude: longitude), + altitude: 0, + horizontalAccuracy: 10, + verticalAccuracy: 10, + timestamp: timestamp + ) + } + + private var performer: AppUnblockIntentPerformer { + performer(deadline: .seconds(300)) + } + + private func performer(deadline: Duration) -> AppUnblockIntentPerformer { + let now = now + return AppUnblockIntentPerformer( container: container, screenTimeService: screenTime, timedUnblockService: timedUnblock, - unlockInbox: inbox + unlockInbox: inbox, + locationVerifier: BackgroundLocationVerifier( + provider: location, + deadline: deadline, + pollInterval: .milliseconds(1), + now: { now } + ), + syncsExternalSurfaces: false ) } @@ -67,30 +99,30 @@ struct AppUnblockIntentPerformerTests { UnblockRequest(groupID: group, duration: .fixed(.oneHour), keyType: key) } - @Test func blockedAppsContinueInApp() throws { + @Test func blockedAppsContinueInApp() async throws { try seed() screenTime.stubBlockStatus = .all - #expect(try performer.unblock(request()) == .continueInApp) + #expect(try await performer.unblock(request()) == .continueInApp(.checkKey)) #expect(!timedUnblock.isMainUnblockActive) } - @Test func nothingBlockedIsAlreadyUnblocked() throws { + @Test func nothingBlockedIsAlreadyUnblocked() async throws { try seed() screenTime.stubBlockStatus = .none - #expect(try performer.unblock(request()) == .alreadyUnblocked(name: "All Apps")) + #expect(try await performer.unblock(request()) == .alreadyUnblocked(name: "All Apps")) } - @Test func activeMainUnblockReportsTheRunningTimer() throws { + @Test func activeMainUnblockReportsTheRunningTimer() async throws { try seed() try timedUnblock.startMain(duration: .fifteenMinutes, selection: FamilyActivitySelection(), screenTimeService: screenTime) screenTime.stubBlockStatus = .all - #expect(try performer.unblock(request()) == .timedUnblockRunning(name: "All Apps")) + #expect(try await performer.unblock(request()) == .timedUnblockRunning(name: "All Apps")) } - @Test func activeGroupUnblockReportsTheRunningTimer() throws { + @Test func activeGroupUnblockReportsTheRunningTimer() async throws { try seed() let group = try seedGroup() try timedUnblock.startGroup( @@ -101,19 +133,19 @@ struct AppUnblockIntentPerformerTests { ) screenTime.stubBlockStatus = .some - #expect(try performer.unblock(request(group: group.id)) == .timedUnblockRunning(name: "Social")) + #expect(try await performer.unblock(request(group: group.id)) == .timedUnblockRunning(name: "Social")) } - @Test func expiredTimedUnblockIsNotMistakenForActive() throws { + @Test func expiredTimedUnblockIsNotMistakenForActive() async throws { try seed() try timedUnblock.startMain(duration: .fifteenMinutes, selection: FamilyActivitySelection(), screenTimeService: screenTime) clock.now = clock.now.addingTimeInterval(20 * 60) screenTime.stubBlockStatus = .all - #expect(try performer.unblock(request()) == .continueInApp) + #expect(try await performer.unblock(request()) == .continueInApp(.checkKey)) } - @Test func doesNotRequireAGlobalKey() throws { + @Test func doesNotRequireAGlobalKey() async throws { let settings = Settings() settings.hasCompletedOnboarding = true settings.enableCustomDomains = true @@ -122,39 +154,39 @@ struct AppUnblockIntentPerformerTests { try context.save() screenTime.stubBlockStatus = .all - #expect(try performer.unblock(request()) == .continueInApp) + #expect(try await performer.unblock(request()) == .continueInApp(.checkKey)) } - @Test func requiresCompletedSetup() throws { + @Test func requiresCompletedSetup() async throws { try seed(onboarded: false) - #expect(throws: BlockIntentError.setupIncomplete) { - try performer.unblock(request()) + await #expect(throws: BlockIntentError.setupIncomplete) { + try await performer.unblock(request()) } } - @Test func requiresScreenTimeAuthorization() throws { + @Test func requiresScreenTimeAuthorization() async throws { try seed() screenTime.stubIsAuthorizedNow = false - #expect(throws: BlockIntentError.screenTimeNotAuthorized) { - try performer.unblock(request()) + await #expect(throws: BlockIntentError.screenTimeNotAuthorized) { + try await performer.unblock(request()) } } - @Test func requiresSomethingSelected() throws { + @Test func requiresSomethingSelected() async throws { try seed(mainDomains: []) - #expect(throws: BlockIntentError.noAppsSelected) { - try performer.unblock(request()) + await #expect(throws: BlockIntentError.noAppsSelected) { + try await performer.unblock(request()) } } - @Test func throwsForDeletedGroup() throws { + @Test func throwsForDeletedGroup() async throws { try seed() - #expect(throws: BlockIntentError.groupNotFound) { - try performer.unblock(request(group: UUID())) + await #expect(throws: BlockIntentError.groupNotFound) { + try await performer.unblock(request(group: UUID())) } } @@ -193,4 +225,168 @@ struct AppUnblockIntentPerformerTests { #expect(inbox.pending?.keyType == .qr) } + + // MARK: - Location + + private func locationRequest(group: UUID? = nil, duration: UnlockDurationRequest = .fixed(.oneHour)) -> UnblockRequest { + UnblockRequest(groupID: group, duration: duration, keyType: .location) + } + + @Test func locationKeyUnblocksWithoutOpeningNormal() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest()) == .unblocked(name: "All Apps", length: .timed(.oneHour))) + #expect(timedUnblock.isMainUnblockActive) + } + + @Test func locationKeyUsesTheDefaultDuration() async throws { + let settings = try seed() + context.insert(locationKey()) + settings.defaultDuration = .thirtyMinutes + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest(duration: .useDefault)) == .unblocked(name: "All Apps", length: .timed(.thirtyMinutes))) + } + + @Test func locationKeyUnblocksUntilManuallyReBlocked() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest(duration: .permanent)) == .unblocked(name: "All Apps", length: .permanent)) + #expect(screenTime.unblockAllCalled) + #expect(!timedUnblock.isMainUnblockActive) + } + + @Test func onlyLocationKeyIsUsedWithoutAKeyType() async throws { + let settings = Settings() + settings.hasCompletedOnboarding = true + context.insert(settings) + context.insert(SelectedApps(selection: FamilyActivitySelection(), customDomains: ["example.com"])) + settings.enableCustomDomains = true + context.insert(locationKey()) + try context.save() + screenTime.stubBlockStatus = .all + + let result = try await performer.unblock(UnblockRequest(groupID: nil, duration: .fixed(.oneHour), keyType: nil)) + + #expect(result == .unblocked(name: "All Apps", length: .timed(.oneHour))) + } + + @Test func choosingTheDurationInNormalHandsOff() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest(duration: .ask)) == .continueInApp(.checkKey)) + #expect(location.requestCount == 0) + } + + @Test func outsideTheZoneThrows() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + location.outcome = .location(Self.fix(latitude: 51.5074, longitude: -0.1278, at: now)) + + await #expect(throws: UnblockIntentError.notAtLocation(.unblock)) { + try await performer.unblock(locationRequest()) + } + #expect(!timedUnblock.isMainUnblockActive) + } + + @Test func whileUsingOnlyHandsOffWithAReason() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + location.authorizationStatus = .authorizedWhenInUse + + #expect(try await performer.unblock(locationRequest()) == .continueInApp(.backgroundLocationOff)) + } + + @Test func preciseLocationOffHandsOffWithAReason() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + location.accuracyAuthorization = .reducedAccuracy + + #expect(try await performer.unblock(locationRequest()) == .continueInApp(.preciseLocationOff)) + } + + @Test func noFixHandsOffWithAReason() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + location.outcome = .throwGeneric + + #expect(try await performer(deadline: .milliseconds(150)).unblock(locationRequest()) == .continueInApp(.noLocationFix)) + } + + @Test(.timeLimit(.minutes(5))) func timerStartedDuringTheCheckIsNotReplaced() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + location.outcome = .pending + let performer = performer + let task = Task { try await performer.unblock(locationRequest(duration: .permanent)) } + await location.waitForRequests(1) + + try timedUnblock.startMain(duration: .fifteenMinutes, selection: FamilyActivitySelection(), screenTimeService: screenTime) + location.deliverPending(Self.fix(latitude: 37.3349, longitude: -122.0090, at: now)) + + #expect(try await task.value == .timedUnblockRunning(name: "All Apps")) + #expect(!screenTime.unblockAllCalled) + } + + @Test(.timeLimit(.minutes(5))) func groupDeletedDuringTheCheckIsNotUnblocked() async throws { + try seed() + let group = try seedGroup() + context.insert(locationKey(groupID: group.id)) + screenTime.stubBlockStatus = .all + location.outcome = .pending + let performer = performer + let task = Task { try await performer.unblock(locationRequest(group: group.id)) } + await location.waitForRequests(1) + + context.delete(group) + try context.save() + location.deliverPending(Self.fix(latitude: 37.3349, longitude: -122.0090, at: now)) + + await #expect(throws: BlockIntentError.groupNotFound) { + try await task.value + } + } + + @Test func unblockAllIgnoresGroupLocationKeys() async throws { + try seed() + let group = try seedGroup() + context.insert(locationKey(groupID: group.id)) + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest()) == .continueInApp(.checkKey)) + #expect(location.requestCount == 0) + } + + @Test func unblockGroupAcceptsItsOwnLocationKey() async throws { + try seed() + let group = try seedGroup() + context.insert(locationKey(groupID: group.id)) + screenTime.stubBlockStatus = .all + + #expect(try await performer.unblock(locationRequest(group: group.id)) == .unblocked(name: "Social", length: .timed(.oneHour))) + #expect(timedUnblock.isGroupUnblockActive(groupId: group.id)) + } + + @Test func failingToStartTheUnblockThrows() async throws { + try seed() + context.insert(locationKey()) + screenTime.stubBlockStatus = .all + activity.startError = DeviceActivityCenter.MonitoringError.excessiveActivities + + await #expect(throws: UnblockIntentError.unblockFailed) { + try await performer.unblock(locationRequest()) + } + #expect(!timedUnblock.isMainUnblockActive) + } } diff --git a/NormalTests/Services/BackgroundLocationVerifierTests.swift b/NormalTests/Services/BackgroundLocationVerifierTests.swift new file mode 100644 index 0000000..290e45b --- /dev/null +++ b/NormalTests/Services/BackgroundLocationVerifierTests.swift @@ -0,0 +1,183 @@ +import CoreLocation +import Foundation +@testable import Normal +import Testing + +@MainActor +struct BackgroundLocationVerifierTests { + private nonisolated static let cupertino = CLLocationCoordinate2D(latitude: 37.3349, longitude: -122.0090) + private static let london = CLLocationCoordinate2D(latitude: 51.5074, longitude: -0.1278) + private let now = Date() + + private func locationKey(kind: LocationRadiusKind = .unblock) -> Key { + Key( + name: "Place", + latitude: Self.cupertino.latitude, + longitude: Self.cupertino.longitude, + radiusMeters: 200, + radiusKind: kind + ) + } + + private func fix( + at coordinate: CLLocationCoordinate2D = cupertino, + metersNorth: Double = 0, + accuracy: CLLocationAccuracy = 10, + age: TimeInterval = 0, + simulated: Bool = false + ) -> CLLocation { + CLLocation( + coordinate: CLLocationCoordinate2D( + latitude: coordinate.latitude + metersNorth / 111_320, + longitude: coordinate.longitude + ), + altitude: 0, + horizontalAccuracy: accuracy, + verticalAccuracy: 10, + course: 0, + courseAccuracy: 0, + speed: 0, + speedAccuracy: 0, + timestamp: now.addingTimeInterval(-age), + sourceInfo: CLLocationSourceInformation( + softwareSimulationState: simulated, + andExternalAccessoryState: false + ) + ) + } + + private func provider( + _ outcome: FakeLocationProvider.Outcome, + status: CLAuthorizationStatus = .authorizedAlways + ) -> FakeLocationProvider { + FakeLocationProvider(outcome: outcome, authorizationStatus: status) + } + + private func check( + _ provider: FakeLocationProvider, + keys: [Key]? = nil, + deadline: Duration = .milliseconds(150) + ) async -> BackgroundLocationCheck { + let now = now + let verifier = BackgroundLocationVerifier(provider: provider, deadline: deadline, pollInterval: .milliseconds(1), now: { now }) + return await verifier.check(keys: keys ?? [locationKey()]) + } + + @Test func noLocationKeys() async { + let provider = provider(.location(fix())) + #expect(await check(provider, keys: [Key(name: "QR", type: .qr, rawValue: "code")]) == .noLocationKey) + #expect(provider.requestCount == 0) + } + + @Test func requiresAlwaysAuthorization() async { + let provider = provider(.location(fix()), status: .authorizedWhenInUse) + #expect(await check(provider) == .needsAlways) + #expect(provider.requestCount == 0) + } + + @Test func requiresPreciseLocation() async { + let provider = provider(.location(fix())) + provider.accuracyAuthorization = .reducedAccuracy + #expect(await check(provider) == .needsPrecise) + #expect(provider.requestCount == 0) + } + + @Test func verifiesInsideUnblockZone() async { + #expect(await check(provider(.location(fix())), deadline: .seconds(300)) == .verified) + } + + @Test func blockKindVerifiesWhenOutside() async { + #expect(await check(provider(.location(fix(at: Self.london))), keys: [locationKey(kind: .block)], deadline: .seconds(300)) == .verified) + } + + @Test func farOutsideFailsWithoutWaiting() async { + let provider = provider(.location(fix(at: Self.london))) + #expect(await check(provider, deadline: .seconds(300)) == .outOfRange) + #expect(provider.requestCount == 1) + } + + @Test func justOutsideWithNoTimeToWalkInIsOutOfRange() async { + let provider = provider(.pending) + provider.queuedOutcomes = [.location(fix(metersNorth: 300))] + #expect(await check(provider, deadline: .seconds(1)) == .outOfRange) + provider.finishPending() + } + + @Test func justOutsideKeepsChecking() async { + let provider = provider(.location(fix())) + provider.queuedOutcomes = [.location(fix(metersNorth: 300)), .location(fix(metersNorth: 250))] + #expect(await check(provider, deadline: .seconds(300)) == .verified) + #expect(provider.requestCount == 3) + } + + @Test(.timeLimit(.minutes(5))) func latestReadingDecidesTheResult() async { + let provider = provider(.pending) + provider.queuedOutcomes = [.location(fix(metersNorth: 220)), .location(fix(metersNorth: 190, accuracy: 50))] + let now = now + let verifier = BackgroundLocationVerifier(provider: provider, deadline: .seconds(300), pollInterval: .milliseconds(1), now: { now }) + let task = Task { await verifier.check(keys: [locationKey()]) } + await provider.waitForRequests(3) + task.cancel() + #expect(await task.value == .inconclusive) + provider.finishPending() + } + + @Test func reachShrinksAsTheDeadlineNears() { + #expect(BackgroundLocationVerifier.isOutOfReach(600, within: .seconds(15))) + #expect(!BackgroundLocationVerifier.isOutOfReach(170, within: .seconds(15))) + #expect(BackgroundLocationVerifier.isOutOfReach(170, within: .seconds(4))) + } + + @Test func verifiesOnceTheDeviceWalksIn() async { + let provider = provider(.location(fix())) + provider.queuedOutcomes = [.location(fix(metersNorth: 300))] + #expect(await check(provider, deadline: .seconds(300)) == .verified) + #expect(provider.requestCount == 2) + } + + @Test func fixAtTheEdgeIsInconclusive() async { + #expect(await check(provider(.location(fix(metersNorth: 190, accuracy: 50)))) == .inconclusive) + } + + @Test(arguments: [150.0, -1.0]) + func rejectsInaccurateFix(_ accuracy: CLLocationAccuracy) async { + #expect(await check(provider(.location(fix(accuracy: accuracy)))) == .inconclusive) + } + + @Test func rejectsStaleFix() async { + #expect(await check(provider(.location(fix(age: 60)))) == .inconclusive) + } + + @Test func rejectsFutureDatedFix() async { + #expect(await check(provider(.location(fix(age: -120)))) == .inconclusive) + } + + @Test func rejectsSimulatedFix() async { + #expect(await check(provider(.location(fix(simulated: true)))) == .inconclusive) + } + + @Test func ignoresTheCachedLocation() async { + let provider = provider(.throwGeneric) + provider.recentLocation = fix() + provider.cachedLocation = fix() + #expect(await check(provider) == .inconclusive) + } + + @Test func noFixBeforeTheDeadlineIsInconclusive() async { + let provider = provider(.pending) + #expect(await check(provider) == .inconclusive) + provider.finishPending() + } + + @Test func cancellingStopsTheCheck() async { + let provider = provider(.pending) + let verifier = BackgroundLocationVerifier(provider: provider, deadline: .seconds(300)) + let task = Task { await verifier.check(keys: [locationKey()]) } + while provider.requestCount == 0 { + await Task.yield() + } + task.cancel() + #expect(await task.value == .inconclusive) + provider.finishPending() + } +} diff --git a/NormalTests/TestSupport/FakeLocationProvider.swift b/NormalTests/TestSupport/FakeLocationProvider.swift index 4a544df..339017f 100644 --- a/NormalTests/TestSupport/FakeLocationProvider.swift +++ b/NormalTests/TestSupport/FakeLocationProvider.swift @@ -8,12 +8,18 @@ final class FakeLocationProvider: LocationProviding { case location(CLLocation) case throwKeyError(LocationKeyError) case throwGeneric + case pending } var outcome: Outcome + var queuedOutcomes: [Outcome] = [] var authorizationStatus: CLAuthorizationStatus + var accuracyAuthorization: CLAccuracyAuthorization = .fullAccuracy var cachedLocation: CLLocation? var recentLocation: CLLocation? + private(set) var requestCount = 0 + private var pendingContinuation: CheckedContinuation? + private var requestWaiters: [(count: Int, continuation: CheckedContinuation)] = [] init( outcome: Outcome, @@ -32,13 +38,35 @@ final class FakeLocationProvider: LocationProviding { } func currentLocation() async throws -> CLLocation { - switch outcome { + requestCount += 1 + let ready = requestWaiters.filter { $0.count <= requestCount } + requestWaiters.removeAll { $0.count <= requestCount } + ready.forEach { $0.continuation.resume() } + let next = queuedOutcomes.isEmpty ? outcome : queuedOutcomes.removeFirst() + switch next { case let .location(location): return location case let .throwKeyError(error): throw error case .throwGeneric: throw NSError(domain: "test", code: 0) + case .pending: + return try await withCheckedThrowingContinuation { pendingContinuation = $0 } } } + + func finishPending() { + pendingContinuation?.resume(throwing: LocationKeyError.unavailable) + pendingContinuation = nil + } + + func waitForRequests(_ count: Int) async { + guard requestCount < count else { return } + await withCheckedContinuation { requestWaiters.append((count, $0)) } + } + + func deliverPending(_ location: CLLocation) { + pendingContinuation?.resume(returning: location) + pendingContinuation = nil + } }