#1899, #1900, #1901 - Implement chat backup setting screens

This commit is contained in:
Stefan Ceriu
2023-10-19 15:34:10 +03:00
committed by GitHub
parent 15b5b44422
commit c8b9d95122
70 changed files with 2293 additions and 48 deletions
@@ -42,7 +42,7 @@ struct AnalyticsPromptScreen: View {
private var header: some View {
VStack(spacing: 8) {
AuthenticationIconImage(image: Image(systemName: "chart.bar"))
HeroImage(image: Image(systemName: "chart.bar"))
.symbolVariant(.fill)
.padding(.bottom, 8)
@@ -25,7 +25,7 @@ struct AppLockScreen: View {
var body: some View {
FullscreenDialog {
VStack(spacing: 8) {
AuthenticationIconImage(image: Image(systemSymbol: .lock))
HeroImage(image: Image(systemSymbol: .lock))
.symbolVariant(.fill)
.padding(.bottom, 8)
@@ -1,51 +0,0 @@
//
// 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 SwiftUI
/// An image that is styled for use as the screen icon in the onboarding flow.
struct AuthenticationIconImage: View {
/// The icon that is shown.
let image: Image
/// The amount of padding between the icon and the borders. Defaults to 16.
var insets: CGFloat = 16
var body: some View {
image
.resizable()
.renderingMode(.template)
.foregroundColor(.compound.iconSecondary)
.aspectRatio(contentMode: .fit)
.accessibilityHidden(true)
.padding(insets)
.frame(width: 70, height: 70)
.background {
RoundedRectangle(cornerRadius: 14)
.fill(Color.compound.bgSubtleSecondary)
}
}
}
// MARK: - Previews
struct AuthenticationIconImage_Previews: PreviewProvider, TestablePreview {
static var previews: some View {
HStack(spacing: 20) {
AuthenticationIconImage(image: Image(asset: Asset.Images.serverSelectionIcon), insets: 19)
AuthenticationIconImage(image: Image(systemName: "hourglass"))
}
}
}
@@ -52,7 +52,7 @@ struct LoginScreen: View {
/// The header containing the title and icon.
var header: some View {
VStack(spacing: 8) {
AuthenticationIconImage(image: Image(systemName: "lock.fill"))
HeroImage(image: Image(systemName: "lock.fill"))
.padding(.bottom, 8)
Text(L10n.screenLoginTitleWithHomeserver(context.viewState.homeserver.address))
@@ -35,7 +35,7 @@ struct ServerConfirmationScreen: View {
/// The main content of the view to be shown in a scroll view.
var header: some View {
VStack(spacing: 8) {
AuthenticationIconImage(image: Image(systemName: "person.crop.circle.fill"))
HeroImage(image: Image(systemName: "person.crop.circle.fill"))
.padding(.bottom, 8)
Text(context.viewState.title)
@@ -40,7 +40,7 @@ struct ServerSelectionScreen: View {
/// The title, message and icon at the top of the screen.
var header: some View {
VStack(spacing: 8) {
AuthenticationIconImage(image: Image(asset: Asset.Images.serverSelectionIcon), insets: 19)
HeroImage(image: Image(asset: Asset.Images.serverSelectionIcon), insets: 19)
.padding(.bottom, 8)
Text(L10n.screenChangeServerTitle)
@@ -71,6 +71,8 @@ struct HomeScreenViewState: BindableState {
var userDisplayName: String?
var userAvatarURL: URL?
var showSessionVerificationBanner = false
var showUserMenuBadge = false
var showSettingsMenuOptionBadge = false
var rooms: [HomeScreenRoom] = []
var roomListMode: HomeScreenRoomListMode = .skeletons
@@ -53,7 +53,7 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
roomSummaryProvider = userSession.clientProxy.roomSummaryProvider
inviteSummaryProvider = userSession.clientProxy.inviteSummaryProvider
super.init(initialViewState: HomeScreenViewState(userID: userSession.userID),
super.init(initialViewState: .init(userID: userSession.userID),
imageProvider: userSession.mediaProvider)
userSession.callbacks
@@ -80,6 +80,19 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
.weakAssign(to: \.state.userDisplayName, on: self)
.store(in: &cancellables)
userSession.clientProxy.secureBackupController.recoveryKeyState
.receive(on: DispatchQueue.main)
.map { state in
state == .unknown || state == .disabled
}
.sink { [weak self] requiresSecureBackupSetup in
guard let self else { return }
state.showUserMenuBadge = requiresSecureBackupSetup && appSettings.chatBackupEnabled
state.showSettingsMenuOptionBadge = requiresSecureBackupSetup && appSettings.chatBackupEnabled
}
.store(in: &cancellables)
selectedRoomPublisher
.weakAssign(to: \.state.selectedRoomID, on: self)
.store(in: &cancellables)
@@ -18,6 +18,7 @@ import SwiftUI
struct HomeScreenUserMenuButton: View {
@State private var showingLogoutConfirmation = false
@Environment(\.colorScheme) var colorScheme
@ObservedObject var context: HomeScreenViewModel.Context
@@ -27,7 +28,11 @@ struct HomeScreenUserMenuButton: View {
Button {
context.send(viewAction: .userMenu(action: .settings))
} label: {
Label(L10n.commonSettings, systemImage: "gearshape")
Label {
Text(L10n.commonSettings)
} icon: {
settingsIconImage
}
}
.accessibilityIdentifier(A11yIdentifiers.homeScreen.settings)
}
@@ -55,6 +60,8 @@ struct HomeScreenUserMenuButton: View {
avatarSize: .user(on: .home),
imageProvider: context.imageProvider)
.accessibilityIdentifier(A11yIdentifiers.homeScreen.userAvatar)
.overlayBadge(10, isBadged: context.viewState.showUserMenuBadge)
.compositingGroup()
}
.alert(L10n.screenSignoutConfirmationDialogTitle,
isPresented: $showingLogoutConfirmation) {
@@ -67,4 +74,24 @@ struct HomeScreenUserMenuButton: View {
}
.accessibilityLabel(L10n.a11yUserMenu)
}
// MARK: - Private
/// Menu doesn't render composed views. Trick it into showing a badge.
private var settingsIconImage: Image? {
let settingsIcon = Image(systemSymbol: .gearshape)
.resizable()
.frame(width: 100, height: 100)
.overlayBadge(40, isBadged: context.viewState.showSettingsMenuOptionBadge)
.colorScheme(colorScheme)
.padding()
let renderer = ImageRenderer(content: settingsIcon)
guard let image = renderer.uiImage else {
return nil
}
return Image(uiImage: image)
}
}
@@ -88,7 +88,7 @@ class RoomDetailsEditScreenViewModel: RoomDetailsEditScreenViewModelType, RoomDe
case .success(.image):
state.localMedia = try? mediaResult.get()
case .failure, .success:
userIndicatorController?.alertInfo = .init(id: .init(), title: L10n.commonError, message: L10n.errorUnknown)
userIndicatorController?.alertInfo = .init(id: .init())
}
}
}
@@ -0,0 +1,62 @@
//
// 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 SecureBackupKeyBackupScreenCoordinatorParameters {
let secureBackupController: SecureBackupControllerProtocol
weak var userIndicatorController: UserIndicatorControllerProtocol?
}
enum SecureBackupKeyBackupScreenCoordinatorAction {
case done
}
final class SecureBackupKeyBackupScreenCoordinator: CoordinatorProtocol {
private let parameters: SecureBackupKeyBackupScreenCoordinatorParameters
private var viewModel: SecureBackupKeyBackupScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<SecureBackupKeyBackupScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<SecureBackupKeyBackupScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SecureBackupKeyBackupScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SecureBackupKeyBackupScreenViewModel(secureBackupController: parameters.secureBackupController,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actions.sink { [weak self] action in
MXLog.info("Coordinator: received view model action: \(action)")
guard let self else { return }
switch action {
case .done:
self.actionsSubject.send(.done)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(SecureBackupKeyBackupScreen(context: viewModel.context))
}
}
@@ -0,0 +1,41 @@
//
// 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 SecureBackupKeyBackupScreenViewModelAction {
case done
}
enum SecureBackupKeyBackupScreenViewMode {
case disableBackup
}
struct SecureBackupKeyBackupScreenViewState: BindableState {
let mode: SecureBackupKeyBackupScreenViewMode
var bindings = SecureBackupKeyBackupScreenViewStateBindings()
}
struct SecureBackupKeyBackupScreenViewStateBindings {
var alertInfo: AlertInfo<UUID>?
}
var alertInfo: AlertInfo<UUID>?
enum SecureBackupKeyBackupScreenViewAction {
case cancel
case toggleBackup
}
@@ -0,0 +1,107 @@
//
// 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 SecureBackupKeyBackupScreenViewModelType = StateStoreViewModel<SecureBackupKeyBackupScreenViewState, SecureBackupKeyBackupScreenViewAction>
class SecureBackupKeyBackupScreenViewModel: SecureBackupKeyBackupScreenViewModelType, SecureBackupKeyBackupScreenViewModelProtocol {
private let secureBackupController: SecureBackupControllerProtocol
private var actionsSubject: PassthroughSubject<SecureBackupKeyBackupScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<SecureBackupKeyBackupScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(secureBackupController: SecureBackupControllerProtocol, userIndicatorController: UserIndicatorControllerProtocol?) {
self.secureBackupController = secureBackupController
super.init(initialViewState: .init(mode: secureBackupController.keyBackupState.value.viewMode))
secureBackupController.keyBackupState
.receive(on: DispatchQueue.main)
.sink { [weak userIndicatorController] state in
let loadingIndicatorIdentifier = "SecureBackupKeyBackupScreenLoading"
switch state {
case .disabling, .enabling, .unknown:
userIndicatorController?.submitIndicator(.init(id: loadingIndicatorIdentifier, type: .modal, title: L10n.commonLoading, persistent: true))
default:
userIndicatorController?.retractIndicatorWithId(loadingIndicatorIdentifier)
}
}
.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: SecureBackupKeyBackupScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .cancel:
actionsSubject.send(.done)
case .toggleBackup:
guard secureBackupController.keyBackupState.value == .enabled else {
fatalError("Tried disabling backup when not enabled")
}
state.bindings.alertInfo = .init(id: .init(),
title: L10n.screenKeyBackupDisableConfirmationTitle,
message: L10n.screenKeyBackupDisableConfirmationDescription,
primaryButton: .init(title: L10n.screenKeyBackupDisableConfirmationActionTurnOff, role: .destructive) { [weak self] in
self?.disableBackup()
},
secondaryButton: .init(title: L10n.actionCancel, role: .cancel, action: nil))
}
}
// MARK: - Private
private func enableBackup() {
Task {
switch await secureBackupController.enableBackup() {
case .success:
actionsSubject.send(.done)
case .failure(let error):
MXLog.error("Failed enabling key backup with error: \(error)")
state.bindings.alertInfo = .init(id: .init())
}
}
}
private func disableBackup() {
Task {
switch await secureBackupController.disableBackup() {
case .success:
actionsSubject.send(.done)
case .failure(let error):
MXLog.error("Failed disabling key backup with error: \(error)")
state.bindings.alertInfo = .init(id: .init())
}
}
}
}
extension SecureBackupKeyBackupState {
var viewMode: SecureBackupKeyBackupScreenViewMode {
guard self == .enabled else {
fatalError("Invalid key backup state")
}
return .disableBackup
}
}
@@ -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 SecureBackupKeyBackupScreenViewModelProtocol {
var actions: AnyPublisher<SecureBackupKeyBackupScreenViewModelAction, Never> { get }
var context: SecureBackupKeyBackupScreenViewModelType.Context { get }
}
@@ -0,0 +1,117 @@
//
// 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 SecureBackupKeyBackupScreen: View {
@ObservedObject var context: SecureBackupKeyBackupScreenViewModel.Context
@ScaledMetric private var iconSize = 70
var body: some View {
mainContent
.padding()
.interactiveDismissDisabled()
.toolbar { toolbar }
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.alert(item: $context.alertInfo)
}
@ViewBuilder
private var mainContent: some View {
switch context.viewState.mode {
case .disableBackup:
disableBackupSection
}
}
private var disableBackupSection: some View {
VStack(spacing: 16) {
HeroImage(image: Image(asset: Asset.Images.secureBackupOff))
Text(L10n.screenKeyBackupDisableTitle)
.foregroundColor(.compound.textPrimary)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
Text(L10n.screenKeyBackupDisableDescription)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
VStack(alignment: .leading) {
Label {
Text(L10n.screenKeyBackupDisableDescriptionPoint1)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodyMD)
} icon: {
CompoundIcon(\.close)
.foregroundColor(.compound.iconCriticalPrimary)
}
Label {
Text(L10n.screenKeyBackupDisableDescriptionPoint2(InfoPlistReader.main.bundleDisplayName))
.foregroundColor(.compound.textSecondary)
.font(.compound.bodyMD)
} icon: {
CompoundIcon(\.close)
.foregroundColor(.compound.iconCriticalPrimary)
}
}
Spacer()
Button(role: .destructive) {
context.send(viewAction: .toggleBackup)
} label: {
Text(L10n.screenChatBackupKeyBackupActionDisable)
}
.buttonStyle(.compound(.primary))
}
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
}
}
// MARK: - Previews
struct SecureBackupKeyBackupScreen_Previews: PreviewProvider, TestablePreview {
static let setupViewModel = viewModel(keyBackupState: .enabled)
static var previews: some View {
NavigationStack {
SecureBackupKeyBackupScreen(context: setupViewModel.context)
}
.previewDisplayName("Set up")
}
static func viewModel(keyBackupState: SecureBackupKeyBackupState) -> SecureBackupKeyBackupScreenViewModelType {
let backupController = SecureBackupControllerMock()
backupController.underlyingKeyBackupState = CurrentValueSubject<SecureBackupKeyBackupState, Never>(keyBackupState).asCurrentValuePublisher()
return SecureBackupKeyBackupScreenViewModel(secureBackupController: backupController,
userIndicatorController: nil)
}
}
@@ -0,0 +1,74 @@
//
// 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 SecureBackupRecoveryKeyScreenCoordinatorParameters {
let secureBackupController: SecureBackupControllerProtocol
weak var userIndicatorController: UserIndicatorControllerProtocol?
}
enum SecureBackupRecoveryKeyScreenCoordinatorAction {
case cancel
case recoverySetUp
case recoveryChanged
case recoveryFixed
}
final class SecureBackupRecoveryKeyScreenCoordinator: CoordinatorProtocol {
private let parameters: SecureBackupRecoveryKeyScreenCoordinatorParameters
private var viewModel: SecureBackupRecoveryKeyScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<SecureBackupRecoveryKeyScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<SecureBackupRecoveryKeyScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SecureBackupRecoveryKeyScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SecureBackupRecoveryKeyScreenViewModel(secureBackupController: parameters.secureBackupController,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actions.sink { [weak self] action in
MXLog.info("Coordinator: received view model action: \(action)")
guard let self else { return }
switch action {
case .cancel:
self.actionsSubject.send(.cancel)
case .done(let mode):
switch mode {
case .setupRecovery:
self.actionsSubject.send(.recoverySetUp)
case .changeRecovery:
self.actionsSubject.send(.recoveryChanged)
case .fixRecovery:
self.actionsSubject.send(.recoveryFixed)
}
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(SecureBackupRecoveryKeyScreen(context: viewModel.context))
}
}
@@ -0,0 +1,84 @@
//
// 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 SecureBackupRecoveryKeyScreenViewModelAction {
case done(mode: SecureBackupRecoveryKeyScreenViewMode)
case cancel
}
enum SecureBackupRecoveryKeyScreenViewMode {
case setupRecovery
case changeRecovery
case fixRecovery
}
struct SecureBackupRecoveryKeyScreenViewState: BindableState {
let mode: SecureBackupRecoveryKeyScreenViewMode
var recoveryKey: String?
var doneButtonEnabled = false
var bindings: SecureBackupRecoveryKeyScreenViewBindings
var title: String {
switch mode {
case .setupRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeySetupTitle : L10n.screenRecoveryKeySaveTitle
case .changeRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeyChangeTitle : L10n.screenRecoveryKeySaveTitle
case .fixRecovery:
return L10n.screenRecoveryKeyConfirmTitle
}
}
var subtitle: String {
switch mode {
case .setupRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeySetupDescription : L10n.screenRecoveryKeySaveDescription
case .changeRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeyChangeDescription : L10n.screenRecoveryKeySaveDescription
case .fixRecovery:
return L10n.screenRecoveryKeyConfirmDescription
}
}
var recoveryKeySubtitle: String {
switch mode {
case .setupRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeySetupGenerateKeyDescription : L10n.screenRecoveryKeySaveKeyDescription
case .changeRecovery:
return recoveryKey == nil ? L10n.screenRecoveryKeyChangeGenerateKeyDescription : L10n.screenRecoveryKeySaveKeyDescription
case .fixRecovery:
return L10n.screenRecoveryKeyConfirmKeyDescription
}
}
}
struct SecureBackupRecoveryKeyScreenViewBindings {
var confirmationRecoveryKey = ""
var alertInfo: AlertInfo<UUID>?
}
enum SecureBackupRecoveryKeyScreenViewAction {
case generateKey
case copyKey
case keySaved
case confirmKey
case done
case cancel
}
@@ -0,0 +1,111 @@
//
// 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 SecureBackupRecoveryKeyScreenViewModelType = StateStoreViewModel<SecureBackupRecoveryKeyScreenViewState, SecureBackupRecoveryKeyScreenViewAction>
class SecureBackupRecoveryKeyScreenViewModel: SecureBackupRecoveryKeyScreenViewModelType, SecureBackupRecoveryKeyScreenViewModelProtocol {
private let secureBackupController: SecureBackupControllerProtocol
private weak var userIndicatorController: UserIndicatorControllerProtocol?
private var actionsSubject: PassthroughSubject<SecureBackupRecoveryKeyScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<SecureBackupRecoveryKeyScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(secureBackupController: SecureBackupControllerProtocol, userIndicatorController: UserIndicatorControllerProtocol?) {
self.secureBackupController = secureBackupController
self.userIndicatorController = userIndicatorController
super.init(initialViewState: .init(mode: secureBackupController.recoveryKeyState.value.viewMode, bindings: .init()))
secureBackupController.recoveryKeyState
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak userIndicatorController] state in
let loadingIndicatorIdentifier = "SecureBackupRecoveryKeyScreenLoading"
switch state {
case .settingUp:
userIndicatorController?.submitIndicator(.init(id: loadingIndicatorIdentifier, type: .modal, title: L10n.commonLoading, persistent: true))
default:
userIndicatorController?.retractIndicatorWithId(loadingIndicatorIdentifier)
}
})
.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: SecureBackupRecoveryKeyScreenViewAction) {
MXLog.info("View model: received view action: \(viewAction)")
switch viewAction {
case .generateKey:
Task {
switch await secureBackupController.generateRecoveryKey() {
case .success(let key):
state.recoveryKey = key
case .failure(let error):
MXLog.error("Failed generating recovery key with error: \(error)")
state.bindings.alertInfo = .init(id: .init())
}
}
case .copyKey:
UIPasteboard.general.string = state.recoveryKey
userIndicatorController?.submitIndicator(.init(title: "Copied recovery key"))
state.doneButtonEnabled = true
case .keySaved:
state.doneButtonEnabled = true
case .confirmKey:
Task {
switch await secureBackupController.confirmRecoveryKey(state.bindings.confirmationRecoveryKey) {
case .success:
actionsSubject.send(.done(mode: context.viewState.mode))
case .failure(let error):
MXLog.error("Failed confirming recovery key with error: \(error)")
state.bindings.alertInfo = .init(id: .init())
}
}
case .cancel:
actionsSubject.send(.cancel)
case .done:
state.bindings.alertInfo = .init(id: .init(),
title: L10n.screenRecoveryKeySetupConfirmationTitle,
message: L10n.screenRecoveryKeySetupConfirmationDescription,
primaryButton: .init(title: L10n.actionCancel, role: .cancel, action: nil),
secondaryButton: .init(title: L10n.actionContinue, action: { [weak self] in
guard let self else { return }
actionsSubject.send(.done(mode: context.viewState.mode))
}))
}
}
}
extension SecureBackupRecoveryKeyState {
var viewMode: SecureBackupRecoveryKeyScreenViewMode {
switch self {
case .disabled:
return .setupRecovery
case .enabled:
return .changeRecovery
case .incomplete:
return .fixRecovery
default:
fatalError("Invalid recovery state")
}
}
}
@@ -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 SecureBackupRecoveryKeyScreenViewModelProtocol {
var actions: AnyPublisher<SecureBackupRecoveryKeyScreenViewModelAction, Never> { get }
var context: SecureBackupRecoveryKeyScreenViewModelType.Context { get }
}
@@ -0,0 +1,213 @@
//
// 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 SecureBackupRecoveryKeyScreen: View {
@ObservedObject var context: SecureBackupRecoveryKeyScreenViewModel.Context
@ScaledMetric private var iconSize = 70
var body: some View {
mainContent
.padding()
.interactiveDismissDisabled()
.toolbar { toolbar }
.toolbar(.visible, for: .navigationBar)
.background(Color.compound.bgCanvasDefault.ignoresSafeArea())
.alert(item: $context.alertInfo)
}
@ViewBuilder
private var mainContent: some View {
VStack(spacing: 48) {
switch context.viewState.mode {
case .setupRecovery, .changeRecovery:
header
newRecoveryKeySection
case .fixRecovery:
header
confirmRecoveryKeySection
}
}
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
if context.viewState.recoveryKey == nil {
ToolbarItem(placement: .cancellationAction) {
Button(L10n.actionCancel) {
context.send(viewAction: .cancel)
}
}
}
}
private var header: some View {
VStack(spacing: 16) {
HeroImage(image: Image(asset: Asset.Images.secureBackupOn))
Text(context.viewState.title)
.foregroundColor(.compound.textPrimary)
.font(.compound.headingMDBold)
.multilineTextAlignment(.center)
Text(context.viewState.subtitle)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodyMD)
.multilineTextAlignment(.center)
}
}
@ViewBuilder
private var newRecoveryKeySection: some View {
generateRecoveryKeySection
Spacer()
if let recoveryKey = context.viewState.recoveryKey {
ShareLink(item: recoveryKey) {
Label(L10n.screenRecoveryKeySaveAction, icon: \.download)
}
.buttonStyle(.compound(.primary))
.simultaneousGesture(TapGesture().onEnded { _ in
context.send(viewAction: .keySaved)
})
}
Button {
context.send(viewAction: .done)
} label: {
Text(L10n.actionDone)
}
.buttonStyle(.compound(.primary))
.disabled(context.viewState.recoveryKey == nil || context.viewState.doneButtonEnabled == false)
}
private var generateRecoveryKeySection: some View {
VStack(alignment: .leading) {
Text(L10n.commonRecoveryKey)
.foregroundColor(.compound.textPrimary)
.font(.compound.bodySM)
HStack {
if context.viewState.recoveryKey == nil {
Button(generateButtonTitle) {
context.send(viewAction: .generateKey)
}
.font(.compound.bodyLGSemibold)
} else {
HStack(alignment: .top) {
Text(context.viewState.recoveryKey ?? "")
.foregroundColor(.compound.textPrimary)
.font(.compound.bodyLG)
Spacer()
Button {
context.send(viewAction: .copyKey)
} label: {
Image(asset: Asset.Images.copy)
}
.tint(.compound.iconSecondary)
.accessibilityLabel(L10n.actionCopy)
}
}
}
.frame(maxWidth: .infinity)
.padding()
.background(Color.compound.bgSubtleSecondaryLevel0)
.clipShape(RoundedRectangle(cornerRadius: 8))
HStack(alignment: .top) {
if context.viewState.recoveryKey == nil {
CompoundIcon(\.info, size: .small, relativeTo: .compound.bodySM)
}
Text(context.viewState.recoveryKeySubtitle)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodySM)
}
}
}
private var generateButtonTitle: String {
context.viewState.mode == .setupRecovery ? L10n.screenRecoveryKeySetupGenerateKey : L10n.screenRecoveryKeyChangeGenerateKey
}
@ViewBuilder
private var confirmRecoveryKeySection: some View {
VStack(alignment: .leading) {
Text(L10n.commonRecoveryKey)
.foregroundColor(.compound.textPrimary)
.font(.compound.bodySM)
TextField(L10n.screenRecoveryKeyConfirmKeyPlaceholder, text: $context.confirmationRecoveryKey, axis: .vertical)
.frame(maxWidth: .infinity)
.padding()
.background(Color.compound.bgSubtleSecondaryLevel0)
.clipShape(RoundedRectangle(cornerRadius: 8))
Text(context.viewState.recoveryKeySubtitle)
.foregroundColor(.compound.textSecondary)
.font(.compound.bodySM)
Spacer()
Button {
context.send(viewAction: .confirmKey)
} label: {
Text(L10n.actionConfirm)
}
.buttonStyle(.compound(.primary))
.disabled(context.confirmationRecoveryKey.isEmpty)
}
}
}
// MARK: - Previews
struct SecureBackupRecoveryKeyScreen_Previews: PreviewProvider, TestablePreview {
static let setupViewModel = viewModel(recoveryKeyState: .enabled)
static let notSetUpViewModel = viewModel(recoveryKeyState: .disabled)
static let incompleteViewModel = viewModel(recoveryKeyState: .incomplete)
static var previews: some View {
NavigationStack {
SecureBackupRecoveryKeyScreen(context: notSetUpViewModel.context)
}
.previewDisplayName("Not set up")
NavigationStack {
SecureBackupRecoveryKeyScreen(context: setupViewModel.context)
}
.previewDisplayName("Set up")
NavigationStack {
SecureBackupRecoveryKeyScreen(context: incompleteViewModel.context)
}
.previewDisplayName("Incomplete")
}
static func viewModel(recoveryKeyState: SecureBackupRecoveryKeyState) -> SecureBackupRecoveryKeyScreenViewModelType {
let backupController = SecureBackupControllerMock()
backupController.underlyingRecoveryKeyState = CurrentValueSubject<SecureBackupRecoveryKeyState, Never>(recoveryKeyState).asCurrentValuePublisher()
return SecureBackupRecoveryKeyScreenViewModel(secureBackupController: backupController, userIndicatorController: nil)
}
}
@@ -0,0 +1,116 @@
//
// 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 SecureBackupScreenCoordinatorParameters {
let appSettings: AppSettings
let secureBackupController: SecureBackupControllerProtocol
weak var navigationStackCoordinator: NavigationStackCoordinator?
weak var userIndicatorController: UserIndicatorControllerProtocol?
}
enum SecureBackupScreenCoordinatorAction { }
final class SecureBackupScreenCoordinator: CoordinatorProtocol {
private let parameters: SecureBackupScreenCoordinatorParameters
private var viewModel: SecureBackupScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<SecureBackupScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<SecureBackupScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: SecureBackupScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SecureBackupScreenViewModel(secureBackupController: parameters.secureBackupController,
userIndicatorController: parameters.userIndicatorController,
chatBackupDetailsURL: parameters.appSettings.chatBackupDetailsURL)
}
func start() {
viewModel.actions.sink { [weak self] action in
guard let self else { return }
switch action {
case .recoveryKey:
let navigationStackCoordinator = NavigationStackCoordinator()
let userIndicatorController = UserIndicatorController(rootCoordinator: navigationStackCoordinator)
let recoveryKeyCoordinator = SecureBackupRecoveryKeyScreenCoordinator(parameters: .init(secureBackupController: parameters.secureBackupController,
userIndicatorController: userIndicatorController))
recoveryKeyCoordinator.actions.sink { [weak self] action in
guard let self else { return }
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
switch action {
case .cancel:
break
case .recoverySetUp:
showSuccessIndicator(title: L10n.screenRecoveryKeySetupSuccess)
case .recoveryChanged:
showSuccessIndicator(title: L10n.screenRecoveryKeyChangeSuccess)
case .recoveryFixed:
showSuccessIndicator(title: L10n.screenRecoveryKeyConfirmSuccess)
}
}
.store(in: &cancellables)
navigationStackCoordinator.setRootCoordinator(recoveryKeyCoordinator, animated: true)
parameters.navigationStackCoordinator?.setSheetCoordinator(userIndicatorController)
case .keyBackup:
let navigationStackCoordinator = NavigationStackCoordinator()
let userIndicatorController = UserIndicatorController(rootCoordinator: navigationStackCoordinator)
let keyBackupCoordinator = SecureBackupKeyBackupScreenCoordinator(parameters: .init(secureBackupController: parameters.secureBackupController,
userIndicatorController: userIndicatorController))
keyBackupCoordinator.actions.sink { [weak self] action in
switch action {
case .done:
self?.parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
}
}
.store(in: &cancellables)
navigationStackCoordinator.setRootCoordinator(keyBackupCoordinator, animated: true)
parameters.navigationStackCoordinator?.setSheetCoordinator(userIndicatorController)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(SecureBackupScreen(context: viewModel.context))
}
// MARK: - Private
private func showSuccessIndicator(title: String) {
parameters.userIndicatorController?.submitIndicator(.init(id: .init(),
type: .modal(progress: .none, interactiveDismissDisabled: false, allowsInteraction: false),
title: title,
iconName: "checkmark",
persistent: false))
}
}
@@ -0,0 +1,38 @@
//
// 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 SecureBackupScreenViewModelAction {
case recoveryKey
case keyBackup
}
struct SecureBackupScreenViewState: BindableState {
let chatBackupDetailsURL: URL
var recoveryKeyState = SecureBackupRecoveryKeyState.unknown
var keyBackupState = SecureBackupKeyBackupState.unknown
var bindings = SecureBackupScreenViewStateBindings()
}
struct SecureBackupScreenViewStateBindings {
var alertInfo: AlertInfo<UUID>?
}
enum SecureBackupScreenViewAction {
case recoveryKey
case keyBackup
}
@@ -0,0 +1,85 @@
//
// 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 SecureBackupScreenViewModelType = StateStoreViewModel<SecureBackupScreenViewState, SecureBackupScreenViewAction>
class SecureBackupScreenViewModel: SecureBackupScreenViewModelType, SecureBackupScreenViewModelProtocol {
private let secureBackupController: SecureBackupControllerProtocol
private weak var userIndicatorController: UserIndicatorControllerProtocol?
private var actionsSubject: PassthroughSubject<SecureBackupScreenViewModelAction, Never> = .init()
var actions: AnyPublisher<SecureBackupScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(secureBackupController: SecureBackupControllerProtocol,
userIndicatorController: UserIndicatorControllerProtocol?,
chatBackupDetailsURL: URL) {
self.secureBackupController = secureBackupController
self.userIndicatorController = userIndicatorController
super.init(initialViewState: .init(chatBackupDetailsURL: chatBackupDetailsURL))
secureBackupController.recoveryKeyState
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.recoveryKeyState, on: self)
.store(in: &cancellables)
secureBackupController.keyBackupState
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.keyBackupState, on: self)
.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: SecureBackupScreenViewAction) {
switch viewAction {
case .recoveryKey:
actionsSubject.send(.recoveryKey)
case .keyBackup:
switch secureBackupController.keyBackupState.value {
case .disabled:
enableKeyBackup()
case .enabled:
actionsSubject.send(.keyBackup)
default:
break
}
}
}
// MARK: - Private
private func enableKeyBackup() {
Task {
let loadingIndicatorIdentifier = "SecureBackupScreenLoading"
userIndicatorController?.submitIndicator(.init(id: loadingIndicatorIdentifier, type: .modal, title: L10n.commonLoading, persistent: true))
switch await secureBackupController.enableBackup() {
case .success:
break
case .failure(let error):
MXLog.error("Failed enabling key backup with error: \(error)")
state.bindings.alertInfo = .init(id: .init())
}
userIndicatorController?.retractIndicatorWithId(loadingIndicatorIdentifier)
}
}
}
@@ -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 SecureBackupScreenViewModelProtocol {
var actions: AnyPublisher<SecureBackupScreenViewModelAction, Never> { get }
var context: SecureBackupScreenViewModelType.Context { get }
}
@@ -0,0 +1,168 @@
//
// 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 SecureBackupScreen: View {
@ObservedObject var context: SecureBackupScreenViewModel.Context
var body: some View {
Form {
if context.viewState.keyBackupState != .enabled {
keyBackupSection
} else {
keyBackupSection
recoveryKeySection
}
}
.compoundList()
.navigationTitle(L10n.commonChatBackup)
.navigationBarTitleDisplayMode(.inline)
.alert(item: $context.alertInfo)
}
// MARK: - Private
@ViewBuilder
private var keyBackupSection: some View {
Section {
ListRow(kind: .custom {
VStack(alignment: .leading, spacing: 2) {
Text(L10n.screenChatBackupKeyBackupTitle)
.font(.compound.bodyLGSemibold)
.foregroundColor(.compound.textPrimary)
Text(keyBackupDescriptionWithLearnMoreLink)
.font(.compound.bodySM)
.foregroundColor(.compound.textSecondary)
}
.padding(.horizontal, ListRowPadding.horizontal)
.padding(.vertical, ListRowPadding.vertical)
.accessibilityElement(children: .combine)
})
keyBackupButton
}
}
private var keyBackupDescriptionWithLearnMoreLink: AttributedString {
let linkPlaceholder = "{link}"
var description = AttributedString(L10n.screenChatBackupKeyBackupDescription(linkPlaceholder))
var linkString = AttributedString(L10n.actionLearnMore)
linkString.link = context.viewState.chatBackupDetailsURL
linkString.bold()
description.replace(linkPlaceholder, with: linkString)
return description
}
@ViewBuilder
private var keyBackupButton: some View {
switch context.viewState.keyBackupState {
case .enabled, .disabling:
ListRow(label: .plain(title: L10n.screenChatBackupKeyBackupActionDisable, role: .destructive), kind: .navigationLink {
context.send(viewAction: .keyBackup)
})
case .disabled, .enabling:
ListRow(label: .plain(title: L10n.screenChatBackupKeyBackupActionEnable), kind: .navigationLink {
context.send(viewAction: .keyBackup)
})
default:
ListRow(label: .plain(title: L10n.commonLoading), details: .isWaiting(true), kind: .label)
}
}
@ViewBuilder
private var recoveryKeySection: some View {
Section {
switch context.viewState.recoveryKeyState {
case .enabled:
ListRow(label: .plain(title: L10n.screenChatBackupRecoveryActionChange),
kind: .navigationLink { context.send(viewAction: .recoveryKey) })
case .disabled:
ListRow(label: .plain(title: L10n.screenChatBackupRecoveryActionSetup),
details: .icon(BadgeView(size: 10)),
kind: .navigationLink { context.send(viewAction: .recoveryKey) })
case .incomplete:
ListRow(label: .plain(title: L10n.screenChatBackupRecoveryActionConfirm),
kind: .navigationLink { context.send(viewAction: .recoveryKey) })
default:
ListRow(label: .plain(title: L10n.commonLoading), details: .isWaiting(true), kind: .label)
}
} footer: {
recoveryKeySectionFooter
.compoundFormSectionFooter()
}
}
@ViewBuilder
private var recoveryKeySectionFooter: some View {
switch context.viewState.recoveryKeyState {
case .disabled:
Text(L10n.screenChatBackupRecoveryActionSetupDescription(InfoPlistReader.main.bundleDisplayName))
case .incomplete:
Text(L10n.screenChatBackupRecoveryActionConfirmDescription)
default:
EmptyView()
}
}
}
// MARK: - Previews
struct SecureBackupScreen_Previews: PreviewProvider, TestablePreview {
static let bothSetupViewModel = viewModel(keyBackupState: .enabled, recoveryKeyState: .enabled)
static let onlyKeyBackupSetUpViewModel = viewModel(keyBackupState: .enabled, recoveryKeyState: .disabled)
static let keyBackupDisabledViewModel = viewModel(keyBackupState: .disabled, recoveryKeyState: .disabled)
static let recoveryIncompleteViewModel = viewModel(keyBackupState: .enabled, recoveryKeyState: .incomplete)
static var previews: some View {
Group {
NavigationStack {
SecureBackupScreen(context: bothSetupViewModel.context)
}
.previewDisplayName("Both setup")
NavigationStack {
SecureBackupScreen(context: onlyKeyBackupSetUpViewModel.context)
}
.previewDisplayName("Only key backup setup")
NavigationStack {
SecureBackupScreen(context: keyBackupDisabledViewModel.context)
}
.previewDisplayName("Key backup disabled")
NavigationStack {
SecureBackupScreen(context: recoveryIncompleteViewModel.context)
}
.previewDisplayName("Recovery incomplete")
}
.snapshot(delay: 0.25)
}
static func viewModel(keyBackupState: SecureBackupKeyBackupState,
recoveryKeyState: SecureBackupRecoveryKeyState) -> SecureBackupScreenViewModelType {
let backupController = SecureBackupControllerMock()
backupController.underlyingKeyBackupState = CurrentValueSubject<SecureBackupKeyBackupState, Never>(keyBackupState).asCurrentValuePublisher()
backupController.underlyingRecoveryKeyState = CurrentValueSubject<SecureBackupRecoveryKeyState, Never>(recoveryKeyState).asCurrentValuePublisher()
return SecureBackupScreenViewModel(secureBackupController: backupController,
userIndicatorController: nil,
chatBackupDetailsURL: .sharedPublicDirectory)
}
}
@@ -71,7 +71,7 @@ struct SessionVerificationScreen: View {
@ViewBuilder
private var screenHeader: some View {
VStack(spacing: 0) {
AuthenticationIconImage(image: Image(systemName: headerImageName))
HeroImage(image: Image(systemName: headerImageName))
.padding(.bottom, 16)
Text(context.viewState.title ?? "")
@@ -53,6 +53,7 @@ protocol DeveloperOptionsProtocol: AnyObject {
var mentionsEnabled: Bool { get set }
var appLockFlowEnabled: Bool { get set }
var elementCallEnabled: Bool { get set }
var chatBackupEnabled: Bool { get set }
}
extension AppSettings: DeveloperOptionsProtocol { }
@@ -31,6 +31,18 @@ struct DeveloperOptionsScreen: View {
}
}
Section("Security") {
Toggle(isOn: $context.chatBackupEnabled) {
Text("Chat backup")
Text("Requires app reboot")
}
Toggle(isOn: $context.appLockFlowEnabled) {
Text("PIN/Biometric lock")
Text("Resets on reboot")
}
}
Section("Timeline") {
Toggle(isOn: $context.shouldCollapseRoomStateEvents) {
Text("Collapse room state events")
@@ -52,7 +64,7 @@ struct DeveloperOptionsScreen: View {
}
Toggle(isOn: $context.elementCallEnabled) {
Text("Elemement Call")
Text("Element Call")
}
}
@@ -67,13 +79,6 @@ struct DeveloperOptionsScreen: View {
Text("Enable voice messages")
}
}
Section("Security") {
Toggle(isOn: $context.appLockFlowEnabled) {
Text("PIN/Biometric lock")
Text("Resets on reboot")
}
}
Section {
Button {
@@ -24,6 +24,7 @@ struct SettingsScreenCoordinatorParameters {
let appLockService: AppLockServiceProtocol
let bugReportService: BugReportServiceProtocol
let notificationSettings: NotificationSettingsProxyProtocol
let secureBackupController: SecureBackupControllerProtocol
let appSettings: AppSettings
}
@@ -49,7 +50,8 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
init(parameters: SettingsScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = SettingsScreenViewModel(userSession: parameters.userSession, appSettings: parameters.appSettings)
viewModel = SettingsScreenViewModel(userSession: parameters.userSession,
appSettings: parameters.appSettings)
viewModel.actions
.sink { [weak self] action in
@@ -71,7 +73,9 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
case .about:
presentLegalInformationScreen()
case .sessionVerification:
verifySession()
presentSessionVerificationScreen()
case .secureBackup:
presentSecureBackupScreen()
case .accountSessionsList:
presentAccountSessionsListURL()
case .notifications:
@@ -172,7 +176,7 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
parameters.navigationStackCoordinator?.push(LegalInformationScreenCoordinator(appSettings: parameters.appSettings))
}
private func verifySession() {
private func presentSessionVerificationScreen() {
guard let sessionVerificationController = parameters.userSession.sessionVerificationController else {
fatalError("The sessionVerificationController should aways be valid at this point")
}
@@ -196,6 +200,15 @@ 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,
@@ -26,6 +26,7 @@ enum SettingsScreenViewModelAction {
case reportBug
case about
case sessionVerification
case secureBackup
case accountSessionsList
case notifications
case advancedSettings
@@ -40,7 +41,9 @@ struct SettingsScreenViewState: BindableState {
var accountSessionsListURL: URL?
var userAvatarURL: URL?
var userDisplayName: String?
var showSessionVerificationSection: Bool
var isSessionVerified: Bool
var chatBackupEnabled = false
var showSecureBackupBadge = false
var showAppLockSettings: Bool
var showDeveloperOptions: Bool
@@ -57,6 +60,7 @@ enum SettingsScreenViewAction {
case reportBug
case about
case sessionVerification
case secureBackup
case accountSessionsList
case notifications
case developerOptions
@@ -33,16 +33,16 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
self.userSession = userSession
self.appSettings = appSettings
var showSessionVerificationSection = false
var isSessionVerified = true
if let sessionVerificationController = userSession.sessionVerificationController {
showSessionVerificationSection = !sessionVerificationController.isVerified
isSessionVerified = sessionVerificationController.isVerified
}
super.init(initialViewState: .init(deviceID: userSession.deviceID,
userID: userSession.userID,
accountProfileURL: userSession.clientProxy.accountURL(action: .profile),
accountSessionsListURL: userSession.clientProxy.accountURL(action: .sessionsList),
showSessionVerificationSection: showSessionVerificationSection,
isSessionVerified: isSessionVerified,
showAppLockSettings: appSettings.appLockFlowEnabled,
showDeveloperOptions: appSettings.canShowDeveloperOptions),
imageProvider: userSession.mediaProvider)
@@ -56,11 +56,24 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userDisplayName, on: self)
.store(in: &cancellables)
appSettings.$appLockFlowEnabled
.weakAssign(to: \.state.showAppLockSettings, on: self)
.store(in: &cancellables)
appSettings.$chatBackupEnabled
.weakAssign(to: \.state.chatBackupEnabled, on: self)
.store(in: &cancellables)
userSession.clientProxy.secureBackupController.recoveryKeyState
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
guard let self else { return }
self.state.showSecureBackupBadge = (state == .unknown || state == .disabled) && appSettings.chatBackupEnabled
}
.store(in: &cancellables)
Task {
await userSession.clientProxy.loadUserAvatarURL()
await userSession.clientProxy.loadUserDisplayName()
@@ -71,9 +84,9 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
.sink { [weak self] callback in
switch callback {
case .sessionVerificationNeeded:
self?.state.showSessionVerificationSection = true
self?.state.isSessionVerified = false
case .didVerifySession:
self?.state.showSessionVerificationSection = false
self?.state.isSessionVerified = true
default:
break
}
@@ -101,6 +114,8 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
actionsSubject.send(.logout)
case .sessionVerification:
actionsSubject.send(.sessionVerification)
case .secureBackup:
actionsSubject.send(.secureBackup)
case .notifications:
actionsSubject.send(.notifications)
case .accountSessionsList:
@@ -27,9 +27,7 @@ struct SettingsScreen: View {
Form {
userSection
if context.viewState.showSessionVerificationSection {
sessionVerificationSection
}
accountSecuritySection
mainSection
@@ -86,11 +84,22 @@ struct SettingsScreen: View {
}
}
private var sessionVerificationSection: some View {
Section {
ListRow(label: .default(title: L10n.actionCompleteVerification,
systemIcon: .checkmarkShield),
kind: .button { context.send(viewAction: .sessionVerification) })
@ViewBuilder
private var accountSecuritySection: some View {
if !context.viewState.isSessionVerified || context.viewState.chatBackupEnabled {
Section {
if !context.viewState.isSessionVerified {
ListRow(label: .default(title: L10n.actionCompleteVerification,
systemIcon: .checkmarkShield),
kind: .button { context.send(viewAction: .sessionVerification) })
} else if context.viewState.chatBackupEnabled {
ListRow(label: .default(title: L10n.commonChatBackup,
icon: Image(asset: Asset.Images.secureBackupIcon)),
details: context.viewState.showSecureBackupBadge ? .icon(secureBackupBadge) : nil,
kind: .navigationLink { context.send(viewAction: .secureBackup) })
.accessibilityIdentifier(A11yIdentifiers.settingsScreen.secureBackup)
}
}
}
}
@@ -222,6 +231,13 @@ struct SettingsScreen: View {
.accessibilityIdentifier(A11yIdentifiers.settingsScreen.done)
}
}
@ViewBuilder
private var secureBackupBadge: some View {
if context.viewState.showSecureBackupBadge {
BadgeView(size: 10)
}
}
}
private extension TimelineStyle {