another.im-ios/old/AppCore/Middlewares/AccountsMiddleware.swift

70 lines
2.9 KiB
Swift
Raw Normal View History

2024-06-19 15:15:27 +00:00
import Combine
2024-07-22 12:02:33 +00:00
import Foundation
2024-06-19 15:15:27 +00:00
final class AccountsMiddleware {
static let shared = AccountsMiddleware()
2024-07-22 12:02:33 +00:00
private lazy var allFeatures: [ServerFeature] = {
guard
let url = Bundle.main.url(forResource: "server_features", withExtension: "plist"),
let data = try? Data(contentsOf: url),
let loaded = try? PropertyListDecoder().decode([ServerFeature].self, from: data)
else {
return []
}
return loaded
}()
2024-06-19 15:15:27 +00:00
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)):
2024-08-07 12:49:47 +00:00
return Deferred {
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))))
2024-06-19 15:15:27 +00:00
2024-08-07 12:49:47 +00:00
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")))
}
2024-06-19 15:15:27 +00:00
2024-08-07 12:49:47 +00:00
default:
promise(.success(.info("AccountsMiddleware: account \(jid) connection status changed to \(connectionStatus)")))
}
} else {
promise(.success(.info("AccountsMiddleware: account \(jid) is not temporary, ignoring")))
2024-06-19 15:15:27 +00:00
}
}
}
.eraseToAnyPublisher()
2024-07-22 12:02:33 +00:00
case .xmppAction(.serverFeaturesLoaded(let jid, let features)):
2024-08-07 12:49:47 +00:00
return Deferred {
Future<AppAction, Never> { [weak self] promise in
let serverFeatures = features
.compactMap { featureId in
self?.allFeatures.first(where: { $0.xmppId == featureId })
}
promise(.success(.accountsAction(.clientServerFeaturesUpdated(jid: jid, features: serverFeatures))))
}
2024-07-22 12:02:33 +00:00
}
.eraseToAnyPublisher()
2024-06-19 15:15:27 +00:00
default:
return Empty().eraseToAnyPublisher()
}
}
}