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

218 lines
9.2 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)
}
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, _)):
return Future<AppAction, Never> { [weak self] promise in
guard let wSelf = self else {
promise(.success(.empty))
return
}
// Observe changes for current conversation
wSelf.conversationCancellables = []
ValueObservation
.tracking(
Message
.filter(
Column("from") == chat.account ||
Column("from") == chat.participant ||
Column("to") == chat.participant ||
Column("to") == chat.participant
)
.order(Column("timestamp").asc)
.fetchAll
)
.publisher(in: wSelf.database._db, scheduling: .immediate)
.sink { _ in
// Handle completion
} receiveValue: { messages in
DispatchQueue.main.async {
store.dispatch(.conversationAction(.messagesUpdated(messages: messages)))
}
}
.store(in: &wSelf.conversationCancellables)
promise(.success(.empty))
}
.eraseToAnyPublisher()
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 {
promise(.success(.empty))
return
}
do {
try database._db.write { db in
try message.insert(db)
promise(.success(.empty))
}
} catch {
promise(.success(.databaseAction(.updateAccountFailed)))
}
}
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-24 13:28:26 +00:00
return Empty().eraseToAnyPublisher()
2024-06-19 15:15:27 +00:00
default:
return Empty().eraseToAnyPublisher()
}
}
}