another.im-ios/ConversationsClassic/AppData/Client/Client+MartinMAM.swift

59 lines
1.8 KiB
Swift
Raw Normal View History

2024-08-18 17:20:55 +00:00
import Combine
import Foundation
import GRDB
import Martin
final class ClientMartinMAM {
private var cancellables: Set<AnyCancellable> = []
2024-08-19 01:25:27 +00:00
private weak var module: MessageArchiveManagementModule?
private var afterAvailable = true
private var beforeAvailable = true
2024-08-18 17:20:55 +00:00
init(_ xmppConnection: XMPPClient) {
2024-08-19 01:25:27 +00:00
module = xmppConnection.module(.mam)
subscribe()
}
2024-08-18 20:27:12 +00:00
2024-08-19 01:25:27 +00:00
private func subscribe() {
2024-08-18 17:20:55 +00:00
// subscribe to archived messages
2024-08-19 01:25:27 +00:00
module?.archivedMessagesPublisher
.delay(for: 0.7, scheduler: DispatchQueue.main)
2024-08-18 17:20:55 +00:00
.sink(receiveValue: { [weak self] archived in
2024-08-18 20:27:12 +00:00
guard let self = self else { return }
Task {
2024-08-19 01:25:27 +00:00
await self.handleMessage(archived)
2024-08-18 20:27:12 +00:00
}
2024-08-18 17:20:55 +00:00
})
.store(in: &cancellables)
}
2024-08-18 20:27:12 +00:00
private func handleMessage(_ received: Martin.MessageArchiveManagementModule.ArchivedMessageReceived) async {
2024-08-18 17:20:55 +00:00
let message = received.message
let date = received.timestamp
2024-08-19 02:38:06 +00:00
let msgId = received.messageId
2024-08-18 17:20:55 +00:00
2024-08-19 02:38:06 +00:00
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)
2024-08-18 17:20:55 +00:00
}
}
}
}
}