Кэш чатов

This commit is contained in:
Халимов Рустам
2026-04-20 00:25:40 +03:00
parent 945134f029
commit 7c66e1c0c0
35 changed files with 2131 additions and 92 deletions
@@ -18,9 +18,10 @@ import java.io.File
import javax.inject.Inject
import core.utils.copyUriToFile
import core.utils.ImageUtils
import chats.data.remote.api.KlipyGifDto
private const val TAG = "ChatDetailViewModel"
data class ChatDetailState(
val messages: List<Message> = emptyList(),
val chatName: String? = null,
@@ -134,8 +135,26 @@ class ChatDetailViewModel @Inject constructor(
fun refreshMessages(chatId: String) {
viewModelScope.launch {
val messages = repository.getMessages(chatId)
updateMessages(messages)
try {
// Сначала пытаемся загрузить из сети
val messages = repository.getMessages(chatId)
if (messages.isNotEmpty()) {
updateMessages(messages)
return@launch
}
} catch (e: Exception) {
android.util.Log.d(TAG, "Network load failed, trying cache")
}
// Если сеть не доступна или пуста - загружаем из Room
try {
val cachedMessages = repository.getMessagesFlow(chatId).first()
android.util.Log.d(TAG, "Loaded ${cachedMessages.size} messages from cache")
updateMessages(cachedMessages)
} catch (e: Exception) {
android.util.Log.e(TAG, "Cache load failed", e)
_state.update { it.copy(isLoading = false, messages = emptyList()) }
}
}
}
@@ -167,14 +186,29 @@ class ChatDetailViewModel @Inject constructor(
private fun loadChatInfo(chatId: String) {
viewModelScope.launch {
// Пробуем загрузить из API
try {
val chats = repository.getChats()
val chat = chats.find { it.id == chatId }
chat?.let { c ->
_state.update { it.copy(chatName = c.name, chatAvatar = c.avatar) }
android.util.Log.d(TAG, "Loaded chat info from API: ${c.name}")
return@launch
}
} catch (e: Exception) {
// Ignore info load error
android.util.Log.d(TAG, "API load failed, will use messages for title")
}
// Если API недоступно - берём имя из сообщений (для личных чатов)
try {
val cachedMessages = repository.getMessagesFlow(chatId).first()
val otherUserMessage = cachedMessages.firstOrNull { it.senderId != getCurrentUserId() }
otherUserMessage?.let { msg ->
_state.update { it.copy(chatName = msg.senderName, chatAvatar = msg.senderAvatar) }
android.util.Log.d(TAG, "Loaded chat title from messages: ${msg.senderName}")
}
} catch (e: Exception) {
android.util.Log.e(TAG, "Failed to load chat title from messages", e)
}
}
}
@@ -191,7 +225,7 @@ class ChatDetailViewModel @Inject constructor(
s.copy(messages = updatedMessages)
}
}
// For handling reaction removed event
private fun removeMessageReaction(messageId: String, userId: String, emoji: String) {
_state.update { s ->
@@ -377,7 +411,7 @@ class ChatDetailViewModel @Inject constructor(
}
}
}
fun onForward(message: Message) {
_state.update { it.copy(forwardingMessages = listOf(message)) }
loadChatsForForwarding()