feat: Disable logging in Protocol and ProtocolManager for improved performance and cleaner UI

This commit is contained in:
k1ngsterr1
2026-01-18 22:57:53 +05:00
parent 89d639a474
commit 6b839d2729
3 changed files with 7 additions and 145 deletions

View File

@@ -34,7 +34,7 @@ class Protocol(
}
private fun log(message: String) {
logger(message)
// Logging disabled for UI connection status
}
private val client = OkHttpClient.Builder()

View File

@@ -59,11 +59,9 @@ object ProtocolManager {
* Инициализация с контекстом для доступа к MessageRepository
*/
fun initialize(context: Context) {
addLog("🚀 ProtocolManager.initialize() called")
messageRepository = MessageRepository.getInstance(context)
setupPacketHandlers()
setupStateMonitoring()
addLog("🚀 ProtocolManager.initialize() completed")
}
/**
@@ -72,7 +70,7 @@ object ProtocolManager {
private fun setupStateMonitoring() {
scope.launch {
getProtocol().state.collect { newState ->
addLog("📡 STATE CHANGED: $newState")
// State monitoring without logging
}
}
}
@@ -82,7 +80,6 @@ object ProtocolManager {
* Должен вызываться после авторизации пользователя
*/
fun initializeAccount(publicKey: String, privateKey: String) {
addLog("🔐 Initializing account for message handling: ${publicKey.take(16)}...")
messageRepository?.initialize(publicKey, privateKey)
}
@@ -90,15 +87,9 @@ object ProtocolManager {
* Настройка обработчиков пакетов
*/
private fun setupPacketHandlers() {
addLog("📦 setupPacketHandlers() - Registering packet handlers...")
// Обработчик входящих сообщений (0x06)
waitPacket(0x06) { packet ->
addLog("📦 ⚡⚡⚡ PACKET 0x06 RECEIVED IN PROTOCOL_MANAGER!!! ⚡⚡⚡")
val messagePacket = packet as PacketMessage
addLog("📩 Incoming message from ${messagePacket.fromPublicKey.take(16)}...")
addLog(" messageRepository = ${if (messageRepository != null) "OK" else "NULL"}")
addLog(" messageRepository.isInitialized = ${messageRepository?.isInitialized() ?: false}")
// ⚡ ВАЖНО: Отправляем подтверждение доставки обратно серверу
// Без этого сервер не будет отправлять следующие сообщения!
@@ -107,14 +98,12 @@ object ProtocolManager {
toPublicKey = messagePacket.fromPublicKey
}
send(deliveryPacket)
addLog("✅ Sent delivery confirmation for message ${messagePacket.messageId.take(16)}...")
scope.launch {
try {
messageRepository?.handleIncomingMessage(messagePacket)
addLog("✅ handleIncomingMessage completed!")
} catch (e: Exception) {
addLog("❌ handleIncomingMessage ERROR: ${e.message}")
// Silent error handling
}
}
}
@@ -122,7 +111,6 @@ object ProtocolManager {
// Обработчик доставки (0x08)
waitPacket(0x08) { packet ->
val deliveryPacket = packet as PacketDelivery
addLog("✓ Delivered: ${deliveryPacket.messageId.take(16)}...")
scope.launch {
messageRepository?.handleDelivery(deliveryPacket)
@@ -133,7 +121,6 @@ object ProtocolManager {
// В Desktop PacketRead не содержит messageId - сообщает что собеседник прочитал сообщения
waitPacket(0x07) { packet ->
val readPacket = packet as PacketRead
addLog("✓✓ Read from: ${readPacket.fromPublicKey.take(16)}...")
scope.launch {
messageRepository?.handleRead(readPacket)
@@ -143,19 +130,12 @@ object ProtocolManager {
// 🟢 Обработчик онлайн-статуса (0x05)
waitPacket(0x05) { packet ->
val onlinePacket = packet as PacketOnlineState
addLog("🟢 Online status received: ${onlinePacket.publicKeysState.size} entries")
scope.launch {
if (messageRepository == null) {
addLog("❌ ERROR: messageRepository is NULL!")
} else {
addLog("✅ messageRepository is initialized")
if (messageRepository != null) {
onlinePacket.publicKeysState.forEach { item ->
val isOnline = item.state == OnlineState.ONLINE
addLog(" ${item.publicKey.take(16)}... -> ${if (isOnline) "ONLINE" else "OFFLINE"}")
addLog(" Calling updateOnlineStatus...")
messageRepository?.updateOnlineStatus(item.publicKey, isOnline)
addLog(" updateOnlineStatus called")
}
}
}
@@ -164,7 +144,6 @@ object ProtocolManager {
// Обработчик typing (0x0B)
waitPacket(0x0B) { packet ->
val typingPacket = packet as PacketTyping
addLog("⌨️ Typing: ${typingPacket.fromPublicKey.take(16)}...")
// Добавляем в set и удаляем через 3 секунды
_typingUsers.value = _typingUsers.value + typingPacket.fromPublicKey
@@ -178,14 +157,12 @@ object ProtocolManager {
// Обновляет информацию о пользователе в диалогах когда приходит ответ от сервера
waitPacket(0x03) { packet ->
val searchPacket = packet as PacketSearch
addLog("🔍 Search/UserInfo response: ${searchPacket.users.size} users")
android.util.Log.d("Protocol", "🔍 Search/UserInfo response: ${searchPacket.users.size} users")
// Обновляем информацию о пользователях в диалогах
if (searchPacket.users.isNotEmpty()) {
scope.launch(Dispatchers.IO) { // 🔥 Запускаем на IO потоке для работы с БД
searchPacket.users.forEach { user ->
addLog(" 📝 Updating user info: ${user.publicKey.take(16)}... title='${user.title}' username='${user.username}'")
android.util.Log.d("Protocol", "📝 Updating user info: ${user.publicKey.take(16)}... title='${user.title}' username='${user.username}'")
messageRepository?.updateDialogUserInfo(
user.publicKey,
@@ -204,7 +181,6 @@ object ProtocolManager {
*/
fun getProtocol(): Protocol {
if (protocol == null) {
addLog("🔌 Creating new Protocol instance for $SERVER_ADDRESS")
protocol = Protocol(SERVER_ADDRESS) { msg -> addLog(msg) }
}
return protocol!!
@@ -226,7 +202,6 @@ object ProtocolManager {
* Connect to server
*/
fun connect() {
addLog("🔌 CONNECT REQUESTED - calling Protocol.connect()")
getProtocol().connect()
}
@@ -234,7 +209,6 @@ object ProtocolManager {
* Authenticate with server
*/
fun authenticate(publicKey: String, privateHash: String) {
addLog("🔐 AUTHENTICATE REQUESTED for ${publicKey.take(16)}...")
getProtocol().startHandshake(publicKey, privateHash)
}

View File

@@ -255,27 +255,19 @@ fun ChatsListScreen(
}
*/
// Enable UI logs when status dialog is shown
LaunchedEffect(showStatusDialog) {
ProtocolManager.enableUILogs(showStatusDialog)
}
// Status dialog with logs
// Status dialog
if (showStatusDialog) {
val clipboardManager = androidx.compose.ui.platform.LocalClipboardManager.current
val scrollState = rememberScrollState()
AlertDialog(
onDismissRequest = { showStatusDialog = false },
title = {
Text(
"Connection Status & Logs",
"Connection Status",
fontWeight = FontWeight.Bold,
color = textColor
)
},
text = {
Column(modifier = Modifier.fillMaxWidth().heightIn(max = 500.dp)) {
Column(modifier = Modifier.fillMaxWidth()) {
// Status indicator
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -313,110 +305,6 @@ fun ChatsListScreen(
color = textColor
)
}
Divider(
color = if (isDarkTheme) Color(0xFF424242) else Color(0xFFE0E0E0),
modifier = Modifier.padding(vertical = 8.dp)
)
// Logs header with copy button
Row(
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
"Debug Logs:",
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = secondaryTextColor
)
TextButton(
onClick = {
val logsText = debugLogs.joinToString("\n")
clipboardManager.setText(
androidx.compose.ui.text.AnnotatedString(logsText)
)
android.widget.Toast.makeText(
context,
"Logs copied to clipboard!",
android.widget.Toast.LENGTH_SHORT
)
.show()
},
enabled = debugLogs.isNotEmpty()
) {
Text(
"Copy All",
fontSize = 12.sp,
color =
if (debugLogs.isNotEmpty()) PrimaryBlue
else Color.Gray
)
}
}
// Logs content
Box(
modifier =
Modifier.fillMaxWidth()
.weight(1f, fill = false)
.clip(RoundedCornerShape(8.dp))
.background(
if (isDarkTheme) Color(0xFF1A1A1A)
else Color(0xFFF5F5F5)
)
.padding(8.dp)
) {
if (debugLogs.isEmpty()) {
Text(
"No logs available.\nLogs are disabled by default for performance.\n\nEnable with:\nProtocolManager.enableUILogs(true)",
fontSize = 12.sp,
color = secondaryTextColor,
modifier = Modifier.padding(8.dp)
)
} else {
Column(
modifier =
Modifier.fillMaxWidth().verticalScroll(scrollState)
) {
debugLogs.forEach { log ->
Text(
log,
fontSize = 11.sp,
fontFamily = FontFamily.Monospace,
color = textColor,
modifier =
Modifier.fillMaxWidth()
.padding(vertical = 2.dp)
)
}
}
}
}
// Enable/Disable logs button
TextButton(
onClick = {
ProtocolManager.enableUILogs(!debugLogs.isNotEmpty())
android.widget.Toast.makeText(
context,
if (debugLogs.isEmpty()) "Logs enabled"
else "Logs disabled",
android.widget.Toast.LENGTH_SHORT
)
.show()
},
modifier = Modifier.fillMaxWidth().padding(top = 8.dp)
) {
Text(
if (debugLogs.isEmpty()) "⚠️ Enable Logs" else "Disable Logs",
fontSize = 12.sp,
color =
if (debugLogs.isEmpty()) Color(0xFFFFC107)
else Color.Gray
)
}
}
},
confirmButton = {