Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Normal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
105 changes: 90 additions & 15 deletions Normal/Intents/AppUnblockIntentPerformer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,56 +5,131 @@ 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,
screenTimeService: screenTimeService,
timedUnblockService: timedUnblockService
)
self.unlockInbox = unlockInbox
self.locationVerifier = locationVerifier
self.syncsExternalSurfaces = syncsExternalSurfaces
}

convenience init(container: ModelContainer, services: AppServices) {
self.init(
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))
)
}
Expand Down
61 changes: 49 additions & 12 deletions Normal/Intents/UnblockIntents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,61 @@ 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."
}
}
}

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")
Expand All @@ -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)
)
Expand All @@ -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?")
Expand Down Expand Up @@ -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)
)
Expand Down Expand Up @@ -163,6 +196,7 @@ struct OpenUnblockIntent: AppIntent {
private extension AppIntent {
func continueInApp(
_ request: UnblockRequest,
reason: HandOffReason,
performer: any UnblockIntentPerforming,
fallback: OpenUnblockIntent
) async throws -> IntentResultContainer<Never, Never, Never, IntentDialog> {
Expand All @@ -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
Expand Down
47 changes: 47 additions & 0 deletions Normal/Models/LocationZones.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading
Loading