feat: Enhance connection handling and add debug logs feature; improve user experience and troubleshooting

This commit is contained in:
k1ngsterr1
2026-01-17 06:21:26 +05:00
parent a64ee04b55
commit a9e426506b
9 changed files with 148 additions and 145 deletions

View File

@@ -151,10 +151,8 @@ class MessageRepository private constructor(private val context: Context) {
attachments: List<MessageAttachment> = emptyList(),
replyToMessageId: String? = null
): Message {
android.util.Log.d("MessageRepo", "📤 sendMessage START: to=${toPublicKey.take(16)}...")
val account = currentAccount ?: throw IllegalStateException("Not initialized")
val privateKey = currentPrivateKey ?: throw IllegalStateException("Not initialized")
android.util.Log.d("MessageRepo", "📤 sendMessage: account=${account.take(16)}...")
val messageId = UUID.randomUUID().toString().replace("-", "").take(32)
val timestamp = System.currentTimeMillis()
@@ -220,7 +218,6 @@ class MessageRepository private constructor(private val context: Context) {
// 🔥 Отмечаем что я отправлял сообщения в этот диалог (перемещает из requests в chats)
val updatedRows = dialogDao.markIHaveSent(account, toPublicKey)
android.util.Log.d("MessageRepo", "📤 MARKED i_have_sent=1 for opponent=${toPublicKey.take(16)}..., updatedRows=$updatedRows")
// Отправляем пакет
val packet = PacketMessage().apply {
@@ -316,17 +313,14 @@ class MessageRepository private constructor(private val context: Context) {
// ✅ Проверяем существование перед вставкой (защита от дубликатов)
val stillExists = messageDao.messageExists(account, messageId)
android.util.Log.d("MessageRepo", "📥 INCOMING: messageId=${messageId.take(16)}..., stillExists=$stillExists")
if (!stillExists) {
// Сохраняем в БД только если сообщения нет
messageDao.insertMessage(entity)
android.util.Log.d("MessageRepo", "📥 INSERTED message with read=0, fromMe=0")
}
// Обновляем диалог ПОСЛЕ вставки сообщения
updateDialog(packet.fromPublicKey, plainText, packet.timestamp, incrementUnread = true)
android.util.Log.d("MessageRepo", "📥 Dialog updated")
// 🔥 Запрашиваем информацию о пользователе для отображения имени вместо ключа
requestUserInfo(packet.fromPublicKey)
@@ -479,25 +473,20 @@ class MessageRepository private constructor(private val context: Context) {
val account = currentAccount ?: return
val privateKey = currentPrivateKey ?: return
android.util.Log.d("MessageRepo", "📊 updateDialog: opponent=${opponentKey.take(16)}..., incrementUnread=$incrementUnread")
try {
// 🔥 КРИТИЧНО: Сначала считаем реальное количество непрочитанных из messages
val unreadCount = messageDao.getUnreadCountForDialog(account, opponentKey)
android.util.Log.d("MessageRepo", "📊 unreadCount from DB: $unreadCount")
// 🔒 Шифруем lastMessage
val encryptedLastMessage = CryptoManager.encryptWithPassword(lastMessage, privateKey)
// Проверяем существует ли диалог
val existing = dialogDao.getDialog(account, opponentKey)
android.util.Log.d("MessageRepo", "📊 existing dialog: ${existing != null}, currentUnread=${existing?.unreadCount}")
if (existing != null) {
// Обновляем существующий диалог
dialogDao.updateLastMessage(account, opponentKey, encryptedLastMessage, timestamp)
dialogDao.updateUnreadCount(account, opponentKey, unreadCount)
android.util.Log.d("MessageRepo", "📊 UPDATED dialog unread to: $unreadCount")
} else {
// Создаем новый диалог
dialogDao.insertDialog(DialogEntity(
@@ -507,11 +496,9 @@ class MessageRepository private constructor(private val context: Context) {
lastMessageTimestamp = timestamp,
unreadCount = unreadCount
))
android.util.Log.d("MessageRepo", "📊 CREATED new dialog with unread: $unreadCount")
}
} catch (e: Exception) {
android.util.Log.e("MessageRepo", "📊 ERROR in updateDialog: ${e.message}")
e.printStackTrace()
}
}
@@ -539,15 +526,10 @@ class MessageRepository private constructor(private val context: Context) {
suspend fun updateDialogUserInfo(publicKey: String, title: String, username: String, verified: Int) {
val account = currentAccount ?: return
android.util.Log.d("MessageRepo", "📋 updateDialogUserInfo: publicKey=${publicKey.take(16)}..., title=$title, username=$username")
// Проверяем существует ли диалог с этим пользователем
val existing = dialogDao.getDialog(account, publicKey)
if (existing != null) {
android.util.Log.d("MessageRepo", "📋 Updating existing dialog info for ${publicKey.take(16)}...")
dialogDao.updateOpponentInfo(account, publicKey, title, username, verified)
} else {
android.util.Log.d("MessageRepo", "📋 Dialog not found for ${publicKey.take(16)}..., skipping")
}
}
@@ -558,14 +540,12 @@ class MessageRepository private constructor(private val context: Context) {
*/
fun clearDialogCache(opponentKey: String) {
val dialogKey = getDialogKey(opponentKey)
android.util.Log.d("MessageRepo", "🗑️ clearDialogCache: dialogKey=$dialogKey")
// Сначала устанавливаем пустой список чтобы все подписчики увидели
messageCache[dialogKey]?.value = emptyList()
// Затем удаляем из кэша
messageCache.remove(dialogKey)
android.util.Log.d("MessageRepo", "🗑️ Cache cleared for dialogKey=$dialogKey")
}
/**