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)):
|
|
|
|
return Future<AppAction, Never> { promise in
|
|
|
|
guard let account = state.accountsState.accounts.first(where: { $0.bareJid == jid }) else {
|
2024-07-16 14:05:15 +00:00
|
|
|
promise(.success(.info("AccountsMiddleware: account not found for jid \(jid)")))
|
2024-06-19 15:15:27 +00:00
|
|
|
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 {
|
2024-07-16 14:05:15 +00:00
|
|
|
promise(.success(.info("AccountsMiddleware: account \(jid) disconnected with no error")))
|
2024-06-19 15:15:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
default:
|
2024-07-16 14:05:15 +00:00
|
|
|
promise(.success(.info("AccountsMiddleware: account \(jid) connection status changed to \(connectionStatus)")))
|
2024-06-19 15:15:27 +00:00
|
|
|
}
|
|
|
|
} else {
|
2024-07-16 14:05:15 +00:00
|
|
|
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)):
|
|
|
|
return Future<AppAction, Never> { [weak self] promise in
|
|
|
|
let serverFeatures = features
|
|
|
|
.compactMap { featureId in
|
|
|
|
self?.allFeatures.first(where: { $0.xep == featureId })
|
|
|
|
}
|
|
|
|
promise(.success(.accountsAction(.clientServerFeaturesUpdated(jid: jid, features: serverFeatures))))
|
|
|
|
}
|
|
|
|
.eraseToAnyPublisher()
|
|
|
|
|
2024-06-19 15:15:27 +00:00
|
|
|
default:
|
|
|
|
return Empty().eraseToAnyPublisher()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|