feat: migrate media storage from Google Drive to Firebase Storage

This commit is contained in:
Jhony Cesar
2026-08-05 12:27:06 -04:00
parent 0d1991337a
commit 6b8653fad3
11 changed files with 210 additions and 268 deletions

View File

@@ -0,0 +1,119 @@
package com.example.data.remote
import android.content.Context
import android.net.Uri
import android.util.Log
import com.example.util.AppLogger
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import kotlinx.coroutines.tasks.await
import java.io.File
import java.io.IOException
data class FirebaseUploadResult(
val downloadUrl: String,
val storagePath: String,
val fileName: String
)
class FirebaseStorageSyncService(
private val context: Context
) {
private val tag = "FirebaseStorageSync"
private val appLogger = AppLogger.getInstance(context)
private val storage: FirebaseStorage by lazy { FirebaseStorage.getInstance() }
/**
* Uploads a local photo file to Firebase Storage under `photos/OS_{osNumber}/{fileName}`.
* Returns FirebaseUploadResult containing the public download URL and storage path.
*/
suspend fun uploadPhoto(photoFile: File, osNumber: String): FirebaseUploadResult {
if (!photoFile.exists()) {
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
appLogger.logError(tag, err)
throw IOException(err)
}
val timestamp = System.currentTimeMillis()
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
val storagePath = "photos/OS_${sanitizedOs}/$fileName"
val photoRef: StorageReference = storage.reference.child(storagePath)
// Ensure user is authenticated with Firebase Auth if possible
val auth = com.google.firebase.auth.FirebaseAuth.getInstance()
if (auth.currentUser == null) {
val lastAccount = com.google.android.gms.auth.api.signin.GoogleSignIn.getLastSignedInAccount(context)
val idToken = lastAccount?.idToken
if (!idToken.isNullOrBlank()) {
try {
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential).await()
Log.d(tag, "Sincronização silenciosa do FirebaseAuth concluída para ${lastAccount.email}")
} catch (e: Exception) {
Log.w(tag, "Tentativa de login silencioso no FirebaseAuth falhou: ${e.message}")
}
} else {
Log.w(tag, "Aviso: Nenhum usuário autenticado no FirebaseAuth nem ID Token do Google disponível.")
}
}
try {
val fileUri = Uri.fromFile(photoFile)
photoRef.putFile(fileUri).await()
val downloadUrl = photoRef.downloadUrl.await().toString()
appLogger.logInfo(tag, "Foto enviada com sucesso para o Firebase Storage. OS: $osNumber, Path: $storagePath")
return FirebaseUploadResult(
downloadUrl = downloadUrl,
storagePath = storagePath,
fileName = fileName
)
} catch (e: Exception) {
val msg = "Erro ao enviar foto da OS $osNumber para o Firebase Storage: ${e.message}"
appLogger.logError(tag, msg, e)
throw IOException(msg, e)
}
}
/**
* Performs Soft Delete by copying the file object in Firebase Storage to have "_DELETED"
* suffix in the exact same folder, and deleting the original reference.
*/
suspend fun softDeletePhoto(photoUrlOrPath: String, osNumber: String): Boolean {
return try {
val ref = if (photoUrlOrPath.startsWith("http://") || photoUrlOrPath.startsWith("https://")) {
storage.getReferenceFromUrl(photoUrlOrPath)
} else {
storage.reference.child(photoUrlOrPath)
}
val currentPath = ref.path
if (currentPath.contains("_DELETED")) {
Log.d(tag, "Arquivo $currentPath já está marcado como deletado.")
return true
}
val dotIndex = currentPath.lastIndexOf('.')
val newPath = if (dotIndex != -1) {
val base = currentPath.substring(0, dotIndex)
val ext = currentPath.substring(dotIndex)
"${base}_DELETED$ext"
} else {
"${currentPath}_DELETED"
}
val newRef = storage.reference.child(newPath)
val bytes = ref.getBytes(10 * 1024 * 1024).await() // Max 10MB photo limit
newRef.putBytes(bytes).await()
ref.delete().await()
Log.d(tag, "Arquivo $currentPath renomeado no Firebase Storage para $newPath (Soft Delete).")
true
} catch (e: Exception) {
Log.e(tag, "Falha ao executar soft delete no Firebase Storage: ${e.message}", e)
false
}
}
}

View File

@@ -1,224 +0,0 @@
package com.example.data.remote
import android.content.Context
import android.util.Log
import com.google.auth.oauth2.GoogleCredentials
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.File
import java.io.IOException
@JsonClass(generateAdapter = true)
data class DriveFileResponse(
val id: String? = null,
val name: String? = null,
val webViewLink: String? = null,
val webContentLink: String? = null
)
data class DriveUploadResult(
val fileId: String,
val webViewLink: String,
val fileName: String
)
class GoogleDriveSyncService(
private val context: Context,
private val folderId: String = "15WJIdzrykXWRSC5Xy4Ci5Cr7gq6FqMxK"
) {
private val tag = "GoogleDriveSync"
private val client = OkHttpClient.Builder()
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor().apply {
level = okhttp3.logging.HttpLoggingInterceptor.Level.BASIC
})
.build()
private val moshi = Moshi.Builder()
.add(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory())
.build()
private var googleCredentials: GoogleCredentials? = null
@Synchronized
private fun getCredentials(): GoogleCredentials {
if (googleCredentials == null) {
val stream = try {
Log.d(tag, "Carregando credenciais do Google Drive de drive-fotos-gestaoosparada.apikey.json")
context.assets.open("drive-fotos-gestaoosparada.apikey.json")
} catch (e: Exception) {
val msg = "Arquivo de credenciais 'drive-fotos-gestaoosparada.apikey.json' não encontrado na pasta assets."
Log.e(tag, msg, e)
throw IOException(msg, e)
}
googleCredentials = GoogleCredentials.fromStream(stream)
.createScoped(listOf("https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"))
}
googleCredentials!!.refreshIfExpired()
return googleCredentials!!
}
private fun getAccessToken(): String {
val creds = getCredentials()
val token = creds.accessToken?.tokenValue
if (token != null) return token
creds.refresh()
return creds.accessToken?.tokenValue
?: throw IOException("Falha ao obter token de acesso para a Google Drive API.")
}
private val appLogger = com.example.util.AppLogger.getInstance(context)
/**
* Uploads a photo file to Google Drive in the specified folder.
* Sets public read permission and returns the DriveUploadResult containing webViewLink and fileId.
*/
fun uploadPhotoToDrive(photoFile: File, osNumber: String): DriveUploadResult {
if (!photoFile.exists()) {
val err = "Arquivo local da foto não existe: ${photoFile.absolutePath}"
appLogger.logError(tag, err)
throw IOException(err)
}
val token = try {
getAccessToken()
} catch (e: Exception) {
appLogger.logError(tag, "Falha ao obter token de acesso do Google Drive: ${e.message}", e)
throw e
}
val timestamp = System.currentTimeMillis()
val sanitizedOs = osNumber.replace("/", "_").replace(" ", "")
val fileName = "OS_${sanitizedOs}_${timestamp}.jpg"
val metadataJson = """
{
"name": "$fileName",
"parents": ["$folderId"]
}
""".trimIndent()
val multipartRelatedType = "multipart/related".toMediaType()
val multipartBody = MultipartBody.Builder()
.setType(multipartRelatedType)
.addPart(
metadataJson.toRequestBody("application/json; charset=UTF-8".toMediaType())
)
.addPart(
photoFile.asRequestBody("image/jpeg".toMediaType())
)
.build()
val uploadRequest = Request.Builder()
.url("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,webViewLink,webContentLink")
.header("Authorization", "Bearer $token")
.post(multipartBody)
.build()
val response = try {
client.newCall(uploadRequest).execute()
} catch (e: Exception) {
appLogger.logError(tag, "Erro de conexão ao enviar foto da OS $osNumber para o Drive: ${e.message}", e)
throw e
}
val responseBody = response.body?.string()
if (!response.isSuccessful || responseBody.isNullOrBlank()) {
val errorMsg = "Erro no upload da OS $osNumber para o Google Drive: HTTP ${response.code} - $responseBody"
appLogger.logError(tag, errorMsg)
throw IOException(errorMsg)
}
val adapter = moshi.adapter(DriveFileResponse::class.java)
val driveFile = adapter.fromJson(responseBody)
?: run {
val msg = "Resposta inválida da API do Google Drive ao criar arquivo da OS $osNumber."
appLogger.logError(tag, msg)
throw IOException(msg)
}
val fileId = driveFile.id ?: run {
val msg = "Id do arquivo não retornado pelo Google Drive para a OS $osNumber."
appLogger.logError(tag, msg)
throw IOException(msg)
}
// Make file publicly viewable
try {
setFilePublicPermission(fileId, token)
} catch (e: Exception) {
appLogger.logWarning(tag, "Falha ao definir permissão pública do arquivo $fileId: ${e.message}")
}
val directViewUrl = "https://lh3.googleusercontent.com/d/$fileId"
appLogger.logInfo(tag, "Foto enviada com sucesso para o Drive. OS: $osNumber, File ID: $fileId")
return DriveUploadResult(
fileId = fileId,
webViewLink = directViewUrl,
fileName = fileName
)
}
/**
* Sets permission on Google Drive file so anyone with link can view.
*/
private fun setFilePublicPermission(fileId: String, token: String) {
val permJson = """{"role":"reader","type":"anyone"}"""
val req = Request.Builder()
.url("https://www.googleapis.com/drive/v3/files/$fileId/permissions")
.header("Authorization", "Bearer $token")
.post(permJson.toRequestBody("application/json; charset=UTF-8".toMediaType()))
.build()
client.newCall(req).execute().close()
}
/**
* Performs Soft Delete by renaming the file on Google Drive to include "_DELETED" suffix before extension.
*/
fun softDeletePhotoOnDrive(fileId: String, currentFileName: String): Boolean {
val token = getAccessToken()
val dotIndex = currentFileName.lastIndexOf('.')
val newName = if (dotIndex != -1) {
val base = currentFileName.substring(0, dotIndex)
val ext = currentFileName.substring(dotIndex)
if (base.endsWith("_DELETED")) {
currentFileName
} else {
"${base}_DELETED$ext"
}
} else {
if (currentFileName.endsWith("_DELETED")) currentFileName else "${currentFileName}_DELETED"
}
val patchJson = """{"name":"$newName"}"""
val req = Request.Builder()
.url("https://www.googleapis.com/drive/v3/files/$fileId")
.header("Authorization", "Bearer $token")
.patch(patchJson.toRequestBody("application/json; charset=UTF-8".toMediaType()))
.build()
val response = client.newCall(req).execute()
val success = response.isSuccessful
response.close()
if (success) {
Log.d(tag, "Arquivo $fileId renomeado no Google Drive para $newName (Soft Delete).")
} else {
Log.e(tag, "Falha ao renomear arquivo $fileId no Google Drive: HTTP ${response.code}")
}
return success
}
}

View File

@@ -23,7 +23,7 @@ class MaintenanceRepository(
private val appDatabase = com.example.data.local.AppDatabase.getDatabase(context)
private val sheetsSyncService = com.example.data.remote.GoogleSheetsSyncService(context, timeGuardManager)
private val driveSyncService = com.example.data.remote.GoogleDriveSyncService(context)
private val firebaseStorageSyncService = com.example.data.remote.FirebaseStorageSyncService(context)
private val networkMonitor = com.example.util.NetworkMonitor(context)
private val appLogDao = appDatabase.appLogDao()
@@ -486,11 +486,11 @@ class MaintenanceRepository(
val file = java.io.File(trimmed)
if (file.exists()) {
try {
val result = driveSyncService.uploadPhotoToDrive(file, history.numeroOs)
val result = firebaseStorageSyncService.uploadPhoto(file, history.numeroOs)
changed = true
result.webViewLink
result.downloadUrl
} catch (e: Exception) {
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Drive: ${e.message}", e)
android.util.Log.e("MaintenanceRepository", "Falha no upload da foto ${file.name} para o Firebase Storage: ${e.message}", e)
trimmed
}
} else {
@@ -516,13 +516,11 @@ class MaintenanceRepository(
}
suspend fun softDeletePhoto(targetPhotoPath: String, osNumber: String) = withContext(Dispatchers.IO) {
val fileId = extractDriveFileId(targetPhotoPath)
if (fileId != null && isCurrentlyConnected()) {
if (isCurrentlyConnected() && (targetPhotoPath.startsWith("http://") || targetPhotoPath.startsWith("https://") || targetPhotoPath.startsWith("photos/"))) {
try {
val fileName = "OS_${osNumber}_photo.jpg"
driveSyncService.softDeletePhotoOnDrive(fileId, fileName)
firebaseStorageSyncService.softDeletePhoto(targetPhotoPath, osNumber)
} catch (e: Exception) {
android.util.Log.e("MaintenanceRepository", "Erro ao executar soft delete no Google Drive: ${e.message}", e)
android.util.Log.e("MaintenanceRepository", "Erro ao executar soft delete no Firebase Storage: ${e.message}", e)
}
}
@@ -548,21 +546,6 @@ class MaintenanceRepository(
dao.updateActivity(activity.copy(fotoPath = updatedPaths.joinToString("|"), synced = false))
}
}
private fun extractDriveFileId(url: String): String? {
if (url.contains("/d/")) {
val parts = url.split("/d/")
if (parts.size > 1) {
return parts[1].split("/").firstOrNull()?.split("?")?.firstOrNull()
}
} else if (url.contains("id=")) {
val parts = url.split("id=")
if (parts.size > 1) {
return parts[1].split("&").firstOrNull()
}
}
return null
}
}
sealed interface SyncResult {

View File

@@ -17,6 +17,7 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
@@ -80,8 +81,18 @@ fun AnalyticsScreen(
val context = LocalContext.current
val gso = remember {
val defaultWebClientId = remember(context) {
try {
val resId = context.resources.getIdentifier("default_web_client_id", "string", context.packageName)
if (resId != 0) context.getString(resId) else "461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
} catch (e: Exception) {
"461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
}
}
val gso = remember(defaultWebClientId) {
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(defaultWebClientId)
.requestEmail()
.requestProfile()
.build()
@@ -98,6 +109,18 @@ fun AnalyticsScreen(
val email = account.email ?: ""
val name = account.displayName ?: ""
viewModel.loginUser(email, name)
val idToken = account.idToken
if (!idToken.isNullOrBlank()) {
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
try {
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
} catch (e: Exception) {
android.util.Log.e("FirebaseAuth", "Erro ao autenticar no Firebase Auth: ${e.message}", e)
}
}
}
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
}
} catch (e: ApiException) {

View File

@@ -16,6 +16,7 @@ import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.await
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
@@ -123,8 +124,18 @@ fun MaintenanceDashboardScreen(
)
}
val gso = remember {
val defaultWebClientId = remember(context) {
try {
val resId = context.resources.getIdentifier("default_web_client_id", "string", context.packageName)
if (resId != 0) context.getString(resId) else "461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
} catch (e: Exception) {
"461441632355-rg9go0tcsr8ora2la83aat9pcekqo13p.apps.googleusercontent.com"
}
}
val gso = remember(defaultWebClientId) {
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(defaultWebClientId)
.requestEmail()
.requestProfile()
.build()
@@ -141,6 +152,19 @@ fun MaintenanceDashboardScreen(
val email = account.email ?: ""
val name = account.displayName ?: ""
viewModel.loginUser(email, name)
val idToken = account.idToken
if (!idToken.isNullOrBlank()) {
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
try {
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
android.util.Log.d("FirebaseAuth", "Autenticado no Firebase Auth com sucesso!")
} catch (e: Exception) {
android.util.Log.e("FirebaseAuth", "Erro ao autenticar no Firebase Auth: ${e.message}", e)
}
}
}
Toast.makeText(context, "Conectado como $name", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(context, "Erro ao obter dados da conta Google.", Toast.LENGTH_SHORT).show()
@@ -158,6 +182,19 @@ fun MaintenanceDashboardScreen(
val email = lastAccount.email ?: ""
val name = lastAccount.displayName ?: ""
viewModel.loginUser(email, name)
val idToken = lastAccount.idToken
if (!idToken.isNullOrBlank() && com.google.firebase.auth.FirebaseAuth.getInstance().currentUser == null) {
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
try {
val credential = com.google.firebase.auth.GoogleAuthProvider.getCredential(idToken, null)
com.google.firebase.auth.FirebaseAuth.getInstance().signInWithCredential(credential).await()
android.util.Log.d("FirebaseAuth", "Reautenticado no Firebase Auth com sucesso!")
} catch (e: Exception) {
android.util.Log.e("FirebaseAuth", "Erro ao reautenticar no Firebase Auth: ${e.message}", e)
}
}
}
}
}