another.im-ios/AnotherIM/AppData/Client/Client+MartinCarbons.swift
2024-11-08 11:55:47 +01:00

49 lines
1.5 KiB
Swift

import Combine
import Foundation
import GRDB
import Martin
final class ClientMartinCarbonsManager {
private var cancellables: Set<AnyCancellable> = []
init(_ xmppConnection: XMPPClient) {
// subscribe to carbons
let ctx = xmppConnection.module(MessageCarbonsModule.self).context
xmppConnection.module(MessageCarbonsModule.self).carbonsPublisher
.sink { [weak self] carbon in
self?.handleMessage(carbon, ctx)
}
.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, _ context: Context?) {
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: context) {
Task {
do {
try await msg.save()
} catch {
logIt(.error, "Error saving message: \(error)")
}
}
}
}
}