diff --git a/Normal.xcodeproj/project.pbxproj b/Normal.xcodeproj/project.pbxproj index c7cd5d4..78335c1 100644 --- a/Normal.xcodeproj/project.pbxproj +++ b/Normal.xcodeproj/project.pbxproj @@ -148,9 +148,11 @@ BlockIntents.swift, DismissUnblockActivityIntent.swift, GroupEntity.swift, + KeyTypeEntity.swift, SharedConstants.swift, TimedUnblockActivityAttributes.swift, TimedUnblockDuration.swift, + UnblockDurationEntity.swift, WidgetSharedData.swift, ); target = 2FDA0000000000000000A003 /* NormalWidget */; diff --git a/Normal/App/AppContainer.swift b/Normal/App/AppContainer.swift index 75f6ec2..5141f48 100644 --- a/Normal/App/AppContainer.swift +++ b/Normal/App/AppContainer.swift @@ -14,6 +14,7 @@ struct AppContainer: View { @State private var emergencyUnblockService: EmergencyUnblockService @State private var donationService = DonationService() @State private var usageLimitService: UsageLimitService + @State private var unlockInbox: UnlockRequestInbox init(services: AppServices) { _screenTimeService = State(initialValue: services.screenTime) @@ -22,6 +23,7 @@ struct AppContainer: View { _appReviewService = State(initialValue: services.appReview) _emergencyUnblockService = State(initialValue: services.emergencyUnblock) _usageLimitService = State(initialValue: services.usageLimit) + _unlockInbox = State(initialValue: services.unlockInbox) } var body: some View { @@ -37,6 +39,7 @@ struct AppContainer: View { .environment(emergencyUnblockService) .environment(donationService) .environment(usageLimitService) + .environment(unlockInbox) .task { mirrorCustomDomainsEnabled() } .onChange(of: allSettings.first?.enableCustomDomains ?? false) { _, enabled in scheduleService.mirrorCustomDomainsEnabled(enabled) diff --git a/Normal/App/AppServices.swift b/Normal/App/AppServices.swift index 30438aa..9ff151d 100644 --- a/Normal/App/AppServices.swift +++ b/Normal/App/AppServices.swift @@ -8,6 +8,7 @@ final class AppServices { let appReview: AppReviewService let emergencyUnblock: EmergencyUnblockService let usageLimit: UsageLimitService + let unlockInbox = UnlockRequestInbox() init() { if UITestSupport.isActive { diff --git a/Normal/App/NormalApp.swift b/Normal/App/NormalApp.swift index c7f142b..65b0e7d 100644 --- a/Normal/App/NormalApp.swift +++ b/Normal/App/NormalApp.swift @@ -81,6 +81,12 @@ struct NormalApp: App { services: services ) AppDependencyManager.shared.add(dependency: blockPerformer) + + let unblockPerformer: any UnblockIntentPerforming = AppUnblockIntentPerformer( + container: container, + services: services + ) + AppDependencyManager.shared.add(dependency: unblockPerformer) } var body: some Scene { diff --git a/Normal/Intents/AppBlockIntentPerformer.swift b/Normal/Intents/AppBlockIntentPerformer.swift index 359d7ae..4c840b0 100644 --- a/Normal/Intents/AppBlockIntentPerformer.swift +++ b/Normal/Intents/AppBlockIntentPerformer.swift @@ -3,9 +3,7 @@ import OSLog import SwiftData final class AppBlockIntentPerformer: BlockIntentPerforming { - private let container: ModelContainer - private let screenTimeService: any ScreenTimeProviding - private let timedUnblockService: TimedUnblockService + private let intents: IntentContext private let syncsExternalSurfaces: Bool private let logger = Logger(subsystem: "com.normalengineering.normal", category: "Intents") @@ -15,9 +13,11 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { timedUnblockService: TimedUnblockService, syncsExternalSurfaces: Bool = true ) { - self.container = container - self.screenTimeService = screenTimeService - self.timedUnblockService = timedUnblockService + intents = IntentContext( + container: container, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) self.syncsExternalSurfaces = syncsExternalSurfaces } @@ -29,29 +29,18 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { ) } - private var context: ModelContext { - container.mainContext - } - func blockAll() throws -> BlockOutcome { logger.info("Block intent: all") - let settings = try validatedSettings() - guard let mainSelection = try context.fetch(FetchDescriptor()).first, - !mainSelection.selection.isEmpty - || (settings.enableCustomDomains && !mainSelection.customDomains.isEmpty) - else { throw BlockIntentError.noAppsSelected } - - let status = screenTimeService.blockStatus( - selection: mainSelection.selection, - customDomains: settings.enableCustomDomains ? mainSelection.customDomains : [] - ) - let wasAlreadyBlocked = status == .all && timedUnblockService.activeUnblocks.isEmpty + let settings = try intents.validatedSettings(requiringGlobalKey: true) + let mainSelection = try intents.mainSelection(settings: settings) + let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .all(mainSelection), settings: settings) == .all + && intents.timedUnblockService.activeUnblocks.isEmpty BlockActions.blockAll( mainSelection: mainSelection, settings: settings, - screenTimeService: screenTimeService, - timedUnblockService: timedUnblockService + screenTimeService: intents.screenTimeService, + timedUnblockService: intents.timedUnblockService ) syncExternalSurfaces(settings: settings) return BlockOutcome(name: String(localized: "All Apps"), wasAlreadyBlocked: wasAlreadyBlocked) @@ -59,48 +48,23 @@ final class AppBlockIntentPerformer: BlockIntentPerforming { func blockGroup(id: UUID) throws -> BlockOutcome { logger.info("Block intent: group") - let settings = try validatedSettings() - let descriptor = FetchDescriptor(predicate: #Predicate { $0.id == id }) - guard let group = try context.fetch(descriptor).first else { - throw BlockIntentError.groupNotFound - } - - let status = screenTimeService.blockStatus( - selection: group.selection, - customDomains: settings.enableCustomDomains ? group.customDomains : [] - ) - let wasAlreadyBlocked = status == .all && !timedUnblockService.isGroupUnblockActive(groupId: id) + let settings = try intents.validatedSettings(requiringGlobalKey: true) + let group = try intents.group(id: id) + let wasAlreadyBlocked = intents.screenTimeService.blockStatus(of: .group(group), settings: settings) == .all + && !intents.timedUnblockService.isGroupUnblockActive(groupId: id) BlockActions.blockGroup( group, settings: settings, - screenTimeService: screenTimeService, - timedUnblockService: timedUnblockService + screenTimeService: intents.screenTimeService, + timedUnblockService: intents.timedUnblockService ) syncExternalSurfaces(settings: settings) return BlockOutcome(name: group.name, wasAlreadyBlocked: wasAlreadyBlocked) } - private func validatedSettings() throws -> Settings { - let settings = try context.fetch(FetchDescriptor()).first - try BlockActions.validate( - isAuthorized: screenTimeService.isAuthorizedNow, - hasCompletedOnboarding: settings?.hasCompletedOnboarding == true, - keys: context.fetch(FetchDescriptor()) - ) - guard let settings else { throw BlockIntentError.setupIncomplete } - return settings - } - private func syncExternalSurfaces(settings: Settings) { guard syncsExternalSurfaces else { return } - let groups = (try? context.fetch(FetchDescriptor(sortBy: [SortDescriptor(\.sortIndex)]))) ?? [] - let keys = (try? context.fetch(FetchDescriptor())) ?? [] - WidgetSync.sync(groups: groups, keys: keys, settings: settings, screenTimeService: screenTimeService) - LiveActivityManager.reconcile( - timedUnblockService: timedUnblockService, - groups: groups, - isEnabled: settings.showTimedUnblockLiveActivity - ) + intents.syncExternalSurfaces(settings: settings) } } diff --git a/Normal/Intents/AppUnblockIntentPerformer.swift b/Normal/Intents/AppUnblockIntentPerformer.swift new file mode 100644 index 0000000..62d7680 --- /dev/null +++ b/Normal/Intents/AppUnblockIntentPerformer.swift @@ -0,0 +1,61 @@ +import Foundation +import OSLog +import SwiftData + +final class AppUnblockIntentPerformer: UnblockIntentPerforming { + private let intents: IntentContext + private let unlockInbox: UnlockRequestInbox + private let logger = Logger(subsystem: "com.normalengineering.normal", category: "Intents") + + init( + container: ModelContainer, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService, + unlockInbox: UnlockRequestInbox + ) { + intents = IntentContext( + container: container, + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService + ) + self.unlockInbox = unlockInbox + } + + convenience init(container: ModelContainer, services: AppServices) { + self.init( + container: container, + screenTimeService: services.screenTime, + timedUnblockService: services.timedUnblock, + unlockInbox: services.unlockInbox + ) + } + + func unblock(_ request: UnblockRequest) 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) + } + return .continueInApp + } + + func continueInApp(_ request: UnblockRequest) { + unlockInbox.post(UnblockRequest( + groupID: request.groupID, + duration: request.duration, + keyType: keyType(for: request) + )) + } + + private func keyType(for request: UnblockRequest) -> KeyType? { + let keys = Key.scoped((try? intents.keys()) ?? [], toGroup: request.groupID) + return KeySelectLogic.shortcutKeyType( + requested: request.keyType, + defaultKeyType: intents.settings()?.defaultKeyType, + availableKeyTypes: KeyType.selectable(registered: keys.map(\.type)) + ) + } +} diff --git a/Normal/Intents/IntentContext.swift b/Normal/Intents/IntentContext.swift new file mode 100644 index 0000000..f7ab2ee --- /dev/null +++ b/Normal/Intents/IntentContext.swift @@ -0,0 +1,73 @@ +import Foundation +import SwiftData + +struct IntentContext { + let container: ModelContainer + let screenTimeService: any ScreenTimeProviding + let timedUnblockService: TimedUnblockService + + private var context: ModelContext { + container.mainContext + } + + func validatedSettings(requiringGlobalKey: Bool) throws -> Settings { + let settings = try context.fetch(FetchDescriptor()).first + let hasCompletedOnboarding = settings?.hasCompletedOnboarding == true + if requiringGlobalKey { + try BlockActions.validate( + isAuthorized: screenTimeService.isAuthorizedNow, + hasCompletedOnboarding: hasCompletedOnboarding, + keys: keys() + ) + } else { + try BlockActions.validateSetup( + isAuthorized: screenTimeService.isAuthorizedNow, + hasCompletedOnboarding: hasCompletedOnboarding + ) + } + guard let settings else { throw BlockIntentError.setupIncomplete } + return settings + } + + func settings() -> Settings? { + try? context.fetch(FetchDescriptor()).first + } + + func keys() throws -> [Key] { + try context.fetch(FetchDescriptor()) + } + + func target(groupID: UUID?, settings: Settings) throws -> UnblockTarget { + if let groupID { + return try .group(group(id: groupID)) + } + return try .all(mainSelection(settings: settings)) + } + + func mainSelection(settings: Settings) throws -> SelectedApps { + guard let mainSelection = try context.fetch(FetchDescriptor()).first, + !mainSelection.selection.isEmpty + || (settings.enableCustomDomains && !mainSelection.customDomains.isEmpty) + else { throw BlockIntentError.noAppsSelected } + return mainSelection + } + + func group(id: UUID) throws -> AppGroup { + let descriptor = FetchDescriptor(predicate: #Predicate { $0.id == id }) + guard let group = try context.fetch(descriptor).first else { + throw BlockIntentError.groupNotFound + } + return group + } + + func syncExternalSurfaces(settings: Settings) { + let groups = (try? context.fetch(FetchDescriptor(sortBy: [SortDescriptor(\.sortIndex)]))) ?? [] + let keys = (try? keys()) ?? [] + WidgetSync.sync(groups: groups, keys: keys, settings: settings, screenTimeService: screenTimeService) + LiveActivityManager.reconcile( + timedUnblockService: timedUnblockService, + groups: groups, + isEnabled: settings.showTimedUnblockLiveActivity + ) + } +} diff --git a/Normal/Intents/NormalShortcuts.swift b/Normal/Intents/NormalShortcuts.swift index 36c5ce2..f44bd38 100644 --- a/Normal/Intents/NormalShortcuts.swift +++ b/Normal/Intents/NormalShortcuts.swift @@ -22,6 +22,26 @@ struct NormalShortcuts: AppShortcutsProvider { shortTitle: "Block Group", systemImageName: "lock.square.stack.fill" ) + AppShortcut( + intent: UnblockAllIntent(), + phrases: [ + "Unblock all apps in \(.applicationName)", + "Unblock everything in \(.applicationName)", + "\(.applicationName) unblock all", + ], + shortTitle: "Unblock All", + systemImageName: "lock.open.fill" + ) + AppShortcut( + intent: UnblockGroupIntent(), + phrases: [ + "Unblock \(\.$group) in \(.applicationName)", + "\(.applicationName) unblock \(\.$group)", + "Unblock a group in \(.applicationName)", + ], + shortTitle: "Unblock Group", + systemImageName: "lock.open" + ) } static let shortcutTileColor: ShortcutTileColor = .blue diff --git a/Normal/Intents/UnblockIntents.swift b/Normal/Intents/UnblockIntents.swift new file mode 100644 index 0000000..f3979b2 --- /dev/null +++ b/Normal/Intents/UnblockIntents.swift @@ -0,0 +1,194 @@ +import AppIntents +import Foundation + +nonisolated extension UnblockRequest { + init(group: GroupEntity?, keyType: KeyTypeEntity?, duration: UnblockDurationEntity?) { + self.init( + groupID: group?.id, + duration: duration?.request ?? .useDefault, + keyType: keyType?.keyType + ) + } +} + +enum UnblockOutcome: Equatable, Sendable { + case alreadyUnblocked(name: String) + case timedUnblockRunning(name: String) + case continueInApp +} + +protocol UnblockIntentPerforming: Sendable { + @MainActor func unblock(_ request: UnblockRequest) throws -> UnblockOutcome + @MainActor func continueInApp(_ request: UnblockRequest) +} + +enum UnblockIntentError: Error, Equatable, CustomLocalizedStringResourceConvertible { + case openNormal + + var localizedStringResource: LocalizedStringResource { + switch self { + case .openNormal: "Open Normal to unblock." + } + } +} + +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." + ) + + @Parameter(title: "Key Type") + var keyType: KeyTypeEntity? + + @Parameter(title: "Unblock Duration") + var duration: UnblockDurationEntity? + + @Dependency private var performer: any UnblockIntentPerforming + + @available(iOS 26.0, *) + static var supportedModes: IntentModes { + [.background, .foreground(.dynamic)] + } + + static var parameterSummary: some ParameterSummary { + Summary("Unblock all apps with \(\.$keyType), \(\.$duration)") + } + + init() {} + + 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 .timedUnblockRunning: + return .result(dialog: "A timed unblock is already running for all apps.") + case .continueInApp: + return try await continueInApp( + request, + performer: performer, + fallback: OpenUnblockIntent(group: nil, keyType: keyType, duration: duration) + ) + } + } +} + +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." + ) + + @Parameter(title: "Group", requestValueDialog: "Which group should Normal unblock?") + var group: GroupEntity + + @Parameter(title: "Key Type") + var keyType: KeyTypeEntity? + + @Parameter(title: "Unblock Duration") + var duration: UnblockDurationEntity? + + @Dependency private var performer: any UnblockIntentPerforming + + @available(iOS 26.0, *) + static var supportedModes: IntentModes { + [.background, .foreground(.dynamic)] + } + + static var parameterSummary: some ParameterSummary { + Summary("Unblock \(\.$group) with \(\.$keyType), \(\.$duration)") + } + + init() {} + + 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 let .timedUnblockRunning(name): + return .result(dialog: "A timed unblock is already running for \(name).") + case .continueInApp: + return try await continueInApp( + request, + performer: performer, + fallback: OpenUnblockIntent(group: group, keyType: keyType, duration: duration) + ) + } + } +} + +struct OpenUnblockIntent: AppIntent { + static let title: LocalizedStringResource = "Unblock in Normal" + + static var isDiscoverable: Bool { + false + } + + static var openAppWhenRun: Bool { + true + } + + @available(iOS 26.0, *) + static var supportedModes: IntentModes { + .foreground(.immediate) + } + + @Parameter(title: "Group") + var group: GroupEntity? + + @Parameter(title: "Key Type") + var keyType: KeyTypeEntity? + + @Parameter(title: "Unblock Duration") + var duration: UnblockDurationEntity? + + @Dependency private var performer: any UnblockIntentPerforming + + init() {} + + init(group: GroupEntity?, keyType: KeyTypeEntity?, duration: UnblockDurationEntity?) { + self.group = group + self.keyType = keyType + self.duration = duration + } + + func perform() async throws -> some IntentResult { + await performer.continueInApp(UnblockRequest(group: group, keyType: keyType, duration: duration)) + return .result() + } +} + +private extension AppIntent { + func continueInApp( + _ request: UnblockRequest, + performer: any UnblockIntentPerforming, + fallback: OpenUnblockIntent + ) async throws -> IntentResultContainer { + if #available(iOS 26.0, *) { + if systemContext.currentMode == .background { + guard systemContext.currentMode.canContinueInForeground else { + performer.continueInApp(request) + throw UnblockIntentError.openNormal + } + try await continueInForeground("Open Normal to check your key?", alwaysConfirm: false) + } + performer.continueInApp(request) + return .result(dialog: "").withoutDialog + } + if #available(iOS 18.2, *) { + return .result(opensIntent: fallback, dialog: "").withoutDialog + } + performer.continueInApp(request) + throw UnblockIntentError.openNormal + } +} + +private extension IntentResultContainer { + var withoutDialog: Self { + var result = self + result.dialog = nil + return result + } +} diff --git a/Normal/Models/Settings+UnblockDurations.swift b/Normal/Models/Settings+UnblockDurations.swift index 6556184..56ed00c 100644 --- a/Normal/Models/Settings+UnblockDurations.swift +++ b/Normal/Models/Settings+UnblockDurations.swift @@ -33,10 +33,11 @@ extension Settings { } } - func duration(for request: UnlockDurationRequest) -> TimedUnblockDuration? { + func unblockLength(for request: UnlockDurationRequest) -> UnblockLength? { switch request { - case let .fixed(duration): duration - case .useDefault: defaultDuration + case let .fixed(duration): .timed(duration) + case .permanent: .permanent + case .useDefault: defaultDuration.map(UnblockLength.timed) case .ask: nil } } diff --git a/Normal/Models/UnblockLength.swift b/Normal/Models/UnblockLength.swift new file mode 100644 index 0000000..e941be2 --- /dev/null +++ b/Normal/Models/UnblockLength.swift @@ -0,0 +1,6 @@ +import Foundation + +enum UnblockLength: Equatable { + case timed(TimedUnblockDuration) + case permanent +} diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index 3abfb3e..ff2510a 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -5,6 +5,8 @@ import SwiftUI private struct WidgetActionResponder: ViewModifier { @Environment(TimedUnblockService.self) private var timedUnblockService @Environment(ScreenTimeService.self) private var screenTimeService + @Environment(UnlockRequestInbox.self) private var unlockInbox + @Environment(\.scenePhase) private var scenePhase @Query private var allSettings: [Settings] @Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var groups: [AppGroup] @Query private var keys: [Key] @@ -38,11 +40,14 @@ private struct WidgetActionResponder: ViewModifier { keyGroupID: active?.target.groupID, requestID: active?.token ) - .sheet(item: $durationTarget, onDismiss: replayHeldRequest) { target in + .sheet(item: $durationTarget, onDismiss: durationSheetDismissed) { target in UnblockDurationSheet(target: target) } .onOpenURL { coordinator.handle(url: $0) } .onChange(of: coordinator.pendingAction) { _, request in resolve(request) } + .onChange(of: unlockInbox.pending, initial: true) { _, _ in takeInboxRequest() } + .onChange(of: scenePhase) { _, _ in takeInboxRequest() } + .onChange(of: screenTimeService.authorizationState) { _, _ in takeInboxRequest() } .onChange(of: groups) { _, _ in syncGroups() } .onChange(of: keys) { _, _ in syncWidget() } .onChange(of: screenTimeService.lastUpdate) { _, _ in syncWidget() } @@ -64,6 +69,26 @@ private struct WidgetActionResponder: ViewModifier { NormalShortcuts.updateAppShortcutParameters() } + private func takeInboxRequest() { + guard scenePhase == .active, + screenTimeService.authorizationState == .authorized, + durationTarget == nil, + let request = unlockInbox.take(), + let settings = allSettings.first, + let target = target(for: request.groupID), + target.canUnblock( + status: screenTimeService.blockStatus(of: target, settings: settings), + timedUnblockService: timedUnblockService + ) + else { return } + coordinator.requestUnblock(request) + } + + private func durationSheetDismissed() { + replayHeldRequest() + takeInboxRequest() + } + private func resolve(_ request: ActionRequest?) { guard let request else { return } coordinator.clearPendingAction() @@ -104,15 +129,16 @@ private struct WidgetActionResponder: ViewModifier { } private func unlock(_ target: UnblockTarget, duration request: UnlockDurationRequest) { - guard let settings = allSettings.first, let duration = settings.duration(for: request) else { + guard let settings = allSettings.first, let length = settings.unblockLength(for: request) else { durationTarget = target return } - try? timedUnblockService.start( + try? BlockActions.unblock( target, - duration: duration, + for: length, settings: settings, - screenTimeService: screenTimeService + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService ) } diff --git a/Normal/Resources/Localizable.xcstrings b/Normal/Resources/Localizable.xcstrings index 0294b39..d252685 100644 --- a/Normal/Resources/Localizable.xcstrings +++ b/Normal/Resources/Localizable.xcstrings @@ -56,6 +56,10 @@ "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 @@ -209,6 +213,14 @@ "comment" : "A usage limit suggestion for social media apps.", "isCommentAutoGenerated" : true }, + "A timed unblock is already running for %@." : { + "comment" : "A description of an error that might occur when unblocking an app. The argument is the name of the app.", + "isCommentAutoGenerated" : true + }, + "A timed unblock is already running for all apps." : { + "comment" : "Text displayed in a result when a timed unblock is already running for all apps.", + "isCommentAutoGenerated" : true + }, "Absolutely, Normal was designed for exactly this." : { }, @@ -317,6 +329,10 @@ "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 @@ -496,6 +512,10 @@ "comment" : "How it works section of the usage limits guide.", "isCommentAutoGenerated" : true }, + "Choose in Normal" : { + "comment" : "Text for the option to choose a unblock duration in the normal (non-widget) UI.", + "isCommentAutoGenerated" : true + }, "Choose Key" : { "comment" : "The title of the view that lets users choose a key to unlock a door.", "isCommentAutoGenerated" : true @@ -1142,10 +1162,26 @@ "comment" : "A label displayed as the footer of a donation view section that offers one-time tips.", "isCommentAutoGenerated" : true }, + "Open Normal to check your key?" : { + "comment" : "Confirmation prompt to open Normal to check the user's key.", + "isCommentAutoGenerated" : true + }, + "Open Normal to unblock." : { + "comment" : "Localized error message for the unblock intent.", + "isCommentAutoGenerated" : true + }, "Open Settings" : { "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.", + "isCommentAutoGenerated" : true + }, "Option A: Ask a trusted friend" : { "comment" : "A title for a card in the \"Pick one option for the passcode and Apple ID\" section of the SettingsBypassGuide view.", "isCommentAutoGenerated" : true @@ -1301,12 +1337,12 @@ "comment" : "A message displayed when the user hasn't selected any apps to manage.", "isCommentAutoGenerated" : true }, - "Select apps in the main picker first." : { - "comment" : "A description text displayed when there are no apps to select.", + "Select apps in Normal first." : { + "comment" : "Error thrown when no apps are selected in Normal.", "isCommentAutoGenerated" : true }, - "Select apps to block in Normal first." : { - "comment" : "Error message when no apps are selected in Normal.", + "Select apps in the main picker first." : { + "comment" : "A description text displayed when there are no apps to select.", "isCommentAutoGenerated" : true }, "Select apps you want to block" : { @@ -1526,6 +1562,9 @@ "Unblock" : { "comment" : "A button label that unblocks an app group.", "isCommentAutoGenerated" : true + }, + "Unblock ${group} with ${keyType}, ${duration}" : { + }, "Unblock All" : { "comment" : "A button that unblocks all apps from being blocked.", @@ -1567,18 +1606,37 @@ "comment" : "A footer explaining why the custom websites toggle is disabled while custom domains are blocked.", "isCommentAutoGenerated" : true }, + "Unblock all apps with ${keyType}, ${duration}" : { + + }, + "Unblock Duration" : { + "comment" : "Unblock duration parameter for unblock all apps intent.", + "isCommentAutoGenerated" : true + }, "Unblock Durations" : { "comment" : "Title of a row that shows the number of unblock durations.", "isCommentAutoGenerated" : true }, + "Unblock Group" : { + "comment" : "Shortcut title for unblocking a group of apps.", + "isCommentAutoGenerated" : true + }, "Unblock ID" : { "comment" : "Parameter title for the \"Unblock ID\" field in the Dismiss Unblock Activity Intent.", "isCommentAutoGenerated" : true }, + "Unblock in Normal" : { + "comment" : "Title of the intent to open Normal to unblock.", + "isCommentAutoGenerated" : true + }, "Unblock radius: your key only works inside the areas you choose, like your office or the gym." : { "comment" : "Text displayed in a card that shows a location key with a description of the unblock radius.", "isCommentAutoGenerated" : true }, + "Unblock with an NFC tag" : { + "comment" : "A heading for the NFC tag unblocking process.", + "isCommentAutoGenerated" : true + }, "Unblocking" : { "comment" : "A section header that lists unblocking-related settings.", "isCommentAutoGenerated" : true @@ -1667,6 +1725,10 @@ "comment" : "Parameter title for selecting a group to block.", "isCommentAutoGenerated" : true }, + "Which group should Normal unblock?" : { + "comment" : "Title of the parameter for selecting a group to unblock.", + "isCommentAutoGenerated" : true + }, "Why the Apple ID matters" : { "comment" : "A section header explaining the importance of using an Apple ID for the bypass process.", "isCommentAutoGenerated" : true @@ -1679,6 +1741,10 @@ }, "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.", + "isCommentAutoGenerated" : true }, "Yes. There are two ways to close the Settings bypass. Pick the one that fits how strict you want to be." : { "comment" : "A description of the two methods of closing the Settings bypass, presented as a question.", diff --git a/Normal/Services/BlockActions.swift b/Normal/Services/BlockActions.swift index 03d8a0a..679ed6d 100644 --- a/Normal/Services/BlockActions.swift +++ b/Normal/Services/BlockActions.swift @@ -28,6 +28,26 @@ enum BlockActions { screenTimeService.block(selection: group.selection, customDomains: customDomains) } + static func unblock( + _ target: UnblockTarget, + for length: UnblockLength, + settings: Settings, + screenTimeService: any ScreenTimeProviding, + timedUnblockService: TimedUnblockService + ) throws { + switch length { + case let .timed(duration): + try timedUnblockService.start( + target, + duration: duration, + settings: settings, + screenTimeService: screenTimeService + ) + case .permanent: + screenTimeService.unblockPermanently(target, settings: settings) + } + } + static func emergencyUnblock( schedules: [BlockSchedule], screenTimeService: any ScreenTimeProviding, @@ -42,8 +62,12 @@ enum BlockActions { } static func validate(isAuthorized: Bool, hasCompletedOnboarding: Bool, keys: [Key]) throws { + try validateSetup(isAuthorized: isAuthorized, hasCompletedOnboarding: hasCompletedOnboarding) + guard Key.hasGlobalKey(in: keys) else { throw BlockIntentError.noGlobalKey } + } + + static func validateSetup(isAuthorized: Bool, hasCompletedOnboarding: Bool) throws { guard hasCompletedOnboarding else { throw BlockIntentError.setupIncomplete } guard isAuthorized else { throw BlockIntentError.screenTimeNotAuthorized } - guard Key.hasGlobalKey(in: keys) else { throw BlockIntentError.noGlobalKey } } } diff --git a/Normal/Services/BlockStatus.swift b/Normal/Services/BlockStatus.swift index 792d841..e959984 100644 --- a/Normal/Services/BlockStatus.swift +++ b/Normal/Services/BlockStatus.swift @@ -38,6 +38,20 @@ enum BlockStatus: Sendable, Equatable { } } +extension BlockStatus { + func canUnblockAll(timedUnblockActive: Bool) -> Bool { + self != .none && !timedUnblockActive + } + + func showsGroupTimedUnblock(timedUnblockActive: Bool) -> Bool { + timedUnblockActive && self != .all + } + + func canUnblockGroup(timedUnblockActive: Bool) -> Bool { + self != .none && !showsGroupTimedUnblock(timedUnblockActive: timedUnblockActive) + } +} + enum AuthorizationState: Sendable, Equatable { case authorized case notAuthorized diff --git a/Normal/Services/Keys/KeySelectLogic.swift b/Normal/Services/Keys/KeySelectLogic.swift index f2c83be..d810819 100644 --- a/Normal/Services/Keys/KeySelectLogic.swift +++ b/Normal/Services/Keys/KeySelectLogic.swift @@ -35,4 +35,18 @@ enum KeySelectLogic { return .showSheet } + + static func shortcutKeyType( + requested: KeyType?, + defaultKeyType: KeyType?, + availableKeyTypes: [KeyType] + ) -> KeyType? { + if let requested { + return requested + } + if let defaultKeyType, availableKeyTypes.contains(defaultKeyType) { + return defaultKeyType + } + return availableKeyTypes.count == 1 ? availableKeyTypes[0] : nil + } } diff --git a/Normal/Services/UnblockTarget.swift b/Normal/Services/UnblockTarget.swift index 23b6eb0..59869f3 100644 --- a/Normal/Services/UnblockTarget.swift +++ b/Normal/Services/UnblockTarget.swift @@ -19,6 +19,13 @@ enum UnblockTarget: Identifiable { return nil } + var name: String { + switch self { + case .all: String(localized: "All Apps") + case let .group(group): group.name + } + } + var selection: FamilyActivitySelection { switch self { case let .all(mainSelection): mainSelection.selection @@ -26,6 +33,15 @@ enum UnblockTarget: Identifiable { } } + func canUnblock(status: BlockStatus, timedUnblockService: TimedUnblockService) -> Bool { + switch self { + case .all: + status.canUnblockAll(timedUnblockActive: timedUnblockService.isMainUnblockActive) + case let .group(group): + status.canUnblockGroup(timedUnblockActive: timedUnblockService.isGroupUnblockActive(groupId: group.id)) + } + } + func customDomains(settings: Settings) -> [String] { guard settings.enableCustomDomains else { return [] } return switch self { @@ -63,6 +79,10 @@ extension TimedUnblockService { } extension ScreenTimeProviding { + func blockStatus(of target: UnblockTarget, settings: Settings) -> BlockStatus { + blockStatus(selection: target.selection, customDomains: target.customDomains(settings: settings)) + } + func unblockPermanently(_ target: UnblockTarget, settings: Settings) { switch target { case .all: diff --git a/Normal/Services/UnlockRequestInbox.swift b/Normal/Services/UnlockRequestInbox.swift new file mode 100644 index 0000000..f036843 --- /dev/null +++ b/Normal/Services/UnlockRequestInbox.swift @@ -0,0 +1,34 @@ +import Foundation +import Observation + +@MainActor +@Observable +final class UnlockRequestInbox { + private struct Entry: Equatable { + let request: UnblockRequest + let postedAt: Date + } + + static let lifetime: TimeInterval = 120 + + private var entry: Entry? + private let clock: () -> Date + + var pending: UnblockRequest? { + entry?.request + } + + init(clock: @escaping () -> Date = { .now }) { + self.clock = clock + } + + func post(_ request: UnblockRequest) { + entry = Entry(request: request, postedAt: clock()) + } + + func take() -> UnblockRequest? { + guard let entry else { return nil } + self.entry = nil + return clock().timeIntervalSince(entry.postedAt) <= Self.lifetime ? entry.request : nil + } +} diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift index 8c63061..a7fd54f 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/TimedUnlockSheet.swift @@ -5,24 +5,21 @@ struct TimedUnblockSheet: View { let title: String let durations: [TimedUnblockDuration] - let onTimedUnblock: (TimedUnblockDuration) throws -> Void - let onPermanentUnblock: () -> Void + let onConfirm: (UnblockLength) throws -> Void - @State private var selectedDuration: TimedUnblockDuration? + @State private var selection: UnblockLength @State private var error: Error? init( title: String, durations: [TimedUnblockDuration], initialDuration: TimedUnblockDuration?, - onTimedUnblock: @escaping (TimedUnblockDuration) throws -> Void, - onPermanentUnblock: @escaping () -> Void + onConfirm: @escaping (UnblockLength) throws -> Void ) { self.title = title self.durations = durations - self.onTimedUnblock = onTimedUnblock - self.onPermanentUnblock = onPermanentUnblock - _selectedDuration = State(initialValue: initialDuration ?? durations.first) + self.onConfirm = onConfirm + _selection = State(initialValue: (initialDuration ?? durations.first).map(UnblockLength.timed) ?? .permanent) } var body: some View { @@ -32,9 +29,9 @@ struct TimedUnblockSheet: View { ForEach(durations) { duration in ChoiceListRow( title: LocalizedStringKey(duration.label), - isSelected: selectedDuration == duration + isSelected: selection == .timed(duration) ) { - selectedDuration = duration + selection = .timed(duration) } .accessibilityIdentifier("timedUnblock.duration.\(duration.seconds)") } @@ -47,9 +44,9 @@ struct TimedUnblockSheet: View { Section { ChoiceListRow( title: "Until Manually Re-Blocked", - isSelected: selectedDuration == nil + isSelected: selection == .permanent ) { - selectedDuration = nil + selection = .permanent } .accessibilityIdentifier("timedUnblock.permanent") } footer: { @@ -78,16 +75,11 @@ struct TimedUnblockSheet: View { } private func performUnblock() { - if let duration = selectedDuration { - do { - try onTimedUnblock(duration) - dismiss() - } catch { - self.error = error - } - } else { - onPermanentUnblock() + do { + try onConfirm(selection) dismiss() + } catch { + self.error = error } } } diff --git a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift index 2a23836..d601e3d 100644 --- a/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift +++ b/Normal/Views/BlockUnblockViews/TimedUnlock/UnblockDurationSheet.swift @@ -25,18 +25,15 @@ struct UnblockDurationSheet: View { title: title, durations: settings.unblockDurations, initialDuration: settings.defaultDuration, - onTimedUnblock: { duration in - try timedUnblockService.start( + onConfirm: { length in + try BlockActions.unblock( target, - duration: duration, + for: length, settings: settings, - screenTimeService: screenTimeService + screenTimeService: screenTimeService, + timedUnblockService: timedUnblockService ) onUnblock() - }, - onPermanentUnblock: { - screenTimeService.unblockPermanently(target, settings: settings) - onUnblock() } ) } diff --git a/Normal/Views/Groups/GroupListCardView.swift b/Normal/Views/Groups/GroupListCardView.swift index bc43ce9..23e1c43 100644 --- a/Normal/Views/Groups/GroupListCardView.swift +++ b/Normal/Views/Groups/GroupListCardView.swift @@ -52,7 +52,7 @@ struct GroupListCardView: View { } private var showsTimedUnblock: Bool { - isTimedUnblockActive && blockStatus != .all + blockStatus.showsGroupTimedUnblock(timedUnblockActive: isTimedUnblockActive) } private var needsSync: Bool { diff --git a/Normal/Views/Home/MainBlockButtonView.swift b/Normal/Views/Home/MainBlockButtonView.swift index 9483384..babf996 100644 --- a/Normal/Views/Home/MainBlockButtonView.swift +++ b/Normal/Views/Home/MainBlockButtonView.swift @@ -30,7 +30,7 @@ struct MainBlockButtonView: View { } private var canShowUnblock: Bool { - blockStatus != .none && !timedUnblockService.isMainUnblockActive + blockStatus.canUnblockAll(timedUnblockActive: timedUnblockService.isMainUnblockActive) } private var hasGlobalKey: Bool { diff --git a/Normal/Views/Settings/FAQ/FAQAnswers.swift b/Normal/Views/Settings/FAQ/FAQAnswers.swift index 6b4d43e..50c4c68 100644 --- a/Normal/Views/Settings/FAQ/FAQAnswers.swift +++ b/Normal/Views/Settings/FAQ/FAQAnswers.swift @@ -167,6 +167,25 @@ enum FAQAnswer { ) static let keyTypes = AnyView(KeyTypesFAQView()) + + 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.") + 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") + NumberedRow(number: 2, text: "Set it to run without asking") + NumberedRow(number: 3, text: "Add Unblock All Apps and set Key Type to NFC Tag") + NumberedRow(number: 4, text: "Tap the tag, then hold your iPhone on it while Normal checks it") + } + VStack(alignment: .leading, spacing: DS.Spacing.xs) { + BulletRow(text: "QR Code / Barcode keys open the scanner in Normal") + BulletRow(text: "With no Key Type, Normal uses your Default Key") + } + } + .font(body) + .foregroundStyle(.secondary) + ) } private struct FAQHeadedParagraph: View { diff --git a/Normal/Views/Settings/FAQ/FAQContent.swift b/Normal/Views/Settings/FAQ/FAQContent.swift index 7e16707..4482b46 100644 --- a/Normal/Views/Settings/FAQ/FAQContent.swift +++ b/Normal/Views/Settings/FAQ/FAQContent.swift @@ -5,6 +5,7 @@ enum FAQContent { FAQSection(title: "Getting Started & Setup", entries: [ FAQEntry(question: "What can I use as a key?", answer: FAQAnswer.keyTypes), FAQEntry(question: "Are Any NFC tags not supported?", answer: FAQAnswer.nfcTypeSupport), + FAQEntry(question: "Can I unblock from Shortcuts or Siri?", answer: FAQAnswer.shortcutsUnblock), FAQEntry(question: "Can I use Normal to make my iPhone a dumbphone or semi-dumb feature phone?", answer: FAQAnswer.dumbphone), FAQEntry(question: "Why do I have to reselect apps in my schedules and groups when I update my selected apps?", answer: FAQAnswer.reselectAppLimitation), FAQEntry(question: "Can I prevent disabling Normal via Settings? I want to make it impossible to access blocked apps.", answer: FAQAnswer.settingsBypass), diff --git a/NormalTests/Models/SettingsUnblockDurationTests.swift b/NormalTests/Models/SettingsUnblockDurationTests.swift index 6d21352..55547be 100644 --- a/NormalTests/Models/SettingsUnblockDurationTests.swift +++ b/NormalTests/Models/SettingsUnblockDurationTests.swift @@ -136,22 +136,28 @@ struct SettingsUnblockDurationTests { @Test func fixedRequestUsesItsDuration() { let s = Settings() s.defaultDuration = .thirtyMinutes - #expect(s.duration(for: .fixed(.fourHours)) == .fourHours) + #expect(s.unblockLength(for: .fixed(.fourHours)) == .timed(.fourHours)) } @Test func defaultRequestUsesDefaultDuration() { let s = Settings() s.defaultDuration = .thirtyMinutes - #expect(s.duration(for: .useDefault) == .thirtyMinutes) + #expect(s.unblockLength(for: .useDefault) == .timed(.thirtyMinutes)) } @Test func defaultRequestWithoutDefaultHasNoDuration() { - #expect(Settings().duration(for: .useDefault) == nil) + #expect(Settings().unblockLength(for: .useDefault) == nil) } @Test func askRequestHasNoDuration() { let s = Settings() s.defaultDuration = .thirtyMinutes - #expect(s.duration(for: .ask) == nil) + #expect(s.unblockLength(for: .ask) == nil) + } + + @Test func permanentRequestIsPermanent() { + let s = Settings() + s.defaultDuration = .thirtyMinutes + #expect(s.unblockLength(for: .permanent) == .permanent) } } diff --git a/NormalTests/Models/TimedUnblockDurationTests.swift b/NormalTests/Models/TimedUnblockDurationTests.swift index bab627b..35fb735 100644 --- a/NormalTests/Models/TimedUnblockDurationTests.swift +++ b/NormalTests/Models/TimedUnblockDurationTests.swift @@ -76,6 +76,10 @@ struct UnlockDurationRequestTests { #expect(UnlockDurationRequest(queryValue: "ask") == .ask) } + @Test func permanentValueIsPermanent() { + #expect(UnlockDurationRequest(queryValue: "permanent") == .permanent) + } + @Test func validSecondsAreFixedEvenIfNotAPreset() throws { let custom = try #require(TimedUnblockDuration(validating: 5700)) #expect(UnlockDurationRequest(queryValue: "5700") == .fixed(custom)) @@ -88,7 +92,7 @@ struct UnlockDurationRequestTests { @Test func queryValueRoundTrips() throws { let custom = try #require(TimedUnblockDuration(validating: 5700)) - for request in [UnlockDurationRequest.useDefault, .ask, .fixed(custom)] { + for request in [UnlockDurationRequest.useDefault, .ask, .fixed(custom), .permanent] { #expect(UnlockDurationRequest(queryValue: request.queryValue) == request) } } diff --git a/NormalTests/Services/AppUnblockIntentPerformerTests.swift b/NormalTests/Services/AppUnblockIntentPerformerTests.swift new file mode 100644 index 0000000..4b2c8b5 --- /dev/null +++ b/NormalTests/Services/AppUnblockIntentPerformerTests.swift @@ -0,0 +1,196 @@ +import FamilyControls +import Foundation +@testable import Normal +import SwiftData +import Testing + +@MainActor +struct AppUnblockIntentPerformerTests { + private let container: ModelContainer + private let screenTime = FakeScreenTimeService() + private let activity = FakeDeviceActivityCenter() + private let store = FakeSharedStore() + private let inbox = UnlockRequestInbox() + private let clock = TestClock() + private let timedUnblock: TimedUnblockService + private let performer: AppUnblockIntentPerformer + + private final class TestClock { + var now = Date() + } + + init() throws { + container = try InMemoryModelContainer.make() + let clock = clock + timedUnblock = TimedUnblockService( + activityCenter: activity, + sharedStore: store, + clock: { clock.now }, + onExpiration: {} + ) + performer = AppUnblockIntentPerformer( + container: container, + screenTimeService: screenTime, + timedUnblockService: timedUnblock, + unlockInbox: inbox + ) + } + + private var context: ModelContext { + container.mainContext + } + + @discardableResult + private func seed(onboarded: Bool = true, mainDomains: [String] = ["example.com"]) throws -> Settings { + let settings = Settings() + settings.hasCompletedOnboarding = onboarded + settings.enableCustomDomains = true + context.insert(settings) + context.insert(SelectedApps(selection: FamilyActivitySelection(), customDomains: mainDomains)) + context.insert(Key(name: "global", type: .qr, rawValue: "g")) + try context.save() + return settings + } + + private func seedGroup() throws -> AppGroup { + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + context.insert(group) + try context.save() + return group + } + + private func locationKey(groupID: UUID? = nil) -> Key { + Key(name: "Place", latitude: 37.3349, longitude: -122.0090, radiusMeters: 200, radiusKind: .unblock, groupID: groupID) + } + + private func request(group: UUID? = nil, key: KeyType? = .nfc) -> UnblockRequest { + UnblockRequest(groupID: group, duration: .fixed(.oneHour), keyType: key) + } + + @Test func blockedAppsContinueInApp() throws { + try seed() + screenTime.stubBlockStatus = .all + + #expect(try performer.unblock(request()) == .continueInApp) + #expect(!timedUnblock.isMainUnblockActive) + } + + @Test func nothingBlockedIsAlreadyUnblocked() throws { + try seed() + screenTime.stubBlockStatus = .none + + #expect(try performer.unblock(request()) == .alreadyUnblocked(name: "All Apps")) + } + + @Test func activeMainUnblockReportsTheRunningTimer() throws { + try seed() + try timedUnblock.startMain(duration: .fifteenMinutes, selection: FamilyActivitySelection(), screenTimeService: screenTime) + screenTime.stubBlockStatus = .all + + #expect(try performer.unblock(request()) == .timedUnblockRunning(name: "All Apps")) + } + + @Test func activeGroupUnblockReportsTheRunningTimer() throws { + try seed() + let group = try seedGroup() + try timedUnblock.startGroup( + duration: .fifteenMinutes, + groupId: group.id, + selection: group.selection, + screenTimeService: screenTime + ) + screenTime.stubBlockStatus = .some + + #expect(try performer.unblock(request(group: group.id)) == .timedUnblockRunning(name: "Social")) + } + + @Test func expiredTimedUnblockIsNotMistakenForActive() 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) + } + + @Test func doesNotRequireAGlobalKey() throws { + let settings = Settings() + settings.hasCompletedOnboarding = true + settings.enableCustomDomains = true + context.insert(settings) + context.insert(SelectedApps(selection: FamilyActivitySelection(), customDomains: ["example.com"])) + try context.save() + screenTime.stubBlockStatus = .all + + #expect(try performer.unblock(request()) == .continueInApp) + } + + @Test func requiresCompletedSetup() throws { + try seed(onboarded: false) + + #expect(throws: BlockIntentError.setupIncomplete) { + try performer.unblock(request()) + } + } + + @Test func requiresScreenTimeAuthorization() throws { + try seed() + screenTime.stubIsAuthorizedNow = false + + #expect(throws: BlockIntentError.screenTimeNotAuthorized) { + try performer.unblock(request()) + } + } + + @Test func requiresSomethingSelected() throws { + try seed(mainDomains: []) + + #expect(throws: BlockIntentError.noAppsSelected) { + try performer.unblock(request()) + } + } + + @Test func throwsForDeletedGroup() throws { + try seed() + + #expect(throws: BlockIntentError.groupNotFound) { + try performer.unblock(request(group: UUID())) + } + } + + @Test func continueInAppPostsTheRequest() throws { + try seed() + let groupID = UUID() + + performer.continueInApp(request(group: groupID, key: .nfc)) + + #expect(inbox.pending == UnblockRequest(groupID: groupID, duration: .fixed(.oneHour), keyType: .nfc)) + } + + @Test func continueInAppUsesTheDefaultKey() throws { + let settings = try seed() + context.insert(locationKey()) + settings.defaultKeyType = .location + + performer.continueInApp(request(key: nil)) + + #expect(inbox.pending?.keyType == .location) + } + + @Test func continueInAppUsesTheOnlyKeyType() throws { + try seed() + + performer.continueInApp(request(key: nil)) + + #expect(inbox.pending?.keyType == .qr) + } + + @Test func continueInAppIgnoresKeysFromOtherGroups() throws { + try seed() + context.insert(locationKey(groupID: UUID())) + + performer.continueInApp(request(key: nil)) + + #expect(inbox.pending?.keyType == .qr) + } +} diff --git a/NormalTests/Services/BlockActionsTests.swift b/NormalTests/Services/BlockActionsTests.swift index 471e80e..45dcbfb 100644 --- a/NormalTests/Services/BlockActionsTests.swift +++ b/NormalTests/Services/BlockActionsTests.swift @@ -116,6 +116,38 @@ struct BlockActionsTests { #expect(stopped.contains(SharedConstants.groupTimedUnblockActivityName(for: group.id))) } + @Test func timedUnblockStartsATimer() throws { + let timedUnblock = makeTimedUnblock() + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + + try BlockActions.unblock( + .group(group), + for: .timed(.oneHour), + settings: makeSettings(), + screenTimeService: screenTime, + timedUnblockService: timedUnblock + ) + + #expect(timedUnblock.isGroupUnblockActive(groupId: group.id)) + #expect(!screenTime.unblockCalled) + } + + @Test func permanentUnblockLiftsTheShieldWithoutATimer() throws { + let timedUnblock = makeTimedUnblock() + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + + try BlockActions.unblock( + .group(group), + for: .permanent, + settings: makeSettings(), + screenTimeService: screenTime, + timedUnblockService: timedUnblock + ) + + #expect(screenTime.unblockCalled) + #expect(!timedUnblock.isGroupUnblockActive(groupId: group.id)) + } + private func timedUnblockRecord(id: String, activityName: String, endingIn interval: TimeInterval) throws -> TimedUnblockDTO { try TimedUnblockDTO( id: id, diff --git a/NormalTests/Services/BlockStatusTests.swift b/NormalTests/Services/BlockStatusTests.swift index 4744641..1ab1447 100644 --- a/NormalTests/Services/BlockStatusTests.swift +++ b/NormalTests/Services/BlockStatusTests.swift @@ -20,6 +20,27 @@ struct BlockStatusTests { #expect(!BlockStatus.none.icon.isEmpty) } + @Test func unblockAllNeedsABlockAndNoActiveTimer() { + #expect(BlockStatus.all.canUnblockAll(timedUnblockActive: false)) + #expect(BlockStatus.some.canUnblockAll(timedUnblockActive: false)) + #expect(!BlockStatus.none.canUnblockAll(timedUnblockActive: false)) + #expect(!BlockStatus.all.canUnblockAll(timedUnblockActive: true)) + } + + @Test func groupTimerShowsUnlessFullyBlockedElsewhere() { + #expect(BlockStatus.some.showsGroupTimedUnblock(timedUnblockActive: true)) + #expect(BlockStatus.none.showsGroupTimedUnblock(timedUnblockActive: true)) + #expect(!BlockStatus.all.showsGroupTimedUnblock(timedUnblockActive: true)) + #expect(!BlockStatus.some.showsGroupTimedUnblock(timedUnblockActive: false)) + } + + @Test func groupCanBeUnblockedWhenBlockedWithoutATimer() { + #expect(BlockStatus.some.canUnblockGroup(timedUnblockActive: false)) + #expect(BlockStatus.all.canUnblockGroup(timedUnblockActive: true)) + #expect(!BlockStatus.some.canUnblockGroup(timedUnblockActive: true)) + #expect(!BlockStatus.none.canUnblockGroup(timedUnblockActive: false)) + } + @Test func authorizationStateEquatable() { #expect(AuthorizationState.authorized == .authorized) #expect(AuthorizationState.notAuthorized == .notAuthorized) diff --git a/NormalTests/Services/KeySelectLogicTests.swift b/NormalTests/Services/KeySelectLogicTests.swift index 3c25447..aef5995 100644 --- a/NormalTests/Services/KeySelectLogicTests.swift +++ b/NormalTests/Services/KeySelectLogicTests.swift @@ -96,4 +96,29 @@ struct KeySelectLogicTests { ) #expect(result == .autoSelect(.nfc)) } + + @Test func shortcutUsesTheRequestedKey() { + let keyType = KeySelectLogic.shortcutKeyType(requested: .qr, defaultKeyType: .nfc, availableKeyTypes: [.nfc, .qr]) + #expect(keyType == .qr) + } + + @Test func shortcutFallsBackToTheDefaultKey() { + let keyType = KeySelectLogic.shortcutKeyType(requested: nil, defaultKeyType: .nfc, availableKeyTypes: [.nfc, .qr]) + #expect(keyType == .nfc) + } + + @Test func shortcutIgnoresAnUnavailableDefault() { + let keyType = KeySelectLogic.shortcutKeyType(requested: nil, defaultKeyType: .nfc, availableKeyTypes: [.location]) + #expect(keyType == .location) + } + + @Test func shortcutUsesTheOnlyKeyType() { + let keyType = KeySelectLogic.shortcutKeyType(requested: nil, defaultKeyType: nil, availableKeyTypes: [.qr]) + #expect(keyType == .qr) + } + + @Test func shortcutLeavesTheChoiceWithSeveralKeyTypes() { + let keyType = KeySelectLogic.shortcutKeyType(requested: nil, defaultKeyType: nil, availableKeyTypes: [.nfc, .qr]) + #expect(keyType == nil) + } } diff --git a/NormalTests/Services/NavigationCoordinatorWidgetTests.swift b/NormalTests/Services/NavigationCoordinatorWidgetTests.swift index 8ee71c5..b72af7e 100644 --- a/NormalTests/Services/NavigationCoordinatorWidgetTests.swift +++ b/NormalTests/Services/NavigationCoordinatorWidgetTests.swift @@ -41,6 +41,14 @@ struct NavigationCoordinatorWidgetTests { #expect(c.pendingAction?.action == .unblock(UnblockRequest(groupID: id, duration: .ask, keyType: nil))) } + @Test func handleParsesUntilManuallyReblocked() { + let c = NavigationCoordinator() + let id = UUID() + c.handle(url: unlockURL(groupID: id, duration: .permanent)) + + #expect(c.pendingAction?.action == .unblock(UnblockRequest(groupID: id, duration: .permanent, keyType: nil))) + } + @Test(arguments: ["999", "60", "90000", "abc"]) func handleFallsBackToAskingForInvalidDuration(_ value: String) throws { let c = NavigationCoordinator() diff --git a/NormalTests/Services/UnblockTargetTests.swift b/NormalTests/Services/UnblockTargetTests.swift index 9a19a7b..5045921 100644 --- a/NormalTests/Services/UnblockTargetTests.swift +++ b/NormalTests/Services/UnblockTargetTests.swift @@ -67,4 +67,21 @@ struct UnblockTargetTests { #expect(screenTime.unblockCustomDomains == ["b.com"]) #expect(!screenTime.unblockAllCalled) } + + @Test func blockedGroupWithoutATimerCanBeUnblocked() { + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + #expect(UnblockTarget.group(group).canUnblock(status: .some, timedUnblockService: service)) + } + + @Test func groupWithATimerCannotBeUnblockedAgain() throws { + let group = AppGroup(name: "Social", selection: FamilyActivitySelection()) + try service.start(.group(group), duration: .oneHour, settings: settings(customDomains: false), screenTimeService: screenTime) + #expect(!UnblockTarget.group(group).canUnblock(status: .some, timedUnblockService: service)) + } + + @Test func allAppsWithATimerCannotBeUnblockedAgain() throws { + let main = SelectedApps(selection: FamilyActivitySelection()) + try service.start(.all(main), duration: .oneHour, settings: settings(customDomains: false), screenTimeService: screenTime) + #expect(!UnblockTarget.all(main).canUnblock(status: .all, timedUnblockService: service)) + } } diff --git a/NormalTests/Services/UnlockRequestInboxTests.swift b/NormalTests/Services/UnlockRequestInboxTests.swift new file mode 100644 index 0000000..fecb818 --- /dev/null +++ b/NormalTests/Services/UnlockRequestInboxTests.swift @@ -0,0 +1,53 @@ +import Foundation +@testable import Normal +import Testing + +@MainActor +struct UnlockRequestInboxTests { + private final class TestClock { + var now = Date() + } + + private let request = UnblockRequest(groupID: UUID(), duration: .fixed(.oneHour), keyType: .nfc) + + @Test func takeReturnsThePostedRequestOnce() { + let inbox = UnlockRequestInbox() + + inbox.post(request) + + #expect(inbox.take() == request) + #expect(inbox.pending == nil) + #expect(inbox.take() == nil) + } + + @Test func newerRequestReplacesOlder() { + let inbox = UnlockRequestInbox() + let newer = UnblockRequest(groupID: nil, duration: .useDefault, keyType: nil) + + inbox.post(request) + inbox.post(newer) + + #expect(inbox.take() == newer) + } + + @Test func requestIsKeptForItsLifetime() { + let clock = TestClock() + let inbox = UnlockRequestInbox(clock: { clock.now }) + + inbox.post(request) + clock.now = clock.now.addingTimeInterval(UnlockRequestInbox.lifetime) + + #expect(inbox.take() == request) + } + + @Test func staleRequestIsDropped() { + let clock = TestClock() + let inbox = UnlockRequestInbox(clock: { clock.now }) + + inbox.post(request) + clock.now = clock.now.addingTimeInterval(UnlockRequestInbox.lifetime + 1) + + #expect(inbox.take() == nil) + #expect(inbox.pending == nil) + } +} diff --git a/NormalTests/Shared/UnblockDurationEntityTests.swift b/NormalTests/Shared/UnblockDurationEntityTests.swift new file mode 100644 index 0000000..524b44b --- /dev/null +++ b/NormalTests/Shared/UnblockDurationEntityTests.swift @@ -0,0 +1,22 @@ +@testable import Normal +import Testing + +struct UnblockDurationEntityTests { + @Test func savedWidgetIDsKeepTheirMeaning() { + #expect(UnblockDurationEntity(id: -1).request == .useDefault) + #expect(UnblockDurationEntity(id: 0).request == .ask) + #expect(UnblockDurationEntity(id: 3600).request == .fixed(.oneHour)) + } + + @Test func everyRequestRoundTripsThroughItsID() throws { + let custom = try #require(TimedUnblockDuration(validating: 5700)) + for request in [UnlockDurationRequest.useDefault, .ask, .fixed(custom), .permanent] { + #expect(UnblockDurationEntity(request).request == request) + } + } + + @Test(arguments: [-3, 60, 999, 90000]) + func invalidIDsDoNotResolve(_ id: Int) { + #expect(UnblockDurationEntity.request(forID: id) == nil) + } +} diff --git a/NormalWidget/SelectGroupIntent.swift b/NormalWidget/SelectGroupIntent.swift index 86e3fe6..6840b53 100644 --- a/NormalWidget/SelectGroupIntent.swift +++ b/NormalWidget/SelectGroupIntent.swift @@ -33,84 +33,3 @@ struct SelectGroupIntent: WidgetConfigurationIntent { .map(UnlockDurationRequest.fixed) ?? .useDefault } } - -struct UnblockDurationEntity: AppEntity { - static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Unblock Duration") - static let defaultQuery = UnblockDurationEntityQuery() - - static let appDefaultID = -1 - static let askEachTimeID = 0 - - /// Seconds, or one of the special ids above. - let id: Int - - static let appDefault = UnblockDurationEntity(id: appDefaultID) - static let askEachTime = UnblockDurationEntity(id: askEachTimeID) - - init(id: Int) { - self.id = id - } - - init(_ duration: TimedUnblockDuration) { - id = duration.seconds - } - - var request: UnlockDurationRequest { - switch id { - case Self.appDefaultID: .useDefault - case Self.askEachTimeID: .ask - default: TimedUnblockDuration(validating: id).map(UnlockDurationRequest.fixed) ?? .ask - } - } - - var displayRepresentation: DisplayRepresentation { - switch id { - case Self.appDefaultID: DisplayRepresentation(title: "App Default") - case Self.askEachTimeID: DisplayRepresentation(title: "Ask Each Time") - default: DisplayRepresentation( - title: "\(TimedUnblockDuration(validating: id)?.label ?? String(id))" - ) - } - } -} - -struct UnblockDurationEntityQuery: EntityQuery { - private let store = WidgetSharedStore() - - /// Resolves any valid id, not only ones still in the list, so a configured widget never silently resets. - func entities(for identifiers: [Int]) async throws -> [UnblockDurationEntity] { - identifiers.compactMap { id in - let isSpecial = id == UnblockDurationEntity.appDefaultID || id == UnblockDurationEntity.askEachTimeID - return isSpecial || TimedUnblockDuration.isValid(id) ? UnblockDurationEntity(id: id) : nil - } - } - - func suggestedEntities() async throws -> [UnblockDurationEntity] { - [.appDefault, .askEachTime] + store.loadUnblockDurations().map(UnblockDurationEntity.init) - } -} - -struct KeyTypeEntity: AppEntity { - static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Key Type") - static let defaultQuery = KeyTypeEntityQuery() - - let id: String - - var displayRepresentation: DisplayRepresentation { - DisplayRepresentation(title: "\(KeyType(rawValue: id)?.label ?? id)") - } -} - -struct KeyTypeEntityQuery: EntityQuery { - private let store = WidgetSharedStore() - - func entities(for identifiers: [String]) async throws -> [KeyTypeEntity] { - store.loadKeyTypes() - .filter { identifiers.contains($0) } - .map { KeyTypeEntity(id: $0) } - } - - func suggestedEntities() async throws -> [KeyTypeEntity] { - store.loadKeyTypes().map { KeyTypeEntity(id: $0) } - } -} diff --git a/Shared/BlockIntents.swift b/Shared/BlockIntents.swift index c9239b2..02704ad 100644 --- a/Shared/BlockIntents.swift +++ b/Shared/BlockIntents.swift @@ -23,7 +23,7 @@ enum BlockIntentError: Error, Equatable, CustomLocalizedStringResourceConvertibl case .setupIncomplete: "Finish setting up Normal first." case .screenTimeNotAuthorized: "Normal needs Screen Time access. Open Normal to allow it." case .noGlobalKey: "Add a key in Normal before blocking apps." - case .noAppsSelected: "Select apps to block in Normal first." + case .noAppsSelected: "Select apps in Normal first." case .groupNotFound: "That group no longer exists." } } diff --git a/Shared/KeyTypeEntity.swift b/Shared/KeyTypeEntity.swift new file mode 100644 index 0000000..dc5eedb --- /dev/null +++ b/Shared/KeyTypeEntity.swift @@ -0,0 +1,33 @@ +import AppIntents + +struct KeyTypeEntity: AppEntity { + static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Key Type") + static let defaultQuery = KeyTypeEntityQuery() + + let id: String + + var keyType: KeyType? { + KeyType(rawValue: id) + } + + var displayRepresentation: DisplayRepresentation { + DisplayRepresentation( + title: "\(keyType?.label ?? id)", + image: keyType.map { DisplayRepresentation.Image(systemName: $0.icon) } + ) + } +} + +struct KeyTypeEntityQuery: EntityQuery { + private let store = WidgetSharedStore() + + func entities(for identifiers: [String]) async throws -> [KeyTypeEntity] { + store.loadKeyTypes() + .filter { identifiers.contains($0) } + .map { KeyTypeEntity(id: $0) } + } + + func suggestedEntities() async throws -> [KeyTypeEntity] { + store.loadKeyTypes().map { KeyTypeEntity(id: $0) } + } +} diff --git a/Shared/TimedUnblockDuration.swift b/Shared/TimedUnblockDuration.swift index 3226e7f..5068901 100644 --- a/Shared/TimedUnblockDuration.swift +++ b/Shared/TimedUnblockDuration.swift @@ -66,8 +66,10 @@ nonisolated enum UnlockDurationRequest: Equatable, Sendable { case useDefault case ask case fixed(TimedUnblockDuration) + case permanent static let askQueryValue = "ask" + static let permanentQueryValue = "permanent" /// `nil` means the query item is omitted. var queryValue: String? { @@ -75,6 +77,7 @@ nonisolated enum UnlockDurationRequest: Equatable, Sendable { case .useDefault: nil case .ask: Self.askQueryValue case let .fixed(duration): String(duration.seconds) + case .permanent: Self.permanentQueryValue } } @@ -83,6 +86,10 @@ nonisolated enum UnlockDurationRequest: Equatable, Sendable { self = .useDefault return } + guard queryValue != Self.permanentQueryValue else { + self = .permanent + return + } if let seconds = Int(queryValue), String(seconds) == queryValue, let duration = TimedUnblockDuration(validating: seconds) { diff --git a/Shared/UnblockDurationEntity.swift b/Shared/UnblockDurationEntity.swift new file mode 100644 index 0000000..65ea5c8 --- /dev/null +++ b/Shared/UnblockDurationEntity.swift @@ -0,0 +1,64 @@ +import AppIntents + +struct UnblockDurationEntity: AppEntity { + static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "Unblock Duration") + static let defaultQuery = UnblockDurationEntityQuery() + + static let appDefaultID = -1 + static let askEachTimeID = 0 + static let permanentID = -2 + + /// Seconds, or one of the special ids above. + let id: Int + + init(id: Int) { + self.id = id + } + + init(_ request: UnlockDurationRequest) { + id = switch request { + case .useDefault: Self.appDefaultID + case .ask: Self.askEachTimeID + case .permanent: Self.permanentID + case let .fixed(duration): duration.seconds + } + } + + static func request(forID id: Int) -> UnlockDurationRequest? { + switch id { + case appDefaultID: .useDefault + case askEachTimeID: .ask + case permanentID: .permanent + default: TimedUnblockDuration(validating: id).map(UnlockDurationRequest.fixed) + } + } + + var request: UnlockDurationRequest { + Self.request(forID: id) ?? .ask + } + + var displayRepresentation: DisplayRepresentation { + switch request { + case .useDefault: DisplayRepresentation(title: "Default Duration") + case .ask: DisplayRepresentation(title: "Choose in Normal") + case .permanent: DisplayRepresentation(title: "Until Manually Re-Blocked") + case let .fixed(duration): DisplayRepresentation(title: "\(duration.label)") + } + } +} + +struct UnblockDurationEntityQuery: EntityQuery { + private let store = WidgetSharedStore() + + /// Resolves any valid id, not only ones still in the list, so a configured widget never silently resets. + func entities(for identifiers: [Int]) async throws -> [UnblockDurationEntity] { + identifiers + .filter { UnblockDurationEntity.request(forID: $0) != nil } + .map(UnblockDurationEntity.init(id:)) + } + + func suggestedEntities() async throws -> [UnblockDurationEntity] { + let timed = store.loadUnblockDurations().map(UnlockDurationRequest.fixed) + return ([.useDefault, .ask] + timed + [.permanent]).map(UnblockDurationEntity.init) + } +}