Change user display name and avatar (#1718)

* Fixes #1715, #1716 - Add new user profile editing screen

* Bump SDK, adopt new `client.removeAvatar()` method

* Address PR review comments
This commit is contained in:
Stefan Ceriu
2023-09-15 16:20:33 +03:00
committed by GitHub
parent b3a0680d64
commit fe711a9a40
20 changed files with 700 additions and 69 deletions
@@ -356,14 +356,9 @@ class AppCoordinator: AppCoordinatorProtocol, AuthenticationCoordinatorDelegate,
}
Task {
var displayName = ""
if case .success(let name) = await userSession.clientProxy.loadUserDisplayName() {
displayName = name
}
let credentials = SoftLogoutScreenCredentials(userID: userSession.userID,
homeserverName: userSession.homeserver,
userDisplayName: displayName,
userDisplayName: userSession.clientProxy.userDisplayName.value ?? "",
deviceID: userSession.deviceID)
let authenticationService = AuthenticationServiceProxy(userSessionStore: userSessionStore, appSettings: appSettings)
+13 -1
View File
@@ -510,6 +510,8 @@ public enum L10n {
public static var richTextEditorOpenComposeOptions: String { return L10n.tr("Localizable", "rich_text_editor_open_compose_options") }
/// Toggle quote
public static var richTextEditorQuote: String { return L10n.tr("Localizable", "rich_text_editor_quote") }
/// Remove link
public static var richTextEditorRemoveLink: String { return L10n.tr("Localizable", "rich_text_editor_remove_link") }
/// Unindent
public static var richTextEditorUnindent: String { return L10n.tr("Localizable", "rich_text_editor_unindent") }
/// Link
@@ -632,7 +634,7 @@ public enum L10n {
public static var screenCreatePollAddOptionBtn: String { return L10n.tr("Localizable", "screen_create_poll_add_option_btn") }
/// Show results only after poll ends
public static var screenCreatePollAnonymousDesc: String { return L10n.tr("Localizable", "screen_create_poll_anonymous_desc") }
/// Anonymous Poll
/// Hide votes
public static var screenCreatePollAnonymousHeadline: String { return L10n.tr("Localizable", "screen_create_poll_anonymous_headline") }
/// Option %1$d
public static func screenCreatePollAnswerHint(_ p1: Int) -> String {
@@ -682,6 +684,16 @@ public enum L10n {
public static var screenDmDetailsUnblockAlertDescription: String { return L10n.tr("Localizable", "screen_dm_details_unblock_alert_description") }
/// Unblock user
public static var screenDmDetailsUnblockUser: String { return L10n.tr("Localizable", "screen_dm_details_unblock_user") }
/// Display name
public static var screenEditProfileDisplayName: String { return L10n.tr("Localizable", "screen_edit_profile_display_name") }
/// Your display name
public static var screenEditProfileDisplayNamePlaceholder: String { return L10n.tr("Localizable", "screen_edit_profile_display_name_placeholder") }
/// An unknown error was encountered and the information couldn't be changed.
public static var screenEditProfileError: String { return L10n.tr("Localizable", "screen_edit_profile_error") }
/// Unable to update profile
public static var screenEditProfileErrorTitle: String { return L10n.tr("Localizable", "screen_edit_profile_error_title") }
/// Updating profile…
public static var screenEditProfileUpdatingDetails: String { return L10n.tr("Localizable", "screen_edit_profile_updating_details") }
/// Are you sure you want to decline the invitation to join %1$@?
public static func screenInvitesDeclineChatMessage(_ p1: Any) -> String {
return L10n.tr("Localizable", "screen_invites_decline_chat_message", String(describing: p1))
@@ -431,6 +431,22 @@ class SDKClientMock: SDKClientProtocol {
return notificationClientProcessSetupReturnValue
}
}
//MARK: - removeAvatar
public var removeAvatarThrowableError: Error?
public var removeAvatarCallsCount = 0
public var removeAvatarCalled: Bool {
return removeAvatarCallsCount > 0
}
public var removeAvatarClosure: (() throws -> Void)?
public func removeAvatar() throws {
if let error = removeAvatarThrowableError {
throw error
}
removeAvatarCallsCount += 1
try removeAvatarClosure?()
}
//MARK: - restoreSession
public var restoreSessionSessionThrowableError: Error?
@@ -70,10 +70,16 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
}
.store(in: &cancellables)
userSession.clientProxy.avatarURLPublisher
userSession.clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userAvatarURL, on: self)
.store(in: &cancellables)
userSession.clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userDisplayName, on: self)
.store(in: &cancellables)
selectedRoomPublisher
.weakAssign(to: \.state.selectedRoomID, on: self)
.store(in: &cancellables)
@@ -182,12 +188,7 @@ class HomeScreenViewModel: HomeScreenViewModelType, HomeScreenViewModelProtocol
if roomListMode == .rooms {
Task {
await self.userSession.clientProxy.loadUserAvatarURL()
}
Task {
if case let .success(userDisplayName) = await self.userSession.clientProxy.loadUserDisplayName() {
self.state.userDisplayName = userDisplayName
}
await self.userSession.clientProxy.loadUserDisplayName()
}
}
}
@@ -57,6 +57,8 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
switch action {
case .close:
actionsSubject.send(.dismiss)
case .userDetails:
presentUserDetailsEditScreen()
case .accountProfile:
presentAccountProfileURL()
case .analytics:
@@ -121,6 +123,15 @@ final class SettingsScreenCoordinator: CoordinatorProtocol {
// MARK: - Private
private func presentUserDetailsEditScreen() {
let coordinator = UserDetailsEditScreenCoordinator(parameters: .init(clientProxy: parameters.userSession.clientProxy,
mediaProvider: parameters.userSession.mediaProvider,
navigationStackCoordinator: parameters.navigationStackCoordinator,
userIndicatorController: parameters.userIndicatorController))
parameters.navigationStackCoordinator?.push(coordinator)
}
private func presentAnalyticsScreen() {
let coordinator = AnalyticsSettingsScreenCoordinator(parameters: .init(appSettings: ServiceLocator.shared.settings,
analytics: ServiceLocator.shared.analytics))
@@ -19,6 +19,7 @@ import UIKit
enum SettingsScreenViewModelAction {
case close
case userDetails
case accountProfile
case analytics
case reportBug
@@ -47,6 +48,7 @@ struct SettingsScreenViewState: BindableState {
enum SettingsScreenViewAction {
case close
case userDetails
case accountProfile
case analytics
case reportBug
@@ -46,18 +46,19 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
showDeveloperOptions: appSettings.canShowDeveloperOptions),
imageProvider: userSession.mediaProvider)
userSession.clientProxy.avatarURLPublisher
userSession.clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userAvatarURL, on: self)
.store(in: &cancellables)
userSession.clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.userDisplayName, on: self)
.store(in: &cancellables)
Task {
await userSession.clientProxy.loadUserAvatarURL()
}
Task {
if case let .success(userDisplayName) = await self.userSession.clientProxy.loadUserDisplayName() {
state.userDisplayName = userDisplayName
}
await userSession.clientProxy.loadUserDisplayName()
}
userSession.callbacks
@@ -79,6 +80,8 @@ class SettingsScreenViewModel: SettingsScreenViewModelType, SettingsScreenViewMo
switch viewAction {
case .close:
actionsSubject.send(.close)
case .userDetails:
actionsSubject.send(.userDetails)
case .accountProfile:
actionsSubject.send(.accountProfile)
case .analytics:
@@ -49,30 +49,40 @@ struct SettingsScreen: View {
context.send(viewAction: .updateWindow(window))
}
}
private var userSection: some View {
Section {
ListRow(kind: .custom {
HStack(spacing: 12) {
LoadableAvatarImage(url: context.viewState.userAvatarURL,
name: context.viewState.userDisplayName,
contentID: context.viewState.userID,
avatarSize: .user(on: .settings),
imageProvider: context.imageProvider)
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 2) {
Text(context.viewState.userDisplayName ?? "")
.font(.compound.headingMD)
.foregroundColor(.compound.textPrimary)
Text(context.viewState.userID)
.font(.compound.bodySM)
.foregroundColor(.compound.textSecondary)
Button {
context.send(viewAction: .userDetails)
} label: {
HStack(spacing: 12) {
LoadableAvatarImage(url: context.viewState.userAvatarURL,
name: context.viewState.userDisplayName,
contentID: context.viewState.userID,
avatarSize: .user(on: .settings),
imageProvider: context.imageProvider)
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 2) {
Text(context.viewState.userDisplayName ?? "")
.font(.compound.headingMD)
.foregroundColor(.compound.textPrimary)
Text(context.viewState.userID)
.font(.compound.bodySM)
.foregroundColor(.compound.textSecondary)
}
Spacer()
CompoundIcon(\.chevronRight)
.font(.system(size: 24))
.foregroundColor(.compound.iconTertiaryAlpha)
.flipsForRightToLeftLayoutDirection(true)
}
.accessibilityElement(children: .combine)
.padding(.horizontal, ListRowPadding.horizontal)
.padding(.vertical, 8)
}
.padding(.horizontal, ListRowPadding.horizontal)
.padding(.vertical, 8)
})
}
}
@@ -0,0 +1,86 @@
//
// 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 UserDetailsEditScreenCoordinatorParameters {
let clientProxy: ClientProxyProtocol
let mediaProvider: MediaProviderProtocol
weak var navigationStackCoordinator: NavigationStackCoordinator?
weak var userIndicatorController: UserIndicatorControllerProtocol?
}
enum UserDetailsEditScreenCoordinatorAction { }
final class UserDetailsEditScreenCoordinator: CoordinatorProtocol {
private let parameters: UserDetailsEditScreenCoordinatorParameters
private var viewModel: UserDetailsEditScreenViewModelProtocol
private let actionsSubject: PassthroughSubject<UserDetailsEditScreenCoordinatorAction, Never> = .init()
private var cancellables = Set<AnyCancellable>()
var actions: AnyPublisher<UserDetailsEditScreenCoordinatorAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(parameters: UserDetailsEditScreenCoordinatorParameters) {
self.parameters = parameters
viewModel = UserDetailsEditScreenViewModel(clientProxy: parameters.clientProxy,
mediaProvider: parameters.mediaProvider,
userIndicatorController: parameters.userIndicatorController)
}
func start() {
viewModel.actions
.sink { [weak self] action in
switch action {
case .displayCameraPicker:
self?.displayMediaPickerWithSource(.camera)
case .displayMediaPicker:
self?.displayMediaPickerWithSource(.photoLibrary)
case .displayFilePicker:
self?.displayMediaPickerWithSource(.documents)
}
}
.store(in: &cancellables)
}
func toPresentable() -> AnyView {
AnyView(UserDetailsEditScreen(context: viewModel.context))
}
// MARK: Private
private func displayMediaPickerWithSource(_ source: MediaPickerScreenSource) {
let stackCoordinator = NavigationStackCoordinator()
let userIndicatorController = UserIndicatorController(rootCoordinator: stackCoordinator)
let mediaPickerCoordinator = MediaPickerScreenCoordinator(userIndicatorController: userIndicatorController, source: source) { [weak self] action in
guard let self else { return }
switch action {
case .cancel:
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
case .selectMediaAtURL(let url):
parameters.navigationStackCoordinator?.setSheetCoordinator(nil)
viewModel.didSelectMediaURL(url: url)
}
}
stackCoordinator.setRootCoordinator(mediaPickerCoordinator)
parameters.navigationStackCoordinator?.setSheetCoordinator(userIndicatorController)
}
}
@@ -0,0 +1,70 @@
//
// 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 UserDetailsEditScreenViewModelAction {
case displayCameraPicker
case displayMediaPicker
case displayFilePicker
}
struct UserDetailsEditScreenViewState: BindableState {
let userID: String
var currentAvatarURL: URL?
var selectedAvatarURL: URL?
var currentDisplayName: String?
var localMedia: MediaInfo?
var bindings: UserDetailsEditScreenViewStateBindings
var nameDidChange: Bool {
bindings.name != currentDisplayName
}
/// The string shown for the room's name when it can't be edited.
var nameRowTitle: String {
bindings.name.isEmpty ? L10n.screenEditProfileDisplayName : bindings.name
}
var avatarDidChange: Bool {
localMedia != nil || selectedAvatarURL != currentAvatarURL
}
var canSave: Bool {
!bindings.name.isEmpty && (avatarDidChange || nameDidChange)
}
var showDeleteImageAction: Bool {
localMedia != nil || selectedAvatarURL != nil
}
}
struct UserDetailsEditScreenViewStateBindings {
var name = ""
var showMediaSheet = false
}
enum UserDetailsEditScreenViewAction {
case save
case presentMediaSource
case displayCameraPicker
case displayMediaPicker
case removeImage
}
@@ -0,0 +1,151 @@
//
// 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 UserDetailsEditScreenViewModelType = StateStoreViewModel<UserDetailsEditScreenViewState, UserDetailsEditScreenViewAction>
class UserDetailsEditScreenViewModel: UserDetailsEditScreenViewModelType, UserDetailsEditScreenViewModelProtocol {
private let actionsSubject: PassthroughSubject<UserDetailsEditScreenViewModelAction, Never> = .init()
private let clientProxy: ClientProxyProtocol
private weak var userIndicatorController: UserIndicatorControllerProtocol?
private let mediaPreprocessor: MediaUploadingPreprocessor = .init()
var actions: AnyPublisher<UserDetailsEditScreenViewModelAction, Never> {
actionsSubject.eraseToAnyPublisher()
}
init(clientProxy: ClientProxyProtocol,
mediaProvider: MediaProviderProtocol,
userIndicatorController: UserIndicatorControllerProtocol?) {
self.clientProxy = clientProxy
self.userIndicatorController = userIndicatorController
super.init(initialViewState: UserDetailsEditScreenViewState(userID: clientProxy.userID,
bindings: .init()), imageProvider: mediaProvider)
clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.currentAvatarURL, on: self)
.store(in: &cancellables)
clientProxy.userAvatarURL
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.selectedAvatarURL, on: self)
.store(in: &cancellables)
clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.weakAssign(to: \.state.currentDisplayName, on: self)
.store(in: &cancellables)
clientProxy.userDisplayName
.receive(on: DispatchQueue.main)
.sink { [weak self] displayName in
guard let self else { return }
state.bindings.name = displayName ?? ""
}
.store(in: &cancellables)
Task {
await self.clientProxy.loadUserAvatarURL()
await self.clientProxy.loadUserDisplayName()
}
}
// MARK: - Public
override func process(viewAction: UserDetailsEditScreenViewAction) {
switch viewAction {
case .save:
saveUserDetails()
case .presentMediaSource:
state.bindings.showMediaSheet = true
case .displayCameraPicker:
actionsSubject.send(.displayCameraPicker)
case .displayMediaPicker:
actionsSubject.send(.displayMediaPicker)
case .removeImage:
state.localMedia = nil
state.selectedAvatarURL = nil
}
}
func didSelectMediaURL(url: URL) {
Task {
let userIndicatorID = UUID().uuidString
defer {
userIndicatorController?.retractIndicatorWithId(userIndicatorID)
}
userIndicatorController?.submitIndicator(UserIndicator(id: userIndicatorID,
type: .modal(progress: .indeterminate, interactiveDismissDisabled: true, allowsInteraction: false),
title: L10n.commonLoading,
persistent: true))
let mediaResult = await mediaPreprocessor.processMedia(at: url)
switch mediaResult {
case .success(.image):
state.localMedia = try? mediaResult.get()
case .failure, .success:
userIndicatorController?.alertInfo = .init(id: .init(), title: L10n.commonError, message: L10n.errorUnknown)
}
}
}
// MARK: - Private
private func saveUserDetails() {
Task {
let userIndicatorID = UUID().uuidString
defer {
userIndicatorController?.retractIndicatorWithId(userIndicatorID)
}
userIndicatorController?.submitIndicator(UserIndicator(id: userIndicatorID,
type: .modal(progress: .indeterminate, interactiveDismissDisabled: true, allowsInteraction: false),
title: L10n.screenEditProfileUpdatingDetails,
persistent: true))
do {
try await withThrowingTaskGroup(of: Void.self) { group in
if state.avatarDidChange {
group.addTask {
if let localMedia = await self.state.localMedia {
try await self.clientProxy.setUserAvatar(media: localMedia).get()
} else if await self.state.selectedAvatarURL == nil {
try await self.clientProxy.removeUserAvatar().get()
}
}
}
if state.nameDidChange {
group.addTask {
try await self.clientProxy.setUserDisplayName(self.state.bindings.name).get()
}
}
try await group.waitForAll()
}
} catch {
userIndicatorController?.alertInfo = .init(id: .init(),
title: L10n.screenEditProfileErrorTitle,
message: L10n.screenEditProfileError)
}
}
}
}
@@ -0,0 +1,26 @@
//
// 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 Foundation
@MainActor
protocol UserDetailsEditScreenViewModelProtocol {
var actions: AnyPublisher<UserDetailsEditScreenViewModelAction, Never> { get }
var context: UserDetailsEditScreenViewModelType.Context { get }
func didSelectMediaURL(url: URL)
}
@@ -0,0 +1,129 @@
//
// 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 Compound
import SwiftUI
struct UserDetailsEditScreen: View {
@ObservedObject var context: UserDetailsEditScreenViewModel.Context
@FocusState private var focus: Bool
var body: some View {
Form {
avatar
nameSection
}
.compoundList()
.scrollDismissesKeyboard(.immediately)
.navigationBarTitleDisplayMode(.inline)
.toolbar { toolbar }
}
// MARK: - Private
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .confirmationAction) {
Button(L10n.actionSave) {
context.send(viewAction: .save)
focus = false
}
.disabled(!context.viewState.canSave)
}
}
private var avatar: some View {
Button {
context.send(viewAction: .presentMediaSource)
} label: {
OverridableAvatarImage(overrideURL: context.viewState.localMedia?.thumbnailURL,
url: context.viewState.selectedAvatarURL,
name: context.viewState.currentDisplayName,
contentID: context.viewState.userID,
avatarSize: .user(on: .memberDetails),
imageProvider: context.imageProvider)
.overlay(alignment: .bottomTrailing) {
avatarOverlayIcon
}
.confirmationDialog("", isPresented: $context.showMediaSheet) {
mediaActionSheet
}
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .center)
.listRowBackground(Color.clear)
}
private var nameSection: some View {
Section {
ListRow(label: .plain(title: L10n.screenEditProfileDisplayNamePlaceholder),
kind: .textField(text: $context.name, axis: .horizontal))
.focused($focus)
} header: {
Text(L10n.screenEditProfileDisplayName)
.compoundListSectionHeader()
}
}
private var avatarOverlayIcon: some View {
Image(systemName: "camera")
.font(.system(size: 14, weight: .semibold))
.padding(3)
.imageScale(.small)
.foregroundColor(.white)
.background {
Circle()
.foregroundColor(.black)
.aspectRatio(1, contentMode: .fill)
}
}
@ViewBuilder
private var mediaActionSheet: some View {
Button {
context.send(viewAction: .displayCameraPicker)
} label: {
Text(L10n.actionTakePhoto)
}
Button {
context.send(viewAction: .displayMediaPicker)
} label: {
Text(L10n.actionChoosePhoto)
}
if context.viewState.showDeleteImageAction {
Button(role: .destructive) {
context.send(viewAction: .removeImage)
} label: {
Text(L10n.actionRemove)
}
}
}
}
// MARK: - Previews
struct UserDetailsEditScreen_Previews: PreviewProvider {
static let viewModel = UserDetailsEditScreenViewModel(clientProxy: MockClientProxy(userID: "@stefan:matrix.org"),
mediaProvider: MockMediaProvider(),
userIndicatorController: UserIndicatorControllerMock.default)
static var previews: some View {
NavigationStack {
UserDetailsEditScreen(context: viewModel.context)
}
}
}
@@ -43,12 +43,14 @@ class ClientProxy: ClientProxyProtocol {
private let roomListRecencyOrderingAllowedEventTypes = ["m.room.message", "m.room.encrypted", "m.sticker"]
private var loadCachedAvatarURLTask: Task<Void, Never>?
private let avatarURLSubject = CurrentValueSubject<URL?, Never>(nil)
var avatarURLPublisher: AnyPublisher<URL?, Never> {
avatarURLSubject
.removeDuplicates()
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
private let userAvatarURLSubject = CurrentValueSubject<URL?, Never>(nil)
var userAvatarURL: CurrentValuePublisher<URL?, Never> {
userAvatarURLSubject.asCurrentValuePublisher()
}
private let userDisplayNameSubject = CurrentValueSubject<String?, Never>(nil)
var userDisplayName: CurrentValuePublisher<String?, Never> {
userDisplayNameSubject.asCurrentValuePublisher()
}
private var cancellables = Set<AnyCancellable>()
@@ -279,26 +281,74 @@ class ClientProxy: ClientProxyProtocol {
backgroundTaskService: backgroundTaskService)
}
func loadUserDisplayName() async -> Result<String, ClientProxyError> {
func loadUserDisplayName() async -> Result<Void, ClientProxyError> {
await Task.dispatch(on: clientQueue) {
do {
let displayName = try self.client.displayName()
return .success(displayName)
self.userDisplayNameSubject.send(displayName)
return .success(())
} catch {
return .failure(.failedRetrievingDisplayName)
return .failure(.failedRetrievingUserDisplayName)
}
}
}
func setUserDisplayName(_ name: String) async -> Result<Void, ClientProxyError> {
await Task.dispatch(on: clientQueue) {
do {
try self.client.setDisplayName(name: name)
Task {
await self.loadUserDisplayName()
}
return .success(())
} catch {
return .failure(.failedSettingUserDisplayName)
}
}
}
func loadUserAvatarURL() async {
func loadUserAvatarURL() async -> Result<Void, ClientProxyError> {
await Task.dispatch(on: clientQueue) {
do {
let urlString = try self.client.avatarUrl()
self.loadCachedAvatarURLTask?.cancel()
self.avatarURLSubject.value = urlString.flatMap(URL.init)
self.userAvatarURLSubject.send(urlString.flatMap(URL.init))
return .success(())
} catch {
MXLog.error("Failed fetching the user avatar url: \(error)")
return
return .failure(.failedRetrievingUserAvatarURL)
}
}
}
func setUserAvatar(media: MediaInfo) async -> Result<Void, ClientProxyError> {
await Task.dispatch(on: .global()) {
guard case let .image(imageURL, _, _) = media, let mimeType = media.mimeType else {
return .failure(.failedSettingUserAvatar)
}
do {
let data = try Data(contentsOf: imageURL)
try self.client.uploadAvatar(mimeType: mimeType, data: [UInt8](data))
Task {
await self.loadUserAvatarURL()
}
return .success(())
} catch {
return .failure(.failedSettingUserAvatar)
}
}
}
func removeUserAvatar() async -> Result<Void, ClientProxyError> {
await Task.dispatch(on: .global()) {
do {
try self.client.removeAvatar()
Task {
await self.loadUserAvatarURL()
}
return .success(())
} catch {
return .failure(.failedSettingUserAvatar)
}
}
}
@@ -381,7 +431,7 @@ class ClientProxy: ClientProxyProtocol {
}
}
guard !Task.isCancelled else { return }
self.avatarURLSubject.value = urlString.flatMap(URL.init)
self.userAvatarURLSubject.value = urlString.flatMap(URL.init)
}
}
@@ -39,7 +39,9 @@ enum ClientProxyLoadingState {
enum ClientProxyError: Error {
case failedCreatingRoom
case failedRetrievingDirectRoom
case failedRetrievingDisplayName
case failedRetrievingUserDisplayName
case failedRetrievingUserAvatarURL
case failedSettingUserDisplayName
case failedRetrievingAccountData
case failedSettingAccountData
case failedRetrievingSessionVerificationController
@@ -48,6 +50,7 @@ enum ClientProxyError: Error {
case failedUploadingMedia(MatrixErrorCode)
case failedSearchingUsers
case failedGettingUserProfile
case failedSettingUserAvatar
}
enum SlidingSyncConstants {
@@ -77,8 +80,10 @@ protocol ClientProxyProtocol: AnyObject, MediaLoaderProtocol {
var deviceID: String? { get }
var homeserver: String { get }
var userDisplayName: CurrentValuePublisher<String?, Never> { get }
var avatarURLPublisher: AnyPublisher<URL?, Never> { get }
var userAvatarURL: CurrentValuePublisher<URL?, Never> { get }
var restorationToken: RestorationToken? { get }
@@ -104,9 +109,15 @@ protocol ClientProxyProtocol: AnyObject, MediaLoaderProtocol {
func roomForIdentifier(_ identifier: String) async -> RoomProxyProtocol?
func loadUserDisplayName() async -> Result<String, ClientProxyError>
@discardableResult func loadUserDisplayName() async -> Result<Void, ClientProxyError>
func setUserDisplayName(_ name: String) async -> Result<Void, ClientProxyError>
func loadUserAvatarURL() async
@discardableResult func loadUserAvatarURL() async -> Result<Void, ClientProxyError>
func setUserAvatar(media: MediaInfo) async -> Result<Void, ClientProxyError>
func removeUserAvatar() async -> Result<Void, ClientProxyError>
func accountDataEvent<Content: Decodable>(type: String) async -> Result<Content?, ClientProxyError>
@@ -32,7 +32,9 @@ class MockClientProxy: ClientProxyProtocol {
var inviteSummaryProvider: RoomSummaryProviderProtocol? = MockRoomSummaryProvider()
var avatarURLPublisher: AnyPublisher<URL?, Never> { Empty().eraseToAnyPublisher() }
var userAvatarURL: CurrentValuePublisher<URL?, Never> { CurrentValueSubject<URL?, Never>(nil).asCurrentValuePublisher() }
var userDisplayName: CurrentValuePublisher<String?, Never> { CurrentValueSubject<String?, Never>("User display name").asCurrentValuePublisher() }
var notificationSettings: NotificationSettingsProxyProtocol = NotificationSettingsProxyMock(with: .init())
@@ -41,8 +43,6 @@ class MockClientProxy: ClientProxyProtocol {
self.deviceID = deviceID
self.roomSummaryProvider = roomSummaryProvider
}
func loadUserAvatarURL() async { }
func startSync() { }
@@ -87,8 +87,24 @@ class MockClientProxy: ClientProxyProtocol {
}
}
func loadUserDisplayName() async -> Result<String, ClientProxyError> {
.success("User display name")
func loadUserDisplayName() async -> Result<Void, ClientProxyError> {
.failure(.failedRetrievingUserDisplayName)
}
func setUserDisplayName(_ name: String) async -> Result<Void, ClientProxyError> {
.failure(.failedSettingUserDisplayName)
}
func loadUserAvatarURL() async -> Result<Void, ClientProxyError> {
.failure(.failedRetrievingUserAvatarURL)
}
func setUserAvatar(media: MediaInfo) async -> Result<Void, ClientProxyError> {
.failure(.failedSettingUserAvatar)
}
func removeUserAvatar() async -> Result<Void, ClientProxyError> {
.failure(.failedSettingUserAvatar)
}
func accountDataEvent<Content>(type: String) async -> Result<Content?, ClientProxyError> where Content: Decodable {