fix: optimize message decryption and caching in ChatsListViewModel and CryptoManager

This commit is contained in:
2026-02-05 00:28:52 +05:00
parent 54c5f015bb
commit e307e8d35d
6 changed files with 244 additions and 160 deletions

View File

@@ -1531,7 +1531,11 @@ val newList = messages + optimisticMessages
val text = caption.trim()
val attachmentId = "img_$timestamp"
// 1. 🚀 МГНОВЕННО показываем optimistic сообщение с localUri
// 🔥 КРИТИЧНО: Получаем размеры СРАЗУ (быстрая операция - только читает заголовок файла)
// Это предотвращает "расширение" пузырька при первом показе
val (imageWidth, imageHeight) = com.rosetta.messenger.utils.MediaUtils.getImageDimensions(context, imageUri)
// 1. 🚀 МГНОВЕННО показываем optimistic сообщение с localUri И РАЗМЕРАМИ
// Используем URI напрямую для отображения (без конвертации в base64)
val optimisticMessage = ChatMessage(
id = messageId,
@@ -1545,8 +1549,8 @@ val newList = messages + optimisticMessages
blob = "", // Пока пустой, обновим после конвертации
type = AttachmentType.IMAGE,
preview = "", // Пока пустой, обновим после генерации
width = 0,
height = 0,
width = imageWidth, // 🔥 Используем реальные размеры сразу!
height = imageHeight, // 🔥 Используем реальные размеры сразу!
localUri = imageUri.toString() // 🔥 Используем localUri для мгновенного показа
)
)
@@ -1558,15 +1562,15 @@ val newList = messages + optimisticMessages
// Чтобы при выходе из диалога сообщение не пропадало
viewModelScope.launch(Dispatchers.IO) {
try {
// Сохраняем с localUri в attachments для восстановления при возврате в чат
// Сохраняем с localUri и размерами в attachments для восстановления при возврате в чат
val attachmentsJson = JSONArray().apply {
put(JSONObject().apply {
put("id", attachmentId)
put("type", AttachmentType.IMAGE.value)
put("preview", "")
put("blob", "")
put("width", 0)
put("height", 0)
put("width", imageWidth) // 🔥 Сохраняем размеры в БД
put("height", imageHeight) // 🔥 Сохраняем размеры в БД
put("localUri", imageUri.toString()) // 🔥 Сохраняем localUri
})
}.toString()

View File

@@ -1318,7 +1318,8 @@ fun ChatItem(
color = secondaryTextColor,
maxLines = 1,
overflow = android.text.TextUtils.TruncateAt.END,
modifier = Modifier.weight(1f)
modifier = Modifier.weight(1f),
enableLinks = false // 🔗 Ссылки не кликабельны в списке чатов
)
Row(verticalAlignment = Alignment.CenterVertically) {
@@ -1941,7 +1942,8 @@ fun DialogItemContent(
else FontWeight.Normal,
maxLines = 1,
overflow = android.text.TextUtils.TruncateAt.END,
modifier = Modifier.weight(1f)
modifier = Modifier.weight(1f),
enableLinks = false // 🔗 Ссылки не кликабельны в списке чатов
)
}

View File

@@ -13,8 +13,11 @@ import com.rosetta.messenger.network.PacketSearch
import com.rosetta.messenger.network.ProtocolManager
import com.rosetta.messenger.network.SearchUser
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* UI модель диалога с расшифрованным lastMessage
@@ -121,76 +124,78 @@ class ChatsListViewModel(application: Application) : AndroidViewModel(applicatio
dialogDao.getDialogsFlow(publicKey)
.flowOn(Dispatchers.IO) // 🚀 Flow работает на IO
.map { dialogsList ->
// 🔓 Расшифровываем lastMessage на IO потоке (PBKDF2 - тяжелая операция!)
dialogsList.map { dialog ->
// 🔥 Загружаем информацию о пользователе если её нет
// 📁 НЕ загружаем для Saved Messages
val isSavedMessages = (dialog.account == dialog.opponentKey)
if (!isSavedMessages && (dialog.opponentTitle.isEmpty() || dialog.opponentTitle == dialog.opponentKey || dialog.opponentTitle == dialog.opponentKey.take(7))) {
loadUserInfoForDialog(dialog.opponentKey)
}
val decryptedLastMessage = try {
if (privateKey.isNotEmpty() && dialog.lastMessage.isNotEmpty()) {
CryptoManager.decryptWithPassword(dialog.lastMessage, privateKey)
?: dialog.lastMessage
} else {
dialog.lastMessage
}
} catch (e: Exception) {
dialog.lastMessage // Fallback на зашифрованный текст
}
// 🔥🔥🔥 НОВЫЙ ПОДХОД: Получаем статус НАПРЯМУЮ из таблицы messages
// Это гарантирует синхронизацию с тем что показывается в диалоге
val lastMsgStatus = messageDao.getLastMessageStatus(publicKey, dialog.opponentKey)
val actualFromMe = lastMsgStatus?.fromMe ?: 0
val actualDelivered = if (actualFromMe == 1) (lastMsgStatus?.delivered ?: 0) else 0
val actualRead = if (actualFromMe == 1) (lastMsgStatus?.read ?: 0) else 0
// 📎 Определяем тип attachment последнего сообщения
val attachmentType = try {
val attachmentsJson = messageDao.getLastMessageAttachments(publicKey, dialog.opponentKey)
if (!attachmentsJson.isNullOrEmpty() && attachmentsJson != "[]") {
val attachments = org.json.JSONArray(attachmentsJson)
if (attachments.length() > 0) {
val firstAttachment = attachments.getJSONObject(0)
val type = firstAttachment.optInt("type", -1)
when (type) {
0 -> "Photo" // AttachmentType.IMAGE = 0
2 -> "File" // AttachmentType.FILE = 2
3 -> "Avatar" // AttachmentType.AVATAR = 3
else -> null
// <EFBFBD> ОПТИМИЗАЦИЯ: Параллельная расшифровка всех сообщений
withContext(Dispatchers.Default) {
dialogsList.map { dialog ->
async {
// 🔥 Загружаем информацию о пользователе если её нет
// 📁 НЕ загружаем для Saved Messages
val isSavedMessages = (dialog.account == dialog.opponentKey)
if (!isSavedMessages && (dialog.opponentTitle.isEmpty() || dialog.opponentTitle == dialog.opponentKey || dialog.opponentTitle == dialog.opponentKey.take(7))) {
loadUserInfoForDialog(dialog.opponentKey)
}
// 🚀 Расшифровка теперь кэшируется в CryptoManager!
val decryptedLastMessage = try {
if (privateKey.isNotEmpty() && dialog.lastMessage.isNotEmpty()) {
CryptoManager.decryptWithPassword(dialog.lastMessage, privateKey)
?: dialog.lastMessage
} else {
dialog.lastMessage
}
} else null
} else null
} catch (e: Exception) {
null
}
// 🔥 Лог для отладки - показываем и старые и новые значения
DialogUiModel(
id = dialog.id,
account = dialog.account,
opponentKey = dialog.opponentKey,
opponentTitle = dialog.opponentTitle,
opponentUsername = dialog.opponentUsername,
lastMessage = decryptedLastMessage,
lastMessageTimestamp = dialog.lastMessageTimestamp,
unreadCount = dialog.unreadCount,
isOnline = dialog.isOnline,
lastSeen = dialog.lastSeen,
verified = dialog.verified,
isSavedMessages = isSavedMessages, // 📁 Saved Messages
lastMessageFromMe = actualFromMe, // 🔥 Используем актуальные данные из messages
lastMessageDelivered = actualDelivered, // 🔥 Используем актуальные данные из messages
lastMessageRead = actualRead, // 🔥 Используем актуальные данные из messages
lastMessageAttachmentType = attachmentType // 📎 Тип attachment
)
} catch (e: Exception) {
dialog.lastMessage // Fallback на зашифрованный текст
}
// 🔥🔥🔥 НОВЫЙ ПОДХОД: Получаем статус НАПРЯМУЮ из таблицы messages
// Это гарантирует синхронизацию с тем что показывается в диалоге
val lastMsgStatus = messageDao.getLastMessageStatus(publicKey, dialog.opponentKey)
val actualFromMe = lastMsgStatus?.fromMe ?: 0
val actualDelivered = if (actualFromMe == 1) (lastMsgStatus?.delivered ?: 0) else 0
val actualRead = if (actualFromMe == 1) (lastMsgStatus?.read ?: 0) else 0
// 📎 Определяем тип attachment последнего сообщения
val attachmentType = try {
val attachmentsJson = messageDao.getLastMessageAttachments(publicKey, dialog.opponentKey)
if (!attachmentsJson.isNullOrEmpty() && attachmentsJson != "[]") {
val attachments = org.json.JSONArray(attachmentsJson)
if (attachments.length() > 0) {
val firstAttachment = attachments.getJSONObject(0)
val type = firstAttachment.optInt("type", -1)
when (type) {
0 -> "Photo" // AttachmentType.IMAGE = 0
2 -> "File" // AttachmentType.FILE = 2
3 -> "Avatar" // AttachmentType.AVATAR = 3
else -> null
}
} else null
} else null
} catch (e: Exception) {
null
}
DialogUiModel(
id = dialog.id,
account = dialog.account,
opponentKey = dialog.opponentKey,
opponentTitle = dialog.opponentTitle,
opponentUsername = dialog.opponentUsername,
lastMessage = decryptedLastMessage,
lastMessageTimestamp = dialog.lastMessageTimestamp,
unreadCount = dialog.unreadCount,
isOnline = dialog.isOnline,
lastSeen = dialog.lastSeen,
verified = dialog.verified,
isSavedMessages = isSavedMessages, // 📁 Saved Messages
lastMessageFromMe = actualFromMe, // 🔥 Используем актуальные данные из messages
lastMessageDelivered = actualDelivered, // 🔥 Используем актуальные данные из messages
lastMessageRead = actualRead, // 🔥 Используем актуальные данные из messages
lastMessageAttachmentType = attachmentType // 📎 Тип attachment
)
}
}.awaitAll()
}
}
.flowOn(Dispatchers.Default) // 🚀 map выполняется на Default (CPU)
.distinctUntilChanged() // 🔥 ИСПРАВЛЕНИЕ: Игнорируем дублирующиеся списки
.collect { decryptedDialogs ->
_dialogs.value = decryptedDialogs
@@ -209,66 +214,71 @@ class ChatsListViewModel(application: Application) : AndroidViewModel(applicatio
dialogDao.getRequestsFlow(publicKey)
.flowOn(Dispatchers.IO)
.map { requestsList ->
requestsList.map { dialog ->
// 🔥 Загружаем информацию о пользователе если её нет
// 📁 НЕ загружаем для Saved Messages
val isSavedMessages = (dialog.account == dialog.opponentKey)
if (!isSavedMessages && (dialog.opponentTitle.isEmpty() || dialog.opponentTitle == dialog.opponentKey)) {
loadUserInfoForRequest(dialog.opponentKey)
}
val decryptedLastMessage = try {
if (privateKey.isNotEmpty() && dialog.lastMessage.isNotEmpty()) {
CryptoManager.decryptWithPassword(dialog.lastMessage, privateKey)
?: dialog.lastMessage
} else {
dialog.lastMessage
}
} catch (e: Exception) {
dialog.lastMessage
}
// 📎 Определяем тип attachment последнего сообщения
val attachmentType = try {
val attachmentsJson = messageDao.getLastMessageAttachments(publicKey, dialog.opponentKey)
if (!attachmentsJson.isNullOrEmpty() && attachmentsJson != "[]") {
val attachments = org.json.JSONArray(attachmentsJson)
if (attachments.length() > 0) {
val firstAttachment = attachments.getJSONObject(0)
val type = firstAttachment.optInt("type", -1)
when (type) {
0 -> "Photo" // AttachmentType.IMAGE = 0
2 -> "File" // AttachmentType.FILE = 2
3 -> "Avatar" // AttachmentType.AVATAR = 3
else -> null
// 🚀 ОПТИМИЗАЦИЯ: Параллельная расшифровка
withContext(Dispatchers.Default) {
requestsList.map { dialog ->
async {
// 🔥 Загружаем информацию о пользователе если её нет
// 📁 НЕ загружаем для Saved Messages
val isSavedMessages = (dialog.account == dialog.opponentKey)
if (!isSavedMessages && (dialog.opponentTitle.isEmpty() || dialog.opponentTitle == dialog.opponentKey)) {
loadUserInfoForRequest(dialog.opponentKey)
}
// 🚀 Расшифровка теперь кэшируется в CryptoManager!
val decryptedLastMessage = try {
if (privateKey.isNotEmpty() && dialog.lastMessage.isNotEmpty()) {
CryptoManager.decryptWithPassword(dialog.lastMessage, privateKey)
?: dialog.lastMessage
} else {
dialog.lastMessage
}
} else null
} else null
} catch (e: Exception) {
null
}
DialogUiModel(
id = dialog.id,
account = dialog.account,
opponentKey = dialog.opponentKey,
opponentTitle = dialog.opponentTitle, // 🔥 Показываем имя как в обычных чатах
opponentUsername = dialog.opponentUsername,
lastMessage = decryptedLastMessage,
lastMessageTimestamp = dialog.lastMessageTimestamp,
unreadCount = dialog.unreadCount,
isOnline = dialog.isOnline,
lastSeen = dialog.lastSeen,
verified = dialog.verified,
isSavedMessages = (dialog.account == dialog.opponentKey), // 📁 Saved Messages
lastMessageFromMe = dialog.lastMessageFromMe,
lastMessageDelivered = dialog.lastMessageDelivered,
lastMessageRead = dialog.lastMessageRead,
lastMessageAttachmentType = attachmentType // 📎 Тип attachment
)
} catch (e: Exception) {
dialog.lastMessage
}
// 📎 Определяем тип attachment последнего сообщения
val attachmentType = try {
val attachmentsJson = messageDao.getLastMessageAttachments(publicKey, dialog.opponentKey)
if (!attachmentsJson.isNullOrEmpty() && attachmentsJson != "[]") {
val attachments = org.json.JSONArray(attachmentsJson)
if (attachments.length() > 0) {
val firstAttachment = attachments.getJSONObject(0)
val type = firstAttachment.optInt("type", -1)
when (type) {
0 -> "Photo" // AttachmentType.IMAGE = 0
2 -> "File" // AttachmentType.FILE = 2
3 -> "Avatar" // AttachmentType.AVATAR = 3
else -> null
}
} else null
} else null
} catch (e: Exception) {
null
}
DialogUiModel(
id = dialog.id,
account = dialog.account,
opponentKey = dialog.opponentKey,
opponentTitle = dialog.opponentTitle, // 🔥 Показываем имя как в обычных чатах
opponentUsername = dialog.opponentUsername,
lastMessage = decryptedLastMessage,
lastMessageTimestamp = dialog.lastMessageTimestamp,
unreadCount = dialog.unreadCount,
isOnline = dialog.isOnline,
lastSeen = dialog.lastSeen,
verified = dialog.verified,
isSavedMessages = (dialog.account == dialog.opponentKey), // 📁 Saved Messages
lastMessageFromMe = dialog.lastMessageFromMe,
lastMessageDelivered = dialog.lastMessageDelivered,
lastMessageRead = dialog.lastMessageRead,
lastMessageAttachmentType = attachmentType // 📎 Тип attachment
)
}
}.awaitAll()
}
}
.flowOn(Dispatchers.Default)
.distinctUntilChanged() // 🔥 ИСПРАВЛЕНИЕ: Игнорируем дублирующиеся списки
.collect { decryptedRequests ->
_requests.value = decryptedRequests

View File

@@ -117,12 +117,24 @@ fun TelegramStyleMessageContent(
// Определяем layout
val (width, height, timeX, timeY) =
if (fillWidth) {
// 🔥 Для caption - занимаем всю доступную ширину, время справа на одной линии
// 🔥 Для caption - занимаем всю доступную ширину
val w = constraints.maxWidth
val h = maxOf(textPlaceable.height, timePlaceable.height)
val tX = w - timeWidth // Время справа
val tY = h - timePlaceable.height // Время внизу строки (выровнено по baseline)
LayoutResult(w, h, tX, tY)
// 🔥 ИСПРАВЛЕНИЕ: Проверяем помещается ли текст + время в одну строку
val availableForTime = w - textWidth - spacingPx
if (availableForTime >= timeWidth) {
// Текст и время помещаются - время справа на одной линии
val h = maxOf(textPlaceable.height, timePlaceable.height)
val tX = w - timeWidth // Время справа
val tY = h - timePlaceable.height // Время внизу строки (выровнено по baseline)
LayoutResult(w, h, tX, tY)
} else {
// Текст длинный - время на новой строке справа внизу
val h = textPlaceable.height + newLineHeightPx
val tX = w - timeWidth // Время справа
val tY = h - timePlaceable.height // Время внизу
LayoutResult(w, h, tX, tY)
}
} else if (!textWraps && totalSingleLineWidth <= constraints.maxWidth) {
// Текст и время на одной строке
val w = totalSingleLineWidth
@@ -510,7 +522,7 @@ fun MessageBubble(
}
val bubbleWidthModifier = if (hasImageWithCaption || hasOnlyMedia) {
Modifier.widthIn(max = photoWidth) // Жёстко ограничиваем ширину размером фото
Modifier.width(photoWidth) // 🔥 Фиксированная ширина = размер фото (убирает лишний отступ)
} else {
Modifier.widthIn(min = 60.dp, max = 280.dp)
}

View File

@@ -35,6 +35,7 @@ import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
@@ -56,6 +57,7 @@ import androidx.compose.ui.graphics.graphicsLayer
* 📷 In-App Camera Screen - как в Telegram
* Кастомная камера без системного превью, сразу переходит в ImageEditorScreen
*/
@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class)
@Composable
fun InAppCameraScreen(
onDismiss: () -> Unit,
@@ -65,6 +67,7 @@ fun InAppCameraScreen(
val lifecycleOwner = LocalLifecycleOwner.current
val scope = rememberCoroutineScope()
val view = LocalView.current
val keyboardController = LocalSoftwareKeyboardController.current
// Camera state
var lensFacing by remember { mutableStateOf(CameraSelector.LENS_FACING_BACK) }
@@ -81,8 +84,9 @@ fun InAppCameraScreen(
var isClosing by remember { mutableStateOf(false) }
val animationProgress = remember { Animatable(0f) }
// Enter animation
// Enter animation + hide keyboard
LaunchedEffect(Unit) {
keyboardController?.hide()
animationProgress.animateTo(
targetValue = 1f,
animationSpec = tween(durationMillis = 200, easing = FastOutSlowInEasing)