48 lines
2.8 KiB
Swift
48 lines
2.8 KiB
Swift
|
import Combine
|
||
|
import Foundation
|
||
|
|
||
|
final class ArchivedMessagesMiddleware {
|
||
|
static let shared = ArchivedMessagesMiddleware()
|
||
|
|
||
|
func middleware(state: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
|
||
|
switch action {
|
||
|
case .conversationAction(.messagesUpdated(let messages)):
|
||
|
if state.conversationsState.archivedMessagesRequested {
|
||
|
return Empty().eraseToAnyPublisher()
|
||
|
} else {
|
||
|
guard let chat = state.conversationsState.currentChat else {
|
||
|
return Empty().eraseToAnyPublisher()
|
||
|
}
|
||
|
return Deferred {
|
||
|
Future<AppAction, Never> { promise in
|
||
|
if let currentClient = state.accountsState.accounts.first(where: { $0.bareJid == chat.account }) {
|
||
|
let features = state.accountsState.discoFeatures[currentClient.bareJid] ?? []
|
||
|
if features.map({ $0.xep }).contains("XEP-0313") {
|
||
|
let roster = chat.participant
|
||
|
if let lastMessage = state.conversationsState.currentMessages.first {
|
||
|
promise(.success(.xmppAction(.xmppLoadArchivedMessages(jid: currentClient.bareJid, to: roster?.bareJid, fromDate: lastMessage.date))))
|
||
|
} else {
|
||
|
let date = Date()
|
||
|
let archivesRequestDate = Calendar.current.date(byAdding: .day, value: -Const.mamRequestLength, to: date) ?? date
|
||
|
promise(.success(.xmppAction(.xmppLoadArchivedMessages(jid: currentClient.bareJid, to: roster?.bareJid, fromDate: archivesRequestDate))))
|
||
|
}
|
||
|
// let oldestMessageDate = state.conversationsState.currentMessages.first?.date ?? Date()
|
||
|
// let archivesRequestDate = Calendar.current.date(byAdding: .day, value: -Const.mamRequestLength, to: oldestMessageDate) ?? Date()
|
||
|
// promise(.success(.xmppAction(.xmppLoadArchivedMessages(jid: currentClient.bareJid, to: roster?.bareJid, fromDate: archivesRequestDate))))
|
||
|
} else {
|
||
|
promise(.success(.info("MessageMiddleware: XEP-0313 not supported for client \(currentClient.bareJid)")))
|
||
|
}
|
||
|
} else {
|
||
|
promise(.success(.info("MessageMiddleware: No client found for account \(chat.account), probably some error here")))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
.eraseToAnyPublisher()
|
||
|
}
|
||
|
|
||
|
default:
|
||
|
return Empty().eraseToAnyPublisher()
|
||
|
}
|
||
|
}
|
||
|
}
|