Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add comments to new rust fxa code, split app delegate up for clarity #6280

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
8 changes: 8 additions & 0 deletions Client.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,8 @@
EB912B9C22722B6800DF585A /* LockProtected.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB912B9122722A7800DF585A /* LockProtected.swift */; };
EB9407492081353100702E05 /* UXConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB940747208134AF00702E05 /* UXConstants.swift */; };
EB94075320850C9F00702E05 /* photon-colors.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C49854D206173C800893DAE /* photon-colors.swift */; };
EB9854FF2422686F0040F24B /* AppDelegate+PushNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB9854FD2422686F0040F24B /* AppDelegate+PushNotifications.swift */; };
EB98550124226EF70040F24B /* AppDelegate+SyncSentTabs.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB98550024226EF60040F24B /* AppDelegate+SyncSentTabs.swift */; };
EB9A178E20E525DF00B12184 /* ThemeSettingsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB9A178D20E525DF00B12184 /* ThemeSettingsController.swift */; };
EB9A179B20E69A7F00B12184 /* ThemeManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB9A179820E69A7E00B12184 /* ThemeManager.swift */; };
EB9A179C20E69A7F00B12184 /* DarkTheme.swift in Sources */ = {isa = PBXBuildFile; fileRef = EB9A179920E69A7E00B12184 /* DarkTheme.swift */; };
Expand Down Expand Up @@ -1847,6 +1849,8 @@
EB912B9022722A7800DF585A /* ReadWriteLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteLock.swift; sourceTree = "<group>"; };
EB912B9122722A7800DF585A /* LockProtected.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockProtected.swift; sourceTree = "<group>"; };
EB940747208134AF00702E05 /* UXConstants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UXConstants.swift; sourceTree = "<group>"; };
EB9854FD2422686F0040F24B /* AppDelegate+PushNotifications.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppDelegate+PushNotifications.swift"; sourceTree = "<group>"; };
EB98550024226EF60040F24B /* AppDelegate+SyncSentTabs.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppDelegate+SyncSentTabs.swift"; sourceTree = "<group>"; };
EB9A178D20E525DF00B12184 /* ThemeSettingsController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThemeSettingsController.swift; sourceTree = "<group>"; };
EB9A179820E69A7E00B12184 /* ThemeManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ThemeManager.swift; sourceTree = "<group>"; };
EB9A179920E69A7E00B12184 /* DarkTheme.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DarkTheme.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -3187,6 +3191,8 @@
isa = PBXGroup;
children = (
F84B21E51A0910F600AAB793 /* AppDelegate.swift */,
EB9854FD2422686F0040F24B /* AppDelegate+PushNotifications.swift */,
EB98550024226EF60040F24B /* AppDelegate+SyncSentTabs.swift */,
D3BE7B451B054F8600641031 /* TestAppDelegate.swift */,
);
name = Delegates;
Expand Down Expand Up @@ -5160,6 +5166,7 @@
D0EAE0E2228B3762001C875A /* DrawerViewController.swift in Sources */,
E689C7301E0C7617008BAADB /* NSAttributedStringExtensions.swift in Sources */,
D0C95E0E200FD3B200E4E51C /* PrintHelper.swift in Sources */,
EB9854FF2422686F0040F24B /* AppDelegate+PushNotifications.swift in Sources */,
E64ED8FA1BC55AE300DAF864 /* UIAlertControllerExtensions.swift in Sources */,
39CE74F821A83105007AE4F2 /* TranslationSettingsController.swift in Sources */,
282DA4731A68C1E700A406E2 /* OpenSearch.swift in Sources */,
Expand Down Expand Up @@ -5268,6 +5275,7 @@
C400467C1CF4E43E00B08303 /* BackForwardListViewController.swift in Sources */,
D3972BF31C22412B00035B87 /* ShareExtensionHelper.swift in Sources */,
F35B8D2D1D6383E9008E3D61 /* SessionRestoreHelper.swift in Sources */,
EB98550124226EF70040F24B /* AppDelegate+SyncSentTabs.swift in Sources */,
744ED5611DBFEB8D00A2B5BE /* MailtoLinkHandler.swift in Sources */,
59A68E0B4ABBF55E14819668 /* BookmarksPanel.swift in Sources */,
D04D1B862097859B0074B35F /* DownloadToast.swift in Sources */,
Expand Down
95 changes: 95 additions & 0 deletions Client/Application/AppDelegate+PushNotifications.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import Shared
import Storage
import Sync
import XCGLogger
import UserNotifications
import Account

private let log = Logger.browserLogger

/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to display a notification.
* This will also likely be the extension point for wipes, resets, and getting access to data sources during a sync.
*/
enum SentTabAction: String {
case view = "TabSendViewAction"

static let TabSendURLKey = "TabSendURL"
static let TabSendTitleKey = "TabSendTitle"
static let TabSendCategory = "TabSendCategory"

static func registerActions() {
let viewAction = UNNotificationAction(identifier: SentTabAction.view.rawValue, title: Strings.SentTabViewActionTitle, options: .foreground)

// Register ourselves to handle the notification category set by NotificationService for APNS notifications
let sentTabCategory = UNNotificationCategory(identifier: "org.mozilla.ios.SentTab.placeholder", actions: [viewAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))
UNUserNotificationCenter.current().setNotificationCategories([sentTabCategory])
}
}

extension AppDelegate {
func pushNotificationSetup() {
UNUserNotificationCenter.current().delegate = self
SentTabAction.registerActions()

NotificationCenter.default.addObserver(forName: .RegisterForPushNotifications, object: nil, queue: .main) { _ in
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
if settings.authorizationStatus != .denied {
UIApplication.shared.registerForRemoteNotifications()
}
}
}
}
}

private func openURLsInNewTabs(_ notification: UNNotification) {
guard let urls = notification.request.content.userInfo["sentTabs"] as? [NSDictionary] else { return }
for sentURL in urls {
if let urlString = sentURL.value(forKey: "url") as? String, let url = URL(string: urlString) {
receivedURLs.append(url)
}
}

// Check if the app is foregrounded, _also_ verify the BVC is initialized. Most BVC functions depend on viewDidLoad() having run –if not, they will crash.
if UIApplication.shared.applicationState == .active && BrowserViewController.foregroundBVC().isViewLoaded {
BrowserViewController.foregroundBVC().loadQueuedTabs(receivedURLs: receivedURLs)
receivedURLs.removeAll()
}
}
}

extension AppDelegate: UNUserNotificationCenterDelegate {
// Called when the user taps on a sent-tab notification from the background.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
openURLsInNewTabs(response.notification)
}

// Called when the user receives a tab (or any other notification) while in foreground.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

if profile?.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false {
FxALoginHelper.sharedInstance.disconnect()
// show the notification
completionHandler([.alert, .sound])
} else {
openURLsInNewTabs(notification)
}
}
}

extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
RustFirefoxAccounts.shared.pushNotifications.didRegister(withDeviceToken: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("failed to register. \(error)")
Sentry.shared.send(message: "Failed to register for APNS")
}
}
77 changes: 77 additions & 0 deletions Client/Application/AppDelegate+SyncSentTabs.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import Shared
import Storage
import Sync
import XCGLogger
import UserNotifications
import Account

private let log = Logger.browserLogger

extension UIApplication {
var syncDelegate: SyncDelegate {
return AppSyncDelegate(app: self)
}
}

/**
Sent tabs can be displayed not only by receiving push notifications, but by sync.
Sync will get the list of sent tabs, and try to display any in that list.
Thus, push notifications are not needed to receive sent tabs, they can be handled
when the app performs a sync.
*/
class AppSyncDelegate: SyncDelegate {
let app: UIApplication

init(app: UIApplication) {
self.app = app
}

func displaySentTab(for url: URL, title: String, from deviceName: String?) {
DispatchQueue.main.sync {
if app.applicationState == .active {
BrowserViewController.foregroundBVC().switchToTabForURLOrOpen(url)
return
}

// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.alertSetting != .enabled {
return
}
if Logger.logPII {
log.info("Displaying notification for URL \(url.absoluteString)")
}

let notificationContent = UNMutableNotificationContent()
let title: String
if let deviceName = deviceName {
title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName)
} else {
title = Strings.SentTab_TabArrivingNotification_NoDevice_title
}
notificationContent.title = title
notificationContent.body = url.absoluteDisplayExternalString
notificationContent.userInfo = [SentTabAction.TabSendURLKey: url.absoluteString, SentTabAction.TabSendTitleKey: title]
notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder"

// `timeInterval` must be greater than zero
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)

// The identifier for each notification request must be unique in order to be created
let requestIdentifier = "\(SentTabAction.TabSendCategory).\(url.absoluteString)"
let request = UNNotificationRequest(identifier: requestIdentifier, content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(request) { error in
if let error = error {
log.error(error.localizedDescription)
}
}
}
}
}
}
137 changes: 1 addition & 136 deletions Client/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestorati

adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions)

UNUserNotificationCenter.current().delegate = self
SentTabAction.registerActions()
UIScrollView.doBadSwizzleStuff()

window!.makeKeyAndVisible()
Expand All @@ -223,15 +221,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestorati
// that is an iOS bug or not.
AutocompleteTextField.appearance().semanticContentAttribute = .forceLeftToRight

NotificationCenter.default.addObserver(forName: .RegisterForPushNotifications, object: nil, queue: .main) { _ in
UNUserNotificationCenter.current().getNotificationSettings { settings in
DispatchQueue.main.async {
if settings.authorizationStatus != .denied {
application.registerForRemoteNotifications()
}
}
}
}
pushNotificationSetup()

RustFirefoxAccounts.startup() { shared in
guard shared.accountManager.hasAccount() else { return }
Expand Down Expand Up @@ -539,21 +529,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestorati
return false
}

fileprivate func openURLsInNewTabs(_ notification: UNNotification) {
guard let urls = notification.request.content.userInfo["sentTabs"] as? [NSDictionary] else { return }
for sentURL in urls {
if let urlString = sentURL.value(forKey: "url") as? String, let url = URL(string: urlString) {
receivedURLs.append(url)
}
}

// Check if the app is foregrounded, _also_ verify the BVC is initialized. Most BVC functions depend on viewDidLoad() having run –if not, they will crash.
if UIApplication.shared.applicationState == .active && BrowserViewController.foregroundBVC().isViewLoaded {
BrowserViewController.foregroundBVC().loadQueuedTabs(receivedURLs: receivedURLs)
receivedURLs.removeAll()
}
}

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: BrowserViewController.foregroundBVC())

Expand Down Expand Up @@ -612,118 +587,8 @@ extension AppDelegate: MFMailComposeViewControllerDelegate {
}
}

extension AppDelegate: UNUserNotificationCenterDelegate {
// Called when the user taps on a sent-tab notification from the background.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
openURLsInNewTabs(response.notification)
}

// Called when the user receives a tab (or any other notification) while in foreground.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

if profile?.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false {
FxALoginHelper.sharedInstance.disconnect()
// show the notification
completionHandler([.alert, .sound])
} else {
openURLsInNewTabs(notification)
}
}
}

extension AppDelegate {
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
RustFirefoxAccounts.shared.pushNotifications.didRegister(withDeviceToken: deviceToken)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("failed to register. \(error)")
Sentry.shared.send(message: "Failed to register for APNS")
}
}

extension UIApplication {
var syncDelegate: SyncDelegate {
return AppSyncDelegate(app: self)
}

static var isInPrivateMode: Bool {
return BrowserViewController.foregroundBVC().tabManager.selectedTab?.isPrivate ?? false
}
}

class AppSyncDelegate: SyncDelegate {
let app: UIApplication

init(app: UIApplication) {
self.app = app
}

open func displaySentTab(for url: URL, title: String, from deviceName: String?) {
DispatchQueue.main.sync {
if app.applicationState == .active {
BrowserViewController.foregroundBVC().switchToTabForURLOrOpen(url)
return
}

// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
UNUserNotificationCenter.current().getNotificationSettings { settings in
if settings.alertSetting == .enabled {
if Logger.logPII {
log.info("Displaying notification for URL \(url.absoluteString)")
}

let notificationContent = UNMutableNotificationContent()
let title: String
if let deviceName = deviceName {
title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName)
} else {
title = Strings.SentTab_TabArrivingNotification_NoDevice_title
}
notificationContent.title = title
notificationContent.body = url.absoluteDisplayExternalString
notificationContent.userInfo = [SentTabAction.TabSendURLKey: url.absoluteString, SentTabAction.TabSendTitleKey: title]
notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder"

// `timeInterval` must be greater than zero
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)

// The identifier for each notification request must be unique in order to be created
let requestIdentifier = "\(SentTabAction.TabSendCategory).\(url.absoluteString)"
let request = UNNotificationRequest(identifier: requestIdentifier, content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(request) { error in
if let error = error {
log.error(error.localizedDescription)
}
}
}
}
}
}
}

/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/

enum SentTabAction: String {
case view = "TabSendViewAction"

static let TabSendURLKey = "TabSendURL"
static let TabSendTitleKey = "TabSendTitle"
static let TabSendCategory = "TabSendCategory"

static func registerActions() {
let viewAction = UNNotificationAction(identifier: SentTabAction.view.rawValue, title: Strings.SentTabViewActionTitle, options: .foreground)

// Register ourselves to handle the notification category set by NotificationService for APNS notifications
let sentTabCategory = UNNotificationCategory(identifier: "org.mozilla.ios.SentTab.placeholder", actions: [viewAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0))
UNUserNotificationCenter.current().setNotificationCategories([sentTabCategory])
}
}
Loading