This repository was archived by the owner on Feb 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathAppDelegate.swift
741 lines (618 loc) · 31.3 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//
// AppDelegate.swift
//
// Copyright © 2020 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Bookmarks
import BrowserServicesKit
import Cocoa
import Combine
import Common
import Configuration
import CoreData
import Crashes
import DDGSync
import History
import MetricKit
import Networking
import Persistence
import PixelKit
import ServiceManagement
import SyncDataProviders
import UserNotifications
import Lottie
import NetworkProtection
import Subscription
import NetworkProtectionIPC
import DataBrokerProtection
import RemoteMessaging
import os.log
final class AppDelegate: NSObject, NSApplicationDelegate {
#if DEBUG
let disableCVDisplayLinkLogs: Void = {
// Disable CVDisplayLink logs
CFPreferencesSetValue("cv_note" as CFString,
0 as CFPropertyList,
"com.apple.corevideo" as CFString,
kCFPreferencesCurrentUser,
kCFPreferencesAnyHost)
CFPreferencesSynchronize("com.apple.corevideo" as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
}()
#endif
let urlEventHandler = URLEventHandler()
#if CI
private let keyStore = (NSClassFromString("MockEncryptionKeyStore") as? EncryptionKeyStoring.Type)!.init()
#else
private let keyStore = EncryptionKeyStore()
#endif
let fileStore: FileStore
#if APPSTORE
private let crashCollection = CrashCollection(platform: .macOSAppStore)
#else
private let crashReporter = CrashReporter()
#endif
let pinnedTabsManager = PinnedTabsManager()
private(set) var stateRestorationManager: AppStateRestorationManager!
private var grammarFeaturesManager = GrammarFeaturesManager()
let internalUserDecider: InternalUserDecider
let featureFlagger: FeatureFlagger
private var appIconChanger: AppIconChanger!
private var autoClearHandler: AutoClearHandler!
private(set) var autofillPixelReporter: AutofillPixelReporter?
private(set) var syncDataProviders: SyncDataProviders!
private(set) var syncService: DDGSyncing?
private var isSyncInProgressCancellable: AnyCancellable?
private var syncFeatureFlagsCancellable: AnyCancellable?
private var screenLockedCancellable: AnyCancellable?
private var emailCancellables = Set<AnyCancellable>()
let bookmarksManager = LocalBookmarkManager.shared
var privacyDashboardWindow: NSWindow?
let activeRemoteMessageModel: ActiveRemoteMessageModel
let homePageSettingsModel = HomePage.Models.SettingsModel()
let remoteMessagingClient: RemoteMessagingClient!
public let subscriptionManager: SubscriptionManager
public let subscriptionUIHandler: SubscriptionUIHandling
public let vpnSettings = VPNSettings(defaults: .netP)
// MARK: - VPN
private var networkProtectionSubscriptionEventHandler: NetworkProtectionSubscriptionEventHandler?
private var vpnXPCClient: VPNControllerXPCClient {
VPNControllerXPCClient.shared
}
// MARK: - DBP
private lazy var dataBrokerProtectionSubscriptionEventHandler: DataBrokerProtectionSubscriptionEventHandler = {
let authManager = DataBrokerAuthenticationManagerBuilder.buildAuthenticationManager(subscriptionManager: subscriptionManager)
return DataBrokerProtectionSubscriptionEventHandler(featureDisabler: DataBrokerProtectionFeatureDisabler(),
authenticationManager: authManager,
pixelHandler: DataBrokerProtectionPixelsHandler())
}()
private lazy var vpnRedditSessionWorkaround: VPNRedditSessionWorkaround = {
let ipcClient = VPNControllerXPCClient.shared
let statusReporter = DefaultNetworkProtectionStatusReporter(
statusObserver: ipcClient.connectionStatusObserver,
serverInfoObserver: ipcClient.serverInfoObserver,
connectionErrorObserver: ipcClient.connectionErrorObserver,
connectivityIssuesObserver: ConnectivityIssueObserverThroughDistributedNotifications(),
controllerErrorMessageObserver: ControllerErrorMesssageObserverThroughDistributedNotifications(),
dataVolumeObserver: ipcClient.dataVolumeObserver,
knownFailureObserver: KnownFailureObserverThroughDistributedNotifications()
)
return VPNRedditSessionWorkaround(
accountManager: subscriptionManager.accountManager,
ipcClient: ipcClient,
statusReporter: statusReporter
)
}()
private var didFinishLaunching = false
#if SPARKLE
var updateController: UpdateController!
#endif
@UserDefaultsWrapper(key: .firstLaunchDate, defaultValue: Date.monthAgo)
static var firstLaunchDate: Date
@UserDefaultsWrapper
private var didCrashDuringCrashHandlersSetUp: Bool
static var isNewUser: Bool {
return firstLaunchDate >= Date.weekAgo
}
@MainActor
override init() {
// will not add crash handlers and will fire pixel on applicationDidFinishLaunching if didCrashDuringCrashHandlersSetUp == true
let didCrashDuringCrashHandlersSetUp = UserDefaultsWrapper(key: .didCrashDuringCrashHandlersSetUp, defaultValue: false)
_didCrashDuringCrashHandlersSetUp = didCrashDuringCrashHandlersSetUp
if case .normal = NSApplication.runType,
!didCrashDuringCrashHandlersSetUp.wrappedValue {
didCrashDuringCrashHandlersSetUp.wrappedValue = true
CrashLogMessageExtractor.setUp(swapCxaThrow: false)
didCrashDuringCrashHandlersSetUp.wrappedValue = false
}
do {
let encryptionKey = NSApplication.runType.requiresEnvironment ? try keyStore.readKey() : nil
fileStore = EncryptedFileStore(encryptionKey: encryptionKey)
} catch {
Logger.general.error("App Encryption Key could not be read: \(error.localizedDescription)")
fileStore = EncryptedFileStore()
}
let internalUserDeciderStore = InternalUserDeciderStore(fileStore: fileStore)
internalUserDecider = DefaultInternalUserDecider(store: internalUserDeciderStore)
if NSApplication.runType.requiresEnvironment {
Self.configurePixelKit()
Database.shared.loadStore { _, error in
guard let error = error else { return }
switch error {
case CoreDataDatabase.Error.containerLocationCouldNotBePrepared(let underlyingError):
PixelKit.fire(DebugEvent(GeneralPixel.dbContainerInitializationError(error: underlyingError)))
default:
PixelKit.fire(DebugEvent(GeneralPixel.dbInitializationError(error: error)))
}
// Give Pixel a chance to be sent, but not too long
Thread.sleep(forTimeInterval: 1)
fatalError("Could not load DB: \(error.localizedDescription)")
}
do {
let formFactorFavMigration = BookmarkFormFactorFavoritesMigration()
let favoritesOrder = try formFactorFavMigration.getFavoritesOrderFromPreV4Model(dbContainerLocation: BookmarkDatabase.defaultDBLocation,
dbFileURL: BookmarkDatabase.defaultDBFileURL)
BookmarkDatabase.shared.preFormFactorSpecificFavoritesFolderOrder = favoritesOrder
} catch {
PixelKit.fire(DebugEvent(GeneralPixel.bookmarksCouldNotLoadDatabase(error: error)))
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create Bookmarks database stack: \(error.localizedDescription)")
}
BookmarkDatabase.shared.db.loadStore { context, error in
guard let context = context else {
PixelKit.fire(DebugEvent(GeneralPixel.bookmarksCouldNotLoadDatabase(error: error)))
Thread.sleep(forTimeInterval: 1)
fatalError("Could not create Bookmarks database stack: \(error?.localizedDescription ?? "err")")
}
let legacyDB = Database.shared.makeContext(concurrencyType: .privateQueueConcurrencyType)
legacyDB.performAndWait {
LegacyBookmarksStoreMigration.setupAndMigrate(from: legacyDB,
to: context)
}
}
}
#if DEBUG
AppPrivacyFeatures.shared = NSApplication.runType.requiresEnvironment
// runtime mock-replacement for Unit Tests, to be redone when we‘ll be doing Dependency Injection
? AppPrivacyFeatures(contentBlocking: AppContentBlocking(internalUserDecider: internalUserDecider), database: Database.shared)
: AppPrivacyFeatures(contentBlocking: ContentBlockingMock(), httpsUpgradeStore: HTTPSUpgradeStoreMock())
#else
AppPrivacyFeatures.shared = AppPrivacyFeatures(contentBlocking: AppContentBlocking(internalUserDecider: internalUserDecider), database: Database.shared)
#endif
if NSApplication.runType.requiresEnvironment {
remoteMessagingClient = RemoteMessagingClient(
database: RemoteMessagingDatabase().db,
bookmarksDatabase: BookmarkDatabase.shared.db,
appearancePreferences: .shared,
pinnedTabsManager: pinnedTabsManager,
internalUserDecider: internalUserDecider,
configurationStore: ConfigurationStore.shared,
remoteMessagingAvailabilityProvider: PrivacyConfigurationRemoteMessagingAvailabilityProvider(
privacyConfigurationManager: ContentBlocking.shared.privacyConfigurationManager
)
)
activeRemoteMessageModel = ActiveRemoteMessageModel(remoteMessagingClient: remoteMessagingClient)
} else {
// As long as remoteMessagingClient is private to App Delegate and activeRemoteMessageModel
// is used only by HomePage RootView as environment object,
// it's safe to not initialize the client for unit tests to avoid side effects.
remoteMessagingClient = nil
activeRemoteMessageModel = ActiveRemoteMessageModel(remoteMessagingStore: nil, remoteMessagingAvailabilityProvider: nil)
}
featureFlagger = DefaultFeatureFlagger(
internalUserDecider: internalUserDecider,
privacyConfigManager: AppPrivacyFeatures.shared.contentBlocking.privacyConfigurationManager
)
// Configure Subscription
subscriptionManager = DefaultSubscriptionManager()
subscriptionUIHandler = SubscriptionUIHandler(windowControllersManagerProvider: {
return WindowControllersManager.shared
})
// Update VPN environment and match the Subscription environment
vpnSettings.alignTo(subscriptionEnvironment: subscriptionManager.currentEnvironment)
// Update DBP environment and match the Subscription environment
DataBrokerProtectionSettings().alignTo(subscriptionEnvironment: subscriptionManager.currentEnvironment)
}
func applicationWillFinishLaunching(_ notification: Notification) {
APIRequest.Headers.setUserAgent(UserAgent.duckDuckGoUserAgent())
Configuration.setURLProvider(AppConfigurationURLProvider())
stateRestorationManager = AppStateRestorationManager(fileStore: fileStore)
#if SPARKLE
if NSApp.runType != .uiTests {
updateController = UpdateController(internalUserDecider: internalUserDecider)
stateRestorationManager.subscribeToAutomaticAppRelaunching(using: updateController.willRelaunchAppPublisher)
}
#endif
appIconChanger = AppIconChanger(internalUserDecider: internalUserDecider)
// Configure Event handlers
let tunnelController = NetworkProtectionIPCTunnelController(ipcClient: vpnXPCClient)
let vpnUninstaller = VPNUninstaller(ipcClient: vpnXPCClient)
networkProtectionSubscriptionEventHandler = NetworkProtectionSubscriptionEventHandler(subscriptionManager: subscriptionManager,
tunnelController: tunnelController,
vpnUninstaller: vpnUninstaller)
}
func applicationDidFinishLaunching(_ notification: Notification) {
guard NSApp.runType.requiresEnvironment else { return }
defer {
didFinishLaunching = true
}
HistoryCoordinator.shared.loadHistory {
HistoryCoordinator.shared.migrateModelV5toV6IfNeeded()
}
PrivacyFeatures.httpsUpgrade.loadDataAsync()
bookmarksManager.loadBookmarks()
// Force use of .mainThread to prevent high WindowServer Usage
// Pending Fix with newer Lottie versions
// https://app.asana.com/0/1177771139624306/1207024603216659/f
LottieConfiguration.shared.renderingEngine = .mainThread
if case .normal = NSApp.runType {
FaviconManager.shared.loadFavicons()
}
ConfigurationManager.shared.start()
_ = DownloadListCoordinator.shared
_ = RecentlyClosedCoordinator.shared
if LocalStatisticsStore().atb == nil {
AppDelegate.firstLaunchDate = Date()
// MARK: Enable pixel experiments here
PixelExperiment.install()
}
AtbAndVariantCleanup.cleanup()
DefaultVariantManager().assignVariantIfNeeded { _ in
// MARK: perform first time launch logic here
}
let statisticsLoader = NSApp.runType.requiresEnvironment ? StatisticsLoader.shared : nil
statisticsLoader?.load()
startupSync()
subscriptionManager.loadInitialData()
if [.normal, .uiTests].contains(NSApp.runType) {
stateRestorationManager.applicationDidFinishLaunching()
}
BWManager.shared.initCommunication()
if WindowsManager.windows.first(where: { $0 is MainWindow }) == nil,
case .normal = NSApp.runType {
WindowsManager.openNewWindow(lazyLoadTabs: true)
}
grammarFeaturesManager.manage()
applyPreferredTheme()
#if APPSTORE
crashCollection.startAttachingCrashLogMessages { pixelParameters, payloads, completion in
pixelParameters.forEach { parameters in
PixelKit.fire(GeneralPixel.crash, withAdditionalParameters: parameters, includeAppVersionParameter: false)
}
guard let lastPayload = payloads.last else {
return
}
DispatchQueue.main.async {
CrashReportPromptPresenter().showPrompt(for: CrashDataPayload(data: lastPayload), userDidAllowToReport: completion)
}
}
#else
crashReporter.checkForNewReports()
#endif
urlEventHandler.applicationDidFinishLaunching()
subscribeToEmailProtectionStatusNotifications()
subscribeToDataImportCompleteNotification()
fireFailedCompilationsPixelIfNeeded()
UserDefaultsWrapper<Any>.clearRemovedKeys()
networkProtectionSubscriptionEventHandler?.registerForSubscriptionAccountManagerEvents()
NetworkProtectionAppEvents(featureGatekeeper: DefaultVPNFeatureGatekeeper(subscriptionManager: subscriptionManager)).applicationDidFinishLaunching()
UNUserNotificationCenter.current().delegate = self
dataBrokerProtectionSubscriptionEventHandler.registerForSubscriptionAccountManagerEvents()
DataBrokerProtectionAppEvents(featureGatekeeper: DefaultDataBrokerProtectionFeatureGatekeeper(accountManager: subscriptionManager.accountManager)).applicationDidFinishLaunching()
setUpAutoClearHandler()
setUpAutofillPixelReporter()
#if SPARKLE
if NSApp.runType != .uiTests {
updateController.checkNewApplicationVersion()
}
#endif
remoteMessagingClient?.startRefreshingRemoteMessages()
// This messaging system has been replaced by RMF, but we need to clean up the message manifest for any users who had it stored.
let deprecatedRemoteMessagingStorage = DefaultSurveyRemoteMessagingStorage.surveys()
deprecatedRemoteMessagingStorage.removeStoredMessagesIfNecessary()
if didCrashDuringCrashHandlersSetUp {
PixelKit.fire(GeneralPixel.crashOnCrashHandlersSetUp)
didCrashDuringCrashHandlersSetUp = false
}
}
private func fireFailedCompilationsPixelIfNeeded() {
let store = FailedCompilationsStore()
if store.hasAnyFailures {
PixelKit.fire(DebugEvent(GeneralPixel.compilationFailed),
frequency: .daily,
withAdditionalParameters: store.summary,
includeAppVersionParameter: true) { didFire, _ in
if !didFire {
store.cleanup()
}
}
}
}
func applicationDidBecomeActive(_ notification: Notification) {
guard didFinishLaunching else { return }
PixelExperiment.fireOnboardingTestPixels()
syncService?.initializeIfNeeded()
syncService?.scheduler.notifyAppLifecycleEvent()
NetworkProtectionAppEvents(featureGatekeeper: DefaultVPNFeatureGatekeeper(subscriptionManager: subscriptionManager)).applicationDidBecomeActive()
DataBrokerProtectionAppEvents(featureGatekeeper:
DefaultDataBrokerProtectionFeatureGatekeeper(accountManager:
subscriptionManager.accountManager)).applicationDidBecomeActive()
subscriptionManager.refreshCachedSubscriptionAndEntitlements { isSubscriptionActive in
if isSubscriptionActive {
PixelKit.fire(PrivacyProPixel.privacyProSubscriptionActive, frequency: .daily)
}
}
Task { @MainActor in
await vpnRedditSessionWorkaround.installRedditSessionWorkaround()
}
}
func applicationDidResignActive(_ notification: Notification) {
Task { @MainActor in
await vpnRedditSessionWorkaround.removeRedditSessionWorkaround()
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
if !FileDownloadManager.shared.downloads.isEmpty {
// if there‘re downloads without location chosen yet (save dialog should display) - ignore them
if FileDownloadManager.shared.downloads.contains(where: { $0.state.isDownloading }) {
let alert = NSAlert.activeDownloadsTerminationAlert(for: FileDownloadManager.shared.downloads)
if alert.runModal() == .cancel {
return .terminateCancel
}
}
FileDownloadManager.shared.cancelAll(waitUntilDone: true)
DownloadListCoordinator.shared.sync()
}
stateRestorationManager?.applicationWillTerminate()
// Handling of "Burn on quit"
if let terminationReply = autoClearHandler.handleAppTermination() {
return terminationReply
}
return .terminateNow
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if WindowControllersManager.shared.mainWindowControllers.isEmpty,
case .normal = sender.runType {
WindowsManager.openNewWindow()
return true
}
return true
}
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
return ApplicationDockMenu(internalUserDecider: internalUserDecider)
}
func application(_ sender: NSApplication, openFiles files: [String]) {
urlEventHandler.handleFiles(files)
}
// MARK: - PixelKit
static func configurePixelKit() {
#if DEBUG
Self.setUpPixelKit(dryRun: true)
#else
Self.setUpPixelKit(dryRun: false)
#endif
}
private static func setUpPixelKit(dryRun: Bool) {
#if APPSTORE
let source = "browser-appstore"
#else
let source = "browser-dmg"
#endif
PixelKit.setUp(dryRun: dryRun,
appVersion: AppVersion.shared.versionNumber,
source: source,
defaultHeaders: [:],
defaults: .netP) { (pixelName: String, headers: [String: String], parameters: [String: String], _, _, onComplete: @escaping PixelKit.CompletionBlock) in
let url = URL.pixelUrl(forPixelNamed: pixelName)
let apiHeaders = APIRequest.Headers(additionalHeaders: headers)
let configuration = APIRequest.Configuration(url: url, method: .get, queryParameters: parameters, headers: apiHeaders)
let request = APIRequest(configuration: configuration)
request.fetch { _, error in
onComplete(error == nil, error)
}
}
}
// MARK: - Theme
private func applyPreferredTheme() {
let appearancePreferences = AppearancePreferences()
appearancePreferences.updateUserInterfaceStyle()
}
// MARK: - Sync
private func startupSync() {
#if DEBUG
let defaultEnvironment = ServerEnvironment.development
#else
let defaultEnvironment = ServerEnvironment.production
#endif
#if DEBUG || REVIEW
let environment = ServerEnvironment(
UserDefaultsWrapper(key: .syncEnvironment, defaultValue: defaultEnvironment.description).wrappedValue
) ?? defaultEnvironment
#else
let environment = defaultEnvironment
#endif
let syncErrorHandler = SyncErrorHandler()
let syncDataProviders = SyncDataProviders(bookmarksDatabase: BookmarkDatabase.shared.db, syncErrorHandler: syncErrorHandler)
let syncService = DDGSync(
dataProvidersSource: syncDataProviders,
errorEvents: SyncErrorHandler(),
privacyConfigurationManager: ContentBlocking.shared.privacyConfigurationManager,
environment: environment
)
syncService.initializeIfNeeded()
syncDataProviders.setUpDatabaseCleaners(syncService: syncService)
// This is also called in applicationDidBecomeActive, but we're also calling it here, since
// syncService can be nil when applicationDidBecomeActive is called during startup, if a modal
// alert is shown before it's instantiated. In any case it should be safe to call this here,
// since the scheduler debounces calls to notifyAppLifecycleEvent().
//
syncService.scheduler.notifyAppLifecycleEvent()
self.syncDataProviders = syncDataProviders
self.syncService = syncService
isSyncInProgressCancellable = syncService.isSyncInProgressPublisher
.filter { $0 }
.asVoid()
.sink { [weak syncService] in
PixelKit.fire(GeneralPixel.syncDaily, frequency: .legacyDaily)
syncService?.syncDailyStats.sendStatsIfNeeded(handler: { params in
PixelKit.fire(GeneralPixel.syncSuccessRateDaily, withAdditionalParameters: params)
})
}
subscribeSyncQueueToScreenLockedNotifications()
subscribeToSyncFeatureFlags(syncService)
}
@UserDefaultsWrapper(key: .syncDidShowSyncPausedByFeatureFlagAlert, defaultValue: false)
private var syncDidShowSyncPausedByFeatureFlagAlert: Bool
private func subscribeToSyncFeatureFlags(_ syncService: DDGSync) {
syncFeatureFlagsCancellable = syncService.featureFlagsPublisher
.dropFirst()
.map { $0.contains(.dataSyncing) }
.receive(on: DispatchQueue.main)
.sink { [weak self, weak syncService] isDataSyncingAvailable in
if isDataSyncingAvailable {
self?.syncDidShowSyncPausedByFeatureFlagAlert = false
} else if syncService?.authState == .active, self?.syncDidShowSyncPausedByFeatureFlagAlert == false {
let isSyncUIVisible = syncService?.featureFlags.contains(.userInterface) == true
let alert = NSAlert.dataSyncingDisabledByFeatureFlag(showLearnMore: isSyncUIVisible)
let response = alert.runModal()
self?.syncDidShowSyncPausedByFeatureFlagAlert = true
switch response {
case .alertSecondButtonReturn:
alert.window.sheetParent?.endSheet(alert.window)
DispatchQueue.main.async {
WindowControllersManager.shared.showPreferencesTab(withSelectedPane: .sync)
}
default:
break
}
}
}
}
private func subscribeSyncQueueToScreenLockedNotifications() {
let screenIsLockedPublisher = DistributedNotificationCenter.default
.publisher(for: .init(rawValue: "com.apple.screenIsLocked"))
.map { _ in true }
let screenIsUnlockedPublisher = DistributedNotificationCenter.default
.publisher(for: .init(rawValue: "com.apple.screenIsUnlocked"))
.map { _ in false }
screenLockedCancellable = Publishers.Merge(screenIsLockedPublisher, screenIsUnlockedPublisher)
.receive(on: DispatchQueue.main)
.sink { [weak self] isLocked in
guard let syncService = self?.syncService, syncService.authState != .inactive else {
return
}
if isLocked {
Logger.sync.debug("Screen is locked")
syncService.scheduler.cancelSyncAndSuspendSyncQueue()
} else {
Logger.sync.debug("Screen is unlocked")
syncService.scheduler.resumeSyncQueue()
}
}
}
private func subscribeToEmailProtectionStatusNotifications() {
NotificationCenter.default.publisher(for: .emailDidSignIn)
.receive(on: DispatchQueue.main)
.sink { [weak self] notification in
self?.emailDidSignInNotification(notification)
}
.store(in: &emailCancellables)
NotificationCenter.default.publisher(for: .emailDidSignOut)
.receive(on: DispatchQueue.main)
.sink { [weak self] notification in
self?.emailDidSignOutNotification(notification)
}
.store(in: &emailCancellables)
}
private func subscribeToDataImportCompleteNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(dataImportCompleteNotification(_:)), name: .dataImportComplete, object: nil)
}
private func emailDidSignInNotification(_ notification: Notification) {
PixelKit.fire(NonStandardEvent(NonStandardPixel.emailEnabled))
if AppDelegate.isNewUser {
PixelKit.fire(GeneralPixel.emailEnabledInitial, frequency: .legacyInitial)
}
if let object = notification.object as? EmailManager, let emailManager = syncDataProviders.settingsAdapter.emailManager, object !== emailManager {
syncService?.scheduler.notifyDataChanged()
}
}
private func emailDidSignOutNotification(_ notification: Notification) {
PixelKit.fire(NonStandardEvent(NonStandardPixel.emailDisabled))
if let object = notification.object as? EmailManager, let emailManager = syncDataProviders.settingsAdapter.emailManager, object !== emailManager {
syncService?.scheduler.notifyDataChanged()
}
}
@objc private func dataImportCompleteNotification(_ notification: Notification) {
if AppDelegate.isNewUser {
PixelKit.fire(GeneralPixel.importDataInitial, frequency: .legacyInitial)
}
}
@MainActor
private func setUpAutoClearHandler() {
let autoClearHandler = AutoClearHandler(preferences: .shared,
fireViewModel: FireCoordinator.fireViewModel,
stateRestorationManager: self.stateRestorationManager)
self.autoClearHandler = autoClearHandler
DispatchQueue.main.async {
autoClearHandler.handleAppLaunch()
autoClearHandler.onAutoClearCompleted = {
NSApplication.shared.reply(toApplicationShouldTerminate: true)
}
}
}
private func setUpAutofillPixelReporter() {
autofillPixelReporter = AutofillPixelReporter(
userDefaults: .standard,
autofillEnabled: AutofillPreferences().askToSaveUsernamesAndPasswords,
eventMapping: EventMapping<AutofillPixelEvent> {event, _, params, _ in
switch event {
case .autofillActiveUser:
PixelKit.fire(GeneralPixel.autofillActiveUser)
case .autofillEnabledUser:
PixelKit.fire(GeneralPixel.autofillEnabledUser)
case .autofillOnboardedUser:
PixelKit.fire(GeneralPixel.autofillOnboardedUser)
case .autofillToggledOn:
PixelKit.fire(GeneralPixel.autofillToggledOn, withAdditionalParameters: params)
case .autofillToggledOff:
PixelKit.fire(GeneralPixel.autofillToggledOff, withAdditionalParameters: params)
case .autofillLoginsStacked:
PixelKit.fire(GeneralPixel.autofillLoginsStacked, withAdditionalParameters: params)
case .autofillCreditCardsStacked:
PixelKit.fire(GeneralPixel.autofillCreditCardsStacked, withAdditionalParameters: params)
case .autofillIdentitiesStacked:
PixelKit.fire(GeneralPixel.autofillIdentitiesStacked, withAdditionalParameters: params)
}
},
passwordManager: PasswordManagerCoordinator.shared,
installDate: AppDelegate.firstLaunchDate)
_ = NotificationCenter.default.addObserver(forName: .autofillUserSettingsDidChange,
object: nil,
queue: nil) { [weak self] _ in
self?.autofillPixelReporter?.updateAutofillEnabledStatus(AutofillPreferences().askToSaveUsernamesAndPasswords)
}
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler(.banner)
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
completionHandler()
}
}