forked from CIT/RehabilitationPatient
190 lines
7.0 KiB
Kotlin
190 lines
7.0 KiB
Kotlin
package com.example.rehabilitation
|
||
|
||
import android.annotation.SuppressLint
|
||
import android.view.WindowManager
|
||
import android.content.Intent
|
||
import android.os.Bundle
|
||
import android.util.Log
|
||
import android.view.View
|
||
import androidx.activity.viewModels
|
||
import androidx.appcompat.app.AppCompatActivity
|
||
import com.example.rehabilitation.Auth.AuthFragment
|
||
import com.example.rehabilitation.Auth.AuthorizationActivity
|
||
import com.example.rehabilitation.CodeError.Code429Activity
|
||
import com.example.rehabilitation.CodeError.Code500Activity
|
||
import com.example.rehabilitation.Enternet.EnternetActivity
|
||
import com.example.rehabilitation.Enternet.EnternetCheck
|
||
import com.example.rehabilitation.Pref.ConclusionPref
|
||
import com.example.rehabilitation.Retrofit.PatientApi
|
||
import com.example.rehabilitation.databinding.ActivityMainBinding
|
||
import com.example.sqlitework.dip.MainViewModel
|
||
import kotlinx.coroutines.CoroutineScope
|
||
import kotlinx.coroutines.Dispatchers
|
||
import kotlinx.coroutines.launch
|
||
import okhttp3.OkHttpClient
|
||
import okhttp3.logging.HttpLoggingInterceptor
|
||
import retrofit2.Retrofit
|
||
import retrofit2.converter.gson.GsonConverterFactory
|
||
|
||
/**
|
||
* Главная активность приложения
|
||
* Отвечает за инициализацию приложения и управление основным потоком
|
||
*/
|
||
class MainActivity : AppCompatActivity() {
|
||
// Привязка к layout файлу
|
||
private lateinit var binding: ActivityMainBinding
|
||
// API для работы с данными пациента
|
||
private lateinit var patientApi: PatientApi
|
||
// ViewModel для работы с данными пациента
|
||
private val modelPatient: PatientViewModel by viewModels()
|
||
// ViewModel для работы с основными данными
|
||
private val model: MainViewModel by viewModels()
|
||
|
||
// Токен авторизации
|
||
private var Token = ""
|
||
// Класс для работы с настройками
|
||
val prefPatientConclusion = ConclusionPref()
|
||
// Время последнего нажатия кнопки "назад"
|
||
var backPressedTime: Long = 0
|
||
|
||
// Класс для проверки интернет-соединения
|
||
val enternetCheck = EnternetCheck()
|
||
|
||
@SuppressLint("DiscouragedApi")
|
||
override fun onCreate(savedInstanceState: Bundle?) {
|
||
super.onCreate(savedInstanceState)
|
||
// Установка флага безопасности для предотвращения скриншотов
|
||
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
|
||
binding = ActivityMainBinding.inflate(layoutInflater)
|
||
setContentView(binding.root)
|
||
|
||
MainAndAuth()
|
||
}
|
||
|
||
/**
|
||
* Проверяет наличие токена и инициализирует соответствующий экран
|
||
*/
|
||
fun MainAndAuth() {
|
||
Token = prefPatientConclusion.conclusionToken(this)
|
||
Log.i("sadasdsadsd", Token)
|
||
if (Token == "") {
|
||
Auth()
|
||
} else {
|
||
CheckTokenAuth(Token)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Показывает экран авторизации
|
||
*/
|
||
fun Auth() {
|
||
binding.CLLoad.visibility = View.GONE
|
||
// Замена текущего фрагмента на экран авторизации
|
||
supportFragmentManager.beginTransaction()
|
||
.replace(R.id.CLMain, AuthFragment.newInstance())
|
||
.commit()
|
||
}
|
||
|
||
/**
|
||
* Инициализирует главный экран приложения
|
||
*/
|
||
fun Main() {
|
||
binding.CLLoad.visibility = View.GONE
|
||
fragment_inicializ()
|
||
}
|
||
|
||
/**
|
||
* Проверяет валидность токена авторизации
|
||
* @param token Токен для проверки
|
||
*/
|
||
@SuppressLint("SuspiciousIndentation")
|
||
private fun CheckTokenAuth(token: String) {
|
||
if (enternetCheck.isOnline(this)) {
|
||
initRetrofit()
|
||
CoroutineScope(Dispatchers.IO).launch {
|
||
val response = patientApi.CheckToken("Bearer $token")
|
||
runOnUiThread {
|
||
// Обработка ответа от сервера
|
||
val List = response.body()
|
||
val Nice = response.isSuccessful
|
||
val Code = response.code()
|
||
|
||
// Обработка различных кодов ответа
|
||
when (Code) {
|
||
429 -> {
|
||
// Слишком много запросов
|
||
val intetn = Intent(this@MainActivity, Code429Activity::class.java)
|
||
startActivity(intetn)
|
||
}
|
||
200 -> {
|
||
// Успешный ответ
|
||
if (Nice) {
|
||
Main()
|
||
} else {
|
||
Auth()
|
||
}
|
||
}
|
||
500 -> {
|
||
// Ошибка сервера
|
||
val intetn = Intent(this@MainActivity, Code500Activity::class.java)
|
||
startActivity(intetn)
|
||
}
|
||
401 -> {
|
||
// Неавторизованный доступ
|
||
val intetn = Intent(this@MainActivity, AuthorizationActivity::class.java)
|
||
finish()
|
||
startActivity(intetn)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
} else {
|
||
// Нет интернет-соединения
|
||
val intetn = Intent(this, Code500Activity::class.java)
|
||
finish()
|
||
startActivity(intetn)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Инициализирует Retrofit для работы с API
|
||
*/
|
||
private fun initRetrofit() {
|
||
// Настройка логирования
|
||
val interceptor = HttpLoggingInterceptor()
|
||
interceptor.level = HttpLoggingInterceptor.Level.BODY
|
||
|
||
// Создание HTTP клиента
|
||
val client = OkHttpClient
|
||
.Builder()
|
||
.addInterceptor(interceptor)
|
||
.build()
|
||
|
||
// Инициализация Retrofit
|
||
val retrofit = Retrofit.Builder()
|
||
.baseUrl("https://rehabilitation.vmeda.org/api/")
|
||
.client(client)
|
||
.addConverterFactory(GsonConverterFactory.create())
|
||
.build()
|
||
|
||
patientApi = retrofit.create(PatientApi::class.java)
|
||
}
|
||
|
||
/**
|
||
* Инициализирует главный фрагмент
|
||
*/
|
||
private fun fragment_inicializ() {
|
||
supportFragmentManager.beginTransaction()
|
||
.replace(R.id.CLMain, MainFragment.newInstance())
|
||
.commit()
|
||
}
|
||
|
||
override fun onDestroy() {
|
||
super.onDestroy()
|
||
finish()
|
||
}
|
||
|
||
override fun onResume() {
|
||
super.onResume()
|
||
}
|
||
} |