another.im-ios/ConversationsClassic/AppCore/Middlewares/AccountsMiddleware.swift
2024-07-16 16:05:15 +02:00

44 lines
1.8 KiB
Swift

import Combine
final class AccountsMiddleware {
static let shared = AccountsMiddleware()
func middleware(state: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
switch action {
case .databaseAction(.storedAccountsLoaded(let accounts)):
return Just(.accountsAction(.accountsListUpdated(accounts: accounts)))
.eraseToAnyPublisher()
case .xmppAction(.clientConnectionChanged(let jid, let connectionStatus)):
return Future<AppAction, Never> { promise in
guard let account = state.accountsState.accounts.first(where: { $0.bareJid == jid }) else {
promise(.success(.info("AccountsMiddleware: account not found for jid \(jid)")))
return
}
if account.isTemp {
switch connectionStatus {
case .connected:
promise(.success(.accountsAction(.makeAccountPermanent(account: account))))
case .disconnected(let reason):
if reason != "No error!" {
promise(.success(.accountsAction(.addAccountError(jid: jid, reason: reason))))
} else {
promise(.success(.info("AccountsMiddleware: account \(jid) disconnected with no error")))
}
default:
promise(.success(.info("AccountsMiddleware: account \(jid) connection status changed to \(connectionStatus)")))
}
} else {
promise(.success(.info("AccountsMiddleware: account \(jid) is not temporary, ignoring")))
}
}
.eraseToAnyPublisher()
default:
return Empty().eraseToAnyPublisher()
}
}
}