V3 S7 : preview cloud + export chiffré + release 1.2.0
Release / release-apk (push) Successful in 8m58s
Release / release-docker (push) Successful in 3m47s
CI / docker (push) Successful in 7s
CI / lint-backend (push) Successful in 1m44s
CI / lint-mobile (push) Failing after 18m59s
CI / test-backend (push) Successful in 2m12s
CI / test-mobile (push) Successful in 8m50s
CI / build-backend (push) Successful in 45s

Backend : resource_previews (000024), GET /files/:id/preview (JPEG
512, images pur Go, PDF page 1 via pdftoppm + poppler au Dockerfile,
cache régénéré sur changement, 404 NO_PREVIEW sinon), POST /export
{password 8+} -> zip AES-256 streamé (fichiers vifs possédés +
manifest.json avec faits, metadata-only sans octets). Deps :
alexmullins/zip, x/image directs. Tests service + handlers + migrations.

Mobile : vignettes distantes (une requête/session puis cache WebP
versionné, garde tried, icône sinon), FileThumbnail cloud-only,
export (mot de passe jamais persisté, cache + partage FileProvider),
bouton Partager ACTION_SEND. Impression papier reportée V4. FR/EN.

Contrat docs/api-v1.md, V3.md (S7 livré, V3 close), AGENTS.md,
VERSION 1.2.0 + CHANGELOG.
This commit is contained in:
venture
2026-09-26 15:08:31 +02:00
parent 1e38e6e4ee
commit 4316da578f
56 changed files with 2004 additions and 37 deletions
@@ -33,6 +33,18 @@
tools:node="remove" />
</provider>
<!-- Partage de l'export chiffré (V3 S7) : FileProvider sur le cache
(jamais d'URI file:// vers une autre app). -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<activity
android:name=".MainActivity"
android:exported="true"
@@ -32,6 +32,7 @@ import com.kazier.mobile.data.remote.dto.SyncOpsResult
import com.kazier.mobile.data.remote.dto.CorrectFactsDto
import com.kazier.mobile.data.remote.dto.DeviceDto
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
import com.kazier.mobile.data.remote.dto.ExportRequestDto
import com.kazier.mobile.data.remote.dto.FactDto
import com.kazier.mobile.data.remote.dto.RelationDto
import com.kazier.mobile.data.remote.dto.RelationVerdictDto
@@ -43,6 +44,7 @@ import okhttp3.MultipartBody
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import okio.IOException
import retrofit2.Response
import timber.log.Timber
@@ -204,6 +206,60 @@ class ApiClient @Inject constructor(
suspend fun getUsage(): UsageDto =
unwrap({ apiService.getUsage() })
/**
* Export chiffré vers un fichier (V3 S7) — `POST /export`, streamé
* direct sur disque (jamais en RAM : un export peut peser des Go).
* 400 si mot de passe trop court, 401 → re-login.
*/
suspend fun exportToFile(password: String, dest: java.io.File) {
val response = try {
apiService.exportZip(ExportRequestDto(password))
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
Timber.d(e, "api: transport error (export)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.d(e, "api: unexpected error (export)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
}
if (!response.isSuccessful) {
val status = response.code()
if (status == 401) {
onUnauthorized?.invoke()
}
val error = response.errorBody()?.use { body ->
body.string().let { raw ->
runCatching { errorEnvelopeAdapter.fromJson(raw)?.error }.getOrNull()
}
}
throw ApiException(
code = error?.code ?: "HTTP_$status",
message = error?.message ?: "HTTP $status",
httpCode = status,
)
}
val body = response.body()
?: throw ApiException("INVALID_RESPONSE", "Réponse serveur invalide (corps vide)", response.code())
try {
dest.parentFile?.mkdirs()
body.byteStream().use { input ->
dest.outputStream().use { out ->
input.copyTo(out)
}
}
} catch (e: CancellationException) {
runCatching { dest.delete() }
throw e
} catch (e: IOException) {
runCatching { dest.delete() }
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} finally {
body.close()
}
}
/** Recherche serveur paginée — `GET /files/search?q=…` (+ `meta`). */
suspend fun searchFilesPaged(
query: String,
@@ -277,17 +333,39 @@ class ApiClient @Inject constructor(
suspend fun downloadContentBytes(
fileId: String,
maxBytes: Long = MAX_CONTENT_BYTES,
): ByteArray = downloadRawBytes(tag = "content", maxBytes = maxBytes) {
apiService.downloadContent(fileId)
}
/**
* Vignette JPEG 512 d'un fichier visible — `GET /files/:id/preview`
* (binaire brut, `inline`). 404 NOT_FOUND si invisible, 404 NO_PREVIEW
* si le type ne se prévisualise pas (code propagé tel quel pour que
* l'UI n'insiste pas).
*/
suspend fun downloadPreviewBytes(
fileId: String,
maxBytes: Long = MAX_PREVIEW_BYTES,
): ByteArray = downloadRawBytes(tag = "preview", maxBytes = maxBytes) {
apiService.downloadPreview(fileId)
}
/** Cœur streaming borné partagé par `content` et `preview` (V3 S7). */
private suspend fun downloadRawBytes(
tag: String,
maxBytes: Long,
call: suspend () -> Response<ResponseBody>,
): ByteArray {
val response = try {
apiService.downloadContent(fileId)
call()
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
Timber.d(e, "api: transport error (content)")
Timber.d(e, "api: transport error ($tag)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
} catch (e: Exception) {
if (e is CancellationException) throw e
Timber.d(e, "api: unexpected error (content)")
Timber.d(e, "api: unexpected error ($tag)")
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
}
if (!response.isSuccessful) {
@@ -342,6 +420,8 @@ class ApiClient @Inject constructor(
companion object {
/** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */
const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L
/** Borne vignette distante : 1 Mo (JPEG 512 ≪ ça, garde-fou). */
const val MAX_PREVIEW_BYTES = 1024 * 1024L
}
private suspend fun <T> unwrap(
@@ -25,6 +25,7 @@ import com.kazier.mobile.data.remote.dto.SyncOpsResult
import com.kazier.mobile.data.remote.dto.CorrectFactsDto
import com.kazier.mobile.data.remote.dto.DeviceDto
import com.kazier.mobile.data.remote.dto.DuplicateGroupDto
import com.kazier.mobile.data.remote.dto.ExportRequestDto
import com.kazier.mobile.data.remote.dto.FactDto
import com.kazier.mobile.data.remote.dto.RelationDto
import com.kazier.mobile.data.remote.dto.RelationVerdictDto
@@ -148,6 +149,18 @@ interface ApiService {
@Path("id") fileId: String,
): Response<ResponseBody>
/**
* Vignette JPEG 512 d'un fichier visible (V3 S7) —
* `GET /files/:id/preview` (binaire brut, `inline`, cache 1 h).
* 404 NOT_FOUND si invisible/metadata-only, 404 NO_PREVIEW si le type
* ne se prévisualise pas (l'UI montre l'icône, sans réessai).
*/
@Streaming
@GET("files/{id}/preview")
suspend fun downloadPreview(
@Path("id") fileId: String,
): Response<ResponseBody>
/** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */
@DELETE("files/{id}")
suspend fun deleteFile(
@@ -239,6 +252,17 @@ interface ApiService {
@GET("users/me/usage")
suspend fun getUsage(): Response<ApiEnvelope<UsageDto>>
/**
* Export chiffré du compte (V3 S7) — `POST /export { password }`
* (mot de passe en corps, jamais en query). Zip AES-256 streamé
* (fichiers vifs possédés + manifest.json, tout chiffré).
*/
@Streaming
@POST("export")
suspend fun exportZip(
@Body body: ExportRequestDto,
): Response<ResponseBody>
/**
* Recherche serveur (`GET /files/search?q=…`, paginé `meta`). Non consommée
* en V1 (recherche 100 % locale via Room) — exposée pour parité contrat.
@@ -369,4 +369,9 @@ data class UsageDto(
@Json(name = "fileCount") val fileCount: Int = 0,
@Json(name = "trashCount") val trashCount: Int = 0,
@Json(name = "trashedBytes") val trashedBytes: Long = 0L,
)
/** Body `POST /export` — mot de passe du zip AES (8+ caractères, V3 S7). */
data class ExportRequestDto(
@Json(name = "password") val password: String,
)
@@ -0,0 +1,52 @@
package com.kazier.mobile.features.thumbnails
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.domain.FileCategory
import com.kazier.mobile.domain.computeCategory
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import timber.log.Timber
/**
* Vignettes des fichiers cloud-only (V3 S7) : `GET /files/:id/preview`
* (JPEG 512 serveur) → cache WebP versionné ([ThumbnailStore.putRemote]).
*
* Garde-fou anti-matraquage : un `tried` process-wide (succès comme échec —
* 404 NO_PREVIEW inclus) garantit au plus UNE requête réseau par ressource et
* par session, même dans une grille de 500 items. Après succès, le cache
* disque prend le relais (zéro réseau) ; après un changement serveur, le
* versionnement `updatedAt + taille` invalide l'ancien fichier.
*/
@Singleton
class RemotePreviewFetcher @Inject constructor(
private val apiClient: ApiClient,
private val thumbnailStore: ThumbnailStore,
) {
private val tried = ConcurrentHashMap.newKeySet<String>()
/** Vignette distante mise en cache, ou `null` (icône de catégorie). */
suspend fun fetch(file: FileEntity): File? {
if (file.uri != null) return null
// computeCategory (domaine) plutôt que categoryValue (UI) : même
// règle, sans dépendance features → ui.
val category = computeCategory(file.mimeType, file.extension)
if (category != FileCategory.IMAGE && category != FileCategory.PDF) return null
// Cache disque d'abord (2e vue de la session, ou pré-rempli).
thumbnailStore.cachedRemote(file.resourceId, file.updatedAt, file.size)?.let { return it }
if (!tried.add(file.resourceId)) return null
return try {
val bytes = apiClient.downloadPreviewBytes(file.resourceId)
thumbnailStore.putRemote(file.resourceId, file.updatedAt, file.size, bytes)
} catch (e: Exception) {
Timber.d("remote preview %s: %s", file.resourceId, e.message)
null
}
}
/** Nombre de ressources tentées cette session (diagnostic/tests). */
internal fun triedCount(): Int = tried.size
}
@@ -111,6 +111,47 @@ class ThumbnailStore @Inject constructor(
}
}
/**
* Persiste des octets de vignette distants (`GET /files/:id/preview`,
* JPEG 512 déjà réduit serveur) en cache WebP versionné
* (`updatedAt + taille` — une source modifiée invalide l'ancien
* fichier, comme en local). Retourne le fichier, `null` si indécodable.
*/
suspend fun putRemote(
resourceId: String,
version: Long?,
sizeBytes: Long?,
bytes: ByteArray,
): File? = withContext(Dispatchers.IO) {
val bitmap = runCatching {
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}.getOrNull() ?: return@withContext null
try {
val target = thumbnailFile(resourceId, version, sizeBytes)
if (isUpToDate(target, null)) return@withContext target
val tmp = File(target.parentFile, "${target.name}.tmp")
try {
dir().mkdirs()
val ok = tmp.outputStream().use { out ->
bitmap.compress(Bitmap.CompressFormat.WEBP, WEBP_QUALITY, out)
}
if (ok && tmp.renameTo(target)) {
pruneSiblings(resourceId, keep = target)
target
} else {
runCatching { tmp.delete() }
null
}
} catch (e: Exception) {
Timber.w(e, "remote thumbnail write failed")
runCatching { tmp.delete() }
null
}
} finally {
bitmap.recycle()
}
}
/** Fichier possédé par une resource : version courante, legacy ou tmp. */
private fun isOwnedThumb(resourceId: String, name: String): Boolean {
if (name == "$resourceId.webp") return true
@@ -119,6 +160,19 @@ class ThumbnailStore @Inject constructor(
return false
}
/**
* Cache disque d'une vignette distante (versionnée, puis legacy) — sans
* réseau. Le nom versionné (`updatedAt + taille`) porte la fraîcheur :
* une source modifiée ne matche plus et sera re-téléchargée.
*/
fun cachedRemote(resourceId: String, version: Long?, sizeBytes: Long?): File? {
val target = thumbnailFile(resourceId, version, sizeBytes)
if (isUpToDate(target, null)) return target
val legacy = thumbnailFile(resourceId)
if (legacy != target && isUpToDate(legacy, null)) return legacy
return null
}
/** Supprime les versions périmées et les `.tmp` orphelins (génération OK). */
private fun pruneSiblings(resourceId: String, keep: File) {
dir().listFiles { f -> f != keep && isOwnedThumb(resourceId, f.name) }
@@ -16,6 +16,7 @@ import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.domain.FileCategory
import com.kazier.mobile.features.thumbnails.RemotePreviewFetcher
import com.kazier.mobile.features.thumbnails.ThumbnailStore
import com.kazier.mobile.ui.theme.ThumbShape
import dagger.hilt.EntryPoint
@@ -32,8 +33,10 @@ import kotlinx.coroutines.withContext
* Images (JPEG/PNG/WebP) et PDF (page 1) n'affichent plus une simple icône :
* la vignette est générée à la demande par [ThumbnailStore] (décodage borné
* 512 px, single-flight, cache disque `filesDir/thumbnails`) puis rendue par
* Coil depuis le fichier local — zéro lecture SAF au scroll. Les autres
* catégories et les fichiers cloud-only conservent l'icône de catégorie.
* Coil depuis le fichier local — zéro lecture SAF au scroll. Les fichiers
* cloud-only (`uri == null`) tentent la preview serveur (`RemotePreviewFetcher`,
* une seule requête par session puis cache disque). Les autres catégories
* conservent l'icône de catégorie.
*/
@Composable
fun FileThumbnail(
@@ -50,9 +53,13 @@ fun FileThumbnail(
val context = LocalContext.current
val thumbnailStore = rememberThumbnailStore(context)
val remoteFetcher = rememberRemoteFetcher(context)
@Suppress("ProduceStateDoesNotAssignValue")
val thumb by produceState<File?>(null, file.resourceId, file.lastModified) {
value = withContext(Dispatchers.IO) { thumbnailStore.ensure(file) }
val thumb by produceState<File?>(null, file.resourceId, file.lastModified, file.updatedAt) {
value = withContext(Dispatchers.IO) {
thumbnailStore.ensure(file)
?: remoteFetcher?.fetch(file)
}
}
val thumbFile = thumb
@@ -84,8 +91,21 @@ private fun rememberThumbnailStore(context: Context): ThumbnailStore =
).thumbnailStore()
}
/** Fetcher optionnel (hors Hilt direct en UI) — null si indisponible. */
@Composable
private fun rememberRemoteFetcher(context: Context): RemotePreviewFetcher? =
remember(context) {
runCatching {
EntryPointAccessors.fromApplication(
context.applicationContext,
ThumbnailStoreEntryPoint::class.java,
).remotePreviewFetcher()
}.getOrNull()
}
@EntryPoint
@InstallIn(SingletonComponent::class)
internal interface ThumbnailStoreEntryPoint {
fun thumbnailStore(): ThumbnailStore
fun remotePreviewFetcher(): RemotePreviewFetcher
}
@@ -28,6 +28,7 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.CloudOff
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.DocumentScanner
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.FactCheck
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ButtonDefaults
@@ -187,6 +188,31 @@ fun DocumentViewerScreen(
snackbarHostState.showSnackbar(context.getString(R.string.document_open_error))
}
}
// B3 : partage système du fichier local (SAF content:// direct + grant).
// Cloud-only : pas de copie locale → pas de partage (télécharger d'abord).
val onShare: (() -> Unit)? = currentFile
?.takeIf { it.uri != null }
?.let { file ->
{
val uri = android.net.Uri.parse(file.uri)
val share = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
type = file.mimeType ?: "application/octet-stream"
putExtra(android.content.Intent.EXTRA_STREAM, uri)
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
clipData = android.content.ClipData.newUri(
context.contentResolver, file.name, uri,
)
}
runCatching {
context.startActivity(
android.content.Intent.createChooser(
share,
context.getString(R.string.document_share_title),
),
)
}.onFailure { onOpenExternalFailed() }
}
}
// Erreurs / succès transitoires (suppression, garder) → Snackbar puis effacés.
LaunchedEffect(viewerState.deleteError) {
@@ -346,6 +372,7 @@ fun DocumentViewerScreen(
} else {
null
},
onShare = onShare,
modifier = Modifier.fillMaxWidth(),
)
}
@@ -660,6 +687,7 @@ private fun DocumentActionBar(
onDeleteModeSelected: (FileDeleter.DeleteMode) -> Unit,
onOcr: (() -> Unit)? = null,
onFacts: (() -> Unit)? = null,
onShare: (() -> Unit)? = null,
releasable: Boolean = false,
onRelease: (() -> Unit)? = null,
modifier: Modifier = Modifier,
@@ -736,6 +764,12 @@ private fun DocumentActionBar(
onClick = onFacts,
)
}
if (onShare != null) {
DocumentShareButton(
enabled = !busy,
onClick = onShare,
)
}
DocumentDeleteMenu(
file = file,
enabled = !busy,
@@ -824,6 +858,31 @@ private fun DocumentOcrButton(
}
}
/** Bouton « Partager » B3 — ACTION_SEND du fichier local (SAF direct). */
@Composable
private fun DocumentShareButton(
enabled: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
FilledTonalButton(
onClick = onClick,
enabled = enabled,
modifier = modifier,
) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = null,
modifier = Modifier.size(20.dp),
)
Spacer(Modifier.size(ButtonDefaults.IconSpacing))
Text(
text = stringResource(R.string.document_share),
maxLines = 1,
)
}
}
/**
* Fenêtre OCR : progression (upload → queued → processing), texte extrait
* (sélectionnable) ou erreur. Le bouton « Relancer » est proposé dès que le
@@ -0,0 +1,71 @@
package com.kazier.mobile.ui.settings
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kazier.mobile.data.remote.ApiClient
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import timber.log.Timber
/**
* Export chiffré du compte (V3 S7 C3) : `POST /export { password }` → zip
* AES-256 téléchargé dans le cache (`cache/exports/`) puis partagé via le
* sheet système (FileProvider, jamais d'URI `file://`). Le mot de passe
* n'est ni persisté ni journalisé (champ seul, 8+ caractères).
*/
@HiltViewModel
class ExportViewModel @Inject constructor(
private val apiClient: ApiClient,
@ApplicationContext private val appContext: Context,
) : ViewModel() {
data class ExportUiState(
val downloading: Boolean = false,
val file: File? = null,
val error: String? = null,
)
private val _uiState = MutableStateFlow(ExportUiState())
val uiState: StateFlow<ExportUiState> = _uiState.asStateFlow()
fun download(password: String) {
if (_uiState.value.downloading) return
viewModelScope.launch {
_uiState.update { it.copy(downloading = true, file = null, error = null) }
runCatching {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val dest = File(File(appContext.cacheDir, "exports"), "kazier-export-$stamp.zip")
// Nettoie les exports précédents (un seul fichier vivant).
dest.parentFile?.listFiles()?.forEach { runCatching { it.delete() } }
apiClient.exportToFile(password, dest)
dest
}.onSuccess { file ->
_uiState.update { it.copy(downloading = false, file = file) }
}.onFailure { e ->
Timber.w(e, "export failed")
_uiState.update {
it.copy(downloading = false, error = e.message ?: e.javaClass.simpleName)
}
}
}
}
fun consumeFile() {
_uiState.update { it.copy(file = null) }
}
fun clearError() {
_uiState.update { it.copy(error = null) }
}
}
@@ -23,6 +23,7 @@ import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Archive
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
@@ -44,10 +45,12 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
@@ -79,6 +82,7 @@ fun SettingsScreen(
connectionStatusViewModel: ConnectionStatusViewModel,
syncViewModel: SyncViewModel,
viewModel: SettingsViewModel = hiltViewModel(),
exportViewModel: ExportViewModel = hiltViewModel(),
) {
val theme by viewModel.theme.collectAsStateWithLifecycle()
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
@@ -95,6 +99,7 @@ fun SettingsScreen(
var showServerDialog by rememberSaveable { mutableStateOf(false) }
var showAuthDialog by rememberSaveable { mutableStateOf(false) }
var showRetentionDialog by rememberSaveable { mutableStateOf(false) }
var showExportDialog by rememberSaveable { mutableStateOf(false) }
// Stats de purge recalculées à l'ouverture du dialogue rétention.
LaunchedEffect(showRetentionDialog) {
@@ -201,6 +206,15 @@ fun SettingsScreen(
onClick = { showRetentionDialog = true },
)
// Export chiffré (V3 S7 C3) : connecté uniquement (données serveur).
if (authState is AuthState.SignedIn) {
HorizontalDivider()
ExportSettingsRow(
onExport = { showExportDialog = true },
exportViewModel = exportViewModel,
)
}
HorizontalDivider()
val signedIn = authState as? AuthState.SignedIn
SettingsRow(
@@ -257,6 +271,34 @@ fun SettingsScreen(
)
}
if (showExportDialog) {
val exportState by exportViewModel.uiState.collectAsStateWithLifecycle()
if (exportState.error != null) {
AlertDialog(
onDismissRequest = {
showExportDialog = false
exportViewModel.clearError()
},
title = { Text(stringResource(R.string.export_title)) },
text = { Text(exportState.error ?: "") },
confirmButton = {
TextButton(onClick = {
showExportDialog = false
exportViewModel.clearError()
}) { Text(stringResource(R.string.delete_cancel)) }
},
)
} else {
ExportPasswordDialog(
onDismiss = { showExportDialog = false },
onConfirm = { password ->
showExportDialog = false
exportViewModel.download(password)
},
)
}
}
if (showAuthDialog) {
when (val state = authState) {
is AuthState.SignedIn -> {
@@ -562,3 +604,117 @@ private fun SettingsRow(
trailing()
}
}
/**
* Ligne + dialogue d'export chiffré (V3 S7 C3) : mot de passe (8+, jamais
* persisté), téléchargement, puis partage via le sheet système (FileProvider).
*/
@Composable
private fun ExportSettingsRow(
onExport: () -> Unit,
exportViewModel: ExportViewModel,
) {
val exportState by exportViewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
// Fichier prêt → ouvre le sheet de partage une fois, puis consomme.
LaunchedEffect(exportState.file) {
val file = exportState.file ?: return@LaunchedEffect
val uri = androidx.core.content.FileProvider.getUriForFile(
context,
"${context.packageName}.fileprovider",
file,
)
val share = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
type = "application/zip"
putExtra(android.content.Intent.EXTRA_STREAM, uri)
addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
runCatching {
context.startActivity(
android.content.Intent.createChooser(share, context.getString(R.string.export_share_title)),
)
}
exportViewModel.consumeFile()
}
LaunchedEffect(exportState.error) {
// L'erreur est affichée par le dialogue (champ dédié) — rien ici.
}
SettingsRow(
icon = { Icon(Icons.Filled.Archive, contentDescription = null) },
title = stringResource(R.string.export_title),
subtitle = stringResource(R.string.export_hint),
trailing = {
if (exportState.downloading) {
CircularProgressIndicator(modifier = Modifier.size(24.dp))
}
},
onClick = { if (!exportState.downloading) onExport() },
)
}
/** Dialogue mot de passe d'export (8+, champ sécurisé, erreur inline). */
@Composable
internal fun ExportPasswordDialog(
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
) {
var password by rememberSaveable { mutableStateOf("") }
var confirm by rememberSaveable { mutableStateOf("") }
val tooShort = password.isNotEmpty() && password.length < 8
val mismatch = confirm.isNotEmpty() && confirm != password
val canConfirm = password.length >= 8 && password == confirm
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.export_password_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(R.string.export_password_hint),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text(stringResource(R.string.export_password)) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
isError = tooShort,
)
OutlinedTextField(
value = confirm,
onValueChange = { confirm = it },
label = { Text(stringResource(R.string.export_password_confirm)) },
singleLine = true,
visualTransformation = PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
isError = mismatch,
)
if (tooShort) {
Text(
text = stringResource(R.string.export_password_too_short),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
} else if (mismatch) {
Text(
text = stringResource(R.string.export_password_mismatch),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
}
},
confirmButton = {
TextButton(onClick = { onConfirm(password) }, enabled = canConfirm) {
Text(stringResource(R.string.export_download))
}
},
dismissButton = {
TextButton(onClick = onDismiss) { Text(stringResource(R.string.delete_cancel)) }
},
)
}
@@ -78,6 +78,8 @@
<string name="document_open_with">Open with</string>
<string name="document_open_with_hint">No built-in reader — open this file in an external app.</string>
<string name="document_open_error">No app can open this file.</string>
<string name="document_share">Share</string>
<string name="document_share_title">Share document</string>
<string name="document_cloud_only">Cloud only</string>
<string name="document_cloud_only_hint">This file is not downloaded on this device. Sign in to your server to make it available.</string>
<string name="document_keep_done">Document kept and synced.</string>
@@ -476,4 +478,15 @@
<string name="family_name">Circle name</string>
<string name="family_default_name">Family</string>
<string name="family_create">Create</string>
<!-- Encrypted export V3 S7 C3 -->
<string name="export_title">Export (encrypted zip)</string>
<string name="export_hint">Full backup: files + manifest, AES-256</string>
<string name="export_password_title">Export password</string>
<string name="export_password_hint">It protects the zip. Don\'t lose it: without it, the backup is unreadable.</string>
<string name="export_password">Password (8+ characters)</string>
<string name="export_password_confirm">Confirm</string>
<string name="export_password_too_short">8 characters minimum.</string>
<string name="export_password_mismatch">Passwords do not match.</string>
<string name="export_download">Download</string>
<string name="export_share_title">Share backup</string>
</resources>
@@ -78,6 +78,8 @@
<string name="document_open_with">Ouvrir avec</string>
<string name="document_open_with_hint">Aucun lecteur intégré — ouvre ce fichier dans une application externe.</string>
<string name="document_open_error">Aucune application ne peut ouvrir ce fichier.</string>
<string name="document_share">Partager</string>
<string name="document_share_title">Partager le document</string>
<string name="document_cloud_only">Disponible uniquement sur le cloud</string>
<string name="document_cloud_only_hint">Ce fichier n\'est pas téléchargé sur cet appareil. Connecte-toi à ton serveur pour le rendre disponible.</string>
<string name="document_keep_done">Document gardé et synchronisé.</string>
@@ -477,4 +479,15 @@
<string name="family_name">Nom du cercle</string>
<string name="family_default_name">Famille</string>
<string name="family_create">Créer</string>
<!-- Export chiffré V3 S7 C3 -->
<string name="export_title">Exporter (zip chiffré)</string>
<string name="export_hint">Sauvegarde complète : fichiers + manifest, AES-256</string>
<string name="export_password_title">Mot de passe de l\'export</string>
<string name="export_password_hint">Il protège le zip. Ne le perdez pas : sans lui, la sauvegarde est illisible.</string>
<string name="export_password">Mot de passe (8+ caractères)</string>
<string name="export_password_confirm">Confirmer</string>
<string name="export_password_too_short">8 caractères minimum.</string>
<string name="export_password_mismatch">Les mots de passe diffèrent.</string>
<string name="export_download">Télécharger</string>
<string name="export_share_title">Partager la sauvegarde</string>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- FileProvider V3 S7 : partage de l'export chiffré depuis le cache. -->
<paths>
<cache-path name="exports" path="exports/" />
</paths>
@@ -384,6 +384,14 @@ class Auth401Test {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -258,6 +258,14 @@ class PaginationTest {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -179,6 +179,10 @@ class RemoteContentTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content()
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> = content()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> = content()
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -386,6 +386,12 @@ class SessionReloginTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -223,6 +223,12 @@ class ShareManagementTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
if (failShares) {
Response.error(404, errBody("NOT_FOUND"))
@@ -313,6 +313,12 @@ class BytesUploadTest {
override suspend fun downloadContent(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -186,6 +186,8 @@ class FactsRepositoryTest {
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<okhttp3.ResponseBody> = TODO()
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO()
override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
@@ -444,6 +444,14 @@ private class FolderMergeApiService : ApiService {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -147,6 +147,8 @@ class LinksRepositoryTest {
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileOcrDto>> = TODO()
override suspend fun getFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.FileDto>> = TODO()
override suspend fun downloadContent(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<okhttp3.ResponseBody> = TODO()
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun listTrash(page: Int?, pageSize: Int?): Response<ApiEnvelope<List<com.kazier.mobile.data.remote.dto.TrashDto>>> = TODO()
override suspend fun restoreFile(fileId: String): Response<ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
@@ -533,6 +533,14 @@ private class MoveProtectionApiService : ApiService {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -451,6 +451,14 @@ private class OcrApiServiceFake : ApiService {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -327,6 +327,12 @@ class OfflineDownloadTest {
Mode.NETWORK -> throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0)
}
override suspend fun downloadPreview(fileId: String): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): Response<ResponseBody> =
Response.success(ByteArray(0).toResponseBody(null))
override suspend fun listShares(fileId: String): Response<ApiEnvelope<List<ShareGrantDto>>> =
Response.success(ApiEnvelope(data = emptyList()))
@@ -300,6 +300,14 @@ private class RefreshVsMoveApiService : ApiService {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -554,6 +554,14 @@ private class FakeApiService : ApiService {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -171,6 +171,8 @@ class ReleaseLocalCopyTest {
override suspend fun changePassword(body: com.kazier.mobile.data.remote.dto.ChangePasswordDto): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.IdResultDto>> = TODO()
override suspend fun getShareLink(token: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<com.kazier.mobile.data.remote.dto.ShareLinkDto>> = TODO()
override suspend fun downloadContent(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun downloadPreview(fileId: String): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun exportZip(body: com.kazier.mobile.data.remote.dto.ExportRequestDto): retrofit2.Response<okhttp3.ResponseBody> = TODO()
override suspend fun listShares(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareGrantDto>>> = TODO()
override suspend fun listLinks(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.ShareLinkDto>>> = TODO()
override suspend fun listPlacements(fileId: String): retrofit2.Response<com.kazier.mobile.data.remote.dto.ApiEnvelope<List<com.kazier.mobile.data.remote.dto.PlacementDto>>> = TODO()
@@ -579,6 +579,14 @@ class OutboxSyncWorkerTest {
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun downloadPreview(
fileId: String,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun exportZip(
body: com.kazier.mobile.data.remote.dto.ExportRequestDto,
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
override suspend fun listShares(
fileId: String,
): Response<ApiEnvelope<List<ShareGrantDto>>> = Response.success(ApiEnvelope(data = emptyList()))
@@ -0,0 +1,142 @@
package com.kazier.mobile.features.thumbnails
import android.content.Context
import android.graphics.Bitmap
import androidx.test.core.app.ApplicationProvider
import com.kazier.mobile.data.local.entity.FileEntity
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.test.runTest
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import retrofit2.Response
import java.io.ByteArrayOutputStream
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
import java.util.concurrent.atomic.AtomicInteger
/**
* Previews distantes V3 (S7) : `GET /files/:id/preview` → cache WebP
* versionné, une seule requête par session (garde `tried`), 404 → icône.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class RemotePreviewFetcherTest {
private lateinit var context: Context
private lateinit var store: ThumbnailStore
private lateinit var calls: AtomicInteger
private lateinit var previewBytes: ByteArray
private var failWith404 = false
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
store = ThumbnailStore(context)
calls = AtomicInteger(0)
previewBytes = jpegBytes(640, 480)
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val handler = InvocationHandler { _, method, _ ->
when (method.name) {
"downloadPreview" -> {
calls.incrementAndGet()
if (failWith404) {
Response.error<okhttp3.ResponseBody>(
404,
"{\"error\":{\"code\":\"NO_PREVIEW\",\"message\":\"none\"}}"
.toResponseBody("application/json".toMediaType()),
)
} else {
Response.success(previewBytes.toResponseBody("image/jpeg".toMediaType()))
}
}
else -> throw UnsupportedOperationException(method.name)
} as Any
}
val apiService = Proxy.newProxyInstance(
javaClass.classLoader, arrayOf(ApiService::class.java), handler,
) as ApiService
val apiClient = ApiClient(apiService, moshi)
fetcher = RemotePreviewFetcher(apiClient, store)
}
private lateinit var fetcher: RemotePreviewFetcher
private fun cloudImage(id: String) = FileEntity(
resourceId = id, uri = null, name = "distant.jpg",
folderResourceId = "f", extension = "jpg", size = 1000,
mimeType = "image/jpeg", exists = 1, processed = true,
addedAt = 1L, updatedAt = 2L,
)
private fun jpegBytes(w: Int, h: Int): ByteArray {
val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
val out = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 80, out)
bmp.recycle()
return out.toByteArray()
}
@Test
fun fetch_met_en_cache_une_seule_requete() = runTest {
val first = fetcher.fetch(cloudImage("r1".padEnd(32, '1')))
assertNotNull(first)
assertTrue(first!!.isFile && first.length() > 0)
assertEquals(1, calls.get())
// Second appel : cache disque, zéro réseau (tried + fichier présent).
val second = fetcher.fetch(cloudImage("r1".padEnd(32, '1')))
assertEquals(1, calls.get())
assertNotNull(second)
assertEquals(1, fetcher.triedCount())
}
@Test
fun no_preview_ne_reessaie_pas() = runTest {
failWith404 = true
assertNull(fetcher.fetch(cloudImage("r2".padEnd(32, '2'))))
assertEquals(1, calls.get())
// Pas de retry en session (icône).
assertNull(fetcher.fetch(cloudImage("r2".padEnd(32, '2'))))
assertEquals(1, calls.get())
}
@Test
fun putRemote_decode_et_versionne() = runTest {
val cached = store.putRemote("r3".padEnd(32, '3'), 2L, 1000L, previewBytes)
assertNotNull(cached)
// Même version → même fichier (cache-hit).
val again = store.putRemote("r3".padEnd(32, '3'), 2L, 1000L, previewBytes)
assertEquals(cached!!.absolutePath, again!!.absolutePath)
// Source modifiée (updatedAt) → nouveau fichier versionné.
val newer = store.putRemote("r3".padEnd(32, '3'), 3L, 1000L, previewBytes)
assertNotNull(newer)
assertTrue(newer!!.absolutePath != cached.absolutePath)
}
@Test
fun putRemote_binaire_pourri_ne_plante_pas() = runTest {
// Note : sous Robolectric le décodeur est indulgent (jamais null) —
// sur device réel, `decodeByteArray` null → `putRemote` null. Ici on
// vérifie seulement l'absence de crash et le contrat de versionnement.
val id = "r4".padEnd(32, '4')
val cached = store.putRemote(id, 2L, 9L, byteArrayOf(1, 2, 3))
assertNotNull(cached)
// Fichier versionné par (updatedAt, taille), comme en production.
assertTrue(cached!!.name.contains("_2_9"))
}
}
@@ -0,0 +1,89 @@
package com.kazier.mobile.ui.settings
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.kazier.mobile.data.remote.ApiClient
import com.kazier.mobile.data.remote.ApiService
import com.kazier.mobile.data.remote.dto.ApiEnvelope
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.ResponseBody.Companion.toResponseBody
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import retrofit2.Response
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
/**
* Export chiffré V3 (S7 C3) : téléchargement vers le cache, erreur remontée,
* mot de passe jamais persisté (champ seul du ViewModel).
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ExportViewModelTest {
private fun viewModel(zipBytes: ByteArray?, fail: Boolean = false): ExportViewModel {
val context = ApplicationProvider.getApplicationContext<Context>()
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val handler = InvocationHandler { _, method, _ ->
when (method.name) {
"exportZip" -> {
if (fail) throw com.kazier.mobile.data.remote.ApiException("NETWORK_ERROR", "down", 0)
Response.success(zipBytes!!.toResponseBody("application/zip".toMediaType()))
}
else -> throw UnsupportedOperationException(method.name)
} as Any
}
val apiService = Proxy.newProxyInstance(
javaClass.classLoader, arrayOf(ApiService::class.java), handler,
) as ApiService
return ExportViewModel(ApiClient(apiService, moshi), context)
}
@Test
fun download_ecrit_le_zip_en_cache() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
val vm = viewModel("PK-fake-zip".toByteArray())
vm.download("motdepasse-8")
testScheduler.advanceUntilIdle()
val file = vm.uiState.value.file
assertNotNull(file)
assertTrue(file!!.isFile && file.length() > 0)
assertTrue(file.name.startsWith("kazier-export-"))
vm.consumeFile()
assertNull(vm.uiState.value.file)
} finally {
Dispatchers.resetMain()
}
}
@Test
fun echec_reseau_remonte_en_erreur() = runTest {
Dispatchers.setMain(StandardTestDispatcher(testScheduler))
try {
val vm = viewModel(null, fail = true)
vm.download("motdepasse-8")
testScheduler.advanceUntilIdle()
// ApiClient normalise le transport (pas de fuite du message fake).
assertEquals("Serveur injoignable", vm.uiState.value.error)
assertNull(vm.uiState.value.file)
vm.clearError()
assertNull(vm.uiState.value.error)
} finally {
Dispatchers.resetMain()
}
}
}