Skip to content

Commit

Permalink
Edit Homepage
Browse files Browse the repository at this point in the history
Signed-off-by: gohj99 <[email protected]>
  • Loading branch information
gohj99 committed Aug 8, 2024
1 parent a38fae7 commit e1b2870
Show file tree
Hide file tree
Showing 9 changed files with 294 additions and 114 deletions.
15 changes: 13 additions & 2 deletions .idea/deploymentTargetSelector.xml

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

6 changes: 6 additions & 0 deletions .idea/developer-tools.xml

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

87 changes: 48 additions & 39 deletions app/src/main/java/com/gohj99/telewatch/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
package com.gohj99.telewatch

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.runtime.*
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.lifecycleScope
import com.gohj99.telewatch.telegram.TgApi
import com.gohj99.telewatch.ui.main.Chat
import com.gohj99.telewatch.ui.main.ErrorScreen
import com.gohj99.telewatch.ui.main.MainScreen
import com.gohj99.telewatch.ui.theme.TelewatchTheme
import org.drinkless.td.libcore.telegram.TdApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
private var tgApi: TgApi? = null
private var isLoggedIn: Boolean = false
private var exceptionState by mutableStateOf<Exception?>(null)
@SuppressLint("MutableCollectionMutableState")
private var chatsList = mutableStateOf(mutableListOf<TdApi.Chat>())
private var chatsList = mutableStateOf(listOf<Chat>())

override fun onDestroy() {
super.onDestroy()
Expand All @@ -37,49 +38,57 @@ class MainActivity : ComponentActivity() {
isLoggedIn = sharedPref.getBoolean("isLoggedIn", false)

if (!isLoggedIn) {
Handler(Looper.getMainLooper()).postDelayed({
startActivity(Intent(this, WelcomeActivity::class.java))
finish()
}, 0)
startWelcomeActivity()
} else {
initMain()
}
}

private fun startWelcomeActivity() {
startActivity(Intent(this, WelcomeActivity::class.java))
finish()
}

private fun initMain() {
lifecycleScope.launch(Dispatchers.IO) {
try {
initMain()
tgApi = TgApi(this@MainActivity)
tgApi?.getChats(
limit = 10,
chatsList = chatsList
)
launch(Dispatchers.Main) {
setContent {
TelewatchTheme {
MainScreen(chatsList)
}
}
}
} catch (e: Exception) {
exceptionState = e
setContent {
TelewatchTheme {
ErrorScreen(
onRetry = { retryInitialization() },
onSetting = {
startActivity(Intent(this, SettingActivity::class.java))
}
)
launch(Dispatchers.Main) {
setContent {
TelewatchTheme {
ErrorScreen(
onRetry = { retryInitialization() },
onSetting = {
startActivity(
Intent(
this@MainActivity,
SettingActivity::class.java
)
)
}
)
}
}
}
}
}
}

private fun initMain() {
//println("start")
tgApi = TgApi(this)
tgApi?.getChats(
limit = 10,
chatsList = chatsList
)
setContent {
TelewatchTheme {
MainScreen(chatsList)
}
}
}

private fun retryInitialization() {
exceptionState = null
try {
initMain()
} catch (e: Exception) {
exceptionState = e
}
initMain()
}
}
103 changes: 72 additions & 31 deletions app/src/main/java/com/gohj99/telewatch/telegram/TgApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ package com.gohj99.telewatch.telegram
import android.content.Context
import android.os.Build
import androidx.compose.runtime.MutableState
import com.gohj99.telewatch.ui.main.Chat
import com.gohj99.telewatch.ui.main.add
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.drinkless.td.libcore.telegram.Client
import org.drinkless.td.libcore.telegram.TdApi
import java.io.IOException
Expand Down Expand Up @@ -52,10 +57,12 @@ class TgApi(private val context: Context) {
try {
authLatch.await()
} catch (e: InterruptedException) {
close()
throw IllegalStateException("Interrupted while waiting for authorization", e)
}

if (!isAuthorized) {
close()
throw IllegalStateException("Failed to authorize")
}
}
Expand All @@ -67,17 +74,24 @@ class TgApi(private val context: Context) {
val authorizationState = (update as TdApi.UpdateAuthorizationState).authorizationState
when (authorizationState.constructor) {
TdApi.AuthorizationStateReady.CONSTRUCTOR -> {
isAuthorized = true
authLatch.countDown()
println("TgApi: Authorization Ready")
}
TdApi.AuthorizationStateClosed.CONSTRUCTOR -> {
isAuthorized = false
authLatch.countDown()
}
TdApi.AuthorizationStateWaitPhoneNumber.CONSTRUCTOR -> {
isAuthorized = false
authLatch.countDown()
}

TdApi.AuthorizationStateWaitTdlibParameters.CONSTRUCTOR -> {}
TdApi.AuthorizationStateWaitEncryptionKey.CONSTRUCTOR -> {}
else -> {
// 其他状态不进行处理
//println("Authorization state: $authorizationState")
isAuthorized = true
authLatch.countDown()
println("Authorization state: $authorizationState")
}
}
}
Expand Down Expand Up @@ -134,47 +148,74 @@ class TgApi(private val context: Context) {
}

// 获取聊天列表
fun getChats(limit: Int = 10, chatsList: MutableState<MutableList<TdApi.Chat>>) {
suspend fun getChats(limit: Int = 10, chatsList: MutableState<List<Chat>>) {
val chatIds = getChatIds(limit)
fetchChatDetails(chatIds, chatsList)
}

private suspend fun getChatIds(limit: Int): List<Long> = withContext(Dispatchers.IO) {
val chatIds = mutableListOf<Long>()
val chatList = TdApi.GetChats().apply {
this.limit = limit
}
client.send(chatList) { result ->
println("GetChats result: $result")
if (result.constructor == TdApi.Error.CONSTRUCTOR) {
val error = result as TdApi.Error
println("Get Chats Error: ${error.message}")
} else {
val chats = result as TdApi.Chats
chatIds.addAll(chats.chatIds.toList())
println("Chats: ${chats.chatIds.joinToString(", ")}")
fetchChatDetails(chatIds, chatsList)
}
val result = sendRequest(chatList)
if (result.constructor == TdApi.Error.CONSTRUCTOR) {
val error = result as TdApi.Error
println("Get Chats Error: ${error.message}")
} else {
val chats = result as TdApi.Chats
chatIds.addAll(chats.chatIds.toList())
println("Chats: ${chats.chatIds.joinToString(", ")}")
}
return@withContext chatIds
}

// 获取聊天详情
private fun fetchChatDetails(chatIds: List<Long>, chatsList: MutableState<MutableList<TdApi.Chat>>) {
private suspend fun fetchChatDetails(chatIds: List<Long>, chatsList: MutableState<List<Chat>>) =
withContext(Dispatchers.IO) {
for (chatId in chatIds) {
println("Sending request for chat ID: $chatId")
client.send(TdApi.GetChat(chatId)) { result ->
println("Received result for chat ID $chatId: $result")
when (result.constructor) {
TdApi.Error.CONSTRUCTOR -> {
val error = result as TdApi.Error
println("Get Chat Details Error for chat ID $chatId: ${error.message}")
}
TdApi.Chat.CONSTRUCTOR -> {
val chat = result as TdApi.Chat
println("Chat Details for chat ID $chatId: $chat")
chatsList.value.add(chat)
}
else -> {
println("Unexpected result for chat ID $chatId: $result")
val result = sendRequest(TdApi.GetChat(chatId))
println("Received result for chat ID $chatId: $result")
when (result.constructor) {
TdApi.Error.CONSTRUCTOR -> {
val error = result as TdApi.Error
println("Get Chat Details Error for chat ID $chatId: ${error.message}")
}

TdApi.Chat.CONSTRUCTOR -> {
val chat = result as TdApi.Chat
println("Chat Details for chat ID $chatId: $chat")
withContext(Dispatchers.Main) {
var message = ""
val lastMessage = chat.lastMessage
if (lastMessage != null) {
val messageContent = lastMessage.content
if (messageContent is TdApi.MessageText) {
message = messageContent.text.text.toString()
}
}
chatsList.add(
Chat(
id = chat.id,
title = chat.title,
message = message
)
)
}
}

else -> {
println("Unexpected result for chat ID $chatId: $result")
}
}
}
}

private suspend fun sendRequest(request: TdApi.Function): TdApi.Object =
withContext(Dispatchers.IO) {
val result = CompletableDeferred<TdApi.Object>()
client.send(request) { result.complete(it) }
return@withContext result.await()
}

// 获取聊天记录
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ fun ErrorScreen(onRetry: () -> Unit, onSetting: () -> Unit) {
verticalArrangement = Arrangement.Center,
horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally
) {
Text(text = "An error occurred\nPlease try again", color = Color.White,)
Text(text = "An error occurred\nPlease try again", color = Color.White)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = onRetry) {
Text(text = stringResource(id = R.string.Retry))
Expand Down
65 changes: 65 additions & 0 deletions app/src/main/java/com/gohj99/telewatch/ui/main/ItemsLazyColumn.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.gohj99.telewatch.ui.main

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

// 定义一个数据类
data class Chat(val id: Long, val title: String, val message: String)

fun <T> MutableState<List<T>>.add(item: T) {
val updatedList = this.value.toMutableList()
updatedList.add(item)
this.value = updatedList
}

@Composable
fun ChatLazyColumn(itemsList: MutableState<List<Chat>>, callback: (Chat) -> Unit) {
LazyColumn(
modifier = Modifier
.fillMaxSize() // 确保 LazyColumn 填满父容器
.padding(horizontal = 16.dp) // 只在左右添加 padding
) {
items(itemsList.value) { item ->
ChatView(item, callback)
}
item {
Spacer(modifier = Modifier.height(30.dp)) // 添加一个高度为 50dp 的 Spacer
}
}
}

@Composable
fun ChatView(item: Chat, callback: (Chat) -> Unit) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 6.dp)
.clickable { callback(item) },
elevation = CardDefaults.cardElevation(4.dp),
colors = CardDefaults.cardColors(
containerColor = Color(0xFF2C323A) // 设置 Card 的背景颜色
)
) {
Column(modifier = Modifier.padding(start = 12.dp, top = 9.dp, end = 14.dp, bottom = 9.dp)) {
Text(text = item.title, color = Color.White)
if (item.message.isNotEmpty()) {
Text(text = item.message, color = Color(0xFF728AA5))
}
}
}
}
Loading

0 comments on commit e1b2870

Please sign in to comment.