feat: implement app security lock system with version validation and remote operation blocking
This commit is contained in:
@@ -17,8 +17,8 @@ android {
|
||||
applicationId = "com.aistudio.gestaoparadaos.xvyzwt"
|
||||
minSdk = 24
|
||||
targetSdk = 36
|
||||
versionCode = 2
|
||||
versionName = "1.1.0"
|
||||
versionCode = 3
|
||||
versionName = "1.2.0"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ import com.example.ui.screens.SettingsScreen
|
||||
import com.example.ui.theme.BrandGreen
|
||||
import com.example.ui.theme.BrandLightGreen
|
||||
import com.example.ui.theme.MyApplicationTheme
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.example.ui.components.AppSecurityLockDialog
|
||||
import com.example.ui.viewmodel.MaintenanceViewModel
|
||||
import com.example.ui.viewmodel.MaintenanceViewModelFactory
|
||||
|
||||
@@ -53,6 +55,15 @@ class MainActivity : ComponentActivity() {
|
||||
val navBackStackEntry by navController.currentBackStackEntryAsState()
|
||||
val currentRoute = navBackStackEntry?.destination?.route
|
||||
|
||||
val securityState by viewModel.appSecurityState.collectAsStateWithLifecycle()
|
||||
val isRefreshingConfig by viewModel.isRefreshingConfig.collectAsStateWithLifecycle()
|
||||
|
||||
AppSecurityLockDialog(
|
||||
securityState = securityState,
|
||||
isRefreshing = isRefreshingConfig,
|
||||
onRetryCheck = { viewModel.checkSecurityConfigNow() }
|
||||
)
|
||||
|
||||
Scaffold(
|
||||
bottomBar = {
|
||||
NavigationBar(
|
||||
|
||||
29
app/src/main/java/com/example/data/model/AppSecurityState.kt
Normal file
29
app/src/main/java/com/example/data/model/AppSecurityState.kt
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.example.data.model
|
||||
|
||||
data class SecurityContact(
|
||||
val role: String,
|
||||
val email: String
|
||||
)
|
||||
|
||||
sealed class AppSecurityState {
|
||||
object Allowed : AppSecurityState()
|
||||
|
||||
data class BlockedByMaintenance(
|
||||
val message: String = "App fora de operação, entrar em contato com o responsável e o desenvolvedor",
|
||||
val contacts: List<SecurityContact> = DEFAULT_CONTACTS
|
||||
) : AppSecurityState()
|
||||
|
||||
data class BlockedByVersion(
|
||||
val minVersion: String,
|
||||
val currentVersion: String,
|
||||
val message: String = "Versão do app incompativel, você deve atualizar o app para continuar usando, procure o responsável e o desenvolvedor",
|
||||
val contacts: List<SecurityContact> = DEFAULT_CONTACTS
|
||||
) : AppSecurityState()
|
||||
|
||||
companion object {
|
||||
val DEFAULT_CONTACTS = listOf(
|
||||
SecurityContact("Desenvolvedor", "cesarjhony+dev@gmail.com"),
|
||||
SecurityContact("Responsável", "gabrielpizzinatto123@gmail.com")
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,14 @@ import com.example.data.model.OSUpdateHistory
|
||||
import com.example.data.model.GoogleUser
|
||||
import com.example.data.model.SyncConflictLog
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.AppSecurityState
|
||||
import com.example.data.model.UserAccess
|
||||
import com.example.util.DeviceUtils
|
||||
import com.example.util.VersionUtils
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
@@ -42,6 +46,30 @@ class MaintenanceRepository(
|
||||
|
||||
val allConfigs: Flow<List<AppConfig>> = dao.getAllConfigsFlow()
|
||||
|
||||
val appSecurityState: Flow<AppSecurityState> = allConfigs.map { configs ->
|
||||
evaluateSecurityState(configs)
|
||||
}
|
||||
|
||||
fun evaluateSecurityState(configs: List<AppConfig>): AppSecurityState {
|
||||
val pararAcesso = configs.find { it.key.equals("PararAcessoApp", ignoreCase = true) }?.value?.trim() ?: "0"
|
||||
if (pararAcesso == "1") {
|
||||
return AppSecurityState.BlockedByMaintenance()
|
||||
}
|
||||
|
||||
val minVersion = configs.find { it.key.equals("VersaoMinimaApp", ignoreCase = true) }?.value?.trim() ?: ""
|
||||
if (minVersion.isNotBlank()) {
|
||||
val currentVersion = DeviceUtils.getAppVersion(context)
|
||||
if (VersionUtils.isVersionLower(currentVersion, minVersion)) {
|
||||
return AppSecurityState.BlockedByVersion(
|
||||
minVersion = minVersion,
|
||||
currentVersion = VersionUtils.sanitizeVersionString(currentVersion)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return AppSecurityState.Allowed
|
||||
}
|
||||
|
||||
val allHistory: Flow<List<OSUpdateHistory>> = dao.getAllHistoryFlow()
|
||||
|
||||
fun getActivityByOs(numeroOs: String): Flow<MaintenanceActivity?> = dao.getActivityByOs(numeroOs)
|
||||
@@ -443,6 +471,19 @@ class MaintenanceRepository(
|
||||
suspend fun synchronizeWithBackend(): SyncResult = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
|
||||
|
||||
// 0. Initial Security State Check from Local Database
|
||||
val localConfigs = dao.getAllConfigs()
|
||||
val initialSecurity = evaluateSecurityState(localConfigs)
|
||||
if (initialSecurity !is AppSecurityState.Allowed) {
|
||||
val msg = when (initialSecurity) {
|
||||
is AppSecurityState.BlockedByMaintenance -> initialSecurity.message
|
||||
is AppSecurityState.BlockedByVersion -> initialSecurity.message
|
||||
else -> "Sincronização bloqueada por trava de segurança."
|
||||
}
|
||||
android.util.Log.e("MaintenanceRepository", "Synchronization blocked by local security state: $msg")
|
||||
return@withContext SyncResult.Error(msg)
|
||||
}
|
||||
|
||||
// Validate system date only when online
|
||||
val isOnline = isCurrentlyConnected()
|
||||
@@ -477,6 +518,16 @@ class MaintenanceRepository(
|
||||
if (remoteConfigs.isNotEmpty()) {
|
||||
dao.insertConfigs(remoteConfigs)
|
||||
android.util.Log.d("MaintenanceRepository", "Sincronizadas ${remoteConfigs.size} configurações da planilha.")
|
||||
val remoteSecurity = evaluateSecurityState(remoteConfigs)
|
||||
if (remoteSecurity !is AppSecurityState.Allowed) {
|
||||
val msg = when (remoteSecurity) {
|
||||
is AppSecurityState.BlockedByMaintenance -> remoteSecurity.message
|
||||
is AppSecurityState.BlockedByVersion -> remoteSecurity.message
|
||||
else -> "Sincronização bloqueada por trava de segurança."
|
||||
}
|
||||
android.util.Log.w("MaintenanceRepository", "Sincronização interrompida devido a trava de segurança remota: $msg")
|
||||
return@withContext SyncResult.Error(msg)
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MaintenanceRepository", "Falha ao carregar configurações da planilha", e)
|
||||
@@ -1106,7 +1157,9 @@ class MaintenanceRepository(
|
||||
com.example.data.model.AppConfig("Link2", "https://exemple.com", "Link de informações de privacidade do app"),
|
||||
com.example.data.model.AppConfig("DescricaoLink2", "Informações de privacidade do APP", "Informações de privacidade"),
|
||||
com.example.data.model.AppConfig("Link3", "https://exemple.com", null),
|
||||
com.example.data.model.AppConfig("DescricaoLink3", "Termos de uso deste APP", "Termos de uso do APP")
|
||||
com.example.data.model.AppConfig("DescricaoLink3", "Termos de uso deste APP", "Termos de uso do APP"),
|
||||
com.example.data.model.AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima para funcionar o aplicativo sem trava-lo e exigir atualização"),
|
||||
com.example.data.model.AppConfig("PararAcessoApp", "0", "0 = Permite acesso ao app; 1 = Trava o acesso ao app")
|
||||
)
|
||||
dao.insertConfigs(defaults)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
package com.example.ui.components
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Block
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Email
|
||||
import androidx.compose.material.icons.filled.Refresh
|
||||
import androidx.compose.material.icons.filled.SystemUpdate
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.example.data.model.AppSecurityState
|
||||
import com.example.data.model.SecurityContact
|
||||
|
||||
@Composable
|
||||
fun AppSecurityLockDialog(
|
||||
securityState: AppSecurityState,
|
||||
isRefreshing: Boolean = false,
|
||||
onRetryCheck: () -> Unit
|
||||
) {
|
||||
if (securityState is AppSecurityState.Allowed) return
|
||||
|
||||
// Prevent physical back button navigation
|
||||
BackHandler(enabled = true) { }
|
||||
|
||||
val context = LocalContext.current
|
||||
|
||||
val title: String
|
||||
val mainMessage: String
|
||||
val contacts: List<SecurityContact>
|
||||
val isVersionError: Boolean
|
||||
val minVersion: String
|
||||
val currentVersion: String
|
||||
|
||||
when (securityState) {
|
||||
is AppSecurityState.BlockedByMaintenance -> {
|
||||
title = "App Fora de Operação"
|
||||
mainMessage = securityState.message
|
||||
contacts = securityState.contacts
|
||||
isVersionError = false
|
||||
minVersion = ""
|
||||
currentVersion = ""
|
||||
}
|
||||
is AppSecurityState.BlockedByVersion -> {
|
||||
title = "Versão Incompatível"
|
||||
mainMessage = securityState.message
|
||||
contacts = securityState.contacts
|
||||
isVersionError = true
|
||||
minVersion = securityState.minVersion
|
||||
currentVersion = securityState.currentVersion
|
||||
}
|
||||
AppSecurityState.Allowed -> return
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = { /* Non-dismissible */ },
|
||||
properties = DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
dismissOnBackPress = false,
|
||||
dismissOnClickOutside = false
|
||||
)
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = Color(0xFF1E1E24).copy(alpha = 0.96f)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(24.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.wrapContentHeight(),
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = Color.White),
|
||||
elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
// Header Icon
|
||||
Surface(
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = if (isVersionError) Color(0xFFFFF3E0) else Color(0xFFFFEBEE),
|
||||
modifier = Modifier.size(64.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
imageVector = if (isVersionError) Icons.Default.SystemUpdate else Icons.Default.Block,
|
||||
contentDescription = null,
|
||||
tint = if (isVersionError) Color(0xFFE65100) else Color(0xFFC62828),
|
||||
modifier = Modifier.size(36.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = title,
|
||||
fontSize = 22.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFF1F2937),
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
Text(
|
||||
text = mainMessage,
|
||||
fontSize = 14.sp,
|
||||
color = Color(0xFF4B5563),
|
||||
textAlign = TextAlign.Center,
|
||||
lineHeight = 20.sp
|
||||
)
|
||||
|
||||
if (isVersionError && minVersion.isNotBlank()) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Surface(
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
color = Color(0xFFF3F4F6),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Text(
|
||||
text = "Versão instalada: $currentVersion",
|
||||
fontSize = 12.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF6B7280)
|
||||
)
|
||||
Text(
|
||||
text = "Versão mínima requerida: $minVersion",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFFC62828)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
HorizontalDivider(color = Color(0xFFE5E7EB))
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = "Contatos para Suporte",
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFF374151),
|
||||
modifier = Modifier.align(Alignment.Start)
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
|
||||
contacts.forEach { contact ->
|
||||
ContactRow(
|
||||
contact = contact,
|
||||
onSendEmail = { email ->
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email"))
|
||||
context.startActivity(intent)
|
||||
} catch (e: Exception) {
|
||||
Toast.makeText(context, "E-mail: $email", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
},
|
||||
onCopyEmail = { email ->
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val clip = ClipData.newPlainText("E-mail Contato", email)
|
||||
clipboard.setPrimaryClip(clip)
|
||||
Toast.makeText(context, "E-mail copiado: $email", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
)
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
Button(
|
||||
onClick = onRetryCheck,
|
||||
enabled = !isRefreshing,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF0284C7)
|
||||
),
|
||||
shape = RoundedCornerShape(10.dp)
|
||||
) {
|
||||
if (isRefreshing) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(18.dp),
|
||||
color = Color.White,
|
||||
strokeWidth = 2.dp
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(text = "Consultando Planilha...", fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||
} else {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Refresh,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text(text = "Verificar Novamente", fontSize = 14.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ContactRow(
|
||||
contact: SecurityContact,
|
||||
onSendEmail: (String) -> Unit,
|
||||
onCopyEmail: (String) -> Unit
|
||||
) {
|
||||
Surface(
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = Color(0xFFF9FAFB),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
text = contact.role,
|
||||
fontSize = 11.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = Color(0xFF6B7280)
|
||||
)
|
||||
Text(
|
||||
text = contact.email,
|
||||
fontSize = 13.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = Color(0xFF111827)
|
||||
)
|
||||
}
|
||||
|
||||
Row {
|
||||
IconButton(
|
||||
onClick = { onSendEmail(contact.email) },
|
||||
modifier = Modifier.size(32.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Email,
|
||||
contentDescription = "Enviar E-mail",
|
||||
tint = Color(0xFF0284C7),
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
|
||||
IconButton(
|
||||
onClick = { onCopyEmail(contact.email) },
|
||||
modifier = Modifier.size(32.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.ContentCopy,
|
||||
contentDescription = "Copiar E-mail",
|
||||
tint = Color(0xFF4B5563),
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import com.example.data.repository.MaintenanceRepository
|
||||
import com.example.data.repository.SyncResult
|
||||
import com.example.data.model.AnalyticsState
|
||||
import com.example.data.model.parseDateOnly
|
||||
import com.example.data.model.AppSecurityState
|
||||
import com.example.data.model.DateSimulationConfig
|
||||
import com.example.data.model.DateSimulationMode
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -169,6 +170,15 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
private val _syncStatusMessage = MutableStateFlow<String?>(null)
|
||||
val syncStatusMessage = _syncStatusMessage.asStateFlow()
|
||||
|
||||
val appSecurityState: StateFlow<AppSecurityState> = repository.appSecurityState.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5000),
|
||||
initialValue = AppSecurityState.Allowed
|
||||
)
|
||||
|
||||
private val _isRefreshingConfig = MutableStateFlow(false)
|
||||
val isRefreshingConfig = _isRefreshingConfig.asStateFlow()
|
||||
|
||||
private val _importStatusMessage = MutableStateFlow<String?>(null)
|
||||
val importStatusMessage = _importStatusMessage.asStateFlow()
|
||||
|
||||
@@ -530,10 +540,41 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
|
||||
}
|
||||
}
|
||||
|
||||
fun checkSecurityConfigNow() {
|
||||
if (_isRefreshingConfig.value) return
|
||||
viewModelScope.launch {
|
||||
_isRefreshingConfig.value = true
|
||||
_syncStatusMessage.value = "Consultando aba 'config' da planilha online..."
|
||||
try {
|
||||
val remoteConfigs = repository.refreshConfigs()
|
||||
if (remoteConfigs.isEmpty()) {
|
||||
_syncStatusMessage.value = "Não foi possível conectar à planilha online para atualizar as configurações."
|
||||
} else {
|
||||
val security = repository.evaluateSecurityState(remoteConfigs)
|
||||
if (security is AppSecurityState.Allowed) {
|
||||
_syncStatusMessage.value = "Configurações atualizadas: Acesso liberado com sucesso!"
|
||||
} else {
|
||||
_syncStatusMessage.value = "Configurações atualizadas: Aplicativo permanece restrito."
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
_syncStatusMessage.value = "Erro ao buscar configurações remotas: ${e.localizedMessage}"
|
||||
} finally {
|
||||
_isRefreshingConfig.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs synchronized check.
|
||||
*/
|
||||
fun syncNow() {
|
||||
val currentSecurity = appSecurityState.value
|
||||
if (currentSecurity !is AppSecurityState.Allowed) {
|
||||
checkSecurityConfigNow()
|
||||
return
|
||||
}
|
||||
|
||||
if (!_internetAvailable.value) {
|
||||
_syncStatusMessage.value = "Sincronização impossível: Sem conectividade de rede na área atual."
|
||||
return
|
||||
|
||||
@@ -46,7 +46,7 @@ object DeviceUtils {
|
||||
fun getAppVersion(context: Context): String {
|
||||
return try {
|
||||
val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
|
||||
val versionName = packageInfo.versionName ?: "1.1.0"
|
||||
val versionName = packageInfo.versionName ?: "1.2.0"
|
||||
@Suppress("DEPRECATION")
|
||||
val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
packageInfo.longVersionCode
|
||||
@@ -55,7 +55,7 @@ object DeviceUtils {
|
||||
}
|
||||
"$versionName (v$versionCode)"
|
||||
} catch (e: Exception) {
|
||||
"1.1.0"
|
||||
"1.2.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
45
app/src/main/java/com/example/util/VersionUtils.kt
Normal file
45
app/src/main/java/com/example/util/VersionUtils.kt
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.example.util
|
||||
|
||||
object VersionUtils {
|
||||
|
||||
/**
|
||||
* Sanitizes a version string by stripping any parenthetical build code suffix (e.g., "1.1.0 (v2)" -> "1.1.0").
|
||||
*/
|
||||
fun sanitizeVersionString(rawVersion: String): String {
|
||||
return rawVersion.trim().split(" ")[0].trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two semantic version strings (e.g., "1.1.0" vs "1.2.0").
|
||||
* Returns:
|
||||
* - negative integer if v1 < v2
|
||||
* - zero if v1 == v2
|
||||
* - positive integer if v1 > v2
|
||||
*/
|
||||
fun compareVersions(v1: String, v2: String): Int {
|
||||
val cleanV1 = sanitizeVersionString(v1)
|
||||
val cleanV2 = sanitizeVersionString(v2)
|
||||
|
||||
val parts1 = cleanV1.split(".").mapNotNull { it.toIntOrNull() }
|
||||
val parts2 = cleanV2.split(".").mapNotNull { it.toIntOrNull() }
|
||||
|
||||
val maxLength = maxOf(parts1.size, parts2.size)
|
||||
|
||||
for (i in 0 until maxLength) {
|
||||
val num1 = parts1.getOrElse(i) { 0 }
|
||||
val num2 = parts2.getOrElse(i) { 0 }
|
||||
if (num1 != num2) {
|
||||
return num1.compareTo(num2)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if currentVersion is strictly lower than minVersion.
|
||||
*/
|
||||
fun isVersionLower(currentVersion: String, minVersion: String): Boolean {
|
||||
if (minVersion.isBlank()) return false
|
||||
return compareVersions(currentVersion, minVersion) < 0
|
||||
}
|
||||
}
|
||||
83
app/src/test/java/com/example/AppSecurityTest.kt
Normal file
83
app/src/test/java/com/example/AppSecurityTest.kt
Normal file
@@ -0,0 +1,83 @@
|
||||
package com.example
|
||||
|
||||
import com.example.data.model.AppConfig
|
||||
import com.example.data.model.AppSecurityState
|
||||
import com.example.util.VersionUtils
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class AppSecurityTest {
|
||||
|
||||
private fun evaluateSecurity(configs: List<AppConfig>, currentVersion: String): AppSecurityState {
|
||||
val pararAcesso = configs.find { it.key.equals("PararAcessoApp", ignoreCase = true) }?.value?.trim() ?: "0"
|
||||
if (pararAcesso == "1") {
|
||||
return AppSecurityState.BlockedByMaintenance()
|
||||
}
|
||||
|
||||
val minVersion = configs.find { it.key.equals("VersaoMinimaApp", ignoreCase = true) }?.value?.trim() ?: ""
|
||||
if (minVersion.isNotBlank()) {
|
||||
if (VersionUtils.isVersionLower(currentVersion, minVersion)) {
|
||||
return AppSecurityState.BlockedByVersion(
|
||||
minVersion = minVersion,
|
||||
currentVersion = VersionUtils.sanitizeVersionString(currentVersion)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return AppSecurityState.Allowed
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testDefaultStateAllowed() {
|
||||
val configs = emptyList<AppConfig>()
|
||||
val state = evaluateSecurity(configs, "1.1.0")
|
||||
assertTrue(state is AppSecurityState.Allowed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testPararAcessoAppBlocksAccess() {
|
||||
val configs = listOf(
|
||||
AppConfig("PararAcessoApp", "1", "Trava o acesso ao app"),
|
||||
AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima")
|
||||
)
|
||||
val state = evaluateSecurity(configs, "1.1.0")
|
||||
assertTrue(state is AppSecurityState.BlockedByMaintenance)
|
||||
val blocked = state as AppSecurityState.BlockedByMaintenance
|
||||
assertEquals("App fora de operação, entrar em contato com o responsável e o desenvolvedor", blocked.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testVersaoMinimaAppBlocksLowerVersion() {
|
||||
val configs = listOf(
|
||||
AppConfig("PararAcessoApp", "0", "Acesso permitido"),
|
||||
AppConfig("VersaoMinimaApp", "2.0.0", "Versão mínima")
|
||||
)
|
||||
val state = evaluateSecurity(configs, "1.1.0 (v2)")
|
||||
assertTrue(state is AppSecurityState.BlockedByVersion)
|
||||
val blocked = state as AppSecurityState.BlockedByVersion
|
||||
assertEquals("2.0.0", blocked.minVersion)
|
||||
assertEquals("1.1.0", blocked.currentVersion)
|
||||
assertEquals("Versão do app incompativel, você deve atualizar o app para continuar usando, procure o responsável e o desenvolvedor", blocked.message)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testVersaoMinimaAppAllowsCompatibleVersion() {
|
||||
val configs = listOf(
|
||||
AppConfig("PararAcessoApp", "0", "Acesso permitido"),
|
||||
AppConfig("VersaoMinimaApp", "1.0.0", "Versão mínima")
|
||||
)
|
||||
val state = evaluateSecurity(configs, "1.1.0")
|
||||
assertTrue(state is AppSecurityState.Allowed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testPararAcessoHasPriorityOverVersionMismatch() {
|
||||
val configs = listOf(
|
||||
AppConfig("PararAcessoApp", "1", "Trava o acesso"),
|
||||
AppConfig("VersaoMinimaApp", "9.9.9", "Versão mínima")
|
||||
)
|
||||
val state = evaluateSecurity(configs, "1.1.0")
|
||||
assertTrue(state is AppSecurityState.BlockedByMaintenance)
|
||||
}
|
||||
}
|
||||
45
app/src/test/java/com/example/util/VersionUtilsTest.kt
Normal file
45
app/src/test/java/com/example/util/VersionUtilsTest.kt
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.example.util
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VersionUtilsTest {
|
||||
|
||||
@Test
|
||||
fun testSanitizeVersionString() {
|
||||
assertEquals("1.1.0", VersionUtils.sanitizeVersionString("1.1.0 (v2)"))
|
||||
assertEquals("2.0.1", VersionUtils.sanitizeVersionString(" 2.0.1 "))
|
||||
assertEquals("1.0.0", VersionUtils.sanitizeVersionString("1.0.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCompareVersionsEqual() {
|
||||
assertEquals(0, VersionUtils.compareVersions("1.0.0", "1.0.0"))
|
||||
assertEquals(0, VersionUtils.compareVersions("1.1.0 (v2)", "1.1.0"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCompareVersionsLower() {
|
||||
assertTrue(VersionUtils.compareVersions("1.0.0", "1.1.0") < 0)
|
||||
assertTrue(VersionUtils.compareVersions("1.0.9", "1.1.0") < 0)
|
||||
assertTrue(VersionUtils.compareVersions("1.1.0", "1.2.0") < 0)
|
||||
assertTrue(VersionUtils.compareVersions("1.1.0 (v2)", "1.2.0") < 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testCompareVersionsGreater() {
|
||||
assertTrue(VersionUtils.compareVersions("1.2.0", "1.1.0") > 0)
|
||||
assertTrue(VersionUtils.compareVersions("2.0.0", "1.9.9") > 0)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testIsVersionLower() {
|
||||
assertTrue(VersionUtils.isVersionLower("1.1.0", "1.2.0"))
|
||||
assertTrue(VersionUtils.isVersionLower("1.1.0 (v2)", "2.0.0"))
|
||||
assertFalse(VersionUtils.isVersionLower("1.2.0", "1.1.0"))
|
||||
assertFalse(VersionUtils.isVersionLower("1.1.0", "1.1.0"))
|
||||
assertFalse(VersionUtils.isVersionLower("1.1.0", ""))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user