2 Commits
Author SHA1 Message Date
Халимов Рустам 58bbdae26c Настройки 2026-04-14 11:46:55 +03:00
Халимов Рустам 3310a3c4a4 Правка чата 2026-04-14 11:31:20 +03:00
25 changed files with 976 additions and 200 deletions
Binary file not shown.
Binary file not shown.
@@ -5,18 +5,23 @@ import auth.data.remote.dto.AuthResponse
import core.domain.model.ServerConfigModel import core.domain.model.ServerConfigModel
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.GET import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.POST import retrofit2.http.POST
interface AuthApi { interface AuthApi {
@POST("auth/login") @POST("auth/login")
@Headers("Cache-Control: no-cache")
suspend fun login(@Body request: AuthRequest): AuthResponse suspend fun login(@Body request: AuthRequest): AuthResponse
@POST("auth/register") @POST("auth/register")
@Headers("Cache-Control: no-cache")
suspend fun register(@Body request: AuthRequest): AuthResponse suspend fun register(@Body request: AuthRequest): AuthResponse
@GET("config") @GET("config")
@Headers("Cache-Control: no-cache")
suspend fun getConfig(): ServerConfigModel suspend fun getConfig(): ServerConfigModel
@POST("auth/push-token") @POST("auth/push-token")
@Headers("Cache-Control: no-cache")
suspend fun updatePushToken(@Body token: String): Unit suspend fun updatePushToken(@Body token: String): Unit
} }
@@ -10,7 +10,9 @@ import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import chats.presentation.components.ChatItem import chats.presentation.components.ChatItem
import stories.presentation.StoryViewModel import stories.presentation.StoryViewModel
@@ -44,9 +46,10 @@ fun ChatListScreen(
Scaffold( Scaffold(
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text(stringResource(R.string.chats_title)) }, title = { Text(stringResource(R.string.chats_title), fontWeight = FontWeight.Bold) },
colors = TopAppBarDefaults.topAppBarColors( colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer containerColor = Color.Transparent,
titleContentColor = Color.White
) )
) )
} }
@@ -58,13 +58,19 @@ class ChatListViewModel @Inject constructor(
_state.update { it.copy(isLoading = true) } _state.update { it.copy(isLoading = true) }
try { try {
val chats = repository.getChats() val chats = repository.getChats()
_state.update { it.copy(chats = chats, isLoading = false) } _state.update { it.copy(chats = sortChats(chats), isLoading = false) }
} catch (e: Exception) { } catch (e: Exception) {
_state.update { it.copy(isLoading = false, error = e.message) } _state.update { it.copy(isLoading = false, error = e.message) }
} }
} }
} }
private fun sortChats(chats: List<Chat>): List<Chat> {
return chats.sortedWith(compareByDescending<Chat> {
it.name.equals("Избранное", ignoreCase = true) || it.name.equals("Saved Messages", ignoreCase = true)
}.thenByDescending { it.lastMessage?.createdAt })
}
private fun observeSignalREvents() { private fun observeSignalREvents() {
signalrClient.events signalrClient.events
.onEach { event -> .onEach { event ->
@@ -94,9 +100,9 @@ class ChatListViewModel @Inject constructor(
unreadCount = chat.unreadCount + 1 unreadCount = chat.unreadCount + 1
) )
} else chat } else chat
}.sortedByDescending { it.lastMessage?.createdAt } }
currentState.copy(chats = updatedChats) currentState.copy(chats = sortChats(updatedChats))
} }
} }
} }
@@ -11,6 +11,7 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -18,8 +19,9 @@ import androidx.compose.ui.unit.sp
import chats.domain.model.Chat import chats.domain.model.Chat
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import coil.compose.AsyncImage import core.presentation.components.AppAvatar
import androidx.compose.ui.layout.ContentScale import chats.domain.model.MediaType
import androidx.compose.runtime.remember
@Composable @Composable
fun ChatItem( fun ChatItem(
@@ -33,28 +35,11 @@ fun ChatItem(
.padding(12.dp), .padding(12.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// Аватар (мягкий квадрат) AppAvatar(
Box( url = chat.avatar,
modifier = Modifier name = chat.name,
.size(50.dp) size = 50.dp
.clip(RoundedCornerShape(12.dp))
.background(MaterialTheme.colorScheme.primaryContainer),
contentAlignment = Alignment.Center
) {
if (chat.avatar != null) {
AsyncImage(
model = chat.avatar,
contentDescription = null,
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop
) )
} else {
Text(
text = chat.name.take(1).uppercase(),
style = MaterialTheme.typography.titleMedium
)
}
}
Spacer(modifier = Modifier.width(12.dp)) Spacer(modifier = Modifier.width(12.dp))
@@ -70,8 +55,15 @@ fun ChatItem(
overflow = TextOverflow.Ellipsis overflow = TextOverflow.Ellipsis
) )
chat.lastMessage?.let { chat.lastMessage?.let {
val formattedTime = remember(it.createdAt) {
try {
it.createdAt.substringAfter('T').take(5)
} catch (e: Exception) {
""
}
}
Text( Text(
text = it.createdAt.takeLast(5), // Упрощенный формат времени text = formattedTime,
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = Color.Gray color = Color.Gray
) )
@@ -82,8 +74,27 @@ fun ChatItem(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween
) { ) {
val previewText = remember(chat.lastMessage) {
val msg = chat.lastMessage
if (msg == null) return@remember "No messages yet"
if (!msg.content.isNullOrBlank()) {
msg.content
} else if (msg.mediaType == MediaType.AUDIO) {
"Голосовое сообщение"
} else if (msg.media.isNotEmpty()) {
when (msg.mediaType) {
MediaType.IMAGE -> "Фото"
MediaType.VIDEO -> "Видео"
MediaType.FILE -> "Файл"
else -> "Медиа"
}
} else {
"Сообщение"
}
}
Text( Text(
text = chat.lastMessage?.content ?: "No messages yet", text = previewText,
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = Color.Gray, color = Color.Gray,
maxLines = 1, maxLines = 1,
@@ -35,6 +35,9 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.VolumeOff
import core.presentation.components.AppMediaLightbox
@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable @Composable
@@ -46,11 +49,12 @@ fun MessageBubble(
) { ) {
val context = LocalContext.current val context = LocalContext.current
var showReactionPicker by remember { mutableStateOf(false) } var showReactionPicker by remember { mutableStateOf(false) }
var lightboxMedia by remember { mutableStateOf<Pair<String, String>?>(null) }
val backgroundColor = if (isCurrentUser) { val backgroundColor = if (isCurrentUser) {
Color(0xFF3390EC) // Telegram Blue Color(0xFF3096E5) // Updated Blue
} else { } else {
Color(0xFF2B2B2B) // Dark Grey Color(0xFF212121) // Updated Dark Grey
} }
val contentColor = Color.White val contentColor = Color.White
@@ -119,13 +123,14 @@ fun MessageBubble(
modifier = Modifier modifier = Modifier
.fillMaxHeight() .fillMaxHeight()
.width(2.dp) .width(2.dp)
.background(if (isCurrentUser) Color.White else Color(0xFF3390EC)) .background(if (isCurrentUser) Color.White else Color(0xFF3096E5))
) )
Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) { Column(modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) {
val accentColor = if (isCurrentUser) Color.White else Color(0xFF3096E5)
Text( Text(
text = reply.senderName, text = reply.senderName,
style = MaterialTheme.typography.labelMedium, style = MaterialTheme.typography.labelMedium,
color = if (isCurrentUser) Color.White else Color(0xFF3390EC), color = accentColor,
maxLines = 1, maxLines = 1,
fontWeight = androidx.compose.ui.text.font.FontWeight.Bold fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
) )
@@ -153,22 +158,41 @@ fun MessageBubble(
.fillMaxWidth() .fillMaxWidth()
.clip(RoundedCornerShape(12.dp)) .clip(RoundedCornerShape(12.dp))
.clickable { .clickable {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(mediaUrl)) lightboxMedia = mediaUrl to "image"
context.startActivity(intent)
}, },
contentScale = ContentScale.FillWidth contentScale = ContentScale.FillWidth
) )
} }
MediaType.VIDEO -> { MediaType.VIDEO -> {
AppVideoPlayer( Box(
url = mediaUrl,
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(200.dp) .height(200.dp)
.clip(RoundedCornerShape(12.dp)), .clip(RoundedCornerShape(12.dp))
useController = true, .background(Color.Black)
autoPlay = false .clickable {
lightboxMedia = mediaUrl to "video"
},
contentAlignment = Alignment.Center
) {
AppVideoPlayer(
url = mediaUrl,
modifier = Modifier.fillMaxSize(),
useController = false,
autoPlay = true,
isMuted = true
) )
// Volume Off icon in top right
Icon(
imageVector = Icons.Default.VolumeOff,
contentDescription = null,
tint = Color.White.copy(alpha = 0.7f),
modifier = Modifier
.align(Alignment.TopEnd)
.padding(8.dp)
.size(20.dp)
)
}
} }
MediaType.AUDIO -> { MediaType.AUDIO -> {
AppAudioPlayer( AppAudioPlayer(
@@ -186,6 +210,7 @@ fun MessageBubble(
// Photo Grid for multiple images // Photo Grid for multiple images
PhotoGrid( PhotoGrid(
urls = message.media, urls = message.media,
onMediaClick = { lightboxMedia = it to "image" },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(300.dp) .height(300.dp)
@@ -218,11 +243,20 @@ fun MessageBubble(
modifier = Modifier.padding(end = 4.dp) modifier = Modifier.padding(end = 4.dp)
) )
} }
val formattedTime = remember(message.createdAt) {
try {
// Handle ISO 8601 strings like 2024-05-14T10:49:02.12Z
val timePart = message.createdAt.substringAfter('T').take(5)
if (timePart.contains(':')) timePart else "00:00"
} catch (e: Exception) {
"00:00"
}
}
Text( Text(
text = message.createdAt.takeLast(5), text = formattedTime,
style = MaterialTheme.typography.labelSmall, style = MaterialTheme.typography.labelSmall,
color = contentColor.copy(alpha = 0.6f), color = contentColor.copy(alpha = 0.6f),
fontSize = 10.sp fontSize = 11.sp
) )
if (isCurrentUser) { if (isCurrentUser) {
Spacer(modifier = Modifier.width(2.dp)) Spacer(modifier = Modifier.width(2.dp))
@@ -236,6 +270,14 @@ fun MessageBubble(
} }
} }
} }
lightboxMedia?.let { (url, type) ->
AppMediaLightbox(
url = url,
type = type,
onClose = { lightboxMedia = null }
)
}
} }
@Composable @Composable
@@ -331,7 +373,7 @@ fun FileItem(mediaUrl: String, isCurrentUser: Boolean, contentColor: Color) {
} }
@Composable @Composable
fun PhotoGrid(urls: List<String>, modifier: Modifier = Modifier) { fun PhotoGrid(urls: List<String>, onMediaClick: (String) -> Unit, modifier: Modifier = Modifier) {
val items = urls.take(4) val items = urls.take(4)
Column(modifier = modifier) { Column(modifier = modifier) {
val rows = (items.size + 1) / 2 val rows = (items.size + 1) / 2
@@ -344,7 +386,8 @@ fun PhotoGrid(urls: List<String>, modifier: Modifier = Modifier) {
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
.fillMaxHeight() .fillMaxHeight()
.padding(1.dp), .padding(1.dp)
.clickable { onMediaClick(items[firstIndex]) },
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
if (firstIndex + 1 < items.size) { if (firstIndex + 1 < items.size) {
@@ -354,7 +397,8 @@ fun PhotoGrid(urls: List<String>, modifier: Modifier = Modifier) {
modifier = Modifier modifier = Modifier
.weight(1f) .weight(1f)
.fillMaxHeight() .fillMaxHeight()
.padding(1.dp), .padding(1.dp)
.clickable { onMediaClick(items[firstIndex + 1]) },
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
} else if (rows > 1) { } else if (rows > 1) {
@@ -3,18 +3,55 @@ package core.domain.model
import com.google.gson.annotations.SerializedName import com.google.gson.annotations.SerializedName
data class ServerConfigModel( data class ServerConfigModel(
@SerializedName("features") val features: FeaturesConfig = FeaturesConfig(), @SerializedName("stories") val stories: StoriesConfig = StoriesConfig(),
@SerializedName("limits") val limits: LimitsConfig = LimitsConfig() @SerializedName("messages") val messages: MessagesConfig = MessagesConfig(),
@SerializedName("chats") val chats: ChatsConfig = ChatsConfig(),
@SerializedName("webRtc") val webRtc: WebRtcConfig = WebRtcConfig()
) {
// Helper to keep the presentation layer simple
val features: FeaturesConfig
get() = FeaturesConfig(
stories = stories.enabled,
polls = messages.allowPolls,
calls = webRtc.enabled && webRtc.enableVoiceCalls,
groups = true // Static for now as chats config doesn't have a simple toggle
)
val limits: LimitsConfig
get() = LimitsConfig(
maxFileSize = messages.maxFileSize,
maxGroupMembers = chats.maxGroupParticipants
)
}
data class StoriesConfig(
@SerializedName("enabled") val enabled: Boolean = true
) )
data class MessagesConfig(
@SerializedName("maxFileSize") val maxFileSize: Long = 100 * 1024 * 1024,
@SerializedName("allowPolls") val allowPolls: Boolean = true
)
data class ChatsConfig(
@SerializedName("maxGroupParticipants") val maxGroupParticipants: Int = 200
)
data class WebRtcConfig(
@SerializedName("enabled") val enabled: Boolean = true,
@SerializedName("enableVoiceCalls") val enableVoiceCalls: Boolean = true,
@SerializedName("enableVideoCalls") val enableVideoCalls: Boolean = true
)
// DTOs to maintain compatibility with existing UI code if possible
data class FeaturesConfig( data class FeaturesConfig(
@SerializedName("stories") val stories: Boolean = true, val stories: Boolean,
@SerializedName("polls") val polls: Boolean = true, val polls: Boolean,
@SerializedName("calls") val calls: Boolean = true, val calls: Boolean,
@SerializedName("groups") val groups: Boolean = true val groups: Boolean
) )
data class LimitsConfig( data class LimitsConfig(
@SerializedName("maxFileSize") val maxFileSize: Long = 100 * 1024 * 1024, // 100MB default val maxFileSize: Long,
@SerializedName("maxGroupMembers") val maxGroupMembers: Int = 200 val maxGroupMembers: Int
) )
+2 -1
View File
@@ -31,7 +31,8 @@ class ServerConfig @Inject constructor(
} }
fun saveServerConfig(config: ServerConfigModel) { fun saveServerConfig(config: ServerConfigModel) {
prefs.edit().putString(KEY_CONFIG_DATA, gson.toJson(config)).apply() android.util.Log.d("ServerConfig", "Saving new config: $config")
prefs.edit().putString(KEY_CONFIG_DATA, gson.toJson(config)).commit()
} }
fun getServerConfig(): ServerConfigModel { fun getServerConfig(): ServerConfigModel {
@@ -26,6 +26,10 @@ import kotlinx.coroutines.delay
import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.GraphicEq import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntSize
@Composable @Composable
fun AppAudioPlayer( fun AppAudioPlayer(
@@ -47,6 +51,7 @@ fun AppAudioPlayer(
var currentPosition by remember { mutableLongStateOf(0L) } var currentPosition by remember { mutableLongStateOf(0L) }
var duration by remember { mutableLongStateOf(0L) } var duration by remember { mutableLongStateOf(0L) }
var playbackSpeed by remember { mutableFloatStateOf(1.0f) } var playbackSpeed by remember { mutableFloatStateOf(1.0f) }
var layoutSize by remember { mutableStateOf(IntSize.Zero) }
val fileName = remember(url) { url.substringAfterLast("/") } val fileName = remember(url) { url.substringAfterLast("/") }
@@ -110,7 +115,7 @@ fun AppAudioPlayer(
) { ) {
Box( Box(
modifier = Modifier modifier = Modifier
.size(36.dp) .size(40.dp)
.clip(CircleShape) .clip(CircleShape)
.background(Color.White) .background(Color.White)
.clickable { if (isPlaying) exoPlayer.pause() else exoPlayer.play() }, .clickable { if (isPlaying) exoPlayer.pause() else exoPlayer.play() },
@@ -119,8 +124,8 @@ fun AppAudioPlayer(
Icon( Icon(
imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow, imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow,
contentDescription = null, contentDescription = null,
tint = Color(0xFF3390EC), tint = Color(0xFF3096E5),
modifier = Modifier.size(24.dp) modifier = Modifier.size(28.dp)
) )
} }
@@ -129,47 +134,74 @@ fun AppAudioPlayer(
.weight(1f) .weight(1f)
.padding(horizontal = 12.dp) .padding(horizontal = 12.dp)
) { ) {
Slider( // Waveform / Progress
value = if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f, Box(
onValueChange = { modifier = Modifier
val newPos = (it * duration).toLong() .fillMaxWidth()
.height(32.dp)
.onSizeChanged { layoutSize = it }
.pointerInput(duration) {
detectTapGestures { offset ->
if (duration > 0 && layoutSize.width > 0) {
val pct = offset.x / layoutSize.width.toFloat()
val newPos = (pct * duration).toLong()
exoPlayer.seekTo(newPos) exoPlayer.seekTo(newPos)
currentPosition = newPos currentPosition = newPos
}
}
}, },
modifier = Modifier.height(16.dp), contentAlignment = Alignment.CenterStart
colors = SliderDefaults.colors(
thumbColor = Color.White,
activeTrackColor = Color.White,
inactiveTrackColor = Color.White.copy(alpha = 0.3f)
)
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Text( androidx.compose.foundation.Canvas(modifier = Modifier.fillMaxSize()) {
text = formatDuration(currentPosition), val barCount = 35
fontSize = 10.sp, val barSpacing = 2.dp.toPx()
color = contentColor.copy(alpha = 0.7f) val barWidth = (size.width - (barCount - 1) * barSpacing) / barCount
val progress = if (duration > 0) currentPosition.toFloat() / duration.toFloat() else 0f
// Fake consistent waveform items
val barHeights = listOf(
0.4f, 0.6f, 0.3f, 0.8f, 0.5f, 0.9f, 0.4f, 0.7f, 0.5f, 0.8f,
0.3f, 0.7f, 0.6f, 0.9f, 0.4f, 0.8f, 0.5f, 0.7f, 0.3f, 0.9f,
0.5f, 0.6f, 0.4f, 0.8f, 0.6f, 0.7f, 0.5f, 0.4f, 0.5f, 0.7f,
0.4f, 0.3f, 0.5f, 0.6f, 0.4f
) )
Row(verticalAlignment = Alignment.CenterVertically) {
Text( for (i in 0 until barCount) {
text = "3.3 MB", // Mock size val x = i * (barWidth + barSpacing)
fontSize = 10.sp, val heightPct = barHeights[i % barHeights.size]
color = contentColor.copy(alpha = 0.7f) val barHeight = size.height * heightPct
) val isActive = (i.toFloat() / barCount) <= progress
Spacer(modifier = Modifier.width(4.dp))
Icon( drawRoundRect(
Icons.Default.Download, color = if (isActive) Color.White else Color.White.copy(alpha = 0.25f),
contentDescription = null, topLeft = androidx.compose.ui.geometry.Offset(x, (size.height - barHeight) / 2),
tint = contentColor.copy(alpha = 0.7f), size = androidx.compose.ui.geometry.Size(barWidth, barHeight),
modifier = Modifier.size(12.dp) cornerRadius = androidx.compose.ui.geometry.CornerRadius(2.dp.toPx())
)
}
}
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = "${formatDuration(currentPosition)} / ${formatDuration(duration)}",
fontSize = 11.sp,
color = contentColor.copy(alpha = 0.7f)
)
if (!isVoiceMessage) {
Icon(
Icons.Default.Download,
contentDescription = null,
tint = contentColor.copy(alpha = 0.7f),
modifier = Modifier.size(14.dp)
) )
} }
} }
} }
if (isVoiceMessage) {
Surface( Surface(
onClick = { onClick = {
playbackSpeed = when (playbackSpeed) { playbackSpeed = when (playbackSpeed) {
@@ -179,22 +211,21 @@ fun AppAudioPlayer(
} }
exoPlayer.playbackParameters = PlaybackParameters(playbackSpeed) exoPlayer.playbackParameters = PlaybackParameters(playbackSpeed)
}, },
color = Color.White.copy(alpha = 0.2f), color = Color.White.copy(alpha = 0.15f),
shape = CircleShape, shape = CircleShape,
modifier = Modifier.size(32.dp) modifier = Modifier.size(36.dp)
) { ) {
Box(contentAlignment = Alignment.Center) { Box(contentAlignment = Alignment.Center) {
Text( Text(
text = "${if (playbackSpeed % 1.0f == 0.0f) playbackSpeed.toInt() else playbackSpeed}x", text = "${if (playbackSpeed % 1.0f == 0.0f) playbackSpeed.toInt() else playbackSpeed}x",
fontSize = 10.sp, fontSize = 11.sp,
fontWeight = FontWeight.Bold, fontWeight = FontWeight.Black,
color = Color.White color = Color.White
) )
} }
} }
} }
} }
}
} }
@@ -10,6 +10,8 @@ import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -24,7 +26,12 @@ fun AppAvatar(
size: Dp = 48.dp, size: Dp = 48.dp,
modifier: Modifier = Modifier modifier: Modifier = Modifier
) { ) {
val isSavedMessages = remember(name) {
name.equals("Избранное", ignoreCase = true) || name.equals("Saved Messages", ignoreCase = true)
}
val initials = remember(name) { val initials = remember(name) {
if (isSavedMessages) "" else {
val words = name.trim().split("\\s+".toRegex()) val words = name.trim().split("\\s+".toRegex())
if (words.size >= 2) { if (words.size >= 2) {
(words[0].take(1) + words[1].take(1)).uppercase() (words[0].take(1) + words[1].take(1)).uppercase()
@@ -34,12 +41,15 @@ fun AppAvatar(
name.take(1).uppercase() name.take(1).uppercase()
} }
} }
}
val avatarColor = Color(0xFF4AA6F3) // Premium Telegram Blue (Web)
Box( Box(
modifier = modifier modifier = modifier
.size(size) .size(size)
.clip(SoftSquareShape) .clip(SoftSquareShape)
.background(MaterialTheme.colorScheme.primary.copy(alpha = 0.2f)), .background(avatarColor),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) { ) {
if (!url.isNullOrBlank()) { if (!url.isNullOrBlank()) {
@@ -49,10 +59,17 @@ fun AppAvatar(
modifier = Modifier.size(size), modifier = Modifier.size(size),
contentScale = ContentScale.Crop contentScale = ContentScale.Crop
) )
} else if (isSavedMessages) {
Icon(
imageVector = Icons.Default.Bookmark,
contentDescription = null,
tint = Color.White,
modifier = Modifier.size((size.value * 0.5).dp)
)
} else { } else {
Text( Text(
text = initials, text = initials,
color = MaterialTheme.colorScheme.primary, color = Color.White,
fontSize = (size.value * 0.4).sp, fontSize = (size.value * 0.4).sp,
fontWeight = androidx.compose.ui.text.font.FontWeight.Bold, fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
style = MaterialTheme.typography.titleMedium style = MaterialTheme.typography.titleMedium
@@ -0,0 +1,105 @@
package core.presentation.components
import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Download
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import coil.compose.AsyncImage
@Composable
fun AppMediaLightbox(
url: String,
type: String = "image",
onClose: () -> Unit
) {
Dialog(
onDismissRequest = onClose,
properties = DialogProperties(
usePlatformDefaultWidth = false,
decorFitsSystemWindows = false
)
) {
var scale by remember { mutableFloatStateOf(1f) }
var offset by remember { mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) }
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Black)
.pointerInput(Unit) {
detectTransformGestures { _, pan, zoom, _ ->
scale = (scale * zoom).coerceIn(1f, 5f)
offset += pan
}
}
) {
if (type == "video") {
AppVideoPlayer(
url = url,
modifier = Modifier.fillMaxSize(),
useController = true,
autoPlay = true
)
} else {
AsyncImage(
model = url,
contentDescription = null,
modifier = Modifier
.fillMaxSize()
.graphicsLayer(
scaleX = scale,
scaleY = scale,
translationX = offset.x,
translationY = offset.y
),
contentScale = ContentScale.Fit
)
}
// Top Bar
Row(
modifier = Modifier
.fillMaxWidth()
.statusBarsPadding()
.padding(16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(
onClick = onClose,
modifier = Modifier
.clip(CircleShape)
.background(Color.Black.copy(alpha = 0.5f))
) {
Icon(Icons.Default.Close, contentDescription = null, tint = Color.White)
}
IconButton(
onClick = { /* Handle download */ },
modifier = Modifier
.clip(CircleShape)
.background(Color.Black.copy(alpha = 0.5f))
) {
Icon(Icons.Default.Download, contentDescription = null, tint = Color.White)
}
}
}
}
}
@@ -20,6 +20,7 @@ fun AppVideoPlayer(
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
useController: Boolean = true, useController: Boolean = true,
autoPlay: Boolean = true, autoPlay: Boolean = true,
isMuted: Boolean = false,
onVideoFinished: () -> Unit = {} onVideoFinished: () -> Unit = {}
) { ) {
val context = LocalContext.current val context = LocalContext.current
@@ -28,6 +29,7 @@ fun AppVideoPlayer(
ExoPlayer.Builder(context).build().apply { ExoPlayer.Builder(context).build().apply {
val mediaItem = MediaItem.fromUri(url) val mediaItem = MediaItem.fromUri(url)
setMediaItem(mediaItem) setMediaItem(mediaItem)
volume = if (isMuted) 0f else 1f
prepare() prepare()
playWhenReady = autoPlay playWhenReady = autoPlay
addListener(object : Player.Listener { addListener(object : Player.Listener {
@@ -40,6 +42,10 @@ fun AppVideoPlayer(
} }
} }
LaunchedEffect(isMuted) {
exoPlayer.volume = if (isMuted) 0f else 1f
}
// Очистка ресурсов при выходе // Очистка ресурсов при выходе
DisposableEffect(Unit) { DisposableEffect(Unit) {
onDispose { onDispose {
@@ -7,13 +7,14 @@ import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ChatBubble import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.People import androidx.compose.material.icons.filled.QuestionAnswer
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.runtime.* import androidx.compose.runtime.*
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.blur
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Brush
@@ -35,25 +36,13 @@ fun GlassNavigationBar(
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(horizontal = 24.dp, vertical = 16.dp) .padding(horizontal = 16.dp, vertical = 12.dp)
.height(72.dp) .height(64.dp)
.clip(RoundedCornerShape(32.dp)) .clip(RoundedCornerShape(32.dp))
.background( .background(Color(0xFF1C1C1E).copy(alpha = 0.95f))
Brush.verticalGradient(
colors = listOf(
MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
MaterialTheme.colorScheme.surface.copy(alpha = 0.5f)
)
)
)
.border( .border(
1.dp, 0.5.dp,
Brush.verticalGradient( Color.White.copy(alpha = 0.1f),
colors = listOf(
Color.White.copy(alpha = 0.2f),
Color.Transparent
)
),
RoundedCornerShape(32.dp) RoundedCornerShape(32.dp)
), ),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
@@ -64,13 +53,13 @@ fun GlassNavigationBar(
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
NavItem( NavItem(
icon = Icons.Default.ChatBubble, icon = Icons.Default.QuestionAnswer,
label = stringResource(R.string.chats), label = stringResource(R.string.chats),
isSelected = currentRoute == "chat_list", isSelected = currentRoute == "chat_list",
onClick = { onNavigate("chat_list") } onClick = { onNavigate("chat_list") }
) )
NavItem( NavItem(
icon = Icons.Default.People, icon = Icons.Default.AccountCircle,
label = stringResource(R.string.contacts_tab), label = stringResource(R.string.contacts_tab),
isSelected = currentRoute == "contacts", isSelected = currentRoute == "contacts",
onClick = { onNavigate("contacts") } onClick = { onNavigate("contacts") }
@@ -93,62 +82,70 @@ fun GlassNavigationBar(
} }
@Composable @Composable
private fun NavItem( private fun RowScope.NavItem(
icon: ImageVector, icon: ImageVector,
label: String, label: String,
isSelected: Boolean, isSelected: Boolean,
onClick: () -> Unit onClick: () -> Unit
) { ) {
val contentColor = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant val contentColor = if (isSelected) Color(0xFF3390EC) else Color(0xFF94A3B8)
val backgroundColor = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.1f) else Color.Transparent
Column( Column(
modifier = Modifier modifier = Modifier
.clip(RoundedCornerShape(20.dp)) .weight(1f)
.background(backgroundColor)
.clickable(onClick = onClick) .clickable(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp), .padding(vertical = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center
) { ) {
Icon(icon, contentDescription = label, tint = contentColor, modifier = Modifier.size(24.dp)) Icon(
Text(text = label, color = contentColor, fontSize = 10.sp, modifier = Modifier.padding(top = 2.dp)) icon,
contentDescription = label,
tint = contentColor,
modifier = Modifier.size(26.dp)
)
Text(
text = label,
color = contentColor,
fontSize = 10.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
modifier = Modifier.padding(top = 2.dp)
)
} }
} }
@Composable @Composable
private fun ProfileNavItem( private fun RowScope.ProfileNavItem(
avatarUrl: String?, avatarUrl: String?,
username: String, username: String,
isSelected: Boolean, isSelected: Boolean,
onClick: () -> Unit onClick: () -> Unit
) { ) {
val borderColor = if (isSelected) MaterialTheme.colorScheme.primary else Color.Transparent val contentColor = if (isSelected) Color(0xFF3390EC) else Color(0xFF94A3B8)
Column( Column(
modifier = Modifier modifier = Modifier
.clip(RoundedCornerShape(20.dp)) .weight(1f)
.clickable(onClick = onClick) .clickable(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 8.dp), .padding(vertical = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally, horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center verticalArrangement = Arrangement.Center
) { ) {
Box( Box(
modifier = Modifier modifier = Modifier
.size(28.dp) .size(26.dp)
.border(2.dp, borderColor, CircleShape) .clip(CircleShape)
.padding(2.dp)
) { ) {
AppAvatar( AppAvatar(
url = avatarUrl, url = avatarUrl,
name = username, name = username,
size = 24.dp size = 26.dp
) )
} }
Text( Text(
text = stringResource(R.string.profile_tab), text = stringResource(R.string.profile_tab),
color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant, color = contentColor,
fontSize = 10.sp, fontSize = 10.sp,
fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal,
modifier = Modifier.padding(top = 2.dp) modifier = Modifier.padding(top = 2.dp)
) )
} }
@@ -1,14 +1,24 @@
package core.presentation.settings package core.presentation.settings
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.filled.Save
import androidx.compose.material3.* import androidx.compose.material3.*
import androidx.compose.runtime.* import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel import androidx.hilt.navigation.compose.hiltViewModel
import ru.knot.messager.R import ru.knot.messager.R
@@ -22,20 +32,38 @@ fun SettingsScreen(
val state by viewModel.state.collectAsState() val state by viewModel.state.collectAsState()
var baseUrl by remember(state.baseUrl) { mutableStateOf(state.baseUrl) } var baseUrl by remember(state.baseUrl) { mutableStateOf(state.baseUrl) }
val lifecycleOwner = androidx.compose.ui.platform.LocalLifecycleOwner.current
DisposableEffect(lifecycleOwner) {
val observer = androidx.lifecycle.LifecycleEventObserver { _, event ->
if (event == androidx.lifecycle.Lifecycle.Event.ON_RESUME) {
viewModel.loadConfig()
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
Scaffold( Scaffold(
containerColor = Color(0xFF0F0F10),
topBar = { topBar = {
TopAppBar( TopAppBar(
title = { Text(stringResource(R.string.settings)) }, title = { Text(stringResource(R.string.settings), fontWeight = FontWeight.Bold) },
navigationIcon = { navigationIcon = {
IconButton(onClick = onBack) { IconButton(onClick = onBack) {
Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back)) Icon(Icons.Default.ArrowBack, contentDescription = stringResource(R.string.back), tint = Color.White)
} }
}, },
actions = { actions = {
IconButton(onClick = { viewModel.saveBaseUrl(baseUrl) }) { IconButton(onClick = { viewModel.loadConfig() }) {
Icon(Icons.Default.Save, contentDescription = stringResource(R.string.save)) Icon(Icons.Default.Sync, contentDescription = "Refresh", tint = Color.White)
}
} }
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color(0xFF0F0F10),
titleContentColor = Color.White
)
) )
} }
) { paddingValues -> ) { paddingValues ->
@@ -43,60 +71,181 @@ fun SettingsScreen(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
.padding(paddingValues) .padding(paddingValues)
.verticalScroll(rememberScrollState())
.padding(16.dp) .padding(16.dp)
) { ) {
Text( if (state.isLoading) {
text = stringResource(R.string.server_connection), LinearProgressIndicator(
style = MaterialTheme.typography.titleMedium, modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
modifier = Modifier.padding(bottom = 8.dp) color = Color(0xFF3390EC)
) )
}
OutlinedTextField( if (state.error != null) {
Text(
text = "Ошибка обновления: ${state.error}",
color = Color.Red,
style = MaterialTheme.typography.labelSmall,
modifier = Modifier.padding(bottom = 16.dp)
)
}
// Server Section
SettingsSection(title = stringResource(R.string.server_connection)) {
Column(modifier = Modifier.padding(12.dp)) {
Text(
text = stringResource(R.string.api_base_url),
style = MaterialTheme.typography.labelMedium,
color = Color(0xFF3390EC)
)
Row(verticalAlignment = Alignment.CenterVertically) {
TextField(
value = baseUrl, value = baseUrl,
onValueChange = { baseUrl = it }, onValueChange = { baseUrl = it },
label = { Text(stringResource(R.string.api_base_url)) }, modifier = Modifier.weight(1f),
modifier = Modifier.fillMaxWidth(), colors = TextFieldDefaults.colors(
placeholder = { Text("https://example.com/api/") } focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedTextColor = Color.White,
unfocusedTextColor = Color.White,
focusedIndicatorColor = Color(0xFF3390EC),
unfocusedIndicatorColor = Color.Gray.copy(alpha = 0.5f)
),
placeholder = { Text("https://...", color = Color.Gray) }
) )
IconButton(onClick = { viewModel.saveBaseUrl(baseUrl) }) {
Icon(Icons.Default.Save, contentDescription = null, tint = Color(0xFF3390EC))
}
}
}
}
Spacer(modifier = Modifier.height(24.dp)) Spacer(modifier = Modifier.height(24.dp))
Text( // Features Section
text = stringResource(R.string.server_features), SettingsSection(title = stringResource(R.string.server_features)) {
style = MaterialTheme.typography.titleMedium, Column {
modifier = Modifier.padding(bottom = 8.dp) SettingsToggleItem(
icon = Icons.Default.History,
label = stringResource(R.string.stories),
enabled = state.config.features.stories
) )
SettingsToggleItem(
FeatureStatusItem(stringResource(R.string.stories), state.config.features.stories) icon = Icons.Default.Poll,
FeatureStatusItem(stringResource(R.string.polls), state.config.features.polls) label = stringResource(R.string.polls),
FeatureStatusItem(stringResource(R.string.calls), state.config.features.calls) enabled = state.config.features.polls
FeatureStatusItem(stringResource(R.string.groups), state.config.features.groups)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = stringResource(R.string.limits),
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
) )
Text("${stringResource(R.string.max_file_size)}: ${state.config.limits.maxFileSize / (1024 * 1024)} MB") SettingsToggleItem(
Text("${stringResource(R.string.max_group_members)}: ${state.config.limits.maxGroupMembers}") icon = Icons.Default.Call,
label = stringResource(R.string.calls),
enabled = state.config.features.calls
)
SettingsToggleItem(
icon = Icons.Default.Group,
label = stringResource(R.string.groups),
enabled = state.config.features.groups
)
}
}
Spacer(modifier = Modifier.height(24.dp))
// Limits Section
SettingsSection(title = stringResource(R.string.limits)) {
Column {
SettingsInfoItem(
icon = Icons.Default.Storage,
label = stringResource(R.string.max_file_size),
value = "${state.config.limits.maxFileSize / (1024 * 1024)} MB"
)
SettingsInfoItem(
icon = Icons.Default.People,
label = stringResource(R.string.max_group_members),
value = state.config.limits.maxGroupMembers.toString()
)
}
}
Spacer(modifier = Modifier.height(32.dp))
// Logout Button
Button(
onClick = onLogout,
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFE53935)),
shape = RoundedCornerShape(12.dp)
) {
Icon(Icons.Default.Logout, contentDescription = null)
Spacer(modifier = Modifier.width(8.dp))
Text(stringResource(R.string.log_out), fontWeight = FontWeight.Bold)
}
Spacer(modifier = Modifier.height(80.dp)) // Space for bottom bar
} }
} }
} }
@Composable @Composable
fun FeatureStatusItem(name: String, enabled: Boolean) { fun SettingsSection(title: String, content: @Composable () -> Unit) {
Column {
Text(
text = title.uppercase(),
style = MaterialTheme.typography.labelSmall,
color = Color(0xFF3390EC),
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(start = 8.dp, bottom = 8.dp)
)
Surface(
color = Color(0xFF1C1C1E),
shape = RoundedCornerShape(16.dp),
modifier = Modifier.fillMaxWidth()
) {
content()
}
}
}
@Composable
fun SettingsToggleItem(icon: ImageVector, label: String, enabled: Boolean) {
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(vertical = 4.dp), .padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween horizontalArrangement = Arrangement.SpaceBetween
) { ) {
Text(name) Row(verticalAlignment = Alignment.CenterVertically) {
Icon(icon, contentDescription = null, tint = Color.Gray, modifier = Modifier.size(24.dp))
Spacer(modifier = Modifier.width(16.dp))
Text(label, color = Color.White, fontSize = 16.sp)
}
Text( Text(
text = if (enabled) stringResource(R.string.enabled) else stringResource(R.string.disabled), text = if (enabled) stringResource(R.string.enabled) else stringResource(R.string.disabled),
color = if (enabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error color = if (enabled) Color(0xFF3390EC) else Color(0xFFE53935),
fontWeight = FontWeight.Bold,
fontSize = 14.sp
)
}
}
@Composable
fun SettingsInfoItem(icon: ImageVector, label: String, value: String) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(icon, contentDescription = null, tint = Color.Gray, modifier = Modifier.size(24.dp))
Spacer(modifier = Modifier.width(16.dp))
Text(label, color = Color.White, fontSize = 16.sp)
}
Text(
text = value,
color = Color.White,
fontWeight = FontWeight.Medium,
fontSize = 14.sp
) )
} }
} }
@@ -1,5 +1,6 @@
package core.presentation.settings package core.presentation.settings
import android.util.Log
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewModelScope
import core.domain.model.ServerConfigModel import core.domain.model.ServerConfigModel
@@ -14,18 +15,26 @@ import javax.inject.Inject
data class SettingsState( data class SettingsState(
val baseUrl: String = "", val baseUrl: String = "",
val config: ServerConfigModel = ServerConfigModel() val config: ServerConfigModel = ServerConfigModel(),
val isLoading: Boolean = false,
val error: String? = null
) )
@HiltViewModel @HiltViewModel
class SettingsViewModel @Inject constructor( class SettingsViewModel @Inject constructor(
private val serverConfig: ServerConfig private val serverConfig: ServerConfig,
private val authRepository: auth.domain.repository.AuthRepository
) : ViewModel() { ) : ViewModel() {
private val _state = MutableStateFlow(SettingsState()) private val _state = MutableStateFlow(SettingsState())
val state: StateFlow<SettingsState> = _state.asStateFlow() val state: StateFlow<SettingsState> = _state.asStateFlow()
init { init {
refreshState()
loadConfig()
}
private fun refreshState() {
_state.update { _state.update {
it.copy( it.copy(
baseUrl = serverConfig.getBaseUrl(), baseUrl = serverConfig.getBaseUrl(),
@@ -34,6 +43,20 @@ class SettingsViewModel @Inject constructor(
} }
} }
fun loadConfig() {
viewModelScope.launch {
_state.update { it.copy(isLoading = true, error = null) }
val result = authRepository.fetchConfig()
Log.d("SettingsViewModel", "Fetch result: ${result.isSuccess}")
if (result.isSuccess) {
refreshState()
} else {
_state.update { it.copy(error = result.exceptionOrNull()?.message) }
}
_state.update { it.copy(isLoading = false) }
}
}
fun saveBaseUrl(url: String) { fun saveBaseUrl(url: String) {
serverConfig.setBaseUrl(url) serverConfig.setBaseUrl(url)
_state.update { it.copy(baseUrl = url) } _state.update { it.copy(baseUrl = url) }
@@ -25,7 +25,7 @@ private val DarkColors = darkColorScheme(
onSurfaceVariant = OnSurfaceVariant onSurfaceVariant = OnSurfaceVariant
) )
val SoftSquareShape = RoundedCornerShape(24.dp) // "Мягкий квадрат" val SoftSquareShape = RoundedCornerShape(14.dp) // "Мягкий квадрат" как в вэб
@Composable @Composable
fun ForkMessengerTheme(content: @Composable () -> Unit) { fun ForkMessengerTheme(content: @Composable () -> Unit) {
Binary file not shown.
+249
View File
@@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+92
View File
@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega