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

83 lines
2.6 KiB
Swift
Raw Normal View History

import Combine
import Foundation
import GRDB
import Martin
private typealias ArchMsg = Martin.MessageArchiveManagementModule.ArchivedMessageReceived
final class ClientMartinMAM {
private var cancellables: Set<AnyCancellable> = []
2024-11-08 13:12:42 +00:00
private var processor: ArchiveMessageProcessor
init(_ xmppConnection: XMPPClient) {
2024-11-08 13:12:42 +00:00
processor = ArchiveMessageProcessor(xmppConnection.context)
// subscribe to archived messages
xmppConnection.module(.mam).archivedMessagesPublisher
.sink(receiveValue: { [weak self] archived in
guard let self = self else { return }
Task {
await self.processor.append(archived)
}
})
.store(in: &cancellables)
}
}
private actor ArchiveMessageProcessor {
private var accumulator: [ArchMsg] = []
2024-11-08 13:12:42 +00:00
private let context: Context?
2024-11-08 13:12:42 +00:00
init(_ ctx: Context?) {
context = ctx
Task {
while true {
try? await Task.sleep(nanoseconds: 700 * NSEC_PER_MSEC)
await process()
}
}
}
func append(_ msg: ArchMsg) async {
accumulator.append(msg)
if accumulator.count >= Const.mamRequestPageSize {
await process()
}
}
func process() async {
if accumulator.isEmpty { return }
await handleMessages(accumulator)
accumulator.removeAll()
}
private func handleMessages(_ received: [ArchMsg]) async {
if received.isEmpty { return }
2024-11-08 13:12:42 +00:00
try? await Database.shared.dbQueue.write { [weak self] db in
for recv in received {
let message = recv.message
let date = recv.timestamp
if let msgId = message.id {
if try Message.fetchOne(db, key: msgId) != nil {
#if DEBUG
print("---")
print("Skipping archived message with id \(msgId) (message exists)")
print("---")
#endif
} else {
#if DEBUG
print("---")
print("Archive message received: \(message)")
print("Date: \(date)")
print("---")
#endif
2024-11-08 13:12:42 +00:00
if var msg = Message.map(message, context: self?.context) {
msg.date = date
try msg.insert(db)
}
}
}
}
}
}
}