59 lines
1.8 KiB
Swift
59 lines
1.8 KiB
Swift
import Combine
|
|
import Foundation
|
|
import GRDB
|
|
import Martin
|
|
|
|
final class ClientMartinMAM {
|
|
private var cancellables: Set<AnyCancellable> = []
|
|
|
|
private weak var module: MessageArchiveManagementModule?
|
|
private var afterAvailable = true
|
|
private var beforeAvailable = true
|
|
|
|
init(_ xmppConnection: XMPPClient) {
|
|
module = xmppConnection.module(.mam)
|
|
subscribe()
|
|
}
|
|
|
|
private func subscribe() {
|
|
// subscribe to archived messages
|
|
module?.archivedMessagesPublisher
|
|
.delay(for: 0.7, scheduler: DispatchQueue.main)
|
|
.sink(receiveValue: { [weak self] archived in
|
|
guard let self = self else { return }
|
|
Task {
|
|
await self.handleMessage(archived)
|
|
}
|
|
})
|
|
.store(in: &cancellables)
|
|
}
|
|
|
|
private func handleMessage(_ received: Martin.MessageArchiveManagementModule.ArchivedMessageReceived) async {
|
|
let message = received.message
|
|
let date = received.timestamp
|
|
let msgId = received.messageId
|
|
|
|
try? await Database.shared.dbQueue.write { db in
|
|
if try Message.fetchOne(db, key: msgId) != nil {
|
|
#if DEBUG
|
|
print("---")
|
|
print("Skipping archived message with id \(message.id ?? "???") (message exists)")
|
|
print("---")
|
|
#endif
|
|
return
|
|
} else {
|
|
#if DEBUG
|
|
print("---")
|
|
print("Archive message received: \(message)")
|
|
print("Date: \(date)")
|
|
print("---")
|
|
#endif
|
|
if var msg = Message.map(message) {
|
|
msg.date = received.timestamp
|
|
try msg.insert(db)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|