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

76 lines
2.7 KiB
Swift
Raw Normal View History

2024-08-06 11:15:13 +00:00
import Foundation
import GRDB
import Martin
final class ClientMartinChatsManager: Martin.ChatManager {
2024-08-06 11:15:13 +00:00
func chats(for context: Martin.Context) -> [any Martin.ChatProtocol] {
do {
let chats: [Chat] = try Database.shared.dbQueue.read { db in
2024-08-06 11:15:13 +00:00
try Chat.filter(Column("account") == context.userBareJid.stringValue).fetchAll(db)
}
return chats.map { chat in
Martin.ChatBase(context: context, jid: BareJID(chat.participant))
}
} catch {
logIt(.error, "Error fetching chats: \(error.localizedDescription)")
return []
}
}
func chat(for context: Martin.Context, with: Martin.BareJID) -> (any Martin.ChatProtocol)? {
do {
let chat: Chat? = try Database.shared.dbQueue.read { db in
2024-08-06 11:15:13 +00:00
try Chat
.filter(Column("account") == context.userBareJid.stringValue)
.filter(Column("participant") == with.stringValue)
.fetchOne(db)
}
if chat != nil {
return Martin.ChatBase(context: context, jid: with)
} else {
return nil
}
} catch {
logIt(.error, "Error fetching chat: \(error.localizedDescription)")
return nil
}
}
func createChat(for context: Martin.Context, with: Martin.BareJID) -> (any Martin.ChatProtocol)? {
do {
let chat: Chat? = try Database.shared.dbQueue.read { db in
2024-08-06 11:15:13 +00:00
try Chat
.filter(Column("account") == context.userBareJid.stringValue)
.filter(Column("participant") == with.stringValue)
.fetchOne(db)
}
if chat != nil {
return Martin.ChatBase(context: context, jid: with)
} else {
let chat = Chat(
id: UUID().uuidString,
account: context.userBareJid.stringValue,
participant: with.stringValue,
type: .chat
)
try Database.shared.dbQueue.write { db in
2024-08-06 11:15:13 +00:00
try chat.save(db)
}
return Martin.ChatBase(context: context, jid: with)
}
} catch {
logIt(.error, "Error fetching chat: \(error.localizedDescription)")
return nil
}
}
func close(chat: any Martin.ChatProtocol) -> Bool {
// not used in Martin library for now
print("Closing chat: \(chat)")
return false
}
func initialize(context _: Martin.Context) {}
func deinitialize(context _: Martin.Context) {}
2024-08-06 11:15:13 +00:00
}