This commit is contained in:
fmodf 2024-06-20 07:43:49 +02:00
parent f8a38b0fdd
commit 0c8df19d55
5 changed files with 48 additions and 4 deletions

View file

@ -2,4 +2,9 @@ enum ChatsAction: Codable {
case chatsListUpdated(chats: [Chat])
case startChat(accountJid: String, participantJid: String)
case chatStarted(chat: Chat)
case createNewChat(accountJid: String, participantJid: String)
case chatCreated(chat: Chat)
case chatCreationFailed(reason: String)
}

View file

@ -11,14 +11,24 @@ final class ChatsMiddleware {
case .chatsAction(.startChat(accountJid: let accountJid, participantJid: let participantJid)):
return Future<AppAction, Never> { promise in
// find existing chat
let exist = state.chatsState.chats.first {
$0.account == accountJid && $0.participant == participantJid
if let exist = state.chatsState.chats.first(where: { $0.account == accountJid && $0.participant == participantJid }) {
// open existing chat
promise(.success(.chatsAction(.chatStarted(chat: exist))))
} else {
// create new chat
promise(.success(.chatsAction(.createNewChat(accountJid: accountJid, participantJid: participantJid))))
}
promise(.success(.empty))
}
.eraseToAnyPublisher()
case .chatsAction(.chatCreated(let chat)):
return Just(.chatsAction(.chatStarted(chat: chat)))
.eraseToAnyPublisher()
case .chatsAction(.chatStarted(let chat)):
// TODO: make transition to chat screen
return Empty().eraseToAnyPublisher()
default:
return Empty().eraseToAnyPublisher()
}

View file

@ -125,6 +125,31 @@ final class DatabaseMiddleware {
}
.eraseToAnyPublisher()
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()
default:
return Empty().eraseToAnyPublisher()
}

View file

@ -4,6 +4,9 @@ extension ChatsState {
case .chatsListUpdated(let chats):
state.chats = chats
case .chatStarted(let chat):
state.currentChat = chat
default:
break
}

View file

@ -1,5 +1,6 @@
struct ChatsState: Stateable {
var chats: [Chat]
var currentChat: Chat?
}
// MARK: Init