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

48 lines
1.4 KiB
Swift
Raw Permalink Normal View History

import Combine
import Foundation
import GRDB
import Martin
final class ClientMartinCarbonsManager {
private var cancellables: Set<AnyCancellable> = []
init(_ xmppConnection: XMPPClient) {
// subscribe to carbons
xmppConnection.module(MessageCarbonsModule.self).carbonsPublisher
.sink { [weak self] carbon in
self?.handleMessage(carbon)
}
.store(in: &cancellables)
// enable carbons if available
xmppConnection.module(.messageCarbons).$isAvailable.filter { $0 }
.sink(receiveValue: { [weak xmppConnection] _ in
xmppConnection?.module(.messageCarbons).enable()
})
.store(in: &cancellables)
}
private func handleMessage(_ received: Martin.MessageCarbonsModule.CarbonReceived) {
let message = received.message
let action = received.action
let onJid = received.jid
#if DEBUG
print("---")
print("Carbons message received: \(message)")
print("Action: \(action)")
print("On JID: \(onJid)")
print("---")
#endif
if let msg = Message.map(message, context: nil) {
Task {
do {
try await msg.save()
} catch {
logIt(.error, "Error saving message: \(error)")
}
}
}
}
}