streaming d'un fichier
This commit is contained in:
@@ -161,6 +161,82 @@ class ApiClient @Inject constructor(
|
||||
suspend fun getShareLink(token: String): ShareLinkDto =
|
||||
unwrap({ apiService.getShareLink(token) }, skipUnauthorizedHandling = true)
|
||||
|
||||
/**
|
||||
* Octets physiques d'un fichier visible — `GET /files/:id/content`
|
||||
* (binaire brut, hors enveloppe). Streaming sans cache : lecture bornée
|
||||
* à [maxBytes] (+1 pour détecter le dépassement → `FILE_TOO_LARGE`),
|
||||
* jamais persistée. 404 = invisible ou metadata-only sans octets.
|
||||
*/
|
||||
suspend fun downloadContentBytes(
|
||||
fileId: String,
|
||||
maxBytes: Long = MAX_CONTENT_BYTES,
|
||||
): ByteArray {
|
||||
val response = try {
|
||||
apiService.downloadContent(fileId)
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
Timber.d(e, "api: transport error (content)")
|
||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||
} catch (e: Exception) {
|
||||
if (e is CancellationException) throw e
|
||||
Timber.d(e, "api: unexpected error (content)")
|
||||
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 ?: if (status == 404) "NOT_FOUND" else "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())
|
||||
if (body.contentLength() > maxBytes) {
|
||||
body.close()
|
||||
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
|
||||
}
|
||||
try {
|
||||
body.byteStream().use { input ->
|
||||
val out = java.io.ByteArrayOutputStream()
|
||||
val buf = ByteArray(32 * 1024)
|
||||
var total = 0L
|
||||
while (true) {
|
||||
val read = input.read(buf)
|
||||
if (read < 0) break
|
||||
total += read
|
||||
if (total > maxBytes) {
|
||||
throw ApiException("FILE_TOO_LARGE", "Fichier trop volumineux pour le streaming", response.code())
|
||||
}
|
||||
out.write(buf, 0, read)
|
||||
}
|
||||
return out.toByteArray()
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
throw e
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
throw ApiException("NETWORK_ERROR", "Serveur injoignable", 0)
|
||||
} finally {
|
||||
body.close()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** Borne streaming sans cache : 12 Mo (jamais en RAM au-delà). */
|
||||
const val MAX_CONTENT_BYTES = 12 * 1024 * 1024L
|
||||
}
|
||||
|
||||
private suspend fun <T> unwrap(
|
||||
call: suspend () -> Response<ApiEnvelope<T>>,
|
||||
skipUnauthorizedHandling: Boolean = false,
|
||||
|
||||
@@ -18,6 +18,7 @@ import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import retrofit2.Response
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.DELETE
|
||||
@@ -28,6 +29,7 @@ import retrofit2.http.POST
|
||||
import retrofit2.http.Part
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
import retrofit2.http.Streaming
|
||||
|
||||
/**
|
||||
* Contrat HTTP V1 — copie de `mobile/api/client.ts` (le client mobile est la
|
||||
@@ -119,6 +121,18 @@ interface ApiService {
|
||||
@Path("id") fileId: String,
|
||||
): Response<ApiEnvelope<FileDto>>
|
||||
|
||||
/**
|
||||
* Octets physiques d'un fichier visible (viewer+, own ou shared) —
|
||||
* `GET /files/:id/content` (binaire brut, hors enveloppe `{data}`).
|
||||
* Streaming lecture seule : le client ne persiste rien (V1 streaming).
|
||||
* 404 = invisible OU metadata-only jamais uploadé (indistinguables).
|
||||
*/
|
||||
@Streaming
|
||||
@GET("files/{id}/content")
|
||||
suspend fun downloadContent(
|
||||
@Path("id") fileId: String,
|
||||
): Response<ResponseBody>
|
||||
|
||||
/** Suppression serveur d'un fichier possédé — `DELETE /files/:id`. */
|
||||
@DELETE("files/{id}")
|
||||
suspend fun deleteFile(
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.kazier.mobile.data.repository
|
||||
|
||||
import com.kazier.mobile.data.remote.ApiClient
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
/**
|
||||
* Contenu distant en streaming (V1 finitions, lot download).
|
||||
*
|
||||
* Lit les octets physiques d'un fichier visible via
|
||||
* `GET /files/:id/content` (binaire brut, hors enveloppe) sans jamais les
|
||||
* persister : ni Room, ni SAF, ni fichier durable. Seul le rendu PDF exige
|
||||
* un fichier temporaire du `cacheDir`, créé à la volée par le viewer et
|
||||
* supprimé à sa sortie (éphémère, pas un cache).
|
||||
*/
|
||||
@Singleton
|
||||
class RemoteContentRepository @Inject constructor(
|
||||
private val apiClient: ApiClient,
|
||||
) {
|
||||
/** Octets du fichier, bornés ([ApiClient.MAX_CONTENT_BYTES]). */
|
||||
suspend fun fetch(fileId: String): ByteArray =
|
||||
apiClient.downloadContentBytes(fileId)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.kazier.mobile.ui.document
|
||||
|
||||
import androidx.lifecycle.ViewModel
|
||||
import com.kazier.mobile.data.remote.ApiException
|
||||
import com.kazier.mobile.data.repository.RemoteContentRepository
|
||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||
import javax.inject.Inject
|
||||
|
||||
/**
|
||||
* Chargement streaming d'un fichier cloud-only (V1 finitions).
|
||||
*
|
||||
* Stateless : [load] lit les octets via `GET /files/:id/content` sans les
|
||||
* persister. Le composant appelant garde l'état (idle/loading/loaded/error).
|
||||
*/
|
||||
@HiltViewModel
|
||||
class RemoteContentViewModel @Inject constructor(
|
||||
private val repository: RemoteContentRepository,
|
||||
) : ViewModel() {
|
||||
|
||||
suspend fun load(fileId: String): Result<ByteArray> =
|
||||
runCatching { repository.fetch(fileId) }
|
||||
|
||||
companion object {
|
||||
/** Code quand le serveur n'a aucun octet (metadata-only jamais uploadé). */
|
||||
fun isNoContent(e: Throwable): Boolean =
|
||||
e is ApiException && e.code == "NOT_FOUND"
|
||||
|
||||
fun isTooLarge(e: Throwable): Boolean =
|
||||
e is ApiException && e.code == "FILE_TOO_LARGE"
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -42,7 +42,7 @@ fun DocumentContentViewer(
|
||||
}
|
||||
|
||||
if (file.uri == null) {
|
||||
CloudOnlyPlaceholder(file, modifier)
|
||||
RemoteDocumentViewer(file, onOpenExternalFailed, modifier)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
package com.kazier.mobile.ui.document.content
|
||||
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.hilt.navigation.compose.hiltViewModel
|
||||
import coil.compose.AsyncImage
|
||||
import com.kazier.mobile.R
|
||||
import com.kazier.mobile.data.local.entity.FileEntity
|
||||
import com.kazier.mobile.domain.FileCategory
|
||||
import com.kazier.mobile.ui.components.FileCategoryIcon
|
||||
import com.kazier.mobile.ui.components.categoryValue
|
||||
import com.kazier.mobile.ui.document.RemoteContentViewModel
|
||||
import java.io.File
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
/**
|
||||
* Lecteur streaming d'un fichier cloud-only (`uri == null`).
|
||||
*
|
||||
* V1 finitions, choix « streaming sans cache » : les octets sont lus via
|
||||
* `GET /files/:id/content` sur demande (bouton, jamais d'auto-load au swipe),
|
||||
* gardés en RAM le temps de l'affichage, jamais persistés (ni Room, ni SAF).
|
||||
* Seul le PDF exige un fichier temporaire du `cacheDir` (le `PdfRenderer`
|
||||
* système ne sait lire que depuis un descripteur) — éphémère, supprimé à la
|
||||
* sortie du viewer. 404 = aucun octet serveur (metadata-only jamais uploadé).
|
||||
*/
|
||||
@Composable
|
||||
fun RemoteDocumentViewer(
|
||||
file: FileEntity,
|
||||
onOpenExternalFailed: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
viewModel: RemoteContentViewModel = hiltViewModel(),
|
||||
) {
|
||||
var started by remember(file.resourceId) { mutableStateOf(false) }
|
||||
var loading by remember(file.resourceId) { mutableStateOf(false) }
|
||||
var bytes by remember(file.resourceId) { mutableStateOf<ByteArray?>(null) }
|
||||
var error by remember(file.resourceId) { mutableStateOf<Throwable?>(null) }
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
fun reload() {
|
||||
loading = true
|
||||
error = null
|
||||
scope.launch {
|
||||
viewModel.load(file.resourceId)
|
||||
.onSuccess {
|
||||
bytes = it
|
||||
loading = false
|
||||
}
|
||||
.onFailure {
|
||||
error = it
|
||||
loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val loaded = bytes
|
||||
when {
|
||||
loaded != null -> RemoteContentBody(
|
||||
file = file,
|
||||
bytes = loaded,
|
||||
onOpenExternalFailed = onOpenExternalFailed,
|
||||
modifier = modifier,
|
||||
)
|
||||
loading -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
CircularProgressIndicator()
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_stream_loading),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
error != null -> RemoteContentError(
|
||||
error = error!!,
|
||||
onRetry = ::reload,
|
||||
modifier = modifier,
|
||||
)
|
||||
!started -> RemoteContentGate(
|
||||
file = file,
|
||||
onLoad = {
|
||||
started = true
|
||||
reload()
|
||||
},
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** État initial : métadonnées + bouton de lecture à la demande (pas d'auto-load). */
|
||||
@Composable
|
||||
private fun RemoteContentGate(
|
||||
file: FileEntity,
|
||||
onLoad: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
FileCategoryIcon(file = file, size = 64.dp)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_cloud_only),
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
text = stringResource(R.string.document_cloud_only_hint),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Button(onClick = onLoad) {
|
||||
Text(stringResource(R.string.document_stream_load))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Échec de streaming : message + réessai (404 → aucun contenu serveur). */
|
||||
@Composable
|
||||
private fun RemoteContentError(
|
||||
error: Throwable,
|
||||
onRetry: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val message = when {
|
||||
RemoteContentViewModel.isNoContent(error) ->
|
||||
stringResource(R.string.document_stream_no_content)
|
||||
RemoteContentViewModel.isTooLarge(error) ->
|
||||
stringResource(R.string.document_stream_too_large)
|
||||
else -> stringResource(R.string.document_stream_error)
|
||||
}
|
||||
Column(
|
||||
modifier = modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
TextButton(onClick = onRetry) {
|
||||
Text(stringResource(R.string.document_stream_retry))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Dispatch du contenu distant par catégorie (PDF / image / texte supportés). */
|
||||
@Composable
|
||||
private fun RemoteContentBody(
|
||||
file: FileEntity,
|
||||
bytes: ByteArray,
|
||||
onOpenExternalFailed: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
when (file.categoryValue()) {
|
||||
FileCategory.IMAGE -> RemoteImageViewer(bytes = bytes, description = file.name, modifier = modifier)
|
||||
FileCategory.TEXT -> RemoteTextViewer(bytes = bytes, modifier = modifier)
|
||||
FileCategory.PDF -> RemotePdfViewer(file = file, bytes = bytes, modifier = modifier)
|
||||
else -> Column(
|
||||
modifier = modifier.padding(24.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = stringResource(R.string.document_stream_unsupported),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
ExternalOpenButton(file = file, onOpenExternalFailed = onOpenExternalFailed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemoteImageViewer(bytes: ByteArray, description: String, modifier: Modifier = Modifier) {
|
||||
val bitmap = remember(bytes) {
|
||||
runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }.getOrNull()
|
||||
}
|
||||
if (bitmap != null) {
|
||||
Image(
|
||||
bitmap = bitmap.asImageBitmap(),
|
||||
contentDescription = description,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
} else {
|
||||
// Repli : Coil décode depuis le ByteArray (mêmes bytes, autre décodeur).
|
||||
AsyncImage(
|
||||
model = bytes,
|
||||
contentDescription = description,
|
||||
modifier = modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Texte distant : décodage UTF-8 borné, même présentation que le viewer local. */
|
||||
@Composable
|
||||
private fun RemoteTextViewer(bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||
val text = remember(bytes) {
|
||||
val capped = bytes.size > REMOTE_TEXT_MAX
|
||||
val length = minOf(bytes.size, REMOTE_TEXT_MAX)
|
||||
String(bytes, 0, length, Charsets.UTF_8).removePrefix("") to capped
|
||||
}
|
||||
Column(modifier.fillMaxSize()) {
|
||||
if (text.second) {
|
||||
Text(
|
||||
text = stringResource(R.string.document_truncated_notice),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
SelectionContainer(Modifier.weight(1f)) {
|
||||
LazyColumn(contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)) {
|
||||
item {
|
||||
Text(text = text.first, style = MaterialTheme.typography.bodyMedium)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PDF distant : le `PdfRenderer` système exige un descripteur de fichier —
|
||||
* les octets sont écrits dans un fichier temporaire du `cacheDir`
|
||||
* (`stream-<resourceId>.pdf`), supprimé à la sortie. Première page affichée
|
||||
* (aperçu streaming, pas de navigation complète).
|
||||
*/
|
||||
@Composable
|
||||
private fun RemotePdfViewer(file: FileEntity, bytes: ByteArray, modifier: Modifier = Modifier) {
|
||||
val context = LocalContext.current
|
||||
var tmpFile by remember(file.resourceId) { mutableStateOf<File?>(null) }
|
||||
var loadFailed by remember(file.resourceId) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(file.resourceId, bytes) {
|
||||
loadFailed = false
|
||||
tmpFile = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val tmp = File(context.cacheDir, "stream-${file.resourceId}.pdf")
|
||||
tmp.writeBytes(bytes)
|
||||
tmp
|
||||
}.getOrNull()
|
||||
}
|
||||
if (tmpFile == null) loadFailed = true
|
||||
}
|
||||
DisposableEffect(file.resourceId) {
|
||||
onDispose {
|
||||
val tmp = tmpFile
|
||||
tmpFile = null
|
||||
if (tmp != null) {
|
||||
runCatching {
|
||||
kotlinx.coroutines.runBlocking(Dispatchers.IO) { tmp.delete() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val tmp = tmpFile
|
||||
when {
|
||||
loadFailed || (tmp != null && !tmp.exists()) -> Text(
|
||||
text = stringResource(R.string.document_cannot_read),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = modifier,
|
||||
)
|
||||
tmp == null -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
else -> RemotePdfFirstPage(tmp = tmp, modifier = modifier)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun RemotePdfFirstPage(tmp: File, modifier: Modifier = Modifier) {
|
||||
var bitmap by remember(tmp.absolutePath) { mutableStateOf<android.graphics.Bitmap?>(null) }
|
||||
var failed by remember(tmp.absolutePath) { mutableStateOf(false) }
|
||||
LaunchedEffect(tmp.absolutePath) {
|
||||
failed = false
|
||||
bitmap = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val pfd = ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
val renderer = PdfRenderer(pfd)
|
||||
try {
|
||||
if (renderer.pageCount <= 0) return@runCatching null
|
||||
val page = renderer.openPage(0)
|
||||
try {
|
||||
val width = (page.width * 2f).toInt().coerceIn(1, 4096)
|
||||
val height = (page.height * 2f).toInt().coerceIn(1, 4096)
|
||||
val bmp = android.graphics.Bitmap.createBitmap(
|
||||
width, height, android.graphics.Bitmap.Config.ARGB_8888,
|
||||
)
|
||||
page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
bmp
|
||||
} finally {
|
||||
page.close()
|
||||
}
|
||||
} finally {
|
||||
renderer.close()
|
||||
pfd.close()
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
if (bitmap == null) failed = true
|
||||
}
|
||||
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
when {
|
||||
bitmap != null -> Image(
|
||||
bitmap = bitmap!!.asImageBitmap(),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentScale = ContentScale.Fit,
|
||||
)
|
||||
failed -> Text(
|
||||
text = stringResource(R.string.document_cannot_read),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
else -> CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private const val REMOTE_TEXT_MAX = 512 * 1024
|
||||
@@ -84,6 +84,13 @@
|
||||
<string name="document_truncated_notice">Preview truncated — the full file is not displayed.</string>
|
||||
<string name="document_loading">Reading document…</string>
|
||||
<string name="document_cannot_read">Could not read this document.</string>
|
||||
<string name="document_stream_load">Stream</string>
|
||||
<string name="document_stream_loading">Loading from the server…</string>
|
||||
<string name="document_stream_retry">Retry</string>
|
||||
<string name="document_stream_error">Streaming failed. Check your connection and retry.</string>
|
||||
<string name="document_stream_no_content">No server content for this file.</string>
|
||||
<string name="document_stream_too_large">File too large for streaming (max 12 MB).</string>
|
||||
<string name="document_stream_unsupported">Streaming preview not supported for this file type.</string>
|
||||
<string name="document_page_unreadable">Unreadable page</string>
|
||||
<string name="focus_tap_to_exit">Tap to exit</string>
|
||||
<string name="login_show_password">Show password</string>
|
||||
|
||||
@@ -84,6 +84,13 @@
|
||||
<string name="document_truncated_notice">Aperçu tronqué — le fichier complet n\'est pas affiché.</string>
|
||||
<string name="document_loading">Lecture du document…</string>
|
||||
<string name="document_cannot_read">Impossible de lire ce document.</string>
|
||||
<string name="document_stream_load">Lire en streaming</string>
|
||||
<string name="document_stream_loading">Chargement depuis le serveur…</string>
|
||||
<string name="document_stream_retry">Réessayer</string>
|
||||
<string name="document_stream_error">Échec du streaming. Vérifie ta connexion puis réessaie.</string>
|
||||
<string name="document_stream_no_content">Aucun contenu sur le serveur pour ce fichier.</string>
|
||||
<string name="document_stream_too_large">Fichier trop volumineux pour le streaming (max 12 Mo).</string>
|
||||
<string name="document_stream_unsupported">Aperçu en streaming non supporté pour ce type de fichier.</string>
|
||||
<string name="document_page_unreadable">Page illisible</string>
|
||||
<string name="focus_tap_to_exit">Toucher pour quitter</string>
|
||||
<string name="login_show_password">Afficher le mot de passe</string>
|
||||
|
||||
@@ -36,6 +36,7 @@ import kotlinx.coroutines.withTimeout
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -303,5 +304,9 @@ class Auth401Test {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ import com.kazier.mobile.domain.GenerateId
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Before
|
||||
@@ -192,5 +193,9 @@ class PaginationTest {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.kazier.mobile.data.remote
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import com.kazier.mobile.data.remote.dto.ApiEnvelope
|
||||
import com.kazier.mobile.data.remote.dto.ChangePasswordDto
|
||||
import com.kazier.mobile.data.remote.dto.DeviceRegistrationDto
|
||||
import com.kazier.mobile.data.remote.dto.FileDto
|
||||
import com.kazier.mobile.data.remote.dto.FileOcrDto
|
||||
import com.kazier.mobile.data.remote.dto.FolderDto
|
||||
import com.kazier.mobile.data.remote.dto.IdResultDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginRequestDto
|
||||
import com.kazier.mobile.data.remote.dto.LoginResponseDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrJobDto
|
||||
import com.kazier.mobile.data.remote.dto.OcrSubmitDto
|
||||
import com.kazier.mobile.data.remote.dto.ResolvedUserDto
|
||||
import com.kazier.mobile.data.remote.dto.ResourcePermissionDto
|
||||
import com.kazier.mobile.data.remote.dto.ShareLinkDto
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsRequest
|
||||
import com.kazier.mobile.data.remote.dto.SyncOpsResult
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
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
|
||||
|
||||
/**
|
||||
* Streaming `GET /files/:id/content` (V1 finitions) : octets bruts bornés,
|
||||
* jamais persistés ; 404 = invisible ou metadata-only sans octets.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [34])
|
||||
class RemoteContentTest {
|
||||
|
||||
private fun client(fake: ContentFake): ApiClient {
|
||||
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
|
||||
return ApiClient(fake, moshi)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_retourne_les_octets_bruts`() = runTest {
|
||||
val fake = ContentFake { Response.success("hello".toResponseBody("text/plain".toMediaType())) }
|
||||
val bytes = client(fake).downloadContentBytes("aabbccddeeff11223344556677889900")
|
||||
assertArrayEquals("hello".toByteArray(), bytes)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_404_mappe_NOT_FOUND`() = runTest {
|
||||
val fake = ContentFake {
|
||||
Response.error(404, "{\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"file not found\"}}".toResponseBody("application/json".toMediaType()))
|
||||
}
|
||||
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("NOT_FOUND", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_borne_maxBytes_FILE_TOO_LARGE`() = runTest {
|
||||
val fake = ContentFake { Response.success("0123456789ABCDEF".toResponseBody("text/plain".toMediaType())) }
|
||||
val ex = runCatching { client(fake).downloadContentBytes("aabbccddeeff11223344556677889900", maxBytes = 4) }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals("FILE_TOO_LARGE", (ex as ApiException).code)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `downloadContentBytes_401_declenche_onUnauthorized`() = runTest {
|
||||
var unauthorized = 0
|
||||
val fake = ContentFake {
|
||||
Response.error(401, "{\"error\":{\"code\":\"UNAUTHORIZED\",\"message\":\"x\"}}".toResponseBody("application/json".toMediaType()))
|
||||
}
|
||||
val c = client(fake)
|
||||
c.onUnauthorized = { unauthorized++ }
|
||||
val ex = runCatching { c.downloadContentBytes("aabbccddeeff11223344556677889900") }.exceptionOrNull()
|
||||
assertTrue(ex is ApiException)
|
||||
assertEquals(1, unauthorized)
|
||||
}
|
||||
|
||||
private class ContentFake(
|
||||
private val content: () -> Response<ResponseBody>,
|
||||
) : ApiService {
|
||||
override suspend fun listFolders(): Response<ApiEnvelope<List<FolderDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun listFiles(folderId: String?, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun registerDevice(body: DeviceRegistrationDto): Response<ApiEnvelope<DeviceRegistrationDto>> =
|
||||
Response.success(ApiEnvelope(data = body))
|
||||
|
||||
override suspend fun login(body: LoginRequestDto): Response<ApiEnvelope<LoginResponseDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncOps(body: SyncOpsRequest): Response<ApiEnvelope<SyncOpsResult>> =
|
||||
Response.success(ApiEnvelope(data = SyncOpsResult(applied = 0)))
|
||||
|
||||
override suspend fun resolveUser(username: String): Response<ApiEnvelope<ResolvedUserDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun syncPermissions(after: Long?): Response<ApiEnvelope<List<ResourcePermissionDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun uploadFile(file: MultipartBody.Part, resourceId: RequestBody?, folderId: RequestBody?): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun submitOcr(body: OcrSubmitDto): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getOcrJob(jobId: String): Response<ApiEnvelope<OcrJobDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFileOcr(fileId: String): Response<ApiEnvelope<FileOcrDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getFile(fileId: String): Response<ApiEnvelope<FileDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun deleteFile(fileId: String): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun searchFiles(query: String, page: Int?, pageSize: Int?): Response<ApiEnvelope<List<FileDto>>> =
|
||||
Response.success(ApiEnvelope(data = emptyList()))
|
||||
|
||||
override suspend fun changePassword(body: ChangePasswordDto): Response<ApiEnvelope<IdResultDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(fileId: String): Response<ResponseBody> = content()
|
||||
}
|
||||
}
|
||||
+5
@@ -52,6 +52,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fous data-layer de la fusion de dossiers : le re-parentage repositionne
|
||||
@@ -378,4 +379,8 @@ private class FolderMergeApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
+5
@@ -54,6 +54,7 @@ import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import org.robolectric.shadows.ShadowContentResolver
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fous outbox du déplacement local : tant qu'un `move_resource` est en
|
||||
@@ -467,4 +468,8 @@ private class MoveProtectionApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
@@ -46,6 +46,7 @@ import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import java.io.ByteArrayInputStream
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Pipeline OCR local : l'upload multipart ciblé envoie les octets du flux SAF
|
||||
@@ -385,4 +386,8 @@ private class OcrApiServiceFake : ApiService {
|
||||
body.writeTo(buffer)
|
||||
return buffer.readUtf8()
|
||||
}
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
@@ -44,6 +44,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Garde-fou refresh serveur vs reparent local (miroir dossiers du
|
||||
@@ -234,4 +235,8 @@ private class RefreshVsMoveApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
|
||||
+5
@@ -45,6 +45,7 @@ import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
import retrofit2.Response
|
||||
import okhttp3.ResponseBody
|
||||
|
||||
/**
|
||||
* Contrat de l'hydratation du snapshot `GET /sync/permissions` :
|
||||
@@ -488,4 +489,8 @@ private class FakeApiService : ApiService {
|
||||
override suspend fun getShareLink(
|
||||
token: String,
|
||||
): Response<ApiEnvelope<ShareLinkDto>> = Response.success(ApiEnvelope())
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
+5
@@ -54,6 +54,7 @@ import kotlinx.coroutines.test.runTest
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.MultipartBody
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.ResponseBody.Companion.toResponseBody
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
@@ -448,5 +449,9 @@ class OutboxSyncWorkerTest {
|
||||
|
||||
override suspend fun getShareLink(token: String): Response<ApiEnvelope<ShareLinkDto>> =
|
||||
throw UnsupportedOperationException()
|
||||
|
||||
override suspend fun downloadContent(
|
||||
fileId: String,
|
||||
): Response<ResponseBody> = Response.success(ResponseBody.create(null, ByteArray(0)))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user