main #6

Closed
student-20690 wants to merge 20 commits from (deleted):main into main
8 changed files with 43 additions and 61 deletions
Showing only changes of commit 355df01846 - Show all commits

View File

@@ -1,7 +1,7 @@
package ru.myitschool.work.core package ru.myitschool.work.core
object Constants { object Constants {
const val HOST = "http://172.22.21.143:8080" const val HOST = "http://10.230.214.96:8080"
const val AUTH_URL = "/auth" const val AUTH_URL = "/auth"
const val INFO_URL = "/info" const val INFO_URL = "/info"
const val BOOKING_URL = "/booking" const val BOOKING_URL = "/booking"

View File

@@ -1,6 +1,8 @@
package ru.myitschool.work.data.repo package ru.myitschool.work.data.repo
import android.util.Log
import io.ktor.client.statement.bodyAsText
import ru.myitschool.work.data.source.DataStoreDataSource.createAuthCode import ru.myitschool.work.data.source.DataStoreDataSource.createAuthCode
import ru.myitschool.work.data.source.NetworkDataSource import ru.myitschool.work.data.source.NetworkDataSource
@@ -9,26 +11,11 @@ object AuthRepository {
private var codeCache: String? = null private var codeCache: String? = null
suspend fun checkAndSave(text: String): Result<Boolean> { suspend fun checkAndSave(text: String): Result<Boolean> {
return try { val result = NetworkDataSource.checkAuth(text)
val result = NetworkDataSource.checkAuth(text) if (result.isSuccess) {
codeCache = text
when { createAuthCode(code = text)
result.isSuccess && result.getOrNull() == true -> {
codeCache = text
createAuthCode(code = text)
Result.success(true)
}
result.isFailure -> {
val exception = result.exceptionOrNull()
val errorMessage = exception?.message ?: "Ошибка авторизации"
Result.failure(Exception(errorMessage))
}
else -> {
Result.success(false)
}
}
} catch (e: Exception) {
Result.failure(e)
} }
return result
} }
} }

View File

@@ -19,7 +19,6 @@ val AUTH_KEY = stringPreferencesKey(DS_AUTH_KEY)
object DataStoreDataSource { object DataStoreDataSource {
fun authFlow(): Flow<String> { fun authFlow(): Flow<String> {
Log.d("AnnaKonda", "Code is checking")
return App.context.dataStore.data.map { preferences -> return App.context.dataStore.data.map { preferences ->
(preferences[AUTH_KEY] ?: 0).toString() (preferences[AUTH_KEY] ?: 0).toString()
} }

View File

@@ -1,5 +1,6 @@
package ru.myitschool.work.data.source package ru.myitschool.work.data.source
import android.util.Log
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
@@ -39,7 +40,7 @@ object NetworkDataSource {
when (response.status) { when (response.status) {
HttpStatusCode.OK -> true HttpStatusCode.OK -> true
HttpStatusCode.Unauthorized, HttpStatusCode.BadRequest -> false HttpStatusCode.Unauthorized -> error("Wrong code!")
else -> error("Request error: ${response.bodyAsText()}") else -> error("Request error: ${response.bodyAsText()}")
} }
} }

View File

@@ -7,9 +7,7 @@ import ru.myitschool.work.data.repo.AuthRepository
) { ) {
suspend operator fun invoke( suspend operator fun invoke(
text: String text: String
): Result<Unit> { ): Result<Boolean> {
return repository.checkAndSave(text).mapCatching { success -> return repository.checkAndSave(text)
if (!success) error("Code is incorrect")
}
} }
} }

View File

@@ -46,16 +46,7 @@ fun AuthScreen(
viewModel.onIntent(AuthIntent.CheckLogIntent) viewModel.onIntent(AuthIntent.CheckLogIntent)
} }
val event = viewModel.actionFlow.collectAsState(initial = null)
LaunchedEffect(event.value) {
if (event.value is AuthAction.LogIn) {
if ((event.value as AuthAction.LogIn).isLogged) {
navController.navigate(MainScreenDestination)
}
}
}
Log.d("AnnaKonda", state.javaClass.toString())
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@@ -69,7 +60,7 @@ fun AuthScreen(
textAlign = TextAlign.Center textAlign = TextAlign.Center
) )
when (val currentState = state) { when (val currentState = state) {
is AuthState.Data -> Content(viewModel, currentState) is AuthState.Data -> Content(viewModel, currentState, navController)
is AuthState.Loading -> { is AuthState.Loading -> {
CircularProgressIndicator( CircularProgressIndicator(
modifier = Modifier.size(64.dp) modifier = Modifier.size(64.dp)
@@ -86,7 +77,8 @@ fun AuthScreen(
@Composable @Composable
private fun Content( private fun Content(
viewModel: AuthViewModel, viewModel: AuthViewModel,
state: AuthState.Data state: AuthState.Data,
navController: NavController
) { ) {
var inputText by remember { mutableStateOf("") } var inputText by remember { mutableStateOf("") }
var errorText: String? by remember { mutableStateOf(null) } var errorText: String? by remember { mutableStateOf(null) }
@@ -94,15 +86,22 @@ private fun Content(
val event = viewModel.actionFlow.collectAsState(initial = null) val event = viewModel.actionFlow.collectAsState(initial = null)
LaunchedEffect(event.value) { // В UI (Composable)
if (event.value is AuthAction.ShowError) { val actionFlow = viewModel.actionFlow // SharedFlow<AuthAction>
errorText = (event.value as AuthAction.ShowError).message
} else if (event.value is AuthAction.AuthBtnEnabled){ LaunchedEffect(Unit) {
Log.d("AnnaKonda", btnEnabled.toString()) // Collect Flow<T> здесь, чтобы потреблять все события
btnEnabled = if ((event.value as AuthAction.AuthBtnEnabled).enabled){ true } else { false } actionFlow.collect { action ->
when (action) {
is AuthAction.ShowError -> {
errorText = action.message
}
is AuthAction.AuthBtnEnabled -> {
btnEnabled = action.enabled
} else -> {}
}
} }
} }
Spacer(modifier = Modifier.size(16.dp)) Spacer(modifier = Modifier.size(16.dp))
TextField( TextField(
modifier = Modifier modifier = Modifier

View File

@@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import ru.myitschool.work.App import ru.myitschool.work.App
@@ -24,7 +25,7 @@ class AuthViewModel : ViewModel() {
private val _uiState = MutableStateFlow<AuthState>(AuthState.Data) private val _uiState = MutableStateFlow<AuthState>(AuthState.Data)
val uiState: StateFlow<AuthState> = _uiState.asStateFlow() val uiState: StateFlow<AuthState> = _uiState.asStateFlow()
private val _actionFlow: MutableSharedFlow<AuthAction> = MutableSharedFlow() private val _actionFlow: MutableSharedFlow<AuthAction> = MutableSharedFlow(replay = 1)
val actionFlow: SharedFlow<AuthAction> = _actionFlow val actionFlow: SharedFlow<AuthAction> = _actionFlow
fun onIntent(intent: AuthIntent) { fun onIntent(intent: AuthIntent) {
@@ -38,17 +39,17 @@ class AuthViewModel : ViewModel() {
}, },
onFailure = { error -> onFailure = { error ->
error.printStackTrace() error.printStackTrace()
error.message?.let { Log.d("AnnaKonda", it) }
if (error.message != null) { if (error.message != null) {
_actionFlow.emit(AuthAction.ShowError(error.message.toString())) _actionFlow.emit(AuthAction.ShowError(error.message))
_uiState.update { AuthState.Data }
} }
_uiState.update { AuthState.Data }
} }
) )
} }
} }
is AuthIntent.TextInput -> { is AuthIntent.TextInput -> {
viewModelScope.launch { viewModelScope.launch {
authFlow().collect { authFlow().collect {
if (CheckCodeInput(intent.text)) { if (CheckCodeInput(intent.text)) {
@@ -59,19 +60,18 @@ class AuthViewModel : ViewModel() {
} }
} }
} }
is AuthIntent.CheckLogIntent -> { is AuthIntent.CheckLogIntent -> {
viewModelScope.launch { viewModelScope.launch {
_uiState.update { AuthState.Loading } _uiState.update { AuthState.Loading }
authFlow().collect { val authCode = authFlow().first()
Log.d("AnnaKonda", it) if (authCode != "0") {
if (it != "0") { _actionFlow.emit(AuthAction.LogIn(true))
_actionFlow.emit(AuthAction.LogIn(true)) _uiState.update { AuthState.LoggedIn }
_uiState.update { AuthState.LoggedIn } } else {
} else { _uiState.update { AuthState.Data }
_actionFlow.emit(AuthAction.ShowError(App.context.getString(R.string.auth_wrong_code)))
_uiState.update { AuthState.Data }
}
} }
} }
} }
} }

View File

@@ -39,7 +39,6 @@ fun MainScreen(
errorMessage = (event.value as MainAction.ShowError).message errorMessage = (event.value as MainAction.ShowError).message
} }
} }
Log.d("AnnaKonda", errorMessage.toString())
// Если ошибка - показываем только ошибку и кнопку обновления // Если ошибка - показываем только ошибку и кнопку обновления
if (errorMessage != null) { if (errorMessage != null) {
ErrorScreen(viewModel = viewModel, navController = navController, errorMessage) ErrorScreen(viewModel = viewModel, navController = navController, errorMessage)
@@ -87,7 +86,6 @@ fun DefaultScreen(viewModel: MainViewModel,
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
// Фото пользователя (main_photo) // Фото пользователя (main_photo)
employee?.photoUrl?.let { msg -> Log.d("AnnaKonda", msg) }
AsyncImage( AsyncImage(
model = employee?.photoUrl ?: "", model = employee?.photoUrl ?: "",
contentDescription = "Фото", contentDescription = "Фото",