Key backup returns (#1951)

* Converge on UserSessionFlowCoordinator logout confirmation

* Add logout confirmation screen strings to untranslated.

* Fix chat backup learn more URl fragment.

* Implement logout flows that check recovery and key backup for the last session

* Move logout confirmation screen strings to localazy

* Change encrypted timeline item copy to "Waiting for decryption key"

* Use different encrypted history banner based on key backup states

* Introduce a SettingsFlowCoordinator and implement navigation directly to the secure backup screen from the logout flows.

* Fix **mocked** secure backup controller flows

* Simplify encrypted history banner logic

* Address PR comments
This commit is contained in:
Stefan Ceriu
2023-10-24 18:38:41 +03:00
committed by GitHub
parent 6e5680fc36
commit 37f1a79a11
34 changed files with 806 additions and 111 deletions
@@ -438,7 +438,7 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationCoordinatorDelegate,
guard let self else { return }
switch action {
case .signOut:
case .logout:
stateMachine.processEvent(.signOut(isSoft: false))
case .clearCache:
stateMachine.processEvent(.clearCache)
@@ -118,7 +118,7 @@ final class AppSettings {
/// An email address that should be used for support requests.
let supportEmailAddress = "support@element.io"
// A URL where users can go read more about the chat backup.
let chatBackupDetailsURL: URL = "https://element.io/help#encryption"
let chatBackupDetailsURL: URL = "https://element.io/help#encryption5"
// MARK: - Security
@@ -24,6 +24,8 @@ enum AppRoute: Equatable {
case roomMemberDetails(userID: String)
case invites
case genericCallLink(url: URL)
case settings
case chatBackupSettings
}
struct AppRouteURLParser {
@@ -106,9 +106,7 @@ class RoomFlowCoordinator: FlowCoordinatorProtocol {
MXLog.error("[RoomFlowCoordinator] Failed to get member: RoomProxy is nil")
}
}
case .invites:
break
case .genericCallLink, .oidcCallback:
case .invites, .genericCallLink, .oidcCallback, .settings, .chatBackupSettings:
break
}
}
@@ -347,7 +345,8 @@ class RoomFlowCoordinator: FlowCoordinatorProtocol {
timelineItemFactory: timelineItemFactory,
mediaProvider: userSession.mediaProvider,
mediaPlayerProvider: mediaPlayerProvider,
voiceMessageMediaManager: userSession.voiceMessageMediaManager)
voiceMessageMediaManager: userSession.voiceMessageMediaManager,
secureBackupController: userSession.clientProxy.secureBackupController)
self.timelineController = timelineController
analytics.trackViewRoom(isDM: roomProxy.isDirect, isSpace: roomProxy.isSpace)
@@ -0,0 +1,135 @@
//
// Copyright 2023 New Vector Ltd
//
// 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 Combine
import Foundation
enum SettingsFlowCoordinatorAction {
case presentedSettings
case dismissedSettings
case runLogoutFlow
case clearCache
}
struct SettingsFlowCoordinatorParameters {
let userSession: UserSessionProtocol
let appLockService: AppLockServiceProtocol
let bugReportService: BugReportServiceProtocol
let notificationSettings: NotificationSettingsProxyProtocol
let secureBackupController: SecureBackupControllerProtocol
let appSettings: AppSettings
let navigationSplitCoordinator: NavigationSplitCoordinator
}
class SettingsFlowCoordinator: FlowCoordinatorProtocol {
private let parameters: SettingsFlowCoordinatorParameters
private var navigationStackCoordinator: NavigationStackCoordinator!
private var userIndicatorController: UserIndicatorControllerProtocol!
private var cancellables = Set<AnyCancellable>()
private let actionsSubject: PassthroughSubject<SettingsFlowCoordinatorAction, Never> = .init()
var actions: AnyPublisher<SettingsFlowCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SettingsFlowCoordinatorParameters) {
self.parameters = parameters
}
func handleAppRoute(_ appRoute: AppRoute, animated: Bool) {
switch appRoute {
case .settings:
presentSettingsScreen(animated: animated)
case .chatBackupSettings:
if navigationStackCoordinator == nil {
presentSettingsScreen(animated: animated)
}
// The navigation stack doesn't like it if the root and the push happen
// on the same loop run
DispatchQueue.main.async {
self.presentSecureBackupScreen(animated: animated)
}
default:
break
}
}
func clearRoute(animated: Bool) { }
// MARK: - Private
private func presentSettingsScreen(animated: Bool) {
navigationStackCoordinator = NavigationStackCoordinator()
userIndicatorController = UserIndicatorController(rootCoordinator: navigationStackCoordinator)
let parameters = SettingsScreenCoordinatorParameters(navigationStackCoordinator: navigationStackCoordinator,
userIndicatorController: userIndicatorController,
userSession: parameters.userSession,
appLockService: parameters.appLockService,
bugReportService: parameters.bugReportService,
notificationSettings: parameters.userSession.clientProxy.notificationSettings,
secureBackupController: parameters.userSession.clientProxy.secureBackupController,
appSettings: parameters.appSettings)
let settingsScreenCoordinator = SettingsScreenCoordinator(parameters: parameters)
settingsScreenCoordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .dismiss:
self.parameters.navigationSplitCoordinator.setSheetCoordinator(nil)
case .logout:
self.parameters.navigationSplitCoordinator.setSheetCoordinator(nil)
// The settings sheet needs to be dismissed before the alert can be shown
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.actionsSubject.send(.runLogoutFlow)
}
case .clearCache:
actionsSubject.send(.clearCache)
case .secureBackup:
presentSecureBackupScreen(animated: true)
}
}
.store(in: &cancellables)
navigationStackCoordinator.setRootCoordinator(settingsScreenCoordinator, animated: animated)
self.parameters.navigationSplitCoordinator.setSheetCoordinator(userIndicatorController) { [weak self] in
guard let self else { return }
navigationStackCoordinator = nil
userIndicatorController = nil
actionsSubject.send(.dismissedSettings)
}
actionsSubject.send(.presentedSettings)
}
private func presentSecureBackupScreen(animated: Bool) {
let coordinator = SecureBackupScreenCoordinator(parameters: .init(appSettings: parameters.appSettings,
secureBackupController: parameters.userSession.clientProxy.secureBackupController,
navigationStackCoordinator: navigationStackCoordinator,
userIndicatorController: userIndicatorController))
navigationStackCoordinator.push(coordinator, animated: animated)
}
}
@@ -18,7 +18,7 @@ import Combine
import SwiftUI
enum UserSessionFlowCoordinatorAction {
case signOut
case logout
case clearCache
}
@@ -34,6 +34,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
private let stateMachine: UserSessionFlowCoordinatorStateMachine
private let roomFlowCoordinator: RoomFlowCoordinator
private let settingsFlowCoordinator: SettingsFlowCoordinator
private var cancellables = Set<AnyCancellable>()
private var migrationCancellable: AnyCancellable?
@@ -76,11 +77,20 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
appSettings: appSettings,
analytics: analytics,
userIndicatorController: ServiceLocator.shared.userIndicatorController)
settingsFlowCoordinator = SettingsFlowCoordinator(parameters: .init(userSession: userSession,
appLockService: appLockService,
bugReportService: bugReportService,
notificationSettings: userSession.clientProxy.notificationSettings,
secureBackupController: userSession.clientProxy.secureBackupController,
appSettings: appSettings,
navigationSplitCoordinator: navigationSplitCoordinator))
setupStateMachine()
roomFlowCoordinator.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .presentedRoom(let roomID):
analytics.signpost.beginRoomFlow(roomID)
@@ -93,6 +103,22 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
}
}
.store(in: &cancellables)
settingsFlowCoordinator.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .presentedSettings:
stateMachine.processEvent(.showSettingsScreen)
case .dismissedSettings:
stateMachine.processEvent(.dismissedSettingsScreen)
case .runLogoutFlow:
runLogoutFlow()
case .clearCache:
actionsSubject.send(.clearCache)
}
}
.store(in: &cancellables)
}
func start() {
@@ -131,6 +157,8 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
self.navigationSplitCoordinator.setSheetCoordinator(GenericCallLinkCoordinator(parameters: .init(url: url)), animated: animated)
case .oidcCallback:
break
case .settings, .chatBackupSettings:
settingsFlowCoordinator.handleAppRoute(appRoute, animated: animated)
}
}
}
@@ -193,7 +221,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
break
case (.roomList, .showSettingsScreen, .settingsScreen):
presentSettingsScreen(animated: animated)
break
case (.settingsScreen, .dismissedSettingsScreen, .roomList):
break
@@ -211,7 +239,12 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
presentInvitesList(animated: animated)
case (.invitesScreen, .showInvitesScreen, .invitesScreen):
break
case (.invitesScreen, .closedInvitesScreen, .roomList):
case (.invitesScreen, .dismissedInvitesScreen, .roomList):
break
case (.roomList, .showLogoutConfirmationScreen, .logoutConfirmationScreen):
presentSecureBackupConfirmationScreen()
case (.logoutConfirmationScreen, .dismissedLogoutConfirmationScreen, .roomList):
break
default:
@@ -288,15 +321,15 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
roomFlowCoordinator.handleAppRoute(.roomList, animated: true)
}
case .presentSettingsScreen:
stateMachine.processEvent(.showSettingsScreen)
settingsFlowCoordinator.handleAppRoute(.settings, animated: true)
case .presentFeedbackScreen:
stateMachine.processEvent(.feedbackScreen)
case .presentSessionVerificationScreen:
stateMachine.processEvent(.showSessionVerificationScreen)
case .presentStartChatScreen:
stateMachine.processEvent(.showStartChatScreen)
case .signOut:
actionsSubject.send(.signOut)
case .logout:
runLogoutFlow()
case .presentInvitesScreen:
stateMachine.processEvent(.showInvitesScreen)
}
@@ -321,44 +354,44 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
}
}
// MARK: Settings
private func presentSettingsScreen(animated: Bool) {
let settingsNavigationStackCoordinator = NavigationStackCoordinator()
private func runLogoutFlow() {
let secureBackupController = userSession.clientProxy.secureBackupController
let userIndicatorController = UserIndicatorController(rootCoordinator: settingsNavigationStackCoordinator)
let parameters = SettingsScreenCoordinatorParameters(navigationStackCoordinator: settingsNavigationStackCoordinator,
userIndicatorController: userIndicatorController,
userSession: userSession,
appLockService: appLockService,
bugReportService: bugReportService,
notificationSettings: userSession.clientProxy.notificationSettings,
secureBackupController: userSession.clientProxy.secureBackupController,
appSettings: appSettings)
let settingsScreenCoordinator = SettingsScreenCoordinator(parameters: parameters)
settingsScreenCoordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .dismiss:
navigationSplitCoordinator.setSheetCoordinator(nil)
case .logout:
navigationSplitCoordinator.setSheetCoordinator(nil)
actionsSubject.send(.signOut)
case .clearCache:
actionsSubject.send(.clearCache)
}
}
.store(in: &cancellables)
settingsNavigationStackCoordinator.setRootCoordinator(settingsScreenCoordinator, animated: animated)
navigationSplitCoordinator.setSheetCoordinator(userIndicatorController) { [weak self] in
self?.stateMachine.processEvent(.dismissedSettingsScreen)
guard secureBackupController.isLastSession, appSettings.chatBackupEnabled else {
ServiceLocator.shared.userIndicatorController.alertInfo = .init(id: .init(),
title: L10n.screenSignoutRecoveryDisabledTitle,
message: L10n.screenSignoutRecoveryDisabledSubtitle,
primaryButton: .init(title: L10n.screenSignoutConfirmationDialogSubmit, role: .destructive) { [weak self] in
self?.actionsSubject.send(.logout)
})
return
}
guard secureBackupController.recoveryKeyState.value == .enabled else {
ServiceLocator.shared.userIndicatorController.alertInfo = .init(id: .init(),
title: L10n.screenSignoutRecoveryDisabledTitle,
message: L10n.screenSignoutRecoveryDisabledSubtitle,
primaryButton: .init(title: L10n.screenSignoutConfirmationDialogSubmit, role: .destructive) { [weak self] in
self?.actionsSubject.send(.logout)
}, secondaryButton: .init(title: L10n.commonSettings, role: .cancel) { [weak self] in
self?.settingsFlowCoordinator.handleAppRoute(.chatBackupSettings, animated: true)
})
return
}
guard secureBackupController.keyBackupState.value == .enabled else {
ServiceLocator.shared.userIndicatorController.alertInfo = .init(id: .init(),
title: L10n.screenSignoutKeyBackupDisabledTitle,
message: L10n.screenSignoutKeyBackupDisabledSubtitle,
primaryButton: .init(title: L10n.screenSignoutConfirmationDialogSubmit, role: .destructive) { [weak self] in
self?.actionsSubject.send(.logout)
}, secondaryButton: .init(title: L10n.commonSettings, role: .cancel) { [weak self] in
self?.settingsFlowCoordinator.handleAppRoute(.chatBackupSettings, animated: true)
})
return
}
presentSecureBackupConfirmationScreen()
}
// MARK: Session verification
@@ -457,7 +490,7 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
.store(in: &cancellables)
sidebarNavigationStackCoordinator.push(coordinator, animated: animated) { [weak self] in
self?.stateMachine.processEvent(.closedInvitesScreen)
self?.stateMachine.processEvent(.dismissedInvitesScreen)
}
}
@@ -479,4 +512,28 @@ class UserSessionFlowCoordinator: FlowCoordinatorProtocol {
navigationSplitCoordinator.setSheetCoordinator(callScreenCoordinator, animated: true)
}
// MARK: Secure backup confirmation
private func presentSecureBackupConfirmationScreen() {
let coordinator = SecureBackupLogoutConfirmationScreenCoordinator(parameters: .init(secureBackupController: userSession.clientProxy.secureBackupController,
networkMonitor: ServiceLocator.shared.networkMonitor))
coordinator.actions
.sink { [weak self] action in
guard let self else { return }
switch action {
case .cancel:
navigationSplitCoordinator.setSheetCoordinator(nil)
case .settings:
settingsFlowCoordinator.handleAppRoute(.chatBackupSettings, animated: true)
case .logout:
actionsSubject.send(.logout)
}
}
.store(in: &cancellables)
navigationSplitCoordinator.setSheetCoordinator(coordinator, animated: true)
}
}
@@ -46,6 +46,9 @@ class UserSessionFlowCoordinatorStateMachine {
/// Showing invites list screen
case invitesScreen(selectedRoomID: String?)
// Showing the logout flows
case logoutConfirmationScreen(selectedRoomID: String?)
}
struct EventUserInfo {
@@ -100,7 +103,12 @@ class UserSessionFlowCoordinatorStateMachine {
/// Request presentation of the invites screen
case showInvitesScreen
/// The invites screen has been dismissed
case closedInvitesScreen
case dismissedInvitesScreen
/// Logout has been requested and this is the last sesion
case showLogoutConfirmationScreen
/// Logout has been cancelled
case dismissedLogoutConfirmationScreen
}
private let stateMachine: StateMachine<State, Event>
@@ -157,12 +165,17 @@ class UserSessionFlowCoordinatorStateMachine {
case (.showInvitesScreen, .invitesScreen(let selectedRoomID)):
return .invitesScreen(selectedRoomID: selectedRoomID)
case (.closedInvitesScreen, .invitesScreen(let selectedRoomID)):
case (.dismissedInvitesScreen, .invitesScreen(let selectedRoomID)):
return .roomList(selectedRoomID: selectedRoomID)
case (.presentWelcomeScreen, .roomList):
return .welcomeScreen
case (.showLogoutConfirmationScreen, .roomList(let selectedRoomID)):
return .logoutConfirmationScreen(selectedRoomID: selectedRoomID)
case (.dismissedLogoutConfirmationScreen, .logoutConfirmationScreen(let selectedRoomID)):
return .roomList(selectedRoomID: selectedRoomID)
default:
return nil
}
@@ -984,6 +984,24 @@ class MediaPlayerProviderMock: MediaPlayerProviderProtocol {
await detachAllStatesExceptClosure?(exception)
}
}
class NetworkMonitorMock: NetworkMonitorProtocol {
var reachabilityPublisher: CurrentValuePublisher<NetworkMonitorReachability, Never> {
get { return underlyingReachabilityPublisher }
set(value) { underlyingReachabilityPublisher = value }
}
var underlyingReachabilityPublisher: CurrentValuePublisher<NetworkMonitorReachability, Never>!
var isCurrentConnectionExpensive: Bool {
get { return underlyingIsCurrentConnectionExpensive }
set(value) { underlyingIsCurrentConnectionExpensive = value }
}
var underlyingIsCurrentConnectionExpensive: Bool!
var isCurrentConnectionConstrained: Bool {
get { return underlyingIsCurrentConnectionConstrained }
set(value) { underlyingIsCurrentConnectionConstrained = value }
}
var underlyingIsCurrentConnectionConstrained: Bool!
}
class NotificationCenterMock: NotificationCenterProtocol {
//MARK: - post
@@ -2400,6 +2418,11 @@ class SecureBackupControllerMock: SecureBackupControllerProtocol {
set(value) { underlyingKeyBackupState = value }
}
var underlyingKeyBackupState: CurrentValuePublisher<SecureBackupKeyBackupState, Never>!
var isLastSession: Bool {
get { return underlyingIsLastSession }
set(value) { underlyingIsLastSession = value }
}
var underlyingIsLastSession: Bool!
//MARK: - enableBackup
@@ -2473,6 +2496,18 @@ class SecureBackupControllerMock: SecureBackupControllerProtocol {
return confirmRecoveryKeyReturnValue
}
}
//MARK: - waitForKeyBackup
var waitForKeyBackupCallsCount = 0
var waitForKeyBackupCalled: Bool {
return waitForKeyBackupCallsCount > 0
}
var waitForKeyBackupClosure: (() async -> Void)?
func waitForKeyBackup() async {
waitForKeyBackupCallsCount += 1
await waitForKeyBackupClosure?()
}
}
class SessionVerificationControllerProxyMock: SessionVerificationControllerProxyProtocol {
var callbacks: PassthroughSubject<SessionVerificationControllerProxyCallback, Never> {
@@ -26,3 +26,6 @@ protocol NetworkMonitorProtocol {
var isCurrentConnectionExpensive: Bool { get }
var isCurrentConnectionConstrained: Bool { get }
}
// sourcery: AutoMockable
extension NetworkMonitorProtocol { }
@@ -34,7 +34,7 @@ enum HomeScreenCoordinatorAction {
case presentSessionVerificationScreen
case presentStartChatScreen
case presentInvitesScreen
case signOut
case logout
}
final class HomeScreenCoordinator: CoordinatorProtocol {
@@ -75,8 +75,8 @@ final class HomeScreenCoordinator: CoordinatorProtocol {
actionsSubject.send(.presentSettingsScreen)
case .presentSessionVerificationScreen:
actionsSubject.send(.presentSessionVerificationScreen)
case .signOut:
actionsSubject.send(.signOut)
case .logout:
actionsSubject.send(.logout)
case .presentStartChatScreen:
actionsSubject.send(.presentStartChatScreen)
case .presentInvitesScreen:
@@ -27,13 +27,13 @@ enum HomeScreenViewModelAction {
case presentFeedbackScreen
case presentStartChatScreen
case presentInvitesScreen
case signOut
case logout
}
enum HomeScreenViewUserMenuAction {
case settings
case feedback
case signOut
case logout
}
enum HomeScreenViewAction {
@@ -138,8 +138,8 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
actionsSubject.send(.presentFeedbackScreen)
case .settings:
actionsSubject.send(.presentSettingsScreen)
case .signOut:
actionsSubject.send(.signOut)
case .logout:
actionsSubject.send(.logout)
}
case .verifySession:
actionsSubject.send(.presentSessionVerificationScreen)
@@ -18,7 +18,6 @@ import Compound
import SwiftUI
struct HomeScreenUserMenuButton: View {
@State private var showingLogoutConfirmation = false
@Environment(\.colorScheme) var colorScheme
@ObservedObject var context: HomeScreenViewModel.Context
@@ -53,7 +52,7 @@ struct HomeScreenUserMenuButton: View {
}
Section {
Button(role: .destructive) {
showingLogoutConfirmation = true
context.send(viewAction: .userMenu(action: .logout))
} label: {
Label(L10n.screenSignoutPreferenceItem, systemImage: "rectangle.portrait.and.arrow.right")
}
@@ -68,15 +67,6 @@ struct HomeScreenUserMenuButton: View {
.overlayBadge(10, isBadged: context.viewState.showUserMenuBadge)
.compositingGroup()
}
.alert(L10n.screenSignoutConfirmationDialogTitle,
isPresented: $showingLogoutConfirmation) {
Button(L10n.screenSignoutConfirmationDialogSubmit,
role: .destructive) {
context.send(viewAction: .userMenu(action: .signOut))
}
} message: {
Text(L10n.screenSignoutConfirmationDialogContent)
}
.accessibilityLabel(L10n.a11yUserMenu)
}
}
@@ -24,7 +24,7 @@ struct EncryptedHistoryRoomTimelineView: View {
var body: some View {
Label {
Text(L10n.screenRoomEncryptedHistoryBanner)
Text(title)
.font(.compound.bodyMDSemibold)
.foregroundColor(.compound.textInfoPrimary)
} icon: {
@@ -43,6 +43,10 @@ struct EncryptedHistoryRoomTimelineView: View {
.padding(.horizontal, 8)
.padding(.vertical, 16)
}
private var title: String {
timelineItem.isSessionVerified ? L10n.screenRoomEncryptedHistoryBanner : L10n.screenRoomEncryptedHistoryBannerUnverified
}
}
private struct EncryptedHistoryLabelStyle: LabelStyle {
@@ -56,7 +60,9 @@ private struct EncryptedHistoryLabelStyle: LabelStyle {
struct EncryptedHistoryRoomTimelineView_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
let item = EncryptedHistoryRoomTimelineItem(id: .random)
EncryptedHistoryRoomTimelineView(timelineItem: item)
VStack {
EncryptedHistoryRoomTimelineView(timelineItem: .init(id: .random, isSessionVerified: true))
EncryptedHistoryRoomTimelineView(timelineItem: .init(id: .random, isSessionVerified: false))
}
}
}
@@ -21,8 +21,6 @@ import SwiftUI
struct SecureBackupKeyBackupScreen: View {
@ObservedObject var context: SecureBackupKeyBackupScreenViewModel.Context
@ScaledMetric private var iconSize = 70
var body: some View {
mainContent
.padding()
@@ -0,0 +1,69 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Combine
import SwiftUI
struct SecureBackupLogoutConfirmationScreenCoordinatorParameters {
let secureBackupController: SecureBackupControllerProtocol
let networkMonitor: NetworkMonitorProtocol
}
enum SecureBackupLogoutConfirmationScreenCoordinatorAction {
case cancel
case settings
case logout
}
final class SecureBackupLogoutConfirmationScreenCoordinator: CoordinatorProtocol {
private let parameters: SecureBackupLogoutConfirmationScreenCoordinatorParameters
private var viewModel: SecureBackupLogoutConfirmationScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<SecureBackupLogoutConfirmationScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<SecureBackupLogoutConfirmationScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SecureBackupLogoutConfirmationScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SecureBackupLogoutConfirmationScreenViewModel(secureBackupController: parameters.secureBackupController,
networkMonitor: parameters.networkMonitor)
}
func start() {
viewModel.actions.sink { [weak self] action in
guard let self else { return }
MXLog.info("Coordinator: received view model action: \(action)")
switch action {
case .cancel:
actionsSubject.send(.cancel)
case .settings:
actionsSubject.send(.settings)
case .logout:
actionsSubject.send(.logout)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(SecureBackupLogoutConfirmationScreen(context: viewModel.context))
}
}
@@ -0,0 +1,39 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Foundation
enum SecureBackupLogoutConfirmationScreenViewModelAction {
case cancel
case settings
case logout
}
enum SecureBackupLogoutConfirmationScreenViewMode {
case saveRecoveryKey
case backupOngoing
case offline
}
struct SecureBackupLogoutConfirmationScreenViewState: BindableState {
var mode: SecureBackupLogoutConfirmationScreenViewMode
}
enum SecureBackupLogoutConfirmationScreenViewAction {
case cancel
case settings
case logout
}
@@ -0,0 +1,90 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Combine
import SwiftUI
typealias SecureBackupLogoutConfirmationScreenViewModelType = StateStoreViewModel<SecureBackupLogoutConfirmationScreenViewState, SecureBackupLogoutConfirmationScreenViewAction>
class SecureBackupLogoutConfirmationScreenViewModel: SecureBackupLogoutConfirmationScreenViewModelType, SecureBackupLogoutConfirmationScreenViewModelProtocol {
private let secureBackupController: SecureBackupControllerProtocol
private let networkMonitor: NetworkMonitorProtocol
@CancellableTask
private var keyUploadWaitingTask: Task<Void, Never>?
private var actionsSubject: PassthroughSubject<SecureBackupLogoutConfirmationScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<SecureBackupLogoutConfirmationScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(secureBackupController: SecureBackupControllerProtocol, networkMonitor: NetworkMonitorProtocol) {
self.secureBackupController = secureBackupController
self.networkMonitor = networkMonitor
super.init(initialViewState: .init(mode: .saveRecoveryKey))
networkMonitor.reachabilityPublisher
.receive(on: DispatchQueue.main)
.sink { [weak self] reachability in
guard let self,
state.mode != .saveRecoveryKey else {
return
}
if reachability == .reachable {
state.mode = .backupOngoing
} else {
state.mode = .offline
}
}
.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: SecureBackupLogoutConfirmationScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .cancel:
keyUploadWaitingTask = nil
actionsSubject.send(.cancel)
case .settings:
actionsSubject.send(.settings)
case .logout:
attemptLogout()
}
}
// MARK: - Private
private func attemptLogout() {
if state.mode == .saveRecoveryKey {
state.mode = networkMonitor.reachabilityPublisher.value == .reachable ? .backupOngoing : .offline
keyUploadWaitingTask = Task {
await secureBackupController.waitForKeyBackup()
guard !Task.isCancelled else { return }
actionsSubject.send(.logout)
}
} else {
actionsSubject.send(.logout)
}
}
}
@@ -0,0 +1,23 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Combine
@MainActor
protocol SecureBackupLogoutConfirmationScreenViewModelProtocol {
var actions: AnyPublisher<SecureBackupLogoutConfirmationScreenViewModelAction, Never> { get }
var context: SecureBackupLogoutConfirmationScreenViewModelType.Context { get }
}
@@ -0,0 +1,134 @@
//
// Copyright 2022 New Vector Ltd
//
// 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 Combine
import Compound
import SwiftUI
struct SecureBackupLogoutConfirmationScreen: View {
@ObservedObject var context: SecureBackupLogoutConfirmationScreenViewModel.Context
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 16) {
header
content
}
.padding()
}
.toolbar { toolbar }
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.safeAreaInset(edge: .bottom) { footer.padding() }
}
}
@ViewBuilder
private var header: some View {
HeroImage(image: Image(asset: Asset.Images.secureBackupOff))
}
@ViewBuilder
private var content: some View {
Text(title)
.foregroundColor(.compound.textPrimary)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
Text(subtitle)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
if context.viewState.mode == .backupOngoing {
Spacer()
ProgressView()
}
}
@ViewBuilder
private var footer: some View {
if context.viewState.mode == .saveRecoveryKey {
Button {
context.send(viewAction: .settings)
} label: {
Text(L10n.commonSettings)
}
.buttonStyle(.compound(.primary))
}
Button(role: .destructive) {
context.send(viewAction: .logout)
} label: {
Text(L10n.actionSignout)
}
.buttonStyle(.compound(.primary))
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
}
var title: String {
switch context.viewState.mode {
case .saveRecoveryKey:
return L10n.screenSignoutSaveRecoveryKeyTitle
case .backupOngoing:
return L10n.screenSignoutKeyBackupOngoingTitle
case .offline:
return L10n.screenSignoutKeyBackupOfflineTitle
}
}
var subtitle: String {
switch context.viewState.mode {
case .saveRecoveryKey:
return L10n.screenSignoutSaveRecoveryKeySubtitle
case .backupOngoing:
return L10n.screenSignoutKeyBackupOngoingSubtitle
case .offline:
return L10n.screenSignoutKeyBackupOfflineSubtitle
}
}
}
// MARK: - Previews
struct SecureBackupLogoutConfirmationScreen_Previews: PreviewProvider, TestablePreview {
static let viewModel = buildViewModel()
static var previews: some View {
NavigationStack {
SecureBackupLogoutConfirmationScreen(context: viewModel.context)
}
}
static func buildViewModel() -> SecureBackupLogoutConfirmationScreenViewModelType {
let secureBackupController = SecureBackupControllerMock()
secureBackupController.underlyingKeyBackupState = CurrentValueSubject<SecureBackupKeyBackupState, Never>(.enabled).asCurrentValuePublisher()
let networkMonitor = NetworkMonitorMock()
networkMonitor.underlyingReachabilityPublisher = CurrentValueSubject<NetworkMonitorReachability, Never>(.reachable).asCurrentValuePublisher()
return SecureBackupLogoutConfirmationScreenViewModel(secureBackupController: secureBackupController,
networkMonitor: networkMonitor)
}
}
@@ -21,8 +21,6 @@ import SwiftUI
struct SecureBackupRecoveryKeyScreen: View {
@ObservedObject var context: SecureBackupRecoveryKeyScreenViewModel.Context
@ScaledMetric private var iconSize = 70
var body: some View {
mainContent
.padding()
@@ -32,6 +32,7 @@ enum SettingsScreenCoordinatorAction {
case dismiss
case logout
case clearCache
case secureBackup
}
final class SettingsScreenCoordinator: CoordinatorProtocol {
@@ -75,7 +76,7 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
case .sessionVerification:
presentSessionVerificationScreen()
case .secureBackup:
presentSecureBackupScreen()
actionsSubject.send(.secureBackup)
case .accountSessionsList:
presentAccountSessionsListURL()
case .notifications:
@@ -200,15 +201,6 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
}
}
private func presentSecureBackupScreen() {
let coordinator = SecureBackupScreenCoordinator(parameters: .init(appSettings: parameters.appSettings,
secureBackupController: parameters.userSession.clientProxy.secureBackupController,
navigationStackCoordinator: parameters.navigationStackCoordinator,
userIndicatorController: parameters.userIndicatorController))
parameters.navigationStackCoordinator?.push(coordinator)
}
private func presentNotificationSettings() {
let notificationParameters = NotificationSettingsScreenCoordinatorParameters(navigationStackCoordinator: parameters.navigationStackCoordinator,
userSession: parameters.userSession,
@@ -19,8 +19,6 @@ import SFSafeSymbols
import SwiftUI
struct SettingsScreen: View {
@State private var showingLogoutConfirmation = false
@ObservedObject var context: SettingsScreenViewModel.Context
var body: some View {
@@ -196,16 +194,9 @@ struct SettingsScreen: View {
ListRow(label: .default(title: L10n.screenSignoutPreferenceItem,
systemIcon: .rectanglePortraitAndArrowRight),
kind: .button {
showingLogoutConfirmation = true
context.send(viewAction: .logout)
})
.accessibilityIdentifier(A11yIdentifiers.settingsScreen.logout)
.alert(L10n.screenSignoutConfirmationDialogTitle, isPresented: $showingLogoutConfirmation) {
Button(L10n.screenSignoutConfirmationDialogSubmit, role: .destructive) {
context.send(viewAction: .logout)
}
} message: {
Text(L10n.screenSignoutConfirmationDialogContent)
}
} footer: {
VStack {
versionText
@@ -29,6 +29,11 @@ class SecureBackupController: SecureBackupControllerProtocol {
keyBackupStateSubject.asCurrentValuePublisher()
}
var isLastSession: Bool {
#warning("FIXME")
return true
}
func enableBackup() async -> Result<Void, SecureBackupControllerError> {
keyBackupStateSubject.send(.enabling)
@@ -76,4 +81,8 @@ class SecureBackupController: SecureBackupControllerProtocol {
return .success(())
}
func waitForKeyBackup() async {
try? await Task.sleep(for: .seconds(5))
}
}
@@ -49,11 +49,15 @@ protocol SecureBackupControllerProtocol {
var keyBackupState: CurrentValuePublisher<SecureBackupKeyBackupState, Never> { get }
var isLastSession: Bool { get }
func enableBackup() async -> Result<Void, SecureBackupControllerError>
func disableBackup() async -> Result<Void, SecureBackupControllerError>
func generateRecoveryKey() async -> Result<String, SecureBackupControllerError>
func confirmRecoveryKey(_ key: String) async -> Result<Void, SecureBackupControllerError>
func waitForKeyBackup() async
}
extension SecureBackupControllerMock {
@@ -17,11 +17,13 @@
import Foundation
struct MockRoomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol {
// swiftlint:disable:next function_parameter_count
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
mediaProvider: MediaProviderProtocol,
mediaPlayerProvider: MediaPlayerProviderProtocol,
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol) -> RoomTimelineControllerProtocol {
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol {
let timelineController = MockRoomTimelineController()
timelineController.timelineItems = RoomTimelineItemFixtures.largeChunk
return timelineController
@@ -26,6 +26,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
private let mediaPlayerProvider: MediaPlayerProviderProtocol
private let voiceMessageMediaManager: VoiceMessageMediaManagerProtocol
private let appSettings: AppSettings
private let secureBackupController: SecureBackupControllerProtocol
private let serialDispatchQueue: DispatchQueue
private var cancellables = Set<AnyCancellable>()
@@ -48,7 +49,8 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
mediaProvider: MediaProviderProtocol,
mediaPlayerProvider: MediaPlayerProviderProtocol,
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol,
appSettings: AppSettings) {
appSettings: AppSettings,
secureBackupController: SecureBackupControllerProtocol) {
self.roomProxy = roomProxy
timelineProvider = roomProxy.timelineProvider
self.timelineItemFactory = timelineItemFactory
@@ -56,6 +58,7 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
self.mediaPlayerProvider = mediaPlayerProvider
self.voiceMessageMediaManager = voiceMessageMediaManager
self.appSettings = appSettings
self.secureBackupController = secureBackupController
serialDispatchQueue = DispatchQueue(label: "io.element.elementx.roomtimelineprovider", qos: .utility)
timelineProvider
@@ -442,8 +445,14 @@ class RoomTimelineController: RoomTimelineControllerProtocol {
case .event(let eventTimelineItem):
let timelineItem = timelineItemFactory.buildTimelineItem(for: eventTimelineItem)
if timelineItem is EncryptedRoomTimelineItem, isItemInEncryptionHistory(eventTimelineItem) {
return EncryptedHistoryRoomTimelineItem(id: eventTimelineItem.id)
// When backup is enabled just show the timeline items, they will most likely
// resolve eventually. If we don't know the backup state then we assume the session is not verified yet,
// otherwise we just treat it as fully disabled.
if secureBackupController.keyBackupState.value != .enabled {
if timelineItem is EncryptedRoomTimelineItem, isItemInEncryptionHistory(eventTimelineItem) {
return EncryptedHistoryRoomTimelineItem(id: eventTimelineItem.id,
isSessionVerified: secureBackupController.keyBackupState.value != .unknown)
}
}
if let messageTimelineItem = timelineItem as? EventBasedMessageTimelineItemProtocol {
@@ -17,16 +17,19 @@
import Foundation
struct RoomTimelineControllerFactory: RoomTimelineControllerFactoryProtocol {
// swiftlint:disable:next function_parameter_count
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
mediaProvider: MediaProviderProtocol,
mediaPlayerProvider: MediaPlayerProviderProtocol,
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol) -> RoomTimelineControllerProtocol {
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol {
RoomTimelineController(roomProxy: roomProxy,
timelineItemFactory: timelineItemFactory,
mediaProvider: mediaProvider,
mediaPlayerProvider: mediaPlayerProvider,
voiceMessageMediaManager: voiceMessageMediaManager,
appSettings: ServiceLocator.shared.settings)
appSettings: ServiceLocator.shared.settings,
secureBackupController: secureBackupController)
}
}
@@ -18,9 +18,11 @@ import Foundation
@MainActor
protocol RoomTimelineControllerFactoryProtocol {
// swiftlint:disable:next function_parameter_count
func buildRoomTimelineController(roomProxy: RoomProxyProtocol,
timelineItemFactory: RoomTimelineItemFactoryProtocol,
mediaProvider: MediaProviderProtocol,
mediaPlayerProvider: MediaPlayerProviderProtocol,
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol) -> RoomTimelineControllerProtocol
voiceMessageMediaManager: VoiceMessageMediaManagerProtocol,
secureBackupController: SecureBackupControllerProtocol) -> RoomTimelineControllerProtocol
}
@@ -18,4 +18,5 @@ import Foundation
struct EncryptedHistoryRoomTimelineItem: DecorationTimelineItemProtocol, Equatable {
let id: TimelineItemIdentifier
let isSessionVerified: Bool
}
@@ -169,7 +169,7 @@ struct RoomTimelineItemFactory: RoomTimelineItemFactoryProtocol {
}
return EncryptedRoomTimelineItem(id: eventItemProxy.id,
body: L10n.commonUnableToDecrypt,
body: L10n.commonWaitingForDecryptionKey,
encryptionType: encryptionType,
timestamp: eventItemProxy.timestamp.formatted(date: .omitted, time: .shortened),
isOutgoing: isOutgoing,