diff --git a/movil/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/movil/src-tauri/gen/android/app/src/main/AndroidManifest.xml
index 92ec3b3c..37605317 100644
--- a/movil/src-tauri/gen/android/app/src/main/AndroidManifest.xml
+++ b/movil/src-tauri/gen/android/app/src/main/AndroidManifest.xml
@@ -7,6 +7,11 @@
+
+
+
+
+
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Adjuntos.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Adjuntos.kt
new file mode 100644
index 00000000..5f9f986d
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Adjuntos.kt
@@ -0,0 +1,339 @@
+package com.toomasmg.sloth.celu
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.content.ActivityNotFoundException
+import android.content.pm.PackageManager
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Matrix
+import android.media.AudioFormat
+import android.media.AudioRecord
+import android.media.ExifInterface
+import android.media.MediaRecorder
+import android.net.Uri
+import android.util.Log
+import android.webkit.WebView
+import androidx.activity.result.PickVisualMediaRequest
+import androidx.activity.result.contract.ActivityResultContracts.PickVisualMedia
+import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
+import androidx.activity.result.contract.ActivityResultContracts.TakePicture
+import androidx.appcompat.app.AlertDialog
+import androidx.core.content.ContextCompat
+import androidx.core.content.FileProvider
+import com.google.android.material.dialog.MaterialAlertDialogBuilder
+import org.json.JSONObject
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.IOException
+import java.io.InputStream
+import kotlin.concurrent.thread
+
+/**
+ * Graba un audio o consigue una foto para la terminal que se está mirando, lo sube a la PC y le devuelve a la página lo
+ * que contestó. La página nunca ve los bytes. Todo se llama desde el hilo de la interfaz y se crea antes de que la
+ * actividad arranque, que es cuando Android deja anotar los pedidos con resultado.
+ */
+class Adjuntos(private val actividad: MainActivity) {
+ /** A qué PC y terminal va. La clave queda solo en memoria. */
+ class Destino(val web: WebView, val pc: Pc, val id: String)
+
+ private class Grabacion(val destino: Destino) {
+ @Volatile var seguir = true
+ var descartada = false
+ }
+
+ val llave = Llave()
+
+ /** Desde que se acepta un pedido hasta que la PC contesta o se abandona: de a un adjunto. */
+ private var ocupado = false
+ private var grabacion: Grabacion? = null
+ private var dialogo: AlertDialog? = null
+ private var esperaMicrofono: Destino? = null
+ private var esperaFoto: Destino? = null
+ private var archivoFoto: File? = null
+
+ private val permisoMicrofono = actividad.registerForActivityResult(RequestPermission()) { dado ->
+ val d = esperaMicrofono ?: return@registerForActivityResult
+ esperaMicrofono = null
+ if (dado) empezar(d) else fallar(d, AUDIO, "Sloth no tiene permiso para usar el micrófono.")
+ }
+
+ private val permisoCamara = actividad.registerForActivityResult(RequestPermission()) { dado ->
+ val d = esperaFoto ?: return@registerForActivityResult
+ if (dado) return@registerForActivityResult abrirCamara(d)
+ esperaFoto = null
+ fallar(d, FOTO, "Sloth no tiene permiso para usar la cámara.")
+ }
+
+ private val camara = actividad.registerForActivityResult(TakePicture()) { sacada ->
+ val d = esperaFoto
+ val archivo = archivoFoto
+ esperaFoto = null
+ archivoFoto = null
+ if (d != null && archivo != null && sacada) {
+ mandarFoto(d, { archivo.inputStream() }, archivo)
+ } else {
+ archivo?.delete()
+ if (d != null) ocupado = false
+ }
+ }
+
+ private val galeria = actividad.registerForActivityResult(PickVisualMedia()) { elegida ->
+ val d = esperaFoto ?: return@registerForActivityResult
+ esperaFoto = null
+ if (elegida == null) ocupado = false else mandarFoto(d, { actividad.contentResolver.openInputStream(elegida)!! }, null)
+ }
+
+ /**
+ * La página solo puede proponer grabar: el micrófono se abre cuando la persona toca «Grabar» en este cartel de la app,
+ * y mientras graba lo que se ve y lo que corta también son de la app.
+ */
+ fun grabar(d: Destino) {
+ if (!tomar(d, AUDIO)) return
+ mostrar("¿Grabar un audio?", "Lo va a recibir tu PC (${d.pc.equipo}).", "Grabar", { pedirMicrofono(d) }, "Cancelar", { ocupado = false })
+ }
+
+ private fun pedirMicrofono(d: Destino) {
+ if (permitido(Manifest.permission.RECORD_AUDIO)) return empezar(d)
+ esperaMicrofono = d
+ permisoMicrofono.launch(Manifest.permission.RECORD_AUDIO)
+ }
+
+ private fun soltar() {
+ val g = grabacion ?: return
+ grabacion = null
+ g.seguir = false
+ avisar(g.destino, "mandando", AUDIO)
+ }
+
+ /** Abandona lo que se esté por grabar o grabando; lo que ya se está mandando sigue. */
+ fun cancelar() {
+ if (grabacion == null && esperaMicrofono == null && dialogo == null) return
+ cerrarDialogo()
+ esperaMicrofono = null
+ grabacion?.let {
+ it.descartada = true
+ it.seguir = false
+ }
+ grabacion = null
+ ocupado = false
+ }
+
+ /** La app dejó de verse: no se sigue escuchando de fondo. */
+ fun cortar() {
+ val d = grabacion?.destino
+ if (d == null && dialogo == null) return
+ cancelar()
+ if (d != null) fallar(d, AUDIO, "Se cortó la grabación porque saliste de la app.")
+ }
+
+ fun foto(d: Destino, deCamara: Boolean) {
+ if (!tomar(d, FOTO)) return
+ esperaFoto = d
+ if (!deCamara) lanzar(d) { galeria.launch(PickVisualMediaRequest(PickVisualMedia.ImageOnly)) }
+ else if (permitido(Manifest.permission.CAMERA)) abrirCamara(d)
+ else permisoCamara.launch(Manifest.permission.CAMERA)
+ }
+
+ fun rechazar(web: WebView, id: String, tipo: String, error: String) = entregar(web, id, "error", tipo, "error" to error)
+
+ private fun tomar(d: Destino, tipo: String): Boolean {
+ if (ocupado) {
+ avisar(d, "ocupado", tipo, "error" to "Esperá a que termine el envío anterior.")
+ return false
+ }
+ ocupado = true
+ return true
+ }
+
+ private fun mostrar(titulo: String, mensaje: String, si: String, alSi: () -> Unit, no: String, alNo: () -> Unit) {
+ dialogo = MaterialAlertDialogBuilder(actividad)
+ .setTitle(titulo)
+ .setMessage(mensaje)
+ .setCancelable(false)
+ .setPositiveButton(si) { _, _ ->
+ dialogo = null
+ alSi()
+ }
+ .setNegativeButton(no) { _, _ ->
+ dialogo = null
+ alNo()
+ }
+ .show()
+ }
+
+ private fun cerrarDialogo() {
+ dialogo?.dismiss()
+ dialogo = null
+ }
+
+ private fun permitido(permiso: String) = ContextCompat.checkSelfPermission(actividad, permiso) == PackageManager.PERMISSION_GRANTED
+
+ private fun abrirCamara(d: Destino) = lanzar(d) {
+ // De a un adjunto: lo que quede con este nombre es de una vez que la app murió con la cámara abierta.
+ actividad.cacheDir.listFiles { f -> f.name.startsWith(PREFIJO_FOTO) }?.forEach { it.delete() }
+ val archivo = File.createTempFile(PREFIJO_FOTO, ".jpg", actividad.cacheDir)
+ archivoFoto = archivo
+ camara.launch(FileProvider.getUriForFile(actividad, "${actividad.packageName}.fileprovider", archivo))
+ }
+
+ private fun lanzar(d: Destino, abrir: () -> Unit) {
+ try {
+ abrir()
+ } catch (e: ActivityNotFoundException) {
+ esperaFoto = null
+ fallar(d, FOTO, "Este teléfono no tiene una app para eso.")
+ } catch (e: IOException) {
+ Log.w(ETIQUETA, "no se pudo preparar la cámara", e)
+ esperaFoto = null
+ fallar(d, FOTO, "No pude preparar la cámara.")
+ }
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun empezar(d: Destino) {
+ val minimo = AudioRecord.getMinBufferSize(Wav.HZ, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT)
+ val micro = try {
+ AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, Wav.HZ, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, maxOf(minimo, Wav.HZ))
+ .also { it.startRecording() }
+ } catch (e: RuntimeException) {
+ Log.w(ETIQUETA, "no se pudo abrir el micrófono", e)
+ null
+ }
+ if (micro == null || micro.recordingState != AudioRecord.RECORDSTATE_RECORDING) {
+ micro?.release()
+ return fallar(d, AUDIO, "No pude usar el micrófono.")
+ }
+ val g = Grabacion(d)
+ grabacion = g
+ mostrar("Grabando…", "Va a tu PC (${d.pc.equipo}). A los 2 minutos se manda sola.", "Terminar y mandar", { soltar() }, "Descartar", { cancelar() })
+ thread {
+ val pcm = ByteArrayOutputStream()
+ val tramo = ByteArray(3200)
+ try {
+ while (g.seguir && pcm.size() < Wav.MAX_PCM) {
+ val n = micro.read(tramo, 0, minOf(tramo.size, Wav.MAX_PCM - pcm.size()))
+ if (n <= 0) break
+ pcm.write(tramo, 0, n)
+ }
+ } finally {
+ micro.release()
+ }
+ val wav = Wav.armar(pcm.toByteArray())
+ actividad.runOnUiThread {
+ // Sigue siendo la actual: paró sola, sin que nadie toque el cartel.
+ if (grabacion === g) {
+ cerrarDialogo()
+ soltar()
+ }
+ if (!g.descartada) thread { mandar(d, AUDIO, wav) }
+ }
+ }
+ }
+
+ private fun mandarFoto(d: Destino, abrir: () -> InputStream, borrar: File?) {
+ // Preparar la foto tarda unos segundos: la página tiene que mostrarlo desde ya.
+ avisar(d, "mandando", FOTO)
+ thread {
+ val jpeg = try {
+ achicar(abrir)
+ } catch (e: Exception) {
+ Log.w(ETIQUETA, "no se pudo leer la foto", e)
+ null
+ } catch (e: OutOfMemoryError) {
+ Log.w(ETIQUETA, "la foto no entra en memoria", e)
+ null
+ } finally {
+ borrar?.delete()
+ }
+ if (jpeg == null) fallar(d, FOTO, "No pude preparar esa foto.") else mandar(d, FOTO, jpeg)
+ }
+ }
+
+ /** Un JPEG derecho y de lado máximo 2048. Al recomprimirlo no viajan los metadatos (dónde y con qué se sacó). */
+ private fun achicar(abrir: () -> InputStream): ByteArray? {
+ val medida = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ abrir().use { BitmapFactory.decodeStream(it, null, medida) }
+ var muestra = 1
+ while (maxOf(medida.outWidth, medida.outHeight) / (muestra * 2) >= LADO) muestra *= 2
+ val leida = abrir().use { BitmapFactory.decodeStream(it, null, BitmapFactory.Options().apply { inSampleSize = muestra }) } ?: return null
+ val orientacion = abrir().use { ExifInterface(it).getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) }
+ val escala = minOf(1f, LADO.toFloat() / maxOf(leida.width, leida.height))
+ val m = Matrix().apply { setScale(escala, escala) }
+ when (orientacion) {
+ ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> m.postScale(-1f, 1f)
+ ExifInterface.ORIENTATION_ROTATE_180 -> m.postRotate(180f)
+ ExifInterface.ORIENTATION_FLIP_VERTICAL -> m.postScale(1f, -1f)
+ ExifInterface.ORIENTATION_TRANSPOSE -> { m.postRotate(90f); m.postScale(-1f, 1f) }
+ ExifInterface.ORIENTATION_ROTATE_90 -> m.postRotate(90f)
+ ExifInterface.ORIENTATION_TRANSVERSE -> { m.postRotate(270f); m.postScale(-1f, 1f) }
+ ExifInterface.ORIENTATION_ROTATE_270 -> m.postRotate(270f)
+ }
+ val derecha = Bitmap.createBitmap(leida, 0, 0, leida.width, leida.height, m, true)
+ for (calidad in 85 downTo 25 step 15) {
+ val salida = ByteArrayOutputStream()
+ if (derecha.compress(Bitmap.CompressFormat.JPEG, calidad, salida) && salida.size() <= MAX_FOTO) return salida.toByteArray()
+ }
+ return null
+ }
+
+ private fun mandar(d: Destino, tipo: String, bytes: ByteArray) {
+ val r = try {
+ d.pc.subir(d.id, tipo, bytes)
+ } catch (e: Exception) {
+ Log.w(ETIQUETA, "no se pudo subir", e)
+ null
+ }
+ val campo = if (tipo == AUDIO) "texto" else "ruta"
+ val valor = if (r?.codigo == 200) r.cuerpo?.optString(campo) else null
+ if (r?.codigo == 401) actividad.runOnUiThread { llave.olvidar() }
+ if (valor.isNullOrEmpty()) fallar(d, tipo, motivo(r)) else terminar(d, "listo", tipo, campo to valor)
+ }
+
+ private fun motivo(r: Pc.Respuesta?): String {
+ if (r == null) return "No pude hablar con la PC."
+ return when (val error = r.cuerpo?.optString("error").orEmpty()) {
+ "reloj" -> "La hora del celu y la de la PC no coinciden."
+ "repetido" -> "La PC ya había recibido ese envío."
+ "" -> when (r.codigo) {
+ 401 -> "Este celu ya no tiene acceso."
+ 413 -> "La PC no lo recibe: revisá que la terminal desde el celu siga prendida."
+ 429 -> "La PC está ocupada con otros adjuntos: probá en un momento."
+ else -> "La PC no pudo recibirlo."
+ }
+ else -> error
+ }
+ }
+
+ private fun fallar(d: Destino, tipo: String, error: String) = terminar(d, "error", tipo, "error" to error)
+
+ private fun terminar(d: Destino, estado: String, tipo: String, dato: Pair) {
+ actividad.runOnUiThread { ocupado = false }
+ avisar(d, estado, tipo, dato)
+ }
+
+ /** Solo si el WebView sigue en la PC que lo pidió: el texto y la ruta no le tocan a otra página. */
+ private fun avisar(d: Destino, estado: String, tipo: String, dato: Pair? = null) {
+ actividad.runOnUiThread {
+ val url = Uri.parse(d.web.url ?: return@runOnUiThread)
+ if ("${url.scheme}://${url.encodedAuthority}" != d.pc.base) return@runOnUiThread
+ entregar(d.web, d.id, estado, tipo, dato)
+ }
+ }
+
+ private fun entregar(web: WebView, id: String, estado: String, tipo: String, dato: Pair?) {
+ val json = JSONObject().put("id", id).put("estado", estado).put("tipo", tipo)
+ dato?.let { json.put(it.first, it.second) }
+ web.evaluateJavascript("window.slothAdjunto && window.slothAdjunto($json)", null)
+ }
+
+ companion object {
+ const val AUDIO = "audio"
+ const val FOTO = "foto"
+ private const val ETIQUETA = "Adjuntos"
+ private const val PREFIJO_FOTO = "foto-para-la-pc"
+ private const val LADO = 2048
+ private const val MAX_FOTO = 4 * 1024 * 1024
+ }
+}
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/MainActivity.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/MainActivity.kt
index a923a2a8..dd73043e 100644
--- a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/MainActivity.kt
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/MainActivity.kt
@@ -10,7 +10,12 @@ import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : TauriActivity() {
+ lateinit var adjuntos: Adjuntos
+ private set
+
override fun onCreate(savedInstanceState: Bundle?) {
+ // Antes de `super`: ahí ya puede nacer el WebView con su puente.
+ adjuntos = Adjuntos(this)
val barras = SystemBarStyle.dark(Color.TRANSPARENT)
enableEdgeToEdge(statusBarStyle = barras, navigationBarStyle = barras)
super.onCreate(savedInstanceState)
@@ -27,6 +32,11 @@ class MainActivity : TauriActivity() {
VigiaService.revivir(this)
}
+ override fun onStop() {
+ adjuntos.cortar()
+ super.onStop()
+ }
+
// La página que sirve la PC reconoce la app por esta marca y le ofrece volver a escanear.
override fun onWebViewCreate(webView: WebView) {
super.onWebViewCreate(webView)
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Pc.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Pc.kt
index 35096063..83772205 100644
--- a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Pc.kt
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Pc.kt
@@ -4,21 +4,19 @@ import android.content.Context
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
+import java.nio.ByteBuffer
/** La PC a la que se le pregunta y la clave de este celu. Queda en los datos privados de la app. */
class Pc(val base: String, private val sello: Sello) {
class Respuesta(val codigo: Int, val cuerpo: JSONObject?)
+ /** Host y puerto, para mostrar. */
+ val equipo get() = base.substringAfter("://")
+
fun pedir(ruta: String, objeto: JSONObject): Respuesta {
val pedido = sello.sellar(ruta, JSONObject().put("t", System.currentTimeMillis()).put("b", objeto).toString())
- val c = URL(base + ruta).openConnection() as HttpURLConnection
+ val c = conectar(ruta, "text/plain", 10000)
try {
- c.requestMethod = "POST"
- c.connectTimeout = 5000
- c.readTimeout = 10000
- c.instanceFollowRedirects = false
- c.doOutput = true
- c.setRequestProperty("content-type", "text/plain")
c.outputStream.use { it.write(pedido.sobre.toByteArray()) }
val codigo = c.responseCode
if (codigo != 200) return Respuesta(codigo, null)
@@ -30,6 +28,38 @@ class Pc(val base: String, private val sello: Sello) {
}
}
+ /** Un audio o una foto para la terminal `id`. Si la PC dice que no, el motivo viene sellado en el cuerpo. */
+ fun subir(id: String, tipo: String, bytes: ByteArray): Respuesta {
+ val pedido = sello.sellarBytes(SUBIR, claro(System.currentTimeMillis(), id, tipo, bytes))
+ // La PC decide con esto, antes de leer el cuerpo, si le guarda lugar.
+ val permiso = sello.sellar(PERMISO, permiso(System.currentTimeMillis(), pedido.sobre.size))
+ // La PC contesta un audio recién cuando terminó de transcribirlo, y lo corta a los 270 s.
+ val c = conectar(SUBIR, "application/octet-stream", 300000)
+ try {
+ c.setRequestProperty("x-sloth-permiso", permiso.sobre)
+ c.setFixedLengthStreamingMode(pedido.sobre.size)
+ c.outputStream.use { it.write(pedido.sobre) }
+ val codigo = c.responseCode
+ if (codigo != 200 && codigo !in CON_MOTIVO) return Respuesta(codigo, null)
+ val cuerpo = if (codigo == 200) c.inputStream else c.errorStream
+ val texto = cuerpo?.use { it.readNBytesCompat(MAX_RESPUESTA) }
+ // Si la PC no llegó a leer el cuerpo, contesta atado al iv del permiso.
+ val plano = texto?.let { sello.abrir(pedido.iv, it) ?: sello.abrir(permiso.iv, it) }
+ return if (plano != null) Respuesta(codigo, JSONObject(plano)) else Respuesta(if (codigo == 200) 0 else codigo, null)
+ } finally {
+ c.disconnect()
+ }
+ }
+
+ private fun conectar(ruta: String, tipo: String, esperaMs: Int) = (URL(base + ruta).openConnection() as HttpURLConnection).apply {
+ requestMethod = "POST"
+ connectTimeout = 5000
+ readTimeout = esperaMs
+ instanceFollowRedirects = false
+ doOutput = true
+ setRequestProperty("content-type", tipo)
+ }
+
private fun java.io.InputStream.readNBytesCompat(max: Int): String {
val salida = java.io.ByteArrayOutputStream()
val tramo = ByteArray(8192)
@@ -43,9 +73,20 @@ class Pc(val base: String, private val sello: Sello) {
companion object {
private const val MAX_RESPUESTA = 262144
+ private const val SUBIR = "/api/subir"
+ private const val PERMISO = "/api/subir/permiso"
+ private val CON_MOTIVO = setOf(400, 403, 404, 409, 413, 429)
private const val PREFS = "vigia"
private val PRIVADA = Regex("(10\\.\\d+|192\\.168|172\\.(1[6-9]|2\\d|3[01])|100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7]))\\.\\d+\\.\\d+")
+ fun permiso(t: Long, largo: Int) = JSONObject().put("t", t).put("largo", largo).toString()
+
+ /** Lo que se sella al subir, como lo lee `adjuntos.rs`: largo de la cabecera, cabecera y bytes. */
+ fun claro(t: Long, id: String, tipo: String, bytes: ByteArray): ByteArray {
+ val cabecera = JSONObject().put("t", t).put("b", JSONObject().put("id", id).put("tipo", tipo)).toString().toByteArray(Charsets.UTF_8)
+ return ByteBuffer.allocate(4 + cabecera.size + bytes.size).putInt(cabecera.size).put(cabecera).put(bytes).array()
+ }
+
/** Solo una PC de la red de casa o de Tailscale, las mismas direcciones que acepta `enlace.rs`. */
fun aceptable(esquema: String?, host: String?) =
host != null && ((esquema == "http" && PRIVADA.matches(host)) || (esquema == "https" && host.endsWith(".ts.net")))
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Puente.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Puente.kt
index 24c60862..0dbd77c8 100644
--- a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Puente.kt
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Puente.kt
@@ -8,8 +8,9 @@ import android.webkit.WebView
import androidx.core.app.ActivityCompat
/**
- * Lo único que la página puede pedirle a Android: que avise con la app cerrada. La dirección no la elige la página,
- * sale de la que está abierta; así solo puede anotarse a sí misma.
+ * Lo único que la página puede pedirle a Android: que avise con la app cerrada y que le mande a la PC un audio o una
+ * foto. Para los avisos la dirección sale de la página abierta, así solo puede anotarse a sí misma. Los adjuntos van
+ * solamente a la PC vinculada por la app, y solo si la página abierta es esa.
*/
class Puente(private val actividad: MainActivity, private val web: WebView) {
@JavascriptInterface
@@ -39,4 +40,40 @@ class Puente(private val actividad: MainActivity, private val web: WebView) {
@JavascriptInterface
fun apagar() = VigiaService.apagar(actividad)
+
+ /** La clave de este celu, para los adjuntos. Solo la anota la página de la PC vinculada. */
+ @JavascriptInterface
+ fun anotar(clave: String) = actividad.runOnUiThread { vinculadaAbierta()?.let { actividad.adjuntos.llave.anotar(it, clave) } }
+
+ @JavascriptInterface
+ fun grabar(id: String) = conDestino(id, Adjuntos.AUDIO) { actividad.adjuntos.grabar(it) }
+
+ @JavascriptInterface
+ fun cancelar() = actividad.runOnUiThread { actividad.adjuntos.cancelar() }
+
+ @JavascriptInterface
+ fun foto(id: String, origen: String) {
+ if (origen != "camara" && origen != "galeria") return
+ conDestino(id, Adjuntos.FOTO) { actividad.adjuntos.foto(it, origen == "camara") }
+ }
+
+ private fun vinculadaAbierta(): String? {
+ val url = Uri.parse(web.url ?: return null)
+ return Vinculo.leer(actividad)?.takeIf { it == "${url.scheme}://${url.encodedAuthority}" }
+ }
+
+ private fun conDestino(id: String, tipo: String, seguir: (Adjuntos.Destino) -> Unit) {
+ if (!ID.matches(id)) return
+ actividad.runOnUiThread {
+ val base = vinculadaAbierta()
+ ?: return@runOnUiThread actividad.adjuntos.rechazar(web, id, tipo, "Esta página no es la de la PC vinculada: volvé a escanear el QR.")
+ val sello = actividad.adjuntos.llave.para(base)
+ ?: return@runOnUiThread actividad.adjuntos.rechazar(web, id, tipo, "Falta la clave de este celu: recargá la página.")
+ seguir(Adjuntos.Destino(web, Pc(base, sello), id))
+ }
+ }
+
+ private companion object {
+ val ID = Regex("[A-Za-z0-9_-]{1,80}")
+ }
}
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Sello.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Sello.kt
index 46c29725..b005c6fe 100644
--- a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Sello.kt
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Sello.kt
@@ -11,11 +11,16 @@ import javax.crypto.spec.SecretKeySpec
/** El mismo sello que `sello.rs` y `sello.js`: AES-256-CTR más HMAC-SHA256, `iv || cifrado || tag` en base64url. */
class Sello private constructor(private val enc: ByteArray, private val mac: ByteArray) {
class Pedido(val sobre: String, val iv: ByteArray)
+ class Binario(val sobre: ByteArray, val iv: ByteArray)
- fun sellar(ruta: String, json: String, iv: ByteArray = ivAleatorio()): Pedido {
- val cifrado = ctr(iv, json.toByteArray(Charsets.UTF_8))
+ fun sellar(ruta: String, json: String, iv: ByteArray = ivAleatorio()) =
+ Pedido(Base64.getUrlEncoder().withoutPadding().encodeToString(sellarBytes(ruta, json.toByteArray(Charsets.UTF_8), iv).sobre), iv)
+
+ /** El mismo sobre sin base64, para lo que sube: audios y fotos. */
+ fun sellarBytes(ruta: String, claro: ByteArray, iv: ByteArray = ivAleatorio()): Binario {
+ val cifrado = ctr(iv, claro)
val tag = hmac(mac, "q$ruta\u0000".toByteArray(Charsets.UTF_8), iv, cifrado)
- return Pedido(Base64.getUrlEncoder().withoutPadding().encodeToString(iv + cifrado + tag), iv)
+ return Binario(iv + cifrado + tag, iv)
}
/** La respuesta ata el iv del pedido: una respuesta vieja repetida no se abre. */
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Vinculo.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Vinculo.kt
new file mode 100644
index 00000000..2c8e5b0f
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Vinculo.kt
@@ -0,0 +1,55 @@
+package com.toomasmg.sloth.celu
+
+import android.content.Context
+import android.util.Log
+import org.json.JSONException
+import org.json.JSONObject
+import java.io.File
+import java.io.IOException
+import java.net.URI
+import java.net.URISyntaxException
+
+/** La PC que la persona vinculó en la pantalla propia de la app (`pc.json`, de `guardado.rs`): una página no la cambia. */
+object Vinculo {
+ fun leer(c: Context): String? {
+ val archivo = File(c.applicationInfo.dataDir, "pc.json")
+ if (!archivo.isFile) return null
+ return try {
+ base(archivo.readText())
+ } catch (e: IOException) {
+ Log.w("Vinculo", "no se pudo leer la PC vinculada", e)
+ null
+ }
+ }
+
+ fun base(guardado: String): String? = try {
+ val v = JSONObject(guardado)
+ val url = URI(v.getString("enlace"))
+ if (v.optInt("version", 1) == 1 && Pc.aceptable(url.scheme, url.host)) "${url.scheme}://${url.rawAuthority}" else null
+ } catch (e: JSONException) {
+ null
+ } catch (e: URISyntaxException) {
+ null
+ }
+}
+
+/**
+ * La clave de este celu en la PC vinculada, solo en memoria. La primera que se anota queda: otra entra recién si la PC
+ * rechazó esa o si se vinculó otra PC.
+ */
+class Llave {
+ private var de: String? = null
+ private var sello: Sello? = null
+
+ fun anotar(base: String, clave: String) {
+ if (para(base) != null) return
+ sello = Sello.de(clave) ?: return
+ de = base
+ }
+
+ fun para(base: String): Sello? = sello.takeIf { de == base }
+
+ fun olvidar() {
+ sello = null
+ }
+}
diff --git a/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Wav.kt b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Wav.kt
new file mode 100644
index 00000000..4f2024ca
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/main/java/com/toomasmg/sloth/celu/Wav.kt
@@ -0,0 +1,19 @@
+package com.toomasmg.sloth.celu
+
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/** El único WAV que acepta la PC (`adjuntos::audio_valido`): PCM de 16 bits, mono, 16 kHz y hasta 120 s. */
+object Wav {
+ const val HZ = 16000
+ const val MAX_PCM = HZ * 2 * 120
+ private const val CABECERA = 44
+
+ fun armar(pcm: ByteArray): ByteArray {
+ val b = ByteBuffer.allocate(CABECERA + pcm.size).order(ByteOrder.LITTLE_ENDIAN)
+ b.put("RIFF".toByteArray()).putInt(CABECERA - 8 + pcm.size).put("WAVEfmt ".toByteArray())
+ b.putInt(16).putShort(1).putShort(1).putInt(HZ).putInt(HZ * 2).putShort(2).putShort(16)
+ b.put("data".toByteArray()).putInt(pcm.size).put(pcm)
+ return b.array()
+ }
+}
diff --git a/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/SubidaTest.kt b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/SubidaTest.kt
new file mode 100644
index 00000000..87315b3a
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/SubidaTest.kt
@@ -0,0 +1,49 @@
+package com.toomasmg.sloth.celu
+
+import org.json.JSONObject
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Test
+import java.nio.ByteBuffer
+
+class SubidaTest {
+ private val sello = Sello.de("BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc")!!
+ private val iv = ByteArray(16) { it.toByte() }
+ private val foto = byteArrayOf(-1, -40, -1, 0, -1, -39)
+
+ private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
+
+ private fun claro(cabecera: String) = ByteBuffer.allocate(4 + cabecera.length + foto.size).putInt(cabecera.length).put(cabecera.toByteArray()).put(foto).array()
+
+ // El mismo vector que prueba `sello.rs`.
+ @Test
+ fun sella_los_bytes_igual_que_la_pc() {
+ val claro = claro("""{"t":1700000000000,"b":{"id":"w1","tipo":"foto"}}""")
+ val sobre = sello.sellarBytes("/api/subir", claro, iv).sobre
+ assertEquals(
+ "000102030405060708090a0b0c0d0e0f8b248e21a1af690f2623ab677ccc56a2f3efdb0e817541e8e2d988ff19a64078002d5ef0c95c11029689ddf22c77e4fb6cc9a1d22565b556e00ff587c8270a25fd747dd8ad5769ee505e88a73614f0c2f16935193f8be7863e8472",
+ hex(sobre)
+ )
+ val otraRuta = sello.sellarBytes("/api/terminal", claro, iv).sobre
+ assertFalse(sobre.contentEquals(otraRuta))
+ }
+
+ @Test
+ fun el_permiso_dice_cuando_y_cuanto() {
+ val json = JSONObject(Pc.permiso(5, 123))
+ assertEquals(5, json.getLong("t"))
+ assertEquals(123, json.getInt("largo"))
+ }
+
+ @Test
+ fun lo_que_sube_lleva_el_largo_la_cabecera_y_los_bytes() {
+ val b = ByteBuffer.wrap(Pc.claro(5, "w1", "foto", foto))
+ val cabecera = ByteArray(b.int).also { b.get(it) }
+ val json = JSONObject(String(cabecera))
+ assertEquals(5, json.getLong("t"))
+ assertEquals("w1", json.getJSONObject("b").getString("id"))
+ assertEquals("foto", json.getJSONObject("b").getString("tipo"))
+ assertArrayEquals(foto, ByteArray(b.remaining()).also { b.get(it) })
+ }
+}
diff --git a/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/VinculoTest.kt b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/VinculoTest.kt
new file mode 100644
index 00000000..a3a5fc20
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/VinculoTest.kt
@@ -0,0 +1,36 @@
+package com.toomasmg.sloth.celu
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertSame
+import org.junit.Test
+
+class VinculoTest {
+ private val clave = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc"
+ private val otra = "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwM"
+
+ private fun guardado(enlace: String, version: Int = 1) = """{"version":$version,"enlace":"$enlace"}"""
+
+ @Test
+ fun la_direccion_sale_de_la_pc_vinculada() {
+ assertEquals("http://192.168.1.20:47321", Vinculo.base(guardado("http://192.168.1.20:47321/#k=$clave")))
+ assertEquals("https://mi-pc.cola.ts.net", Vinculo.base(guardado("https://mi-pc.cola.ts.net/#k=$clave")))
+ assertNull(Vinculo.base(guardado("https://toomasmg.github.io/sloth/celu/#p=abc")))
+ assertNull(Vinculo.base(guardado("http://192.168.1.20:47321/#k=$clave", 2)))
+ assertNull(Vinculo.base("roto"))
+ }
+
+ @Test
+ fun la_primera_clave_queda_hasta_que_la_pc_la_rechaza_o_cambia_la_pc() {
+ val llave = Llave()
+ llave.anotar("http://10.0.0.1:1", clave)
+ val primera = llave.para("http://10.0.0.1:1")
+ llave.anotar("http://10.0.0.1:1", otra)
+ assertSame(primera, llave.para("http://10.0.0.1:1"))
+ assertNull(llave.para("http://10.0.0.2:1"))
+ llave.olvidar()
+ assertNull(llave.para("http://10.0.0.1:1"))
+ llave.anotar("http://10.0.0.2:1", otra)
+ assertNull(llave.para("http://10.0.0.1:1"))
+ }
+}
diff --git a/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/WavTest.kt b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/WavTest.kt
new file mode 100644
index 00000000..8e9aa1a7
--- /dev/null
+++ b/movil/src-tauri/gen/android/app/src/test/java/com/toomasmg/sloth/celu/WavTest.kt
@@ -0,0 +1,29 @@
+package com.toomasmg.sloth.celu
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+class WavTest {
+ // Las reglas de `adjuntos::audio_valido`, campo por campo.
+ @Test
+ fun la_cabecera_es_la_que_acepta_la_pc() {
+ val pcm = ByteArray(3200) { it.toByte() }
+ val wav = Wav.armar(pcm)
+ val b = ByteBuffer.wrap(wav).order(ByteOrder.LITTLE_ENDIAN)
+ fun texto(en: Int, largo: Int) = String(wav, en, largo)
+ assertEquals(44 + pcm.size, wav.size)
+ assertEquals("RIFF", texto(0, 4))
+ assertEquals(wav.size - 8, b.getInt(4))
+ assertEquals("WAVEfmt ", texto(8, 8))
+ assertEquals(16, b.getInt(16))
+ assertEquals(listOf(1, 1), listOf(b.getShort(20), b.getShort(22)))
+ assertEquals(listOf(16000, 32000), listOf(b.getInt(24), b.getInt(28)))
+ assertEquals(listOf(2, 16), listOf(b.getShort(32), b.getShort(34)))
+ assertEquals("data", texto(36, 4))
+ assertEquals(pcm.size, b.getInt(40))
+ assertArrayEquals(pcm, wav.copyOfRange(44, wav.size))
+ }
+}
diff --git a/native/core/src/features/celular/adjuntos.rs b/native/core/src/features/celular/adjuntos.rs
new file mode 100644
index 00000000..1a0dfa35
--- /dev/null
+++ b/native/core/src/features/celular/adjuntos.rs
@@ -0,0 +1,259 @@
+//! Lo que el celu manda por `/api/subir`: un audio para dictar o una foto. Son datos de afuera que llegan a disco y a una
+//! terminal, así que acá se lee y se valida todo, y ningún nombre, ruta ni extensión viaja desde el celu.
+//!
+//! En claro: `u32 BE largo de la cabecera || cabecera JSON {"t":ms,"b":{"id":"","tipo":"audio"|"foto"}} || bytes`.
+use super::cortar_utf16;
+use super::terminal_core::{id_valido, MAX_ESCRIBIR};
+use crate::features::permissions::es_invisible;
+use crate::persistencia::escribir_atomico_si;
+use serde_json::Value;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::time::UNIX_EPOCH;
+
+pub const MAX_FOTO: usize = 4 * 1024 * 1024;
+/// 120 s, 16 kHz mono de 16 bits.
+pub const MAX_AUDIO: usize = 44 + 16_000 * 2 * 120;
+/// La foto más grande con su cabecera.
+pub const MAX_SUBIDA: usize = MAX_FOTO + 1024;
+/// Lo dictado termina en el cuadro del celu, que se manda como cualquier escritura.
+pub const MAX_TEXTO_DICTADO: usize = MAX_ESCRIBIR;
+
+const MAX_CABECERA_SUBIDA: usize = 512;
+const GUARDADA_MS: i64 = 7 * 24 * 3600_000;
+const MAX_GUARDADAS: usize = 50;
+const MAX_BYTES_GUARDADOS: u64 = 100 * 1024 * 1024;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TipoAdjunto {
+ Audio,
+ Foto,
+}
+
+#[derive(Debug)]
+pub struct Subida<'a> {
+ pub id: String,
+ pub tipo: TipoAdjunto,
+ pub t: Value,
+ pub bytes: &'a [u8],
+}
+
+pub fn leer_subida(claro: &[u8]) -> Option> {
+ let largo = u32::from_be_bytes(claro.get(..4)?.try_into().ok()?) as usize;
+ if !(2..=MAX_CABECERA_SUBIDA).contains(&largo) {
+ return None;
+ }
+ let cabecera: Value = serde_json::from_slice(claro.get(4..4 + largo)?).ok()?;
+ let b = cabecera.get("b")?;
+ let id = b.get("id")?.as_str().filter(|i| id_valido(i, 1, 80))?;
+ let tipo = match b.get("tipo")?.as_str()? {
+ "audio" => TipoAdjunto::Audio,
+ "foto" => TipoAdjunto::Foto,
+ _ => return None,
+ };
+ Some(Subida { id: id.to_string(), tipo, t: cabecera.get("t").cloned().unwrap_or(Value::Null), bytes: &claro[4 + largo..] })
+}
+
+/// Un JPEG entero: la app recomprime todo a JPEG, así que no se acepta otro formato.
+pub fn foto_valida(b: &[u8]) -> bool {
+ b.len() <= MAX_FOTO && b.starts_with(&[0xFF, 0xD8, 0xFF]) && b.ends_with(&[0xFF, 0xD9])
+}
+
+/// El WAV exacto que arma la app (cabecera de 44 bytes, PCM de 16 bits, 16 kHz, mono): cualquier otra forma no llega a whisper.
+pub fn audio_valido(b: &[u8]) -> bool {
+ if !(44..=MAX_AUDIO).contains(&b.len()) {
+ return false;
+ }
+ let largo = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]) as usize;
+ let corto = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
+ &b[..4] == b"RIFF"
+ && largo(4) == b.len() - 8
+ && &b[8..16] == b"WAVEfmt "
+ && largo(16) == 16
+ && (corto(20), corto(22)) == (1, 1)
+ && (largo(24), largo(28)) == (16_000, 32_000)
+ && (corto(32), corto(34)) == (2, 16)
+ && &b[36..40] == b"data"
+ && largo(40) == b.len() - 44
+}
+
+/// Lo transcripto va al cuadro del celu y de ahí a una terminal: sin controles (un CR mandaría el mensaje, un ESC abre
+/// secuencias) ni caracteres invisibles que hagan ver otra cosa.
+pub fn limpiar_dictado(t: &str) -> String {
+ let visible: String = t.chars().filter_map(|c| if c.is_control() || c.is_whitespace() { Some(' ') } else { (!es_invisible(c)).then_some(c) }).collect();
+ let junto = visible.split_whitespace().collect::>().join(" ");
+ cortar_utf16(&junto, MAX_TEXTO_DICTADO).trim_end().to_string()
+}
+
+/// Qué fotos guardadas `(ruta, bytes, mtime ms)` borrar: las de más de 7 días y, de las que quedan, las más viejas hasta
+/// entrar en la cantidad y el peso.
+pub fn sobrantes(archivos: &[(PathBuf, u64, i64)], ahora: i64) -> Vec {
+ let mut orden: Vec<&(PathBuf, u64, i64)> = archivos.iter().collect();
+ orden.sort_by_key(|a| a.2);
+ let mut quedan = orden.len();
+ let mut peso: u64 = orden.iter().map(|a| a.1).sum();
+ orden
+ .into_iter()
+ .take_while(|(_, bytes, mtime)| {
+ let sobra = ahora - mtime > GUARDADA_MS || quedan > MAX_GUARDADAS || peso > MAX_BYTES_GUARDADOS;
+ if sobra {
+ quedan -= 1;
+ peso -= bytes;
+ }
+ sobra
+ })
+ .map(|a| a.0.clone())
+ .collect()
+}
+
+pub fn guardar_foto(dir: &Path, nombre: &str, bytes: &[u8]) -> std::io::Result {
+ let destino = dir.join(nombre);
+ escribir_atomico_si(&destino, bytes, || Ok(true))?;
+ limpiar_carpeta(dir, &destino);
+ Ok(destino)
+}
+
+/// Solo archivos propios de la carpeta. Lo que no se pueda leer o borrar ahora se reintenta con la próxima foto: la de
+/// recién ya quedó guardada.
+fn limpiar_carpeta(dir: &Path, recien: &Path) {
+ let Ok(entradas) = fs::read_dir(dir) else { return };
+ let archivos: Vec<(PathBuf, u64, i64)> = entradas
+ .filter_map(Result::ok)
+ .filter_map(|e| {
+ let ruta = e.path();
+ let datos = e.metadata().ok().filter(|d| d.is_file())?;
+ if !ruta.extension().is_some_and(|x| x == "jpg" || x == "tmp") {
+ return None;
+ }
+ let mtime = datos.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_millis() as i64;
+ Some((ruta, datos.len(), mtime))
+ })
+ .collect();
+ for viejo in sobrantes(&archivos, super::ahora_ms()).iter().filter(|r| *r != recien) {
+ let _ = fs::remove_file(viejo);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::features::celular::pruebas::carpeta_temporal;
+ use crate::features::dictado_core::encode_wav;
+ use serde_json::json;
+ use std::time::{Duration, SystemTime};
+
+ fn claro(cabecera: &str, bytes: &[u8]) -> Vec {
+ [&(cabecera.len() as u32).to_be_bytes()[..], cabecera.as_bytes(), bytes].concat()
+ }
+
+ fn cabecera(id: &str, tipo: &str) -> String {
+ json!({ "t": 5, "b": { "id": id, "tipo": tipo, "nombre": "../x.exe" } }).to_string()
+ }
+
+ fn wav(muestras: usize, frecuencia: u32) -> Vec {
+ encode_wav(&vec![0.1; muestras], frecuencia)
+ }
+
+ fn con(mut b: Vec, en: usize, valor: &[u8]) -> Vec {
+ b[en..en + valor.len()].copy_from_slice(valor);
+ b
+ }
+
+ #[test]
+ fn lee_la_cabecera_y_deja_los_bytes_sin_mirar_los_campos_de_mas() {
+ let c = claro(&cabecera("w1", "foto"), b"datos");
+ let s = leer_subida(&c).unwrap();
+ assert_eq!((s.id.as_str(), s.tipo, s.t.clone(), s.bytes), ("w1", TipoAdjunto::Foto, json!(5), &b"datos"[..]));
+ assert_eq!(leer_subida(&claro(&cabecera("w1", "audio"), b"")).unwrap().tipo, TipoAdjunto::Audio);
+ }
+
+ #[test]
+ fn una_cabecera_con_largo_imposible_tipo_desconocido_o_id_con_barras_no_se_lee() {
+ let buena = cabecera("w1", "foto");
+ let con_largo = |n: u32| [&n.to_be_bytes()[..], buena.as_bytes()].concat();
+ for n in [0, 1, 513, buena.len() as u32 + 1, u32::MAX] {
+ assert!(leer_subida(&con_largo(n)).is_none(), "largo {n}");
+ }
+ let larga = format!("{}{}", buena, " ".repeat(513 - buena.len()));
+ assert!(leer_subida(&claro(&larga, b"x")).is_none());
+ assert!(leer_subida(&[0, 0]).is_none());
+ for (id, tipo) in [("w1", "video"), ("../w1", "foto"), ("a/b", "foto"), ("", "foto"), (&"x".repeat(81), "foto")] {
+ assert!(leer_subida(&claro(&cabecera(id, tipo), b"x")).is_none(), "{id} {tipo}");
+ }
+ for mala in ["[]", "{}", "{\"b\":1}", "no es json"] {
+ assert!(leer_subida(&claro(mala, b"x")).is_none(), "{mala}");
+ }
+ }
+
+ #[test]
+ fn solo_vale_un_jpeg_entero_y_chico() {
+ assert!(foto_valida(&[0xFF, 0xD8, 0xFF, 0xE0, 1, 0xFF, 0xD9]));
+ assert!(!foto_valida(b"\x89PNG\r\n\x1a\n\xFF\xD9"));
+ assert!(!foto_valida(&[0xFF, 0xD8, 0xFF, 0xE0, 1, 2]), "truncada");
+ assert!(!foto_valida(&[]));
+ let mut justa = vec![0u8; MAX_FOTO];
+ justa[..3].copy_from_slice(&[0xFF, 0xD8, 0xFF]);
+ justa[MAX_FOTO - 2..].copy_from_slice(&[0xFF, 0xD9]);
+ assert!(foto_valida(&justa));
+ justa.insert(3, 0);
+ assert!(!foto_valida(&justa), "enorme");
+ }
+
+ #[test]
+ fn solo_vale_el_wav_de_16_khz_mono_con_largos_que_cierran() {
+ assert!(audio_valido(&wav(16_000, 16_000)));
+ assert!(audio_valido(&wav(0, 16_000)));
+ assert!(audio_valido(&wav(16_000 * 120, 16_000)));
+ assert!(!audio_valido(&wav(16_000 * 120 + 1, 16_000)), "más de 120 s");
+ assert!(!audio_valido(&wav(44_100, 44_100)));
+ assert!(!audio_valido(&con(wav(100, 16_000), 22, &2u16.to_le_bytes())), "estéreo");
+ assert!(!audio_valido(&con(wav(100, 16_000), 20, &3u16.to_le_bytes())), "float");
+ assert!(!audio_valido(&con(wav(100, 16_000), 34, &8u16.to_le_bytes())));
+ assert!(!audio_valido(&con(wav(100, 16_000), 40, &9999u32.to_le_bytes())), "data mentiroso");
+ assert!(!audio_valido(&con(wav(100, 16_000), 4, &9999u32.to_le_bytes())));
+ assert!(!audio_valido(&con(wav(100, 16_000), 36, b"LIST")));
+ assert!(!audio_valido(&wav(100, 16_000)[..43]));
+ }
+
+ #[test]
+ fn el_dictado_sale_sin_secuencias_saltos_ni_invisibles_y_cortado_sin_partir_caracteres() {
+ assert_eq!(limpiar_dictado("hola\u{1b}[200~rm -rf\r\n\tya\u{202E}fue\u{200B}!\u{2028}fin "), "hola [200~rm -rf yafue! fin");
+ assert_eq!(limpiar_dictado(" \r\n\u{FEFF} "), "");
+ let justo = format!("{}😀", "a".repeat(MAX_TEXTO_DICTADO - 2));
+ assert_eq!(limpiar_dictado(&justo), justo);
+ assert_eq!(limpiar_dictado(&format!("{}😀", "a".repeat(MAX_TEXTO_DICTADO - 1))), "a".repeat(MAX_TEXTO_DICTADO - 1));
+ }
+
+ fn archivo(n: usize, bytes: u64, mtime: i64) -> (PathBuf, u64, i64) {
+ (PathBuf::from(format!("{n}.jpg")), bytes, mtime)
+ }
+
+ #[test]
+ fn sobran_las_vencidas_y_las_mas_viejas_que_pasan_la_cantidad_o_el_peso() {
+ let ahora = 100 * GUARDADA_MS;
+ let por_edad = [archivo(1, 1, ahora - GUARDADA_MS - 1), archivo(2, 1, ahora - GUARDADA_MS)];
+ assert_eq!(sobrantes(&por_edad, ahora), [PathBuf::from("1.jpg")]);
+ let muchas: Vec<_> = (0..MAX_GUARDADAS + 2).rev().map(|n| archivo(n, 1, ahora - 1000 + n as i64)).collect();
+ assert_eq!(sobrantes(&muchas, ahora), [PathBuf::from("0.jpg"), PathBuf::from("1.jpg")]);
+ let pesadas: Vec<_> = (0..4).map(|n| archivo(n, MAX_BYTES_GUARDADOS / 3, ahora - 10 + n as i64)).collect();
+ assert_eq!(sobrantes(&pesadas, ahora), [PathBuf::from("0.jpg")]);
+ assert!(sobrantes(&muchas[2..], ahora).is_empty());
+ }
+
+ #[test]
+ fn guardar_crea_la_carpeta_y_limpia_solo_lo_propio() {
+ let dir = carpeta_temporal("adjuntos").join("celu-adjuntos");
+ fs::create_dir_all(dir.join("vieja.jpg")).unwrap();
+ let hace_mucho = SystemTime::now() - Duration::from_millis(GUARDADA_MS as u64 + 60_000);
+ for n in ["a.jpg", "b.tmp", "notas.txt"] {
+ fs::write(dir.join(n), b"x").unwrap();
+ fs::File::options().write(true).open(dir.join(n)).unwrap().set_modified(hace_mucho).unwrap();
+ }
+ let ruta = guardar_foto(&dir, "nueva.jpg", b"foto").unwrap();
+ assert_eq!(fs::read(&ruta).unwrap(), b"foto");
+ assert_eq!(ruta.parent(), Some(dir.as_path()));
+ let mut quedan: Vec = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ quedan.sort();
+ assert_eq!(quedan, ["notas.txt", "nueva.jpg", "vieja.jpg"]);
+ }
+}
diff --git a/native/core/src/features/celular/contexto.rs b/native/core/src/features/celular/contexto.rs
index d1c84189..db011a66 100644
--- a/native/core/src/features/celular/contexto.rs
+++ b/native/core/src/features/celular/contexto.rs
@@ -9,6 +9,10 @@ use crate::features::chat::principal::SesionChat;
use crate::usage::UsoCuenta;
use serde_json::Value;
use std::collections::HashMap;
+use std::path::PathBuf;
+
+/// Con este error de `transcribir`, el celu recibe un 429: no es el audio, hay que probar en un rato.
+pub const DICTADO_OCUPADO: &str = "La PC está dictando: probá en un momento.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CuentaInfo {
@@ -59,6 +63,15 @@ pub trait ContextoCelular: Send + Sync {
/// Cambia el tamaño de la PTY sin tocar el que recuerda la PC (`tam_pty`).
fn redimensionar_pty(&self, id: &str, cols: u32, rows: u32);
+ /// El texto de un WAV que ya pasó `adjuntos::audio_valido`, con el dictado de la PC. El error se le muestra al celu.
+ fn transcribir(&self, _wav: &[u8]) -> Result {
+ Err("Esta PC no puede dictar.".into())
+ }
+ /// Dónde quedan las fotos que manda el celu.
+ fn carpeta_adjuntos(&self) -> Option {
+ None
+ }
+
fn interfaces_de_red(&self) -> Vec<(String, Vec)>;
/// Los PNG de la página: sin archivo, el de 192 px.
fn leer_icono(&self, archivo: Option<&str>) -> Option>;
diff --git a/native/core/src/features/celular/core.rs b/native/core/src/features/celular/core.rs
index 7a95adf2..30ad5d83 100644
--- a/native/core/src/features/celular/core.rs
+++ b/native/core/src/features/celular/core.rs
@@ -477,7 +477,7 @@ pub fn armar_estado(e: &Entrada, p: &dyn ClasificadorPermisos) -> EstadoCelular
PedidoCelular { id: pe.id.clone(), sesion_id: pe.ws.clone(), sesion: corto(nombres[pe.ws.as_str()], 60), texto: v.texto, titulo: v.titulo, destructivo: v.destructivo, cortado: v.cortado, desde: pe.at, vence: pe.expires_at }
})
.collect();
- EstadoCelular { ahora: e.ahora, aprobar: e.aprobar, terminal: e.terminal, terminal_en_wifi: None, cuentas, sesiones, pedidos }
+ EstadoCelular { ahora: e.ahora, aprobar: e.aprobar, terminal: e.terminal, terminal_en_wifi: None, adjuntos: None, cuentas, sesiones, pedidos }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/native/core/src/features/celular/mod.rs b/native/core/src/features/celular/mod.rs
index 03204ac4..954cf2e5 100644
--- a/native/core/src/features/celular/mod.rs
+++ b/native/core/src/features/celular/mod.rs
@@ -4,6 +4,7 @@
//! `contexto::ContextoCelular`, que implementa la cáscara.
pub mod acceso;
pub mod actividad;
+pub mod adjuntos;
pub mod ajuste;
pub mod conexiones;
pub mod config;
diff --git a/native/core/src/features/celular/pagina/app.css b/native/core/src/features/celular/pagina/app.css
index 41d6ea87..f8accc2a 100644
--- a/native/core/src/features/celular/pagina/app.css
+++ b/native/core/src/features/celular/pagina/app.css
@@ -339,6 +339,10 @@ html.quieto *, html.quieto *::before, html.quieto *::after, html.quieto ::backdr
.term-escribir input { min-height: 48px; padding: 0 18px; border-radius: 24px; background: #151925; }
.term-escribir input:focus { outline: none; border-color: #8ab4ff; box-shadow: 0 0 0 3px rgba(138,180,255,.18); }
.term-hist { width: 44px; border-radius: 50%; background: rgba(255,255,255,.06); border-color: transparent; }
+.term-adj { flex: none; width: 40px; height: 48px; display: inline-flex; align-items: center; justify-content: center; padding: 0; border: 0; border-radius: 20px; background: rgba(255,255,255,.06); color: var(--texto); touch-action: manipulation; }
+.term-adj[aria-expanded="true"] { background: rgba(138,180,255,.28); }
+.term-adjunto { flex: none; display: flex; align-items: center; gap: 8px; padding: 8px 10px 0; font-size: 13px; color: var(--texto); }
+.term-adjunto button { flex: 1; min-height: 44px; padding: 0 12px; border: 1px solid rgba(255,255,255,.1); border-radius: 12px; background: #171b27; color: var(--fuerte); font-weight: 600; touch-action: manipulation; }
.term-mandar { width: 48px; min-height: 48px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 50%; background: linear-gradient(135deg, #a9c8ff, #8ab4ff); box-shadow: 0 6px 18px rgba(138,180,255,.35); }
.term-teclas { gap: 6px; padding: 10px 10px 8px; border-top: 0; }
.term-teclas button { border-radius: 12px; border-color: transparent; background: #171b27; font-size: 12.5px; box-shadow: inset 0 -2px 0 rgba(0,0,0,.35); }
diff --git a/native/core/src/features/celular/pagina/app.js b/native/core/src/features/celular/pagina/app.js
index 158786a6..4e74b21e 100644
--- a/native/core/src/features/celular/pagina/app.js
+++ b/native/core/src/features/celular/pagina/app.js
@@ -794,6 +794,7 @@
function pintar() {
pintarConexion();
+ pintarAdjuntos();
if (!ultimo) return;
pintarCuentas(ultimo);
pintarLimites(ultimo);
@@ -1267,6 +1268,57 @@
$('term-texto').value = termHistI < 0 ? '' : termHist[termHistI];
}
+ // Solo una app de Android que sepa grabar, y con la PC diciendo que este celu puede.
+ function pintarAdjuntos() {
+ var hay = !!(avisos && typeof avisos.grabar === 'function' && ultimo && ultimo.adjuntos);
+ $('term-audio').hidden = !hay;
+ $('term-foto').hidden = !hay;
+ if (!hay) elegirFoto(false);
+ }
+
+ function elegirFoto(si) {
+ $('term-foto-de').hidden = !si;
+ $('term-foto').setAttribute('aria-expanded', String(si));
+ }
+
+ function mandandoAdjunto(texto) {
+ $('term-mandando').hidden = !texto;
+ $('term-mandando').textContent = texto || '';
+ }
+
+ function soltarAdjuntos() {
+ mandandoAdjunto('');
+ elegirFoto(false);
+ }
+
+ function puedeAdjuntar() {
+ return !!termId && !termCerrada && !termParada && $('term-mandando').hidden;
+ }
+
+ function notaTerm(texto) {
+ termNota = texto;
+ avisoTerm(texto);
+ }
+
+ // Lo que vuelve de la PC se suma al cuadro y no se manda: primero lo revisa la persona.
+ function sumarAlCuadro(texto) {
+ var campo = $('term-texto');
+ var junto = campo.value && !/\s$/.test(campo.value) ? campo.value + ' ' + texto : campo.value + texto;
+ if (junto.length > campo.maxLength) return notaTerm('No entra en el cuadro: mandá lo que tenés escrito y probá de nuevo.');
+ campo.value = junto;
+ }
+
+ // Lo llama la app de Android con cómo va el audio o la foto. La grabación la muestra y la corta la app.
+ window.slothAdjunto = function (a) {
+ if (!a || !termId || a.id !== termId) return;
+ // Rechazó un segundo pedido: el anterior sigue en curso.
+ if (a.estado === 'ocupado') return notaTerm(a.error);
+ var audio = a.tipo === 'audio';
+ mandandoAdjunto(a.estado === 'mandando' ? (audio ? 'Pasando el audio a texto…' : 'Mandando la foto…') : '');
+ if (a.estado === 'error') notaTerm(a.error);
+ else if (a.estado === 'listo') sumarAlCuadro(audio ? a.texto : 'Mirá esta imagen: "' + a.ruta + '" ');
+ };
+
// Lo que llegue de un pedido de mirar anterior a esto ya no vale: se compara termGen.
function soltarMirar() {
termGen++;
@@ -1511,6 +1563,8 @@
termCols = 0;
termCedido = false;
pintarAjuste();
+ soltarAdjuntos();
+ pintarAdjuntos();
$('term-texto').value = '';
$('term-nombre').textContent = nombre;
$('term-sub').textContent = cuenta || '';
@@ -1558,6 +1612,8 @@
function cerrarTerminal(desdeHistoria) {
if (!termId) return;
soltarAjuste();
+ if (avisos && avisos.cancelar) avisos.cancelar();
+ soltarAdjuntos();
termId = null;
termCola = [];
soltarMirar();
@@ -1628,7 +1684,25 @@
});
});
}
- botonesTecla.push($('term-texto'), $('term-mandar'), $('term-a-texto'));
+ botonesTecla.push($('term-texto'), $('term-mandar'), $('term-a-texto'), $('term-audio'), $('term-foto'));
+ $('term-audio').addEventListener('click', function () {
+ if (!puedeAdjuntar()) return;
+ elegirFoto(false);
+ avisos.anotar(token);
+ avisos.grabar(termId);
+ });
+ $('term-foto').addEventListener('click', function () { if (puedeAdjuntar()) elegirFoto($('term-foto-de').hidden); });
+ [].forEach.call($('term-foto-de').querySelectorAll('button'), function (b) {
+ b.addEventListener('click', function () {
+ elegirFoto(false);
+ if (!puedeAdjuntar()) return;
+ avisos.anotar(token);
+ avisos.foto(termId, b.getAttribute('data-origen'));
+ });
+ });
+ ['term-audio', 'term-foto'].forEach(function (id) {
+ $(id).addEventListener('mousedown', function (ev) { ev.preventDefault(); });
+ });
$('term-escribir').addEventListener('submit', function (ev) { ev.preventDefault(); mandarTexto(); });
// Mandar y el historial no se llevan el foco: el teclado del celu queda abierto para seguir escribiendo.
$('term-mandar').addEventListener('mousedown', function (ev) { ev.preventDefault(); });
diff --git a/native/core/src/features/celular/pagina/index.html b/native/core/src/features/celular/pagina/index.html
index cf76ada6..131ad6c0 100644
--- a/native/core/src/features/celular/pagina/index.html
+++ b/native/core/src/features/celular/pagina/index.html
@@ -109,8 +109,12 @@ Cuenta
+
+
diff --git a/native/core/src/features/celular/principal.rs b/native/core/src/features/celular/principal.rs
index f977ab66..e0ef7cab 100644
--- a/native/core/src/features/celular/principal.rs
+++ b/native/core/src/features/celular/principal.rs
@@ -4,10 +4,11 @@
//! celus conectados, pedidos de entrada que vencen, visores sin uso y revisar la IP) son plazos de un solo hilo.
use super::acceso::{para_vista, permisos_de, sin_vencidos, usar, CeluGuardado, Entradas, ResultadoPedir, MAX_CELUS};
use super::actividad::{Actividad, Quien};
+use super::adjuntos::{audio_valido, foto_valida, guardar_foto, limpiar_dictado, Subida, TipoAdjunto};
use super::ahora_ms;
use super::ajuste::{Ajustes, Dueno};
use super::config::{ArchivoCelular, Config, Sorteado};
-use super::contexto::ContextoCelular;
+use super::contexto::{ContextoCelular, DICTADO_OCUPADO};
use super::core::{
armar_estado, clave_valida_json, cuerpo_ntfy, debe_avisar, elegir_ip, enlace_aviso, https_tailscale, ip_tailscale, leer_limites, pedido_para_celu, puerto_valido, puertos_a_probar, resumen_permiso, servidor_ntfy, tema_valido, texto_aviso, texto_aviso_privado,
token_ntfy_tras, token_ntfy_valido, CuentaEntrada, DePermisos, Entrada, OrigenesAviso, TextoAviso, TipoAviso, LIMITES_ARCHIVO, TEMA_MIN, VENTANA_AVISOS_MS,
@@ -16,7 +17,7 @@ use super::escrituras::Escrituras;
use super::espera::{Esperas, Inicio, MotivoEspera};
use super::remoto::{CambioRemoto, FuenteRemota, OpcionesRemota};
use super::remoto_core::{enlace_celu, Emparejamiento, CELU_WEB_URL};
-use super::sello::{codificar, Repetidos};
+use super::sello::{codificar, iv_aleatorio, Repetidos};
use super::servidor::{Decision, ErrorTerminal, FuenteWifi, OpcionesWifi, ProveedorDeEstado};
use super::terminal_core::{debe_esperar, nuevo_visor, poner_foto, salida_desde, sin_automaticas, sin_salida, sumar_salida, vencidos, PedidoTerminal, RespuestaTerminal, Salida, Tam, Visor, MAX_DATOS_PESO, VISOR_VENCE_MS};
use super::tipos::{CelularVista, EstadoRemoto, NivelCelu, NtfyVista, RemotoVista, TailscaleVista, TipoEventoCelu};
@@ -28,6 +29,7 @@ use crate::features::permissions::tipo_de;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
use std::time::Duration;
@@ -40,6 +42,7 @@ const VENCER_VISORES_MS: i64 = 10_000;
const NTFY_MS: u64 = 8000;
const VALOR_INVALIDO: &str = "Valor inválido.";
const TERMINAL_APAGADA: &str = "La terminal desde el celu está apagada en Sloth.";
+const SIN_PERMISO_DE_TERMINAL: &str = "Este celu no tiene permiso para abrir las terminales. En la PC, panel «Celular», podés dárselo.";
const DEMASIADOS: &str = "Esta PC ya tiene demasiados celus con acceso.";
/// Lo que cambia en las pruebas: la red de ntfy, el socket del canal remoto y los ritmos.
@@ -132,6 +135,8 @@ struct Interno {
esperas: Esperas,
escrituras: Escrituras,
repetidos: Arc,
+ /// Un audio del celu a la vez: whisper ocupa la PC.
+ transcribiendo: AtomicBool,
enviados: Mutex>,
/// Abrir y cerrar los servidores no se pisa entre dos pedidos de la UI.
aplicando: Mutex<()>,
@@ -189,6 +194,7 @@ impl Celular {
esperas: Esperas::default(),
escrituras: Escrituras::default(),
repetidos: Arc::default(),
+ transcribiendo: AtomicBool::new(false),
enviados: Mutex::default(),
aplicando: Mutex::new(()),
plazos: Mutex::default(),
@@ -1114,17 +1120,74 @@ impl Interno {
bloquear(&self.visores).get_mut(id).map(|v| v.usado_en = ahora_ms()).is_some()
}
- fn terminal(&self, p: &PedidoTerminal, cancelada: &dyn Fn() -> bool, quien: Option<&Quien>) -> Result {
- let error = |status, e: &str| Err(ErrorTerminal { status, error: e.into() });
+ fn acceso_a_terminal(&self, id: &str, quien: Option<&Quien>) -> Result<(), ErrorTerminal> {
if !self.e().cfg.terminal {
return error(403, TERMINAL_APAGADA);
}
if !self.permisos(quien).1 {
- return error(403, "Este celu no tiene permiso para abrir las terminales. En la PC, panel «Celular», podés dárselo.");
+ return error(403, SIN_PERMISO_DE_TERMINAL);
}
- if self.ctx.nombre_espacio(&p.id).is_none() {
+ if self.ctx.nombre_espacio(id).is_none() {
return error(404, "Ese espacio ya no está en la PC.");
}
+ Ok(())
+ }
+
+ /// Un adjunto pide lo mismo que escribir en esa terminal, abierta, y además la clave de un celu: sin ella no hay a
+ /// quién medirle el permiso.
+ fn puede_adjuntar(&self, id: &str, quien: Option<&Quien>) -> Result<(), ErrorTerminal> {
+ if !quien.is_some_and(|q| q.celu.is_some()) {
+ return error(403, "Solo un celu con acceso puede mandar adjuntos.");
+ }
+ self.acceso_a_terminal(id, quien)?;
+ if !self.ctx.terminal_viva(id) {
+ return error(409, "Esa sesión no está abierta.");
+ }
+ Ok(())
+ }
+
+ fn subir(&self, s: &Subida, quien: Option<&Quien>) -> Result {
+ self.puede_adjuntar(&s.id, quien)?;
+ let respuesta = match s.tipo {
+ TipoAdjunto::Audio => self.dictar(s, quien)?,
+ TipoAdjunto::Foto => self.recibir_foto(s.bytes)?,
+ };
+ self.anotar_celu(quien, TipoEventoCelu::Adjunto, &s.id);
+ Ok(respuesta)
+ }
+
+ fn dictar(&self, s: &Subida, quien: Option<&Quien>) -> Result {
+ if !audio_valido(s.bytes) {
+ return error(400, "Ese audio no sirve.");
+ }
+ let Some(_turno) = Turno::tomar(&self.transcribiendo) else { return error(429, "La PC está transcribiendo otro audio.") };
+ let texto = self.ctx.transcribir(s.bytes).map_err(|e| ErrorTerminal { status: if e == DICTADO_OCUPADO { 429 } else { 409 }, error: e })?;
+ // Transcribir tarda: mientras tanto pudieron sacar el celu, apagar la terminal o cerrarse la sesión.
+ self.puede_adjuntar(&s.id, quien)?;
+ let texto = limpiar_dictado(&texto);
+ if texto.is_empty() {
+ return error(409, "No se escuchó nada.");
+ }
+ Ok(json!({ "texto": texto }))
+ }
+
+ fn recibir_foto(&self, bytes: &[u8]) -> Result {
+ if !foto_valida(bytes) {
+ return error(400, "Esa foto no sirve.");
+ }
+ let nombre = format!("{}.jpg", hex::encode(iv_aleatorio()));
+ let guardada = self.ctx.carpeta_adjuntos().ok_or_else(|| "no hay dónde".to_string()).and_then(|dir| guardar_foto(&dir, &nombre, bytes).map_err(|e| e.to_string()));
+ match guardada {
+ Ok(ruta) => Ok(json!({ "ruta": ruta.to_string_lossy() })),
+ Err(e) => {
+ self.ctx.log(&format!("no se pudo guardar la foto del celu: {e}"));
+ error(409, "La PC no pudo guardar la foto.")
+ }
+ }
+ }
+
+ fn terminal(&self, p: &PedidoTerminal, cancelada: &dyn Fn() -> bool, quien: Option<&Quien>) -> Result {
+ self.acceso_a_terminal(&p.id, quien)?;
if p.desde == -1 && !p.solo_escribir {
self.anotar_celu(quien, TipoEventoCelu::Abrio, &p.id);
}
@@ -1204,6 +1267,24 @@ impl Interno {
}
}
+fn error(status: u16, texto: &str) -> Result {
+ Err(ErrorTerminal { status, error: texto.into() })
+}
+
+struct Turno<'a>(&'a AtomicBool);
+
+impl<'a> Turno<'a> {
+ fn tomar(ocupado: &'a AtomicBool) -> Option {
+ (!ocupado.swap(true, Ordering::SeqCst)).then(|| Turno(ocupado))
+ }
+}
+
+impl Drop for Turno<'_> {
+ fn drop(&mut self) {
+ self.0.store(false, Ordering::SeqCst);
+ }
+}
+
impl ProveedorDeEstado for Proveedor {
fn estado(&self, quien: Option<&Quien>) -> super::tipos::EstadoCelular {
let Some(i) = self.0.upgrade() else { return armar_estado(&vacio(), &DePermisos) };
@@ -1243,7 +1324,9 @@ impl ProveedorDeEstado for Proveedor {
limites: i.limites(&cuentas),
pedidos: i.ctx.pedidos_pendientes(),
};
- armar_estado(&entrada, &DePermisos)
+ let mut estado = armar_estado(&entrada, &DePermisos);
+ estado.adjuntos = (terminal && quien.is_some_and(|q| q.celu.is_some())).then_some(true);
+ estado
}
fn decidir(&self, id: &str, decision: Decision, quien: Option<&Quien>) -> Result<(), String> {
@@ -1316,6 +1399,15 @@ impl ProveedorDeEstado for Proveedor {
fn xterm(&self) -> Option<(String, String)> {
self.0.upgrade()?.ctx.xterm()
}
+
+ fn admite_subida(&self) -> bool {
+ self.0.upgrade().is_some_and(|i| i.e().cfg.terminal)
+ }
+
+ fn subir(&self, s: &Subida, quien: Option<&Quien>) -> Result {
+ let i = self.0.upgrade().ok_or_else(|| ErrorTerminal { status: 403, error: TERMINAL_APAGADA.into() })?;
+ i.subir(s, quien)
+ }
}
fn vacio() -> Entrada {
diff --git a/native/core/src/features/celular/principal_pruebas.rs b/native/core/src/features/celular/principal_pruebas.rs
index ac2e13fd..7b28d487 100644
--- a/native/core/src/features/celular/principal_pruebas.rs
+++ b/native/core/src/features/celular/principal_pruebas.rs
@@ -1,9 +1,11 @@
use super::*;
+use crate::features::celular::adjuntos::{Subida, TipoAdjunto};
use crate::features::celular::contexto::{CuentaInfo, FotoTerminal};
use crate::features::celular::core::{AgenteEstado, EspacioEntrada, InterfazRed, LimitesLeidos, PedidoPendiente};
use crate::features::celular::pruebas::{carpeta_temporal, clave_de};
use crate::features::chat::http::pruebas::{json_resp, HttpFalso};
use crate::features::chat::principal::SesionChat;
+use crate::features::dictado_core::encode_wav;
use crate::usage::UsoCuenta;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -21,6 +23,12 @@ struct Falso {
/// El tamaño de la PC; `None` = 120x30.
pc: Mutex