151 lines
4.9 KiB
Swift
151 lines
4.9 KiB
Swift
import Combine
|
|
import Foundation
|
|
import GRDB
|
|
import Martin
|
|
|
|
@MainActor
|
|
final class MessagesStore: ObservableObject {
|
|
@Published private(set) var messages: [Message] = []
|
|
@Published var replyText = ""
|
|
|
|
private(set) var roster: Roster
|
|
private let client: Client
|
|
|
|
private var messagesCancellable: AnyCancellable?
|
|
private let archiver = ArchiveMessageFetcher()
|
|
|
|
init(roster: Roster, client: Client) {
|
|
self.client = client
|
|
self.roster = roster
|
|
subscribe()
|
|
}
|
|
}
|
|
|
|
// MARK: - Send message
|
|
extension MessagesStore {
|
|
func sendMessage(_ message: String) {
|
|
Task {
|
|
var msg = Message.blank
|
|
msg.from = roster.bareJid
|
|
msg.to = roster.contactBareJid
|
|
msg.body = message
|
|
msg.secure = true
|
|
|
|
// store as pending on db, and send
|
|
do {
|
|
try await msg.save()
|
|
try await client.sendMessage(msg)
|
|
try await msg.setStatus(.sent)
|
|
} catch {
|
|
try? await msg.setStatus(.error)
|
|
}
|
|
}
|
|
}
|
|
|
|
func sendContact(_ jidStr: String) {
|
|
sendMessage("contact:\(jidStr)")
|
|
}
|
|
|
|
func sendLocation(_ lat: Double, _ lon: Double) {
|
|
sendMessage("geo:\(lat),\(lon)")
|
|
}
|
|
}
|
|
|
|
// MARK: - Subscriptions
|
|
private extension MessagesStore {
|
|
func subscribe() {
|
|
messagesCancellable = ValueObservation.tracking(Message
|
|
.filter(
|
|
(Column("to") == roster.bareJid && Column("from") == roster.contactBareJid) ||
|
|
(Column("from") == roster.bareJid && Column("to") == roster.contactBareJid)
|
|
)
|
|
.order(Column("date").desc)
|
|
.fetchAll
|
|
)
|
|
.publisher(in: Database.shared.dbQueue, scheduling: .immediate)
|
|
.receive(on: DispatchQueue.main)
|
|
.sink { _ in
|
|
} receiveValue: { [weak self] messages in
|
|
guard let self else { return }
|
|
self.messages = messages
|
|
Task {
|
|
await self.archiver.initialFetch(messages, self.roster, self.client)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Archived messages
|
|
extension MessagesStore {
|
|
func scrolledMessage(_ messageId: String) {
|
|
if messageId == messages.last?.id {
|
|
Task {
|
|
await archiver.fetchBackward(roster, client)
|
|
}
|
|
} else if messageId == messages.first?.id {
|
|
Task {
|
|
await archiver.fetchForward(roster, client)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private actor ArchiveMessageFetcher {
|
|
private var initFetchStarted = false
|
|
private var forwardRsm: RSM.Query?
|
|
private var backwardRsm: RSM.Query?
|
|
private var fetchInProgress = false
|
|
|
|
func initialFetch(_ messages: [Message], _ roster: Roster, _ client: Client) async {
|
|
if initFetchStarted { return }
|
|
initFetchStarted = true
|
|
fetchInProgress = true
|
|
|
|
do {
|
|
if let firstExistId = messages.first?.id {
|
|
let result = try await client.fetchArchiveMessages(for: roster, query: .init(before: firstExistId, max: Const.mamRequestPageSize))
|
|
result.complete ? forwardRsm = nil : (forwardRsm = .init(after: result.rsm?.last, max: Const.mamRequestPageSize))
|
|
result.complete ? backwardRsm = nil : (backwardRsm = .init(before: result.rsm?.first, max: Const.mamRequestPageSize))
|
|
} else {
|
|
let result = try await client.fetchArchiveMessages(for: roster, query: .init(lastItems: Const.mamRequestPageSize))
|
|
result.complete ? backwardRsm = nil : (backwardRsm = .init(before: result.rsm?.first, max: Const.mamRequestPageSize))
|
|
}
|
|
} catch {
|
|
logIt(.error, "Error requesting archived messages: \(error)")
|
|
initFetchStarted = false
|
|
}
|
|
|
|
fetchInProgress = false
|
|
}
|
|
|
|
func fetchForward(_ roster: Roster, _ client: Client) async {
|
|
while !initFetchStarted {
|
|
await Task.yield()
|
|
}
|
|
guard let rsm = forwardRsm else { return }
|
|
if fetchInProgress { return }
|
|
|
|
fetchInProgress = true
|
|
Task {
|
|
let result = try await client.fetchArchiveMessages(for: roster, query: rsm)
|
|
result.complete ? (forwardRsm = nil) : (forwardRsm = .init(after: result.rsm?.last, max: Const.mamRequestPageSize))
|
|
fetchInProgress = false
|
|
}
|
|
}
|
|
|
|
func fetchBackward(_ roster: Roster, _ client: Client) async {
|
|
while !initFetchStarted {
|
|
await Task.yield()
|
|
}
|
|
guard let rsm = backwardRsm else { return }
|
|
if fetchInProgress { return }
|
|
|
|
fetchInProgress = true
|
|
Task {
|
|
let result = try await client.fetchArchiveMessages(for: roster, query: rsm)
|
|
result.complete ? (backwardRsm = nil) : (backwardRsm = .init(before: result.rsm?.first, max: Const.mamRequestPageSize))
|
|
fetchInProgress = false
|
|
}
|
|
}
|
|
}
|