fix: improve photo synchronization logic by preserving local delete states and performing granular path updates during cloud uploads

This commit is contained in:
Jhony Cesar
2026-08-06 07:51:16 -04:00
parent 824a64b22a
commit 554a34f8b1
2 changed files with 44 additions and 11 deletions

View File

@@ -449,9 +449,13 @@ class MaintenanceRepository(
when { when {
localItem != null && remoteItem != null -> { localItem != null && remoteItem != null -> {
val localHasDeleted = localItem.fotoPath?.contains("_DELETED") == true
val localHasUrl = localItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true val localHasUrl = localItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
val remoteHasUrl = remoteItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true val remoteHasUrl = remoteItem.fotoPath?.let { it.contains("http://") || it.contains("https://") } == true
if (localHasUrl && !remoteHasUrl) { // Always preserve local if it has _DELETED markings (user deleted a photo)
if (localHasDeleted) {
localItem
} else if (localHasUrl && !remoteHasUrl) {
localItem localItem
} else { } else {
remoteItem remoteItem
@@ -694,6 +698,9 @@ class MaintenanceRepository(
suspend fun uploadPendingPhotos() = withContext(Dispatchers.IO) { suspend fun uploadPendingPhotos() = withContext(Dispatchers.IO) {
if (!isCurrentlyConnected()) return@withContext if (!isCurrentlyConnected()) return@withContext
// Collect all local→URL replacements per OS to batch-update activity fotoPath
val replacementsByOs = mutableMapOf<String, MutableList<Pair<String, String>>>()
val historyList = dao.getAllHistoryList() val historyList = dao.getAllHistoryList()
for (history in historyList) { for (history in historyList) {
val rawPath = history.fotoPath val rawPath = history.fotoPath
@@ -702,13 +709,16 @@ class MaintenanceRepository(
var changed = false var changed = false
val uploadedSubPaths = subPaths.map { path -> val uploadedSubPaths = subPaths.map { path ->
val trimmed = path.trim() val trimmed = path.trim()
if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED")) { if (trimmed.isNotBlank() && !trimmed.startsWith("http://") && !trimmed.startsWith("https://") && !trimmed.endsWith("_DELETED") && !trimmed.contains("_DELETED")) {
val file = java.io.File(trimmed) val file = java.io.File(trimmed)
if (file.exists()) { if (file.exists()) {
try { try {
val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L) val compressedFile = com.example.util.ImageCompressor.compressImageFile(file, 500 * 1024L)
val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs) val result = firebaseStorageSyncService.uploadPhoto(compressedFile, history.numeroOs)
changed = true changed = true
// Track the local→URL replacement for this OS
replacementsByOs.getOrPut(history.numeroOs) { mutableListOf() }
.add(Pair(trimmed, result.downloadUrl))
result.downloadUrl result.downloadUrl
} catch (e: Exception) { } catch (e: Exception) {
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e) android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
@@ -726,20 +736,37 @@ class MaintenanceRepository(
val updatedJoinedPath = uploadedSubPaths.joinToString("|") val updatedJoinedPath = uploadedSubPaths.joinToString("|")
val updatedHistory = history.copy(fotoPath = updatedJoinedPath) val updatedHistory = history.copy(fotoPath = updatedJoinedPath)
dao.insertHistory(updatedHistory) dao.insertHistory(updatedHistory)
val activity = dao.getActivityByOsOneShot(history.numeroOs)
if (activity != null) {
dao.updateActivity(activity.copy(fotoPath = updatedJoinedPath))
}
} }
} }
} }
// Now update each activity's fotoPath by replacing local paths with uploaded URLs
// without overwriting the entire fotoPath (preserves photos from other history entries)
for ((osNumber, replacements) in replacementsByOs) {
val activity = dao.getActivityByOsOneShot(osNumber) ?: continue
val currentFotoPath = activity.fotoPath ?: continue
var updatedFotoPath = currentFotoPath
for ((localPath, uploadedUrl) in replacements) {
// Replace the local path with the uploaded URL in the full pipe-separated string
updatedFotoPath = updatedFotoPath.split("|").joinToString("|") { p ->
if (p.trim() == localPath.trim()) uploadedUrl else p
}
}
if (updatedFotoPath != currentFotoPath) {
dao.updateActivity(activity.copy(fotoPath = updatedFotoPath))
}
}
} }
private fun extractPhotoFileName(path: String): String { private fun extractPhotoFileName(path: String): String {
val clean = path.trim().substringBefore("?").substringBefore("#") val clean = path.trim().substringBefore("?").substringBefore("#")
val fileName = clean.substringAfterLast("/").substringAfterLast("\\") // Handle both regular slashes and URL-encoded slashes (%2F)
return fileName.removeSuffix("_DELETED") val decoded = clean.replace("%2F", "/", ignoreCase = true)
val fileName = decoded.substringAfterLast("/").substringAfterLast("\\")
return fileName.removeSuffix("_DELETED").removeSuffix(".jpg_DELETED").let {
// Also handle _DELETED inserted before extension: photo_DELETED.jpg
it.replace("_DELETED", "")
}
} }
private fun isSamePhoto(path1: String?, path2: String?): Boolean { private fun isSamePhoto(path1: String?, path2: String?): Boolean {

View File

@@ -633,9 +633,15 @@ class MaintenanceViewModel(private val repository: MaintenanceRepository) : View
try { try {
repository.softDeletePhoto(fotoPath, osNumber) repository.softDeletePhoto(fotoPath, osNumber)
_syncStatusMessage.value = "Foto excluída com sucesso." _syncStatusMessage.value = "Foto excluída com sucesso."
if (_internetAvailable.value) { // Refresh selected activity from local DB to reflect the deletion immediately
syncNow() _selectedActivity.value?.let { active ->
if (active.numeroOs == osNumber) {
_selectedActivity.value = allActivitiesState.value.find { it.numeroOs == osNumber }
}
} }
// Do NOT auto-sync here — the sync would reconcile with remote data
// and potentially overwrite the local _DELETED marking while the dialog is open.
// The deletion will be synced on the next manual or periodic sync.
} catch (e: Exception) { } catch (e: Exception) {
_syncStatusMessage.value = "Erro ao excluir foto: ${e.message}" _syncStatusMessage.value = "Erro ao excluir foto: ${e.message}"
} }