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

refactor: Decouple current account #892

Merged
merged 3 commits into from
Jul 21, 2023
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
6 changes: 3 additions & 3 deletions Mail/MailApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ struct MailApp: App {
break
}
}
.onChange(of: accountManager.currentAccount) { _ in
.onChange(of: navigationState.account) { _ in
refreshCacheData()
}
}
Expand All @@ -148,13 +148,13 @@ struct MailApp: App {
}

func refreshCacheData() {
guard let currentAccount = accountManager.currentAccount else {
guard let account = navigationState.account else {
return
}

Task {
do {
try await accountManager.updateUser(for: currentAccount)
try await accountManager.updateUser(for: account)
accountManager.enableBugTrackerIfAvailable()

try await accountManager.currentMailboxManager?.contactManager.fetchContactsAndAddressBooks()
Expand Down
2 changes: 1 addition & 1 deletion Mail/NotificationCenterDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class NotificationCenterDelegate: NSObject, UNUserNotificationCenterDelegate {
}

if AccountManager.instance.currentMailboxManager?.mailbox != mailboxManager.mailbox {
if AccountManager.instance.currentAccount.userId != mailboxManager.mailbox.userId {
if AccountManager.instance.getCurrentAccount()?.userId != mailboxManager.mailbox.userId {
if let switchedAccount = AccountManager.instance.accounts
.first(where: { $0.userId == mailboxManager.mailbox.userId }) {
AccountManager.instance.switchAccount(newAccount: switchedAccount)
Expand Down
49 changes: 25 additions & 24 deletions Mail/Utils/NavigationState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import Combine
import Foundation
import InfomaniakCore
import InfomaniakCoreUI
import InfomaniakDI
import MailCore
Expand Down Expand Up @@ -92,28 +93,41 @@ class NavigationState: ObservableObject {
/// The selected thread is the last in collection, by convention.
@Published var threadPath = [Thread]()

private(set) var account: Account?

init() {
if accountManager.currentAccount != nil,
let currentMailboxManager = accountManager.currentMailboxManager {
rootViewState = .mainView(currentMailboxManager)
} else if !accountManager.mailboxes.isEmpty && accountManager.mailboxes.allSatisfy({ !$0.isAvailable }) {
rootViewState = .unavailableMailboxes
} else {
rootViewState = .onboarding
}
account = AccountManager.instance.getCurrentAccount()
rootViewState = NavigationState.getMainViewStateIfPossible()

accountManagerObservation = accountManager.objectWillChange.receive(on: RunLoop.main).sink { [weak self] in
self?.switchToCurrentMailboxManagerIfPossible()
self?.account = AccountManager.instance.getCurrentAccount()
self?.rootViewState = NavigationState.getMainViewStateIfPossible()
}
}

static func getMainViewStateIfPossible() -> RootViewState {
let accountManager = AccountManager.instance
if let currentAccount = accountManager.getCurrentAccount() {
PhilippeWeidmann marked this conversation as resolved.
Show resolved Hide resolved
if let currentMailboxManager = accountManager.currentMailboxManager {
return .mainView(currentMailboxManager)
} else {
let mailboxes = MailboxInfosManager.instance.getMailboxes(for: currentAccount.userId)
if !mailboxes.isEmpty && mailboxes.allSatisfy({ !$0.isAvailable }) {
return .unavailableMailboxes
}
}
}

return .onboarding
}

func transitionToRootViewDestination(_ destination: RootViewDestination) {
withAnimation {
switch destination {
case .appLocked:
rootViewState = .appLocked
case .mainView:
switchToCurrentMailboxManagerIfPossible()
rootViewState = NavigationState.getMainViewStateIfPossible()
case .onboarding:
rootViewState = .onboarding
case .noMailboxes:
Expand All @@ -127,21 +141,8 @@ class NavigationState: ObservableObject {
func transitionToLockViewIfNeeded() {
if UserDefaults.shared.isAppLockEnabled
&& appLockHelper.isAppLocked
&& accountManager.currentAccount != nil {
&& account != nil {
transitionToRootViewDestination(.appLocked)
}
}

private func switchToCurrentMailboxManagerIfPossible() {
if accountManager.currentAccount != nil,
let currentMailboxManager = accountManager.currentMailboxManager {
if rootViewState != .mainView(currentMailboxManager) {
rootViewState = .mainView(currentMailboxManager)
}
} else if !accountManager.mailboxes.isEmpty && accountManager.mailboxes.allSatisfy({ !$0.isAvailable }) {
rootViewState = .unavailableMailboxes
} else {
rootViewState = .onboarding
}
}
}
4 changes: 2 additions & 2 deletions Mail/Views/Bottom sheets/Actions/ActionsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ enum ActionsTarget: Equatable, Identifiable {
spamAction,
unread ? .markAsRead : .markAsUnread,
archive ? .archive : .moveToInbox,
star ? .unstar : .star,
star ? .unstar : .star
]

listActions = tempListActions.compactMap { $0 }
Expand All @@ -309,7 +309,7 @@ enum ActionsTarget: Equatable, Identifiable {
let archive = message.folder?.role != .archive
let unread = !message.seen
let star = message.flagged
let isStaff = AccountManager.instance.currentAccount?.user?.isStaff ?? false
let isStaff = mailboxManager.account.user?.isStaff ?? false
let tempListActions: [Action?] = [
.move,
.reportJunk,
Expand Down
4 changes: 3 additions & 1 deletion Mail/Views/Menu Drawer/Items/MenuDrawerItemsListView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ struct MenuDrawerItemsAdvancedListView: View {
}

struct MenuDrawerItemsHelpListView: View {
@EnvironmentObject private var mailboxManager: MailboxManager

@State private var isShowingHelp = false
@State private var isShowingBugTracker = false

Expand All @@ -80,7 +82,7 @@ struct MenuDrawerItemsHelpListView: View {
}

private func sendFeedback() {
if AccountManager.instance.currentAccount?.user?.isStaff == true {
if mailboxManager.account.user?.isStaff == true {
isShowingBugTracker.toggle()
} else if let userReportURL = URL(string: MailResourcesStrings.Localizable.urlUserReportiOS) {
UIApplication.shared.open(userReportURL)
Expand Down
2 changes: 1 addition & 1 deletion Mail/Views/Onboarding/OnboardingView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ class LoginHandler: InfomaniakLoginDelegate, ObservableObject {

private func loginSuccessful(code: String, codeVerifier verifier: String) {
matomo.track(eventWithCategory: .account, name: "loggedIn")
let previousAccount = AccountManager.instance.currentAccount
let previousAccount = AccountManager.instance.getCurrentAccount()
Task {
do {
_ = try await AccountManager.instance.createAndSetCurrentAccount(code: code, codeVerifier: verifier)
Expand Down
2 changes: 1 addition & 1 deletion Mail/Views/Switch User/AccountView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import SwiftUI

class AccountViewDelegate: DeleteAccountDelegate {
@MainActor func didCompleteDeleteAccount() {
guard let account = AccountManager.instance.currentAccount else { return }
guard let account = AccountManager.instance.getCurrentAccount() else { return }
AccountManager.instance.removeTokenAndAccount(token: account.token)
if let nextAccount = AccountManager.instance.accounts.first {
AccountManager.instance.switchAccount(newAccount: nextAccount)
Expand Down
4 changes: 2 additions & 2 deletions Mail/Views/Thread List/ThreadListModifiers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,9 @@ struct ThreadListToolbar: ViewModifier {
}

Button {
presentedCurrentAccount = AccountManager.instance.currentAccount
presentedCurrentAccount = viewModel.mailboxManager.account
} label: {
if let currentAccountUser = AccountManager.instance.currentAccount?.user {
if let currentAccountUser = viewModel.mailboxManager.account.user {
AvatarView(displayablePerson: CommonContact(user: currentAccountUser))
}
}
Expand Down
6 changes: 5 additions & 1 deletion MailCore/API/MailError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@ public class MailError: LocalizedError {
}

public static let unknownError = MailError(code: "unknownError", shouldDisplay: true)
public static let noToken = MailError(code: "noToken", shouldDisplay: true)
public static let noToken = MailError(
code: "noToken",
localizedDescription: MailResourcesStrings.Localizable.refreshTokenError,
shouldDisplay: true
)
public static let resourceError = MailError(code: "resourceError", shouldDisplay: true)
public static let unknownToken = MailError(code: "unknownToken", shouldDisplay: true)
public static let noMailbox = MailError(code: "noMailbox")
Expand Down
16 changes: 10 additions & 6 deletions MailCore/Cache/AccountManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public class AccountManager: RefreshTokenDelegate, ObservableObject {
public static let accessGroup: String = AccountManager.appIdentifierPrefix + AccountManager.group
public static var instance = AccountManager()
private let tag = "ch.infomaniak.token".data(using: .utf8)!
public var currentAccount: Account!
private var currentAccount: Account?
public var accounts = [Account]()
public var tokens = [ApiToken]()
public let refreshTokenLockedQueue = DispatchQueue(label: "com.infomaniak.mail.refreshtoken")
Expand All @@ -100,7 +100,7 @@ public class AccountManager: RefreshTokenDelegate, ObservableObject {
}
}

public var mailboxes: [Mailbox] {
private var mailboxes: [Mailbox] {
return MailboxInfosManager.instance.getMailboxes(for: currentUserId)
}

Expand Down Expand Up @@ -130,6 +130,10 @@ public class AccountManager: RefreshTokenDelegate, ObservableObject {
forceReload()
}

public func getCurrentAccount() -> Account? {
return currentAccount
}

public func forceReload() {
currentMailboxId = UserDefaults.shared.currentMailboxId
currentUserId = UserDefaults.shared.currentMailUserId
Expand Down Expand Up @@ -287,9 +291,9 @@ public class AccountManager: RefreshTokenDelegate, ObservableObject {
return newAccount
}

public func updateUser(for account: Account) async throws {
guard account.isConnected else {
throw MailError.unknownError
public func updateUser(for account: Account?) async throws {
guard let account, account.isConnected else {
throw MailError.noToken
}

let apiFetcher = await AccountActor.run {
Expand Down Expand Up @@ -503,7 +507,7 @@ public class AccountManager: RefreshTokenDelegate, ObservableObject {
}

public func enableBugTrackerIfAvailable() {
if currentAccount.user?.isStaff == true {
if let currentAccount, currentAccount.user?.isStaff == true {
bugTracker.activateOnScreenshot()
let apiFetcher = getApiFetcher(for: currentAccount.userId, token: currentAccount.token)
bugTracker.configure(with: apiFetcher)
Expand Down
7 changes: 6 additions & 1 deletion MailCore/Utils/URLSchemeHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,17 @@ public class URLSchemeHandler: NSObject, WKURLSchemeHandler {
urlSchemeTask.didFailWithError(MailError.resourceError)
return
}

guard let currentAccessToken = AccountManager.instance.getCurrentAccount()?.token?.accessToken else {
urlSchemeTask.didFailWithError(MailError.unknownError)
return
}

var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
components?.scheme = "https"
var request = URLRequest(url: components!.url!)
request.addValue(
"Bearer \(AccountManager.instance.currentAccount.token.accessToken)",
"Bearer \(currentAccessToken)",
forHTTPHeaderField: "Authorization"
)
let dataTask = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
Expand Down
Loading