feat: implement TimeGuardManager to enforce system clock synchronization with server time during data operations

This commit is contained in:
Jhony Cesar
2026-07-29 11:55:45 -04:00
parent 646c6abc6b
commit bc03351363
5 changed files with 274 additions and 34 deletions

View File

@@ -41,7 +41,10 @@ data class AppendBody(
val values: List<List<String>>
)
class GoogleSheetsSyncService(private val context: Context) {
class GoogleSheetsSyncService(
private val context: Context,
val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager()
) {
private val tag = "GoogleSheetsSync"
private fun readSpreadsheetId(): String {
@@ -60,6 +63,15 @@ class GoogleSheetsSyncService(private val context: Context) {
}
private val client = OkHttpClient.Builder()
.addInterceptor { chain ->
val response = chain.proceed(chain.request())
val dateHeader = response.header("Date")
val parsedDate = com.example.util.TimeGuardManager.parseHttpDate(dateHeader)
if (parsedDate != null) {
timeGuardManager.updateVerifiedServerTime(parsedDate.time)
}
response
}
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
level = okhttp3.logging.HttpLoggingInterceptor.Level.BASIC
})

View File

@@ -17,10 +17,11 @@ import java.io.InputStreamReader
class MaintenanceRepository(
private val dao: MaintenanceDao,
private val context: Context
private val context: Context,
val timeGuardManager: com.example.util.TimeGuardManager = com.example.util.TimeGuardManager()
) {
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context)
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager)
private val networkMonitor = com.example.util.NetworkMonitor(context)
val isNetworkConnected: Flow<Boolean> = networkMonitor.isConnected
@@ -53,6 +54,13 @@ class MaintenanceRepository(
recurso: String,
emailEditor: String?
) = withContext(Dispatchers.IO) {
// Validate system date only when online
val isOnline = isCurrentlyConnected()
val timeValidation = timeGuardManager.validateSystemTime(isOnline)
if (timeValidation is com.example.util.TimeValidationResult.InvalidFutureDate) {
throw IllegalStateException(timeValidation.message)
}
val currentActivity = dao.getActivityByOsOneShot(numeroOs) ?: return@withContext
val updatedActivity = currentActivity.copy(
@@ -148,53 +156,52 @@ class MaintenanceRepository(
val pctIdx = headers.indexOfFirst { it.contains("pct") || it.contains("%") || it.contains("percent") || it.contains("exec") }
val tagIdx = headers.indexOfFirst { it == "tag" || it.contains("tag") }
if (osIdx == -1 || descIdx == -1) {
return@withContext Result.failure(Exception("Colunas obrigatórias não encontradas. Certifique-se de ter ao menos 'Número da OS' e 'Descrição'."))
if (osIdx == -1) {
return@withContext Result.failure(Exception("Cabeçalho 'Número da OS' não encontrado no CSV."))
}
val importedActivities = mutableListOf<MaintenanceActivity>()
val now = System.currentTimeMillis()
val activities = mutableListOf<MaintenanceActivity>()
for (i in 1 until lines.size) {
val rowCells = lines[i].split(separator).map { it.replace("\"", "").trim() }
if (rowCells.size <= osIdx || rowCells.size <= descIdx) continue
val row = lines[i].split(separator).map { it.replace("\"", "").trim() }
if (row.size <= osIdx || row[osIdx].isBlank()) continue
val osNum = rowCells[osIdx]
if (osNum.isBlank()) continue
val osNum = row[osIdx]
val desc = if (descIdx != -1 && row.size > descIdx) row[descIdx] else "Sem Descrição"
val rawSetor = if (setorIdx != -1 && row.size > setorIdx) row[setorIdx] else "Preparação"
val rawEquipe = if (eqIdx != -1 && row.size > eqIdx) row[eqIdx] else "Mecânica"
val resp = if (respIdx != -1 && row.size > respIdx) row[respIdx] else "N/A"
val inicio = if (inicioIdx != -1 && row.size > inicioIdx) row[inicioIdx] else "N/A"
val fim = if (fimIdx != -1 && row.size > fimIdx) row[fimIdx] else "N/A"
val pctStr = if (pctIdx != -1 && row.size > pctIdx) row[pctIdx] else "0"
val tag = if (tagIdx != -1 && row.size > tagIdx) row[tagIdx] else ""
val desc = rowCells[descIdx]
val setor = if (setorIdx != -1 && setorIdx < rowCells.size) rowCells[setorIdx] else "Geral"
val equipe = if (eqIdx != -1 && eqIdx < rowCells.size) rowCells[eqIdx] else "Mecânica"
val recurso = if (respIdx != -1 && respIdx < rowCells.size) rowCells[respIdx] else "Sem Recurso"
val dataInicio = if (inicioIdx != -1 && inicioIdx < rowCells.size) rowCells[inicioIdx] else "N/A"
val dataFim = if (fimIdx != -1 && fimIdx < rowCells.size) rowCells[fimIdx] else "N/A"
val pctStr = if (pctIdx != -1 && pctIdx < rowCells.size) rowCells[pctIdx].replace("%", "").trim() else "0"
val pct = pctStr.toIntOrNull() ?: 0
val tag = if (tagIdx != -1 && tagIdx < rowCells.size) rowCells[tagIdx] else "Sem TAG"
val pct = pctStr.replace("%", "").trim().toIntOrNull() ?: 0
val setorClean = sanitizeSetor(rawSetor)
val equipeClean = sanitizeEquipe(rawEquipe)
importedActivities.add(
activities.add(
MaintenanceActivity(
numeroOs = osNum,
descricao = desc,
setor = sanitizeSetor(setor),
equipe = sanitizeEquipe(equipe),
recurso = recurso,
dataInicio = dataInicio,
dataFim = dataFim,
setor = setorClean,
equipe = equipeClean,
recurso = resp,
dataInicio = inicio,
dataFim = fim,
percentualExecucao = pct.coerceIn(0, 100),
synced = false,
tag = tag,
lastUpdated = now
synced = false,
lastUpdated = System.currentTimeMillis()
)
)
}
if (importedActivities.isEmpty()) {
return@withContext Result.failure(Exception("Nenhuma linha válida pôde ser importada."))
if (activities.isEmpty()) {
return@withContext Result.failure(Exception("Nenhuma atividade válida encontrada no arquivo."))
}
dao.insertActivities(importedActivities)
Result.success(importedActivities.size)
dao.insertActivities(activities)
Result.success(activities.size)
} catch (e: Exception) {
Result.failure(e)
}
@@ -211,6 +218,14 @@ class MaintenanceRepository(
try {
android.util.Log.d("MaintenanceRepository", "Starting Google Sheets synchronization...")
// Validate system date only when online
val isOnline = isCurrentlyConnected()
val timeValidation = timeGuardManager.validateSystemTime(isOnline)
if (timeValidation is com.example.util.TimeValidationResult.InvalidFutureDate) {
android.util.Log.e("MaintenanceRepository", "Synchronization blocked: ${timeValidation.message}")
return@withContext SyncResult.Error(timeValidation.message)
}
// 0. Fetch user access list and store locally
try {
val remoteAccessList = sheetsSyncService.fetchUserAccessList()

View File

@@ -379,7 +379,12 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
_syncStatusMessage.value = "Erro: Nível de acesso '$level' não possui permissão para editar."
return@launch
}
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
try {
repository.updateProgress(numeroOs, novoPercentual, observacao, fotoPath, recurso, emailEditor)
} catch (e: Exception) {
_syncStatusMessage.value = e.message ?: "Erro ao atualizar a OS."
return@launch
}
// Update selected activity model in state to refresh UI
_selectedActivity.value?.let { active ->
if (active.numeroOs == numeroOs) {

View File

@@ -0,0 +1,156 @@
package com.example.util
import android.os.SystemClock
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
sealed class TimeValidationResult {
object Valid : TimeValidationResult()
data class InvalidFutureDate(
val deviceTimeMillis: Long,
val serverTimeMillis: Long,
val diffMillis: Long,
val message: String
) : TimeValidationResult()
}
class TimeGuardManager(
private val client: OkHttpClient = defaultOkHttpClient
) {
companion object {
private const val TAG = "TimeGuardManager"
// 8 hours tolerance as requested by user
const val MAX_FUTURE_TOLERANCE_MS: Long = 8 * 60 * 60 * 1000L
private val defaultOkHttpClient: OkHttpClient by lazy {
OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.build()
}
private val httpDateFormats = listOf(
"EEE, dd MMM yyyy HH:mm:ss z",
"EEE, dd-MMM-yy HH:mm:ss z",
"EEE MMM dd HH:mm:ss yyyy"
)
fun parseHttpDate(dateStr: String?): Date? {
if (dateStr.isNullOrBlank()) return null
for (format in httpDateFormats) {
try {
val sdf = SimpleDateFormat(format, Locale.US)
sdf.timeZone = TimeZone.getTimeZone("GMT")
val parsed = sdf.parse(dateStr.trim())
if (parsed != null) return parsed
} catch (_: Exception) {
// Try next format
}
}
return null
}
}
@Volatile
private var lastKnownServerTimeMs: Long = 0L
@Volatile
private var lastKnownElapsedRealtimeMs: Long = 0L
/**
* Updates verified real server time whenever an HTTP response header is received.
*/
@Synchronized
fun updateVerifiedServerTime(serverTimeMs: Long) {
if (serverTimeMs > 0) {
lastKnownServerTimeMs = serverTimeMs
lastKnownElapsedRealtimeMs = SystemClock.elapsedRealtime()
Log.d(TAG, "Horário real do servidor atualizado: $serverTimeMs")
}
}
/**
* Returns the estimated current server time in millis using the monotonic clock offset,
* or 0L if no verified server time is available yet.
*/
fun getEstimatedServerTimeMs(): Long {
val serverTime = lastKnownServerTimeMs
val elapsed = lastKnownElapsedRealtimeMs
if (serverTime <= 0L || elapsed <= 0L) return 0L
val currentElapsed = SystemClock.elapsedRealtime()
return serverTime + (currentElapsed - elapsed)
}
/**
* Attempts to fetch current real server time from Google HTTP servers.
*/
suspend fun fetchServerTimeFromNetwork(): Long? = withContext(Dispatchers.IO) {
try {
val request = Request.Builder()
.url("https://www.google.com")
.head()
.build()
client.newCall(request).execute().use { response ->
val dateHeader = response.header("Date")
val parsedDate = parseHttpDate(dateHeader)
if (parsedDate != null) {
val serverTimeMs = parsedDate.time
updateVerifiedServerTime(serverTimeMs)
return@withContext serverTimeMs
}
}
} catch (e: Exception) {
Log.w(TAG, "Falha ao obter horário do servidor via HTTP HEAD: ${e.message}")
}
return@withContext null
}
/**
* Validates device system time against real server time.
* Block / Invalid ONLY when online (`isOnline == true`) and device time is > 8h ahead of real server time.
*/
suspend fun validateSystemTime(isOnline: Boolean): TimeValidationResult {
// As per user requirement: impediments only apply when app is online
if (!isOnline) {
return TimeValidationResult.Valid
}
val deviceTimeMs = System.currentTimeMillis()
// 1. Try to get fresh server time or estimate from previous baseline
var serverTimeMs = fetchServerTimeFromNetwork()
if (serverTimeMs == null || serverTimeMs <= 0L) {
serverTimeMs = getEstimatedServerTimeMs()
}
// If we still have no server time baseline, we cannot confirm a future date error online, so return Valid
if (serverTimeMs <= 0L) {
return TimeValidationResult.Valid
}
val diffMs = deviceTimeMs - serverTimeMs
if (diffMs > MAX_FUTURE_TOLERANCE_MS) {
val hoursDiff = diffMs / (1000 * 60 * 60)
val message = "Operação bloqueada: A data do dispositivo está no futuro ($hoursDiff horas à frente do horário dos servidores). Ajuste a data e hora do sistema."
Log.e(TAG, message)
return TimeValidationResult.InvalidFutureDate(
deviceTimeMillis = deviceTimeMs,
serverTimeMillis = serverTimeMs,
diffMillis = diffMs,
message = message
)
}
return TimeValidationResult.Valid
}
}

View File

@@ -0,0 +1,52 @@
package com.example.util
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.Date
class TimeGuardManagerTest {
@Test
fun testParseHttpDate() {
val dateStr = "Wed, 29 Jul 2026 15:48:35 GMT"
val parsed = TimeGuardManager.parseHttpDate(dateStr)
assertTrue(parsed != null)
}
@Test
fun testValidateSystemTimeOnlineValidWithinTolerance() = runBlocking {
val timeGuard = TimeGuardManager()
val now = System.currentTimeMillis()
timeGuard.updateVerifiedServerTime(now - (2 * 60 * 60 * 1000L)) // Server is 2 hours behind device (device is 2h ahead)
// 2h ahead is within 8h tolerance
val result = timeGuard.validateSystemTime(isOnline = true)
assertTrue("Expect Valid when device is 2h ahead (within 8h tolerance)", result is TimeValidationResult.Valid)
}
@Test
fun testValidateSystemTimeOnlineInvalidBeyond8HoursTolerance() = runBlocking {
val timeGuard = TimeGuardManager()
val now = System.currentTimeMillis()
timeGuard.updateVerifiedServerTime(now - (10 * 60 * 60 * 1000L)) // Device is 10 hours ahead of server
// 10h ahead exceeds 8h tolerance
val result = timeGuard.validateSystemTime(isOnline = true)
assertTrue("Expect InvalidFutureDate when device is 10h ahead (> 8h tolerance)", result is TimeValidationResult.InvalidFutureDate)
val invalidResult = result as TimeValidationResult.InvalidFutureDate
assertTrue(invalidResult.message.contains("no futuro"))
}
@Test
fun testValidateSystemTimeOfflineAllowsEditEvenIfFutureDate() = runBlocking {
val timeGuard = TimeGuardManager()
val now = System.currentTimeMillis()
timeGuard.updateVerifiedServerTime(now - (12 * 60 * 60 * 1000L)) // Device is 12 hours ahead
// When offline, impediments do NOT apply as per user requirement
val result = timeGuard.validateSystemTime(isOnline = false)
assertTrue("Expect Valid when offline even if date is far in future", result is TimeValidationResult.Valid)
}
}