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 @@ -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 */;
Expand Down
3 changes: 3 additions & 0 deletions Normal/App/AppContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions Normal/App/AppServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ final class AppServices {
let appReview: AppReviewService
let emergencyUnblock: EmergencyUnblockService
let usageLimit: UsageLimitService
let unlockInbox = UnlockRequestInbox()

init() {
if UITestSupport.isActive {
Expand Down
6 changes: 6 additions & 0 deletions Normal/App/NormalApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
74 changes: 19 additions & 55 deletions Normal/Intents/AppBlockIntentPerformer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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
}

Expand All @@ -29,78 +29,42 @@ 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<SelectedApps>()).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)
}

func blockGroup(id: UUID) throws -> BlockOutcome {
logger.info("Block intent: group")
let settings = try validatedSettings()
let descriptor = FetchDescriptor<AppGroup>(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<Settings>()).first
try BlockActions.validate(
isAuthorized: screenTimeService.isAuthorizedNow,
hasCompletedOnboarding: settings?.hasCompletedOnboarding == true,
keys: context.fetch(FetchDescriptor<Key>())
)
guard let settings else { throw BlockIntentError.setupIncomplete }
return settings
}

private func syncExternalSurfaces(settings: Settings) {
guard syncsExternalSurfaces else { return }
let groups = (try? context.fetch(FetchDescriptor<AppGroup>(sortBy: [SortDescriptor(\.sortIndex)]))) ?? []
let keys = (try? context.fetch(FetchDescriptor<Key>())) ?? []
WidgetSync.sync(groups: groups, keys: keys, settings: settings, screenTimeService: screenTimeService)
LiveActivityManager.reconcile(
timedUnblockService: timedUnblockService,
groups: groups,
isEnabled: settings.showTimedUnblockLiveActivity
)
intents.syncExternalSurfaces(settings: settings)
}
}
61 changes: 61 additions & 0 deletions Normal/Intents/AppUnblockIntentPerformer.swift
Original file line number Diff line number Diff line change
@@ -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))
)
}
}
73 changes: 73 additions & 0 deletions Normal/Intents/IntentContext.swift
Original file line number Diff line number Diff line change
@@ -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<Settings>()).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<Settings>()).first
}

func keys() throws -> [Key] {
try context.fetch(FetchDescriptor<Key>())
}

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<SelectedApps>()).first,
!mainSelection.selection.isEmpty
|| (settings.enableCustomDomains && !mainSelection.customDomains.isEmpty)
else { throw BlockIntentError.noAppsSelected }
return mainSelection
}

func group(id: UUID) throws -> AppGroup {
let descriptor = FetchDescriptor<AppGroup>(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<AppGroup>(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
)
}
}
20 changes: 20 additions & 0 deletions Normal/Intents/NormalShortcuts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading