refactor: remove excessive logging and improve code clarity in various components
This commit is contained in:
@@ -107,24 +107,16 @@ class MessageRepository private constructor(private val context: Context) {
|
|||||||
*/
|
*/
|
||||||
fun initialize(publicKey: String, privateKey: String) {
|
fun initialize(publicKey: String, privateKey: String) {
|
||||||
val start = System.currentTimeMillis()
|
val start = System.currentTimeMillis()
|
||||||
android.util.Log.d("MessageRepository", "🔧 initialize started for ${publicKey.take(8)}...")
|
|
||||||
|
|
||||||
// 🔥 Очищаем кэш запрошенных user info при смене аккаунта
|
// 🔥 Очищаем кэш запрошенных user info при смене аккаунта
|
||||||
if (currentAccount != publicKey) {
|
if (currentAccount != publicKey) {
|
||||||
requestedUserInfoKeys.clear()
|
requestedUserInfoKeys.clear()
|
||||||
android.util.Log.d("MessageRepository", "🔧 Cleared user info cache (account changed)")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
currentAccount = publicKey
|
currentAccount = publicKey
|
||||||
currentPrivateKey = privateKey
|
currentPrivateKey = privateKey
|
||||||
|
|
||||||
android.util.Log.d("MessageRepository", "🔧 initialize completed in ${System.currentTimeMillis() - start}ms (launching dialogs flow in background)")
|
|
||||||
|
|
||||||
// Загрузка диалогов
|
// Загрузка диалогов
|
||||||
scope.launch {
|
scope.launch {
|
||||||
android.util.Log.d("MessageRepository", "📂 Starting dialogs flow collection...")
|
|
||||||
dialogDao.getDialogsFlow(publicKey).collect { entities ->
|
dialogDao.getDialogsFlow(publicKey).collect { entities ->
|
||||||
android.util.Log.d("MessageRepository", "📂 Got ${entities.size} dialogs from DB")
|
|
||||||
_dialogs.value = entities.map { it.toDialog() }
|
_dialogs.value = entities.map { it.toDialog() }
|
||||||
|
|
||||||
// 🔥 Запрашиваем информацию о пользователях, у которых нет имени
|
// 🔥 Запрашиваем информацию о пользователях, у которых нет имени
|
||||||
|
|||||||
@@ -81,9 +81,7 @@ object ProtocolManager {
|
|||||||
*/
|
*/
|
||||||
fun initializeAccount(publicKey: String, privateKey: String) {
|
fun initializeAccount(publicKey: String, privateKey: String) {
|
||||||
val start = System.currentTimeMillis()
|
val start = System.currentTimeMillis()
|
||||||
android.util.Log.d("ProtocolManager", "🔧 initializeAccount started")
|
|
||||||
messageRepository?.initialize(publicKey, privateKey)
|
messageRepository?.initialize(publicKey, privateKey)
|
||||||
android.util.Log.d("ProtocolManager", "🔧 initializeAccount completed in ${System.currentTimeMillis() - start}ms")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -82,23 +82,17 @@ private suspend fun performUnlock(
|
|||||||
}
|
}
|
||||||
|
|
||||||
onUnlocking(true)
|
onUnlocking(true)
|
||||||
android.util.Log.d(TAG, "🔓 Starting unlock for account: ${selectedAccount.name}")
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val account = selectedAccount.encryptedAccount
|
val account = selectedAccount.encryptedAccount
|
||||||
|
|
||||||
// Try to decrypt private key
|
// Try to decrypt private key
|
||||||
val decryptStart = System.currentTimeMillis()
|
val decryptStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🔐 Decrypting private key (PBKDF2)...")
|
|
||||||
val decryptedPrivateKey = CryptoManager.decryptWithPassword(
|
val decryptedPrivateKey = CryptoManager.decryptWithPassword(
|
||||||
account.encryptedPrivateKey,
|
account.encryptedPrivateKey,
|
||||||
password
|
password
|
||||||
)
|
)
|
||||||
val decryptPrivateKeyTime = System.currentTimeMillis() - decryptStart
|
val decryptPrivateKeyTime = System.currentTimeMillis() - decryptStart
|
||||||
android.util.Log.d(TAG, "🔐 Private key decrypted in ${decryptPrivateKeyTime}ms")
|
|
||||||
|
|
||||||
if (decryptedPrivateKey == null) {
|
if (decryptedPrivateKey == null) {
|
||||||
android.util.Log.w(TAG, "❌ Decryption failed - incorrect password")
|
|
||||||
onError("Incorrect password")
|
onError("Incorrect password")
|
||||||
onUnlocking(false)
|
onUnlocking(false)
|
||||||
return
|
return
|
||||||
@@ -106,21 +100,15 @@ private suspend fun performUnlock(
|
|||||||
|
|
||||||
// Decrypt seed phrase
|
// Decrypt seed phrase
|
||||||
val seedStart = System.currentTimeMillis()
|
val seedStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🌱 Decrypting seed phrase...")
|
|
||||||
val decryptedSeedPhrase = CryptoManager.decryptWithPassword(
|
val decryptedSeedPhrase = CryptoManager.decryptWithPassword(
|
||||||
account.encryptedSeedPhrase,
|
account.encryptedSeedPhrase,
|
||||||
password
|
password
|
||||||
)?.split(" ") ?: emptyList()
|
)?.split(" ") ?: emptyList()
|
||||||
val seedTime = System.currentTimeMillis() - seedStart
|
val seedTime = System.currentTimeMillis() - seedStart
|
||||||
android.util.Log.d(TAG, "🌱 Seed phrase decrypted in ${seedTime}ms")
|
|
||||||
|
|
||||||
// Generate private key hash
|
// Generate private key hash
|
||||||
val hashStart = System.currentTimeMillis()
|
val hashStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🔑 Generating private key hash...")
|
|
||||||
val privateKeyHash = CryptoManager.generatePrivateKeyHash(decryptedPrivateKey)
|
val privateKeyHash = CryptoManager.generatePrivateKeyHash(decryptedPrivateKey)
|
||||||
val hashTime = System.currentTimeMillis() - hashStart
|
val hashTime = System.currentTimeMillis() - hashStart
|
||||||
android.util.Log.d(TAG, "🔑 Hash generated in ${hashTime}ms")
|
|
||||||
|
|
||||||
val decryptedAccount = DecryptedAccount(
|
val decryptedAccount = DecryptedAccount(
|
||||||
publicKey = account.publicKey,
|
publicKey = account.publicKey,
|
||||||
privateKey = decryptedPrivateKey,
|
privateKey = decryptedPrivateKey,
|
||||||
@@ -131,7 +119,6 @@ private suspend fun performUnlock(
|
|||||||
|
|
||||||
// Connect to server
|
// Connect to server
|
||||||
val connectStart = System.currentTimeMillis()
|
val connectStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🌐 Connecting to server...")
|
|
||||||
ProtocolManager.connect()
|
ProtocolManager.connect()
|
||||||
|
|
||||||
// Wait for websocket connection
|
// Wait for websocket connection
|
||||||
@@ -141,10 +128,7 @@ private suspend fun performUnlock(
|
|||||||
waitAttempts++
|
waitAttempts++
|
||||||
}
|
}
|
||||||
val connectTime = System.currentTimeMillis() - connectStart
|
val connectTime = System.currentTimeMillis() - connectStart
|
||||||
android.util.Log.d(TAG, "🌐 Connected in ${connectTime}ms (attempts: $waitAttempts)")
|
|
||||||
|
|
||||||
if (ProtocolManager.state.value == ProtocolState.DISCONNECTED) {
|
if (ProtocolManager.state.value == ProtocolState.DISCONNECTED) {
|
||||||
android.util.Log.e(TAG, "❌ Connection failed after $waitAttempts attempts")
|
|
||||||
onError("Failed to connect to server")
|
onError("Failed to connect to server")
|
||||||
onUnlocking(false)
|
onUnlocking(false)
|
||||||
return
|
return
|
||||||
@@ -154,20 +138,13 @@ private suspend fun performUnlock(
|
|||||||
|
|
||||||
// Authenticate
|
// Authenticate
|
||||||
val authStart = System.currentTimeMillis()
|
val authStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🔒 Authenticating...")
|
|
||||||
ProtocolManager.authenticate(account.publicKey, privateKeyHash)
|
ProtocolManager.authenticate(account.publicKey, privateKeyHash)
|
||||||
val authTime = System.currentTimeMillis() - authStart
|
val authTime = System.currentTimeMillis() - authStart
|
||||||
android.util.Log.d(TAG, "🔒 Auth request sent in ${authTime}ms")
|
|
||||||
|
|
||||||
accountManager.setCurrentAccount(account.publicKey)
|
accountManager.setCurrentAccount(account.publicKey)
|
||||||
|
|
||||||
val totalTime = System.currentTimeMillis() - totalStart
|
val totalTime = System.currentTimeMillis() - totalStart
|
||||||
android.util.Log.d(TAG, "✅ UNLOCK COMPLETE in ${totalTime}ms")
|
|
||||||
android.util.Log.d(TAG, " 📊 Breakdown: privateKey=${decryptPrivateKeyTime}ms, seed=${seedTime}ms, hash=${hashTime}ms, connect=${connectTime}ms, auth=${authTime}ms")
|
|
||||||
|
|
||||||
onSuccess(decryptedAccount)
|
onSuccess(decryptedAccount)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
android.util.Log.e(TAG, "❌ Unlock failed: ${e.message}", e)
|
|
||||||
onError("Failed to unlock: ${e.message}")
|
onError("Failed to unlock: ${e.message}")
|
||||||
onUnlocking(false)
|
onUnlocking(false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -630,8 +630,6 @@ if (message.id in currentIds) {
|
|||||||
withContext(Dispatchers.Main.immediate) {
|
withContext(Dispatchers.Main.immediate) {
|
||||||
val dbIds = messages.map { it.id }.toSet()
|
val dbIds = messages.map { it.id }.toSet()
|
||||||
val currentMsgs = _messages.value
|
val currentMsgs = _messages.value
|
||||||
android.util.Log.d("ChatViewModel", " Current ids: ${currentMsgs.map { it.id }.take(5)}...")
|
|
||||||
|
|
||||||
val optimisticMessages = currentMsgs.filter { msg ->
|
val optimisticMessages = currentMsgs.filter { msg ->
|
||||||
msg.status == MessageStatus.SENDING && msg.id !in dbIds
|
msg.status == MessageStatus.SENDING && msg.id !in dbIds
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -253,11 +253,7 @@ fun ChatsListScreen(
|
|||||||
LaunchedEffect(accountPublicKey, accountPrivateKey) {
|
LaunchedEffect(accountPublicKey, accountPrivateKey) {
|
||||||
if (accountPublicKey.isNotEmpty() && accountPrivateKey.isNotEmpty()) {
|
if (accountPublicKey.isNotEmpty() && accountPrivateKey.isNotEmpty()) {
|
||||||
val launchStart = System.currentTimeMillis()
|
val launchStart = System.currentTimeMillis()
|
||||||
android.util.Log.d("ChatsListScreen", "🚀 LaunchedEffect started")
|
|
||||||
|
|
||||||
chatsViewModel.setAccount(accountPublicKey, accountPrivateKey)
|
chatsViewModel.setAccount(accountPublicKey, accountPrivateKey)
|
||||||
android.util.Log.d("ChatsListScreen", "📋 setAccount took ${System.currentTimeMillis() - launchStart}ms")
|
|
||||||
|
|
||||||
// Устанавливаем аккаунт для RecentSearchesManager
|
// Устанавливаем аккаунт для RecentSearchesManager
|
||||||
RecentSearchesManager.setAccount(accountPublicKey)
|
RecentSearchesManager.setAccount(accountPublicKey)
|
||||||
|
|
||||||
@@ -265,7 +261,6 @@ fun ChatsListScreen(
|
|||||||
// сообщений
|
// сообщений
|
||||||
val initStart = System.currentTimeMillis()
|
val initStart = System.currentTimeMillis()
|
||||||
ProtocolManager.initializeAccount(accountPublicKey, accountPrivateKey)
|
ProtocolManager.initializeAccount(accountPublicKey, accountPrivateKey)
|
||||||
android.util.Log.d("ChatsListScreen", "🌐 initializeAccount took ${System.currentTimeMillis() - initStart}ms")
|
|
||||||
android.util.Log.d("ChatsListScreen", "✅ Total LaunchedEffect: ${System.currentTimeMillis() - launchStart}ms")
|
android.util.Log.d("ChatsListScreen", "✅ Total LaunchedEffect: ${System.currentTimeMillis() - launchStart}ms")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,10 +112,7 @@ class ChatsListViewModel(application: Application) : AndroidViewModel(applicatio
|
|||||||
*/
|
*/
|
||||||
fun setAccount(publicKey: String, privateKey: String) {
|
fun setAccount(publicKey: String, privateKey: String) {
|
||||||
val setAccountStart = System.currentTimeMillis()
|
val setAccountStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "📋 setAccount called for: ${publicKey.take(8)}...")
|
|
||||||
|
|
||||||
if (currentAccount == publicKey) {
|
if (currentAccount == publicKey) {
|
||||||
android.util.Log.d(TAG, "📋 Account already set, skipping")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,16 +121,12 @@ class ChatsListViewModel(application: Application) : AndroidViewModel(applicatio
|
|||||||
|
|
||||||
currentAccount = publicKey
|
currentAccount = publicKey
|
||||||
currentPrivateKey = privateKey
|
currentPrivateKey = privateKey
|
||||||
|
|
||||||
android.util.Log.d(TAG, "📋 Starting dialogs subscription...")
|
|
||||||
|
|
||||||
// Подписываемся на обычные диалоги
|
// Подписываемся на обычные диалоги
|
||||||
viewModelScope.launch {
|
viewModelScope.launch {
|
||||||
dialogDao.getDialogsFlow(publicKey)
|
dialogDao.getDialogsFlow(publicKey)
|
||||||
.flowOn(Dispatchers.IO) // 🚀 Flow работает на IO
|
.flowOn(Dispatchers.IO) // 🚀 Flow работает на IO
|
||||||
.map { dialogsList ->
|
.map { dialogsList ->
|
||||||
val mapStart = System.currentTimeMillis()
|
val mapStart = System.currentTimeMillis()
|
||||||
android.util.Log.d(TAG, "🔄 Processing ${dialogsList.size} dialogs...")
|
|
||||||
// <20> ОПТИМИЗАЦИЯ: Параллельная расшифровка всех сообщений
|
// <20> ОПТИМИЗАЦИЯ: Параллельная расшифровка всех сообщений
|
||||||
withContext(Dispatchers.Default) {
|
withContext(Dispatchers.Default) {
|
||||||
dialogsList.map { dialog ->
|
dialogsList.map { dialog ->
|
||||||
@@ -207,12 +200,10 @@ class ChatsListViewModel(application: Application) : AndroidViewModel(applicatio
|
|||||||
}.awaitAll()
|
}.awaitAll()
|
||||||
}.also {
|
}.also {
|
||||||
val mapTime = System.currentTimeMillis() - mapStart
|
val mapTime = System.currentTimeMillis() - mapStart
|
||||||
android.util.Log.d(TAG, "🔄 Dialogs processed in ${mapTime}ms (${dialogsList.size} items)")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.distinctUntilChanged() // 🔥 ИСПРАВЛЕНИЕ: Игнорируем дублирующиеся списки
|
.distinctUntilChanged() // 🔥 ИСПРАВЛЕНИЕ: Игнорируем дублирующиеся списки
|
||||||
.collect { decryptedDialogs ->
|
.collect { decryptedDialogs ->
|
||||||
android.util.Log.d(TAG, "✅ Dialogs collected: ${decryptedDialogs.size} items")
|
|
||||||
_dialogs.value = decryptedDialogs
|
_dialogs.value = decryptedDialogs
|
||||||
|
|
||||||
// 🟢 Подписываемся на онлайн-статусы всех собеседников
|
// 🟢 Подписываемся на онлайн-статусы всех собеседников
|
||||||
|
|||||||
@@ -66,6 +66,37 @@ fun ForwardChatPickerBottomSheet(
|
|||||||
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 🎨 Плавное затемнение статус бара когда bottom sheet открыт
|
||||||
|
DisposableEffect(Unit) {
|
||||||
|
if (!view.isInEditMode) {
|
||||||
|
val window = (view.context as? android.app.Activity)?.window
|
||||||
|
val originalStatusBarColor = window?.statusBarColor ?: 0
|
||||||
|
val scrimColor = android.graphics.Color.argb(153, 0, 0, 0) // 60% черный
|
||||||
|
|
||||||
|
// Плавное затемнение
|
||||||
|
val fadeInAnimator = android.animation.ValueAnimator.ofArgb(originalStatusBarColor, scrimColor).apply {
|
||||||
|
duration = 200
|
||||||
|
addUpdateListener { animator ->
|
||||||
|
window?.statusBarColor = animator.animatedValue as Int
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fadeInAnimator.start()
|
||||||
|
|
||||||
|
onDispose {
|
||||||
|
// Плавное восстановление
|
||||||
|
val fadeOutAnimator = android.animation.ValueAnimator.ofArgb(scrimColor, originalStatusBarColor).apply {
|
||||||
|
duration = 150
|
||||||
|
addUpdateListener { animator ->
|
||||||
|
window?.statusBarColor = animator.animatedValue as Int
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fadeOutAnimator.start()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
onDispose { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 🔥 Функция для красивого закрытия с анимацией
|
// 🔥 Функция для красивого закрытия с анимацией
|
||||||
fun dismissWithAnimation() {
|
fun dismissWithAnimation() {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
|
|||||||
@@ -183,7 +183,6 @@ fun InAppCameraScreen(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onError(exc: ImageCaptureException) {
|
override fun onError(exc: ImageCaptureException) {
|
||||||
Log.e("InAppCamera", "Photo capture failed: ${exc.message}", exc)
|
|
||||||
isCapturing = false
|
isCapturing = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,7 +226,6 @@ fun InAppCameraScreen(
|
|||||||
capture
|
capture
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.e("InAppCamera", "Use case binding failed", e)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user