another.im-ios/ConversationsClassic/AppCore/Middlewares/DatabaseMiddleware.swift

323 lines
14 KiB
Swift
Raw Normal View History

2024-06-19 15:15:27 +00:00
import Combine
import Foundation
import GRDB
final class DatabaseMiddleware {
static let shared = DatabaseMiddleware()
private let database = Database.shared
private var cancellables: Set<AnyCancellable> = []
2024-06-26 08:00:59 +00:00
private var conversationCancellables: Set<AnyCancellable> = []
2024-06-19 15:15:27 +00:00
private init() {
// Database changes
ValueObservation
.tracking(Roster.fetchAll)
.publisher(in: database._db, scheduling: .immediate)
.sink { _ in
// Handle completion
} receiveValue: { rosters in
DispatchQueue.main.async {
store.dispatch(.databaseAction(.storedRostersLoaded(rosters: rosters)))
}
}
.store(in: &cancellables)
ValueObservation
.tracking(Chat.fetchAll)
.publisher(in: database._db, scheduling: .immediate)
.sink { _ in
// Handle completion
} receiveValue: { chats in
DispatchQueue.main.async {
store.dispatch(.databaseAction(.storedChatsLoaded(chats: chats)))
}
}
.store(in: &cancellables)
}
2024-06-26 09:29:30 +00:00
// swiftlint:disable:next function_body_length
2024-06-19 15:15:27 +00:00
func middleware(state _: AppState, action: AppAction) -> AnyPublisher<AppAction, Never> {
switch action {
2024-06-26 08:00:59 +00:00
// MARK: Accounts
2024-06-19 15:15:27 +00:00
case .startAction(.loadStoredAccounts):
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.databaseAction(.loadingStoredAccountsFailed)))
return
}
do {
try database._db.read { db in
let accounts = try Account.fetchAll(db)
promise(.success(.databaseAction(.storedAccountsLoaded(accounts: accounts))))
}
} catch {
promise(.success(.databaseAction(.loadingStoredAccountsFailed)))
}
}
}
.eraseToAnyPublisher()
case .accountsAction(.makeAccountPermanent(let account)):
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.databaseAction(.updateAccountFailed)))
return
}
do {
try database._db.write { db in
// make permanent and store to database
var acc = account
acc.isTemp = false
try acc.insert(db)
// Re-Fetch all accounts
let accounts = try Account.fetchAll(db)
// Use the accounts
promise(.success(.databaseAction(.storedAccountsLoaded(accounts: accounts))))
}
} catch {
promise(.success(.databaseAction(.updateAccountFailed)))
}
}
}
.eraseToAnyPublisher()
2024-06-26 08:00:59 +00:00
// MARK: Rosters
2024-06-19 15:15:27 +00:00
case .rostersAction(.markRosterAsLocallyDeleted(let ownerJID, let contactJID)):
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.rostersAction(.rosterDeletingFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
_ = try database._db.write { db in
try Roster
.filter(Column("bareJid") == ownerJID)
.filter(Column("contactBareJid") == contactJID)
.updateAll(db, Column("locallyDeleted").set(to: true))
}
promise(.success(.empty))
} catch {
promise(.success(.rostersAction(.rosterDeletingFailed(reason: L10n.Global.Error.genericDbError))))
}
}
}
.eraseToAnyPublisher()
case .rostersAction(.unmarkRosterAsLocallyDeleted(let ownerJID, let contactJID)):
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.rostersAction(.rosterDeletingFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
_ = try database._db.write { db in
try Roster
.filter(Column("bareJid") == ownerJID)
.filter(Column("contactBareJid") == contactJID)
.updateAll(db, Column("locallyDeleted").set(to: false))
}
promise(.success(.empty))
} catch {
promise(.success(.rostersAction(.rosterDeletingFailed(reason: L10n.Global.Error.genericDbError))))
}
}
}
.eraseToAnyPublisher()
2024-06-26 08:00:59 +00:00
// MARK: Chats
2024-06-20 05:43:49 +00:00
case .chatsAction(.createNewChat(let accountJid, let participantJid)):
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.chatsAction(.chatCreationFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
try database._db.write { db in
let chat = Chat(
id: UUID().uuidString,
account: accountJid,
participant: participantJid,
type: .chat
)
try chat.insert(db)
promise(.success(.chatsAction(.chatCreated(chat: chat))))
}
} catch {
promise(.success(.chatsAction(.chatCreationFailed(reason: L10n.Global.Error.genericDbError))))
}
}
}
.eraseToAnyPublisher()
2024-06-26 08:00:59 +00:00
// MARK: Conversation and messages
case .conversationAction(.makeConversationActive(let chat, _)):
2024-06-26 09:29:30 +00:00
subscribeToMessages(chat: chat)
return Empty().eraseToAnyPublisher()
2024-06-26 08:00:59 +00:00
2024-06-24 13:28:26 +00:00
case .xmppAction(.xmppMessageReceived(let message)):
2024-06-26 08:00:59 +00:00
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
2024-06-26 09:29:30 +00:00
promise(.success(.databaseAction(.storeMessageFailed(reason: L10n.Global.Error.genericDbError))))
return
}
2024-07-02 07:22:28 +00:00
guard message.contentType != .typing, message.body != nil else {
2024-06-26 08:00:59 +00:00
promise(.success(.empty))
return
}
do {
try database._db.write { db in
try message.insert(db)
}
2024-07-11 13:59:24 +00:00
if let remoteUrl = message.oobUrl {
let attachment = Attachment(
id: UUID().uuidString,
type: remoteUrl.attachmentType,
localPath: nil,
remotePath: URL(string: remoteUrl),
localThumbnailPath: nil,
messageId: message.id
)
try database._db.write { db in
try attachment.insert(db)
try Message
.filter(Column("id") == message.id)
.updateAll(db, [Column("attachmentId").set(to: attachment.id)])
}
}
2024-06-26 09:29:30 +00:00
promise(.success(.empty))
2024-06-26 08:00:59 +00:00
} catch {
2024-06-26 09:29:30 +00:00
promise(.success(.databaseAction(.storeMessageFailed(reason: error.localizedDescription))))
2024-06-26 08:00:59 +00:00
}
}
2024-06-24 13:28:26 +00:00
}
2024-06-26 08:00:59 +00:00
.eraseToAnyPublisher()
case .conversationAction(.sendMessage(let from, let to, let body)):
2024-06-26 10:26:04 +00:00
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.databaseAction(.storeMessageFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
let message = Message(
id: UUID().uuidString,
type: .chat,
contentType: .text,
from: from,
to: to,
body: body,
subject: nil,
thread: nil,
oobUrl: nil,
date: Date(),
pending: true,
sentError: false
)
try database._db.write { db in
try message.insert(db)
}
promise(.success(.xmppAction(.xmppMessageSent(message))))
} catch {
promise(.success(.databaseAction(.storeMessageFailed(reason: error.localizedDescription))))
}
}
}
.eraseToAnyPublisher()
case .xmppAction(.xmppMessageSendSuccess(let msgId)):
// mark message as pending false and sentError false
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.databaseAction(.storeMessageFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
_ = try database._db.write { db in
try Message
.filter(Column("id") == msgId)
.updateAll(db, Column("pending").set(to: false), Column("sentError").set(to: false))
}
promise(.success(.empty))
} catch {
promise(.success(.databaseAction(.storeMessageFailed(reason: error.localizedDescription)))
)
}
}
}
.eraseToAnyPublisher()
case .xmppAction(.xmppMessageSendFailed(let msgId)):
// mark message as pending false and sentError true
return Future<AppAction, Never> { promise in
Task(priority: .background) { [weak self] in
guard let database = self?.database else {
promise(.success(.databaseAction(.storeMessageFailed(reason: L10n.Global.Error.genericDbError))))
return
}
do {
_ = try database._db.write { db in
try Message
.filter(Column("id") == msgId)
.updateAll(db, Column("pending").set(to: false), Column("sentError").set(to: true))
}
promise(.success(.empty))
} catch {
promise(.success(.databaseAction(.storeMessageFailed(reason: error.localizedDescription)))
)
}
}
}
.eraseToAnyPublisher()
2024-06-24 13:28:26 +00:00
2024-06-19 15:15:27 +00:00
default:
return Empty().eraseToAnyPublisher()
}
}
}
2024-06-26 09:29:30 +00:00
private extension DatabaseMiddleware {
func subscribeToMessages(chat: Chat) {
conversationCancellables = []
ValueObservation
.tracking(
Message
.filter(
2024-07-02 06:32:23 +00:00
(Column("to") == chat.account && Column("from") == chat.participant) ||
2024-06-26 09:29:30 +00:00
(Column("from") == chat.account && Column("to") == chat.participant)
)
2024-07-01 10:05:39 +00:00
.order(Column("date").desc)
2024-07-11 13:59:24 +00:00
.including(optional: Message.attachment)
2024-06-26 09:29:30 +00:00
.fetchAll
)
.publisher(in: database._db, scheduling: .immediate)
2024-06-26 10:26:04 +00:00
.sink { _ in
2024-06-26 09:29:30 +00:00
} receiveValue: { messages in
DispatchQueue.main.async {
store.dispatch(.conversationAction(.messagesUpdated(messages: messages)))
}
}
.store(in: &conversationCancellables)
}
}
2024-07-11 13:59:24 +00:00
// try db.write { db in
// // Update the attachment
// var attachment = try Attachment.fetchOne(db, key: attachmentId)!
// attachment.someField = newValue
// try attachment.update(db)
//
// // Update the message
// var message = try Message.fetchOne(db, key: messageId)!
// message.someField = newValue
// try message.update(db)
// }