Skip to content

Commit

Permalink
Add chat updates
Browse files Browse the repository at this point in the history
Signed-off-by: gohj99 <[email protected]>
  • Loading branch information
gohj99 committed Aug 10, 2024
1 parent 9a3c29b commit 233ad05
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 42 deletions.
2 changes: 1 addition & 1 deletion .idea/deploymentTargetSelector.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 9 additions & 15 deletions app/src/main/java/com/gohj99/telewatch/ChatActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -45,29 +45,23 @@ class ChatActivity : ComponentActivity() {

enableEdgeToEdge()

// 异步获取当前用户 ID
// 清空旧的聊天消息
chatList.value = emptyList()

// 异步获取当前用户 ID 和聊天记录
lifecycleScope.launch {
tgApi?.let {
currentUserId.value = it.getCurrentUserId()
}
currentUserId.value = tgApi!!.getCurrentUserId()
tgApi!!.getChatMessages(chat!!.id, chatList) // 异步加载全部聊天消息
}

// chat 不为 null 时,获取聊天消息
tgApi!!.getChatMessages(chat!!.id, 10, chatList)

setContent {
TelewatchTheme {
SplashChatScreen(
chatTitle = chat!!.title,
chatList = chatList,
currentUserId = currentUserId.value // 传递当前用户 ID
)
{ messageText ->
println(messageText)
tgApi?.sendMessage(
chatId = chat!!.id,
messageText = messageText
)
currentUserId = currentUserId.value
) { messageText ->
tgApi?.sendMessage(chatId = chat!!.id, messageText = messageText)
}
}
}
Expand Down
76 changes: 53 additions & 23 deletions app/src/main/java/com/gohj99/telewatch/telegram/TgApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package com.gohj99.telewatch.telegram
import android.content.Context
import android.os.Build
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.gohj99.telewatch.R
import com.gohj99.telewatch.ui.main.Chat
import com.gohj99.telewatch.ui.main.add
Expand All @@ -24,6 +25,8 @@ import java.util.Properties
import java.util.concurrent.CountDownLatch

class TgApi(private val context: Context, private var chatsList: MutableState<List<Chat>>) {
private var saveChatId = 1L
private var saveChatList = mutableStateOf(emptyList<TdApi.Message>())
private val client: Client = Client.create({ update -> handleUpdate(update) }, null, null)
private val sharedPref = context.getSharedPreferences("LoginPref", Context.MODE_PRIVATE)
@Volatile private var isAuthorized: Boolean = false
Expand Down Expand Up @@ -142,24 +145,36 @@ class TgApi(private val context: Context, private var chatsList: MutableState<Li
private fun updateChatList(message: TdApi.Message) {
val chatId = message.chatId
val newMessageText = when (val content = message.content) {
is TdApi.MessageText -> {
val text = content.text.text
if (text.length > 20) text.take(20) + "..." else text
}

is TdApi.MessageText -> content.text.text
else -> context.getString(R.string.Unknown_Message)
}

if (chatId == saveChatId) {
// 将新消息添加到保存的聊天列表的前面
saveChatList.value = saveChatList.value.toMutableList().apply {
add(0, message) // 新消息存储在最前面
}
}

chatsList.value = chatsList.value.toMutableList().apply {
// 查找现有的聊天并更新
val existingChatIndex = indexOfFirst { it.id == chatId }
if (existingChatIndex >= 0) {
val updatedChat = get(existingChatIndex).copy(message = newMessageText)
val updatedChat = get(existingChatIndex).copy(
message = if (newMessageText.length > 20) newMessageText.take(20) + "..." else newMessageText
)
removeAt(existingChatIndex)
add(0, updatedChat)
} else {
// 新增聊天到列表顶部
add(0, Chat(id = chatId, title = "New Chat", message = newMessageText))
add(
0,
Chat(
id = chatId,
title = "New Chat",
message = if (newMessageText.length > 20) newMessageText.take(20) + "..." else newMessageText
)
)
}
}
}
Expand Down Expand Up @@ -296,26 +311,41 @@ class TgApi(private val context: Context, private var chatsList: MutableState<Li
// 获取聊天记录
fun getChatMessages(
chatId: Long,
limit: Int = 10,
chatList: MutableState<List<TdApi.Message>>
) {
val messagesList = mutableListOf<TdApi.Message>()
val getChatMessages = TdApi.GetChatHistory().apply {
this.chatId = chatId
this.limit = limit
}
client.send(getChatMessages) { result ->
println("GetChatMessages result: $result")
if (result.constructor == TdApi.Error.CONSTRUCTOR) {
val error = result as TdApi.Error
println("Get Chat Messages Error: ${error.message}")
} else {
val messages = result as TdApi.Messages
messagesList.addAll(messages.messages.toList())
chatList.value = messagesList
println("Messages: ${messages.messages.joinToString(", ")}")
saveChatList = chatList
saveChatId = chatId

// 定义一个内部函数用于异步递归获取消息
fun fetchMessages(fromMessageId: Long) {
val getChatMessages = TdApi.GetChatHistory().apply {
this.chatId = chatId
this.limit = 10 // 每次获取 10 条消息
this.fromMessageId = fromMessageId
}

client.send(getChatMessages) { result ->
println("GetChatMessages result: $result")
if (result.constructor == TdApi.Error.CONSTRUCTOR) {
val error = result as TdApi.Error
println("Get Chat Messages Error: ${error.message}")
} else {
val messages = result as TdApi.Messages
if (messages.messages.isNotEmpty()) {
val sortedMessages =
messages.messages.toList().sortedByDescending { it.date }
saveChatList.value = saveChatList.value.toMutableList().apply {
addAll(sortedMessages) // 将新消息添加到列表最后面
}
// 继续加载更旧的消息
fetchMessages(messages.messages.last().id)
}
}
}
}

// 从最新的消息开始获取
fetchMessages(0)
}

// 关闭连接
Expand Down
4 changes: 1 addition & 3 deletions app/src/main/java/com/gohj99/telewatch/ui/chat/ChatScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -129,15 +129,13 @@ fun SplashChatScreen(
.fillMaxWidth()
.padding(top = 8.dp)
.weight(1f),
reverseLayout = true, // 反转布局,使列表从下往上打印
reverseLayout = true, // 反转布局
verticalArrangement = Arrangement.Top
) {
item {
Spacer(modifier = Modifier.height(70.dp)) // 添加一个高度为 70dp 的 Spacer
}
items(chatList.value) { message ->
println("开始渲染列表")
println(message)
val isCurrentUser =
(message.senderId as? TdApi.MessageSenderUser)?.userId == currentUserId
val backgroundColor =
Expand Down

0 comments on commit 233ad05

Please sign in to comment.