PACKET v1.0.0 - Initial release
App móvil Flutter para capturar contenido multimedia, etiquetarlo con hashes y enviarlo a backends configurables. Features: - Captura de fotos, audio, video y archivos - Sistema de etiquetas con bibliotecas externas (HST) - Packs de etiquetas predefinidos - Cola de reintentos (hasta 20 contenedores) - Soporte GPS - Hash SHA-256 auto-generado por contenedor - Persistencia SQLite local - Múltiples destinos configurables Stack: Flutter 3.38.5, flutter_bloc, sqflite, dio 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
45
lib/core/constants/app_constants.dart
Normal file
45
lib/core/constants/app_constants.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
class AppConstants {
|
||||
static const int maxPendientes = 20;
|
||||
static const int maxReintentos = 20;
|
||||
static const int hashLength = 64;
|
||||
static const int chunkSize = 512 * 1024; // 512KB
|
||||
|
||||
static const String hstBibliotecaHash =
|
||||
'b7149f9e2106c566032aeb29a26e4c6cdd5f5c16b4421025c58166ee345740d1';
|
||||
static const String hstApiUrl = 'https://tzrtech.org';
|
||||
static const String hstApiEndpoint = '/api/tags';
|
||||
|
||||
static const Duration httpTimeout = Duration(seconds: 30);
|
||||
static const Duration retryCheckInterval = Duration(seconds: 30);
|
||||
}
|
||||
|
||||
class RetryDelays {
|
||||
static const List<Duration> delays = [
|
||||
Duration(minutes: 1),
|
||||
Duration(minutes: 2),
|
||||
Duration(minutes: 5),
|
||||
Duration(minutes: 10),
|
||||
Duration(minutes: 20),
|
||||
Duration(minutes: 30),
|
||||
Duration(hours: 1),
|
||||
Duration(hours: 2),
|
||||
Duration(hours: 3),
|
||||
Duration(hours: 4),
|
||||
Duration(hours: 5),
|
||||
Duration(hours: 6),
|
||||
Duration(hours: 6),
|
||||
Duration(hours: 6),
|
||||
Duration(hours: 8),
|
||||
Duration(hours: 8),
|
||||
Duration(hours: 8),
|
||||
Duration(hours: 8),
|
||||
Duration(hours: 6),
|
||||
];
|
||||
|
||||
static Duration getDelay(int intento) {
|
||||
if (intento < 0 || intento >= delays.length) {
|
||||
return Duration.zero;
|
||||
}
|
||||
return delays[intento];
|
||||
}
|
||||
}
|
||||
25
lib/core/errors/exceptions.dart
Normal file
25
lib/core/errors/exceptions.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
class PacketException implements Exception {
|
||||
final String message;
|
||||
final String? code;
|
||||
|
||||
PacketException(this.message, {this.code});
|
||||
|
||||
@override
|
||||
String toString() => 'PacketException: $message';
|
||||
}
|
||||
|
||||
class NetworkException extends PacketException {
|
||||
NetworkException(super.message, {super.code});
|
||||
}
|
||||
|
||||
class HashExistsException extends PacketException {
|
||||
HashExistsException() : super('Hash already exists', code: 'hash_exists');
|
||||
}
|
||||
|
||||
class QueueFullException extends PacketException {
|
||||
QueueFullException() : super('Queue is full (max 20)', code: 'queue_full');
|
||||
}
|
||||
|
||||
class DatabaseException extends PacketException {
|
||||
DatabaseException(super.message, {super.code});
|
||||
}
|
||||
60
lib/core/theme/app_theme.dart
Normal file
60
lib/core/theme/app_theme.dart
Normal file
@@ -0,0 +1,60 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppTheme {
|
||||
static const Color primaryColor = Color(0xFF2196F3);
|
||||
static const Color accentColor = Color(0xFF03A9F4);
|
||||
static const Color errorColor = Color(0xFFE53935);
|
||||
static const Color successColor = Color(0xFF43A047);
|
||||
static const Color warningColor = Color(0xFFFFA726);
|
||||
|
||||
static ThemeData get lightTheme => ThemeData(
|
||||
useMaterial3: true,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: primaryColor,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
centerTitle: true,
|
||||
elevation: 0,
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
elevation: 2,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
filled: true,
|
||||
),
|
||||
floatingActionButtonTheme: const FloatingActionButtonThemeData(
|
||||
elevation: 4,
|
||||
),
|
||||
);
|
||||
|
||||
static ThemeData get darkTheme => ThemeData(
|
||||
useMaterial3: true,
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: primaryColor,
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
appBarTheme: const AppBarTheme(
|
||||
centerTitle: true,
|
||||
elevation: 0,
|
||||
),
|
||||
cardTheme: CardThemeData(
|
||||
elevation: 2,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
filled: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
36
lib/core/utils/hash_utils.dart
Normal file
36
lib/core/utils/hash_utils.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
class HashUtils {
|
||||
static final _random = Random.secure();
|
||||
|
||||
static String generateHash() {
|
||||
final bytes = List<int>.generate(32, (_) => _random.nextInt(256));
|
||||
return sha256.convert(bytes).toString();
|
||||
}
|
||||
|
||||
static String hashFromBytes(Uint8List bytes) {
|
||||
return sha256.convert(bytes).toString();
|
||||
}
|
||||
|
||||
static String hashFromString(String input) {
|
||||
return sha256.convert(utf8.encode(input)).toString();
|
||||
}
|
||||
|
||||
static bool isValidHash(String hash) {
|
||||
if (hash.length != 64) return false;
|
||||
return RegExp(r'^[a-f0-9]{64}$').hasMatch(hash);
|
||||
}
|
||||
|
||||
static List<String> extractHashes(String text) {
|
||||
final regex = RegExp(r'[a-f0-9]{64}');
|
||||
return regex.allMatches(text).map((m) => m.group(0)!).toList();
|
||||
}
|
||||
|
||||
static String truncateHash(String hash, {int length = 8}) {
|
||||
if (hash.length <= length) return hash;
|
||||
return '${hash.substring(0, length)}...';
|
||||
}
|
||||
}
|
||||
20
lib/core/utils/retry_utils.dart
Normal file
20
lib/core/utils/retry_utils.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
import '../constants/app_constants.dart';
|
||||
|
||||
class RetryUtils {
|
||||
static DateTime calculateNextRetry(int intentoActual) {
|
||||
final delay = RetryDelays.getDelay(intentoActual);
|
||||
return DateTime.now().add(delay);
|
||||
}
|
||||
|
||||
static bool shouldRetry(int intentos) {
|
||||
return intentos < AppConstants.maxReintentos;
|
||||
}
|
||||
|
||||
static String formatTimeRemaining(DateTime nextRetry) {
|
||||
final diff = nextRetry.difference(DateTime.now());
|
||||
if (diff.isNegative) return 'Ahora';
|
||||
if (diff.inHours > 0) return '${diff.inHours}h ${diff.inMinutes % 60}m';
|
||||
if (diff.inMinutes > 0) return '${diff.inMinutes}m';
|
||||
return '${diff.inSeconds}s';
|
||||
}
|
||||
}
|
||||
119
lib/data/datasources/backend_api.dart
Normal file
119
lib/data/datasources/backend_api.dart
Normal file
@@ -0,0 +1,119 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/errors/exceptions.dart';
|
||||
import '../../domain/entities/contenedor.dart';
|
||||
import '../../domain/entities/destino.dart';
|
||||
|
||||
class BackendApi {
|
||||
final Dio _dio;
|
||||
|
||||
BackendApi() : _dio = Dio() {
|
||||
_dio.options.connectTimeout = AppConstants.httpTimeout;
|
||||
_dio.options.receiveTimeout = AppConstants.httpTimeout;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> enviarContenedor(
|
||||
Contenedor contenedor,
|
||||
Destino destino,
|
||||
) async {
|
||||
try {
|
||||
final archivosJson = contenedor.archivos.map((a) => {
|
||||
'nombre': a.nombre,
|
||||
'tipo': a.mimeType,
|
||||
'contenido': base64Encode(a.bytes),
|
||||
}).toList();
|
||||
|
||||
final response = await _dio.post(
|
||||
'${destino.url}/ingest',
|
||||
options: Options(
|
||||
headers: {
|
||||
'X-Auth-Key': destino.hash,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
),
|
||||
data: {
|
||||
'hash': contenedor.hash,
|
||||
if (contenedor.titulo != null) 'titulo': contenedor.titulo,
|
||||
if (contenedor.descripcion != null) 'descripcion': contenedor.descripcion,
|
||||
'etiquetas': contenedor.etiquetas,
|
||||
if (contenedor.gps != null) 'gps': contenedor.gps!.toJson(),
|
||||
'archivos': archivosJson,
|
||||
},
|
||||
);
|
||||
|
||||
return response.data as Map<String, dynamic>;
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 409) {
|
||||
throw HashExistsException();
|
||||
}
|
||||
throw NetworkException(
|
||||
e.message ?? 'Network error',
|
||||
code: e.response?.statusCode?.toString(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> initChunkUpload(
|
||||
String hash,
|
||||
int totalChunks,
|
||||
String fileName,
|
||||
Destino destino,
|
||||
) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'${destino.url}/upload/init',
|
||||
options: Options(
|
||||
headers: {'X-Auth-Key': destino.hash},
|
||||
),
|
||||
data: {
|
||||
'hash': hash,
|
||||
'total_chunks': totalChunks,
|
||||
'file_name': fileName,
|
||||
},
|
||||
);
|
||||
return response.data['upload_id'] as String;
|
||||
} on DioException catch (e) {
|
||||
throw NetworkException(e.message ?? 'Failed to init upload');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> uploadChunk(
|
||||
String uploadId,
|
||||
int chunkNumber,
|
||||
List<int> bytes,
|
||||
Destino destino,
|
||||
) async {
|
||||
try {
|
||||
await _dio.post(
|
||||
'${destino.url}/upload/chunk/$uploadId/$chunkNumber',
|
||||
options: Options(
|
||||
headers: {
|
||||
'X-Auth-Key': destino.hash,
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
),
|
||||
data: bytes,
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
throw NetworkException(e.message ?? 'Failed to upload chunk');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> completeUpload(
|
||||
String uploadId,
|
||||
Destino destino,
|
||||
) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'${destino.url}/upload/complete/$uploadId',
|
||||
options: Options(
|
||||
headers: {'X-Auth-Key': destino.hash},
|
||||
),
|
||||
);
|
||||
return response.data as Map<String, dynamic>;
|
||||
} on DioException catch (e) {
|
||||
throw NetworkException(e.message ?? 'Failed to complete upload');
|
||||
}
|
||||
}
|
||||
}
|
||||
42
lib/data/datasources/biblioteca_api.dart
Normal file
42
lib/data/datasources/biblioteca_api.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/errors/exceptions.dart';
|
||||
import '../../domain/entities/biblioteca.dart';
|
||||
import '../../domain/entities/etiqueta.dart';
|
||||
|
||||
class BibliotecaApi {
|
||||
final Dio _dio;
|
||||
|
||||
BibliotecaApi() : _dio = Dio() {
|
||||
_dio.options.connectTimeout = AppConstants.httpTimeout;
|
||||
_dio.options.receiveTimeout = AppConstants.httpTimeout;
|
||||
}
|
||||
|
||||
Future<List<Etiqueta>> fetchEtiquetas(Biblioteca biblioteca) async {
|
||||
try {
|
||||
final response = await _dio.get(biblioteca.fullUrl);
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
final results = data['results'] as List<dynamic>;
|
||||
return results
|
||||
.map((e) => Etiqueta.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
} on DioException catch (e) {
|
||||
throw NetworkException(e.message ?? 'Failed to fetch etiquetas');
|
||||
}
|
||||
}
|
||||
|
||||
Future<Etiqueta?> resolveHash(String hash, Biblioteca biblioteca) async {
|
||||
try {
|
||||
final response = await _dio.get(
|
||||
biblioteca.fullUrl,
|
||||
queryParameters: {'hash': hash},
|
||||
);
|
||||
final data = response.data as Map<String, dynamic>;
|
||||
final results = data['results'] as List<dynamic>;
|
||||
if (results.isEmpty) return null;
|
||||
return Etiqueta.fromJson(results.first as Map<String, dynamic>);
|
||||
} on DioException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
125
lib/data/datasources/local_database.dart
Normal file
125
lib/data/datasources/local_database.dart
Normal file
@@ -0,0 +1,125 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:path/path.dart';
|
||||
|
||||
class LocalDatabase {
|
||||
static Database? _database;
|
||||
static const String _dbName = 'packet.db';
|
||||
static const int _dbVersion = 1;
|
||||
|
||||
static Future<Database> get database async {
|
||||
_database ??= await _initDatabase();
|
||||
return _database!;
|
||||
}
|
||||
|
||||
static Future<Database> _initDatabase() async {
|
||||
final path = join(await getDatabasesPath(), _dbName);
|
||||
return openDatabase(
|
||||
path,
|
||||
version: _dbVersion,
|
||||
onCreate: _onCreate,
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> _onCreate(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE registro (
|
||||
hash TEXT PRIMARY KEY,
|
||||
titulo TEXT,
|
||||
hora_envio TEXT NOT NULL,
|
||||
primera_conf TEXT,
|
||||
ultima_conf TEXT,
|
||||
destino_id INTEGER
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE destinos (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
activo INTEGER DEFAULT 1
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE bibliotecas (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
endpoint TEXT NOT NULL,
|
||||
h_biblioteca TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE etiquetas_cache (
|
||||
h_maestro TEXT PRIMARY KEY,
|
||||
h_global TEXT,
|
||||
mrf TEXT,
|
||||
ref TEXT,
|
||||
nombre_es TEXT,
|
||||
nombre_en TEXT,
|
||||
grupo TEXT,
|
||||
biblioteca_id INTEGER
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE packs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
nombre TEXT NOT NULL,
|
||||
icono TEXT DEFAULT '📦',
|
||||
tags TEXT NOT NULL
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE pendientes (
|
||||
hash TEXT PRIMARY KEY,
|
||||
titulo TEXT,
|
||||
contenido BLOB NOT NULL,
|
||||
intentos INTEGER DEFAULT 0,
|
||||
ultimo_intento TEXT,
|
||||
proximo_intento TEXT,
|
||||
destino_id INTEGER
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE app_state (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
// Insert default HST biblioteca
|
||||
await db.insert('bibliotecas', {
|
||||
'nombre': 'HST',
|
||||
'url': 'https://tzrtech.org',
|
||||
'endpoint': '/api/tags',
|
||||
'h_biblioteca': 'b7149f9e2106c566032aeb29a26e4c6cdd5f5c16b4421025c58166ee345740d1',
|
||||
});
|
||||
}
|
||||
|
||||
// App State methods
|
||||
static Future<void> setState(String key, String value) async {
|
||||
final db = await database;
|
||||
await db.insert(
|
||||
'app_state',
|
||||
{'key': key, 'value': value},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
static Future<String?> getState(String key) async {
|
||||
final db = await database;
|
||||
final result = await db.query(
|
||||
'app_state',
|
||||
where: 'key = ?',
|
||||
whereArgs: [key],
|
||||
);
|
||||
if (result.isEmpty) return null;
|
||||
return result.first['value'] as String?;
|
||||
}
|
||||
}
|
||||
77
lib/data/repositories/config_repository.dart
Normal file
77
lib/data/repositories/config_repository.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import '../datasources/local_database.dart';
|
||||
import '../../domain/entities/destino.dart';
|
||||
import '../../domain/entities/biblioteca.dart';
|
||||
|
||||
class ConfigRepository {
|
||||
// Destinos
|
||||
Future<List<Destino>> getDestinos() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query('destinos');
|
||||
return results.map((m) => Destino.fromMap(m)).toList();
|
||||
}
|
||||
|
||||
Future<Destino?> getDestinoActivo() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query(
|
||||
'destinos',
|
||||
where: 'activo = ?',
|
||||
whereArgs: [1],
|
||||
limit: 1,
|
||||
);
|
||||
if (results.isEmpty) return null;
|
||||
return Destino.fromMap(results.first);
|
||||
}
|
||||
|
||||
Future<int> insertDestino(Destino destino) async {
|
||||
final db = await LocalDatabase.database;
|
||||
return db.insert('destinos', destino.toMap());
|
||||
}
|
||||
|
||||
Future<void> updateDestino(Destino destino) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.update(
|
||||
'destinos',
|
||||
destino.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [destino.id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deleteDestino(int id) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.delete('destinos', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<void> setDestinoActivo(int id) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.update('destinos', {'activo': 0});
|
||||
await db.update('destinos', {'activo': 1}, where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
// Bibliotecas
|
||||
Future<List<Biblioteca>> getBibliotecas() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query('bibliotecas');
|
||||
return results.map((m) => Biblioteca.fromMap(m)).toList();
|
||||
}
|
||||
|
||||
Future<int> insertBiblioteca(Biblioteca biblioteca) async {
|
||||
final db = await LocalDatabase.database;
|
||||
return db.insert('bibliotecas', biblioteca.toMap());
|
||||
}
|
||||
|
||||
Future<void> updateBiblioteca(Biblioteca biblioteca) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.update(
|
||||
'bibliotecas',
|
||||
biblioteca.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [biblioteca.id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deleteBiblioteca(int id) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.delete('bibliotecas', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
}
|
||||
129
lib/data/repositories/contenedor_repository.dart
Normal file
129
lib/data/repositories/contenedor_repository.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
import '../datasources/local_database.dart';
|
||||
import '../datasources/backend_api.dart';
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/errors/exceptions.dart';
|
||||
import '../../core/utils/retry_utils.dart';
|
||||
import '../../domain/entities/contenedor.dart';
|
||||
import '../../domain/entities/destino.dart';
|
||||
import '../../domain/entities/pendiente.dart';
|
||||
|
||||
class ContenedorRepository {
|
||||
final BackendApi _api = BackendApi();
|
||||
|
||||
Future<Map<String, dynamic>> enviar(Contenedor contenedor, Destino destino) async {
|
||||
try {
|
||||
final result = await _api.enviarContenedor(contenedor, destino);
|
||||
await _registrarEnvio(contenedor, destino, result);
|
||||
return result;
|
||||
} catch (e) {
|
||||
await _agregarAPendientes(contenedor, destino);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _registrarEnvio(
|
||||
Contenedor contenedor,
|
||||
Destino destino,
|
||||
Map<String, dynamic> response,
|
||||
) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.insert('registro', {
|
||||
'hash': contenedor.hash,
|
||||
'titulo': contenedor.titulo,
|
||||
'hora_envio': DateTime.now().toIso8601String(),
|
||||
'primera_conf': response['received_at'],
|
||||
'ultima_conf': response['received_at'],
|
||||
'destino_id': destino.id,
|
||||
});
|
||||
}
|
||||
|
||||
// Pendientes
|
||||
Future<void> _agregarAPendientes(Contenedor contenedor, Destino destino) async {
|
||||
final count = await getPendientesCount();
|
||||
if (count >= AppConstants.maxPendientes) {
|
||||
throw QueueFullException();
|
||||
}
|
||||
|
||||
final db = await LocalDatabase.database;
|
||||
final contenidoJson = jsonEncode(contenedor.toJson());
|
||||
|
||||
await db.insert('pendientes', {
|
||||
'hash': contenedor.hash,
|
||||
'titulo': contenedor.titulo,
|
||||
'contenido': Uint8List.fromList(utf8.encode(contenidoJson)),
|
||||
'intentos': 1,
|
||||
'ultimo_intento': DateTime.now().toIso8601String(),
|
||||
'proximo_intento': RetryUtils.calculateNextRetry(1).toIso8601String(),
|
||||
'destino_id': destino.id,
|
||||
});
|
||||
}
|
||||
|
||||
Future<int> getPendientesCount() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final result = await db.rawQuery('SELECT COUNT(*) as count FROM pendientes');
|
||||
return result.first['count'] as int;
|
||||
}
|
||||
|
||||
Future<List<Pendiente>> getPendientes() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query('pendientes', orderBy: 'ultimo_intento DESC');
|
||||
return results.map((m) => Pendiente.fromMap(m)).toList();
|
||||
}
|
||||
|
||||
Future<void> reintentar(Pendiente pendiente, Destino destino) async {
|
||||
if (!pendiente.puedeReintentar) return;
|
||||
|
||||
final db = await LocalDatabase.database;
|
||||
final contenidoStr = utf8.decode(pendiente.contenido);
|
||||
final contenidoJson = jsonDecode(contenidoStr) as Map<String, dynamic>;
|
||||
|
||||
// Reconstruct basic contenedor for retry
|
||||
final contenedor = Contenedor(
|
||||
hash: contenidoJson['hash'] as String,
|
||||
titulo: contenidoJson['titulo'] as String?,
|
||||
descripcion: contenidoJson['descripcion'] as String?,
|
||||
etiquetas: (contenidoJson['etiquetas'] as List<dynamic>?)
|
||||
?.map((e) => e as String)
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
|
||||
try {
|
||||
await _api.enviarContenedor(contenedor, destino);
|
||||
await db.delete('pendientes', where: 'hash = ?', whereArgs: [pendiente.hash]);
|
||||
} catch (e) {
|
||||
final nuevoIntento = pendiente.intentos + 1;
|
||||
if (nuevoIntento >= AppConstants.maxReintentos) {
|
||||
// Keep in queue but mark as exhausted
|
||||
await db.update(
|
||||
'pendientes',
|
||||
{
|
||||
'intentos': nuevoIntento,
|
||||
'ultimo_intento': DateTime.now().toIso8601String(),
|
||||
'proximo_intento': null,
|
||||
},
|
||||
where: 'hash = ?',
|
||||
whereArgs: [pendiente.hash],
|
||||
);
|
||||
} else {
|
||||
await db.update(
|
||||
'pendientes',
|
||||
{
|
||||
'intentos': nuevoIntento,
|
||||
'ultimo_intento': DateTime.now().toIso8601String(),
|
||||
'proximo_intento': RetryUtils.calculateNextRetry(nuevoIntento).toIso8601String(),
|
||||
},
|
||||
where: 'hash = ?',
|
||||
whereArgs: [pendiente.hash],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> eliminarPendiente(String hash) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.delete('pendientes', where: 'hash = ?', whereArgs: [hash]);
|
||||
}
|
||||
}
|
||||
97
lib/data/repositories/etiqueta_repository.dart
Normal file
97
lib/data/repositories/etiqueta_repository.dart
Normal file
@@ -0,0 +1,97 @@
|
||||
import '../datasources/local_database.dart';
|
||||
import '../datasources/biblioteca_api.dart';
|
||||
import '../../domain/entities/etiqueta.dart';
|
||||
import '../../domain/entities/biblioteca.dart';
|
||||
import '../../domain/entities/pack.dart';
|
||||
|
||||
class EtiquetaRepository {
|
||||
final BibliotecaApi _api = BibliotecaApi();
|
||||
|
||||
// Etiquetas Cache
|
||||
Future<List<Etiqueta>> getEtiquetasByBiblioteca(int bibliotecaId) async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query(
|
||||
'etiquetas_cache',
|
||||
where: 'biblioteca_id = ?',
|
||||
whereArgs: [bibliotecaId],
|
||||
);
|
||||
return results.map((m) => Etiqueta(
|
||||
hMaestro: m['h_maestro'] as String,
|
||||
hGlobal: m['h_global'] as String? ?? '',
|
||||
mrf: m['mrf'] as String?,
|
||||
ref: m['ref'] as String?,
|
||||
nombreEs: m['nombre_es'] as String?,
|
||||
nombreEn: m['nombre_en'] as String?,
|
||||
grupo: m['grupo'] as String? ?? 'default',
|
||||
bibliotecaId: bibliotecaId,
|
||||
)).toList();
|
||||
}
|
||||
|
||||
Future<void> syncBiblioteca(Biblioteca biblioteca) async {
|
||||
final etiquetas = await _api.fetchEtiquetas(biblioteca);
|
||||
final db = await LocalDatabase.database;
|
||||
|
||||
// Clear old cache
|
||||
await db.delete(
|
||||
'etiquetas_cache',
|
||||
where: 'biblioteca_id = ?',
|
||||
whereArgs: [biblioteca.id],
|
||||
);
|
||||
|
||||
// Insert new
|
||||
for (final etiqueta in etiquetas) {
|
||||
await db.insert('etiquetas_cache', {
|
||||
...etiqueta.toMap(),
|
||||
'biblioteca_id': biblioteca.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<Etiqueta?> resolveHash(String hash) async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query(
|
||||
'etiquetas_cache',
|
||||
where: 'h_maestro = ? OR h_global = ?',
|
||||
whereArgs: [hash, hash],
|
||||
);
|
||||
if (results.isEmpty) return null;
|
||||
final m = results.first;
|
||||
return Etiqueta(
|
||||
hMaestro: m['h_maestro'] as String,
|
||||
hGlobal: m['h_global'] as String? ?? '',
|
||||
mrf: m['mrf'] as String?,
|
||||
ref: m['ref'] as String?,
|
||||
nombreEs: m['nombre_es'] as String?,
|
||||
nombreEn: m['nombre_en'] as String?,
|
||||
grupo: m['grupo'] as String? ?? 'default',
|
||||
bibliotecaId: m['biblioteca_id'] as int?,
|
||||
);
|
||||
}
|
||||
|
||||
// Packs
|
||||
Future<List<Pack>> getPacks() async {
|
||||
final db = await LocalDatabase.database;
|
||||
final results = await db.query('packs');
|
||||
return results.map((m) => Pack.fromMap(m)).toList();
|
||||
}
|
||||
|
||||
Future<int> insertPack(Pack pack) async {
|
||||
final db = await LocalDatabase.database;
|
||||
return db.insert('packs', pack.toMap());
|
||||
}
|
||||
|
||||
Future<void> updatePack(Pack pack) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.update(
|
||||
'packs',
|
||||
pack.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [pack.id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> deletePack(int id) async {
|
||||
final db = await LocalDatabase.database;
|
||||
await db.delete('packs', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
}
|
||||
33
lib/domain/entities/archivo_adjunto.dart
Normal file
33
lib/domain/entities/archivo_adjunto.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
enum ArchivoTipo { image, audio, video, document }
|
||||
|
||||
class ArchivoAdjunto {
|
||||
final String nombre;
|
||||
final String mimeType;
|
||||
final Uint8List bytes;
|
||||
final ArchivoTipo tipo;
|
||||
final String? hash;
|
||||
|
||||
ArchivoAdjunto({
|
||||
required this.nombre,
|
||||
required this.mimeType,
|
||||
required this.bytes,
|
||||
required this.tipo,
|
||||
this.hash,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'nombre': nombre,
|
||||
'tipo': mimeType,
|
||||
'contenido': bytes,
|
||||
};
|
||||
|
||||
int get sizeBytes => bytes.length;
|
||||
|
||||
String get sizeFormatted {
|
||||
if (sizeBytes < 1024) return '$sizeBytes B';
|
||||
if (sizeBytes < 1024 * 1024) return '${(sizeBytes / 1024).toStringAsFixed(1)} KB';
|
||||
return '${(sizeBytes / (1024 * 1024)).toStringAsFixed(1)} MB';
|
||||
}
|
||||
}
|
||||
33
lib/domain/entities/biblioteca.dart
Normal file
33
lib/domain/entities/biblioteca.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
class Biblioteca {
|
||||
final int? id;
|
||||
final String nombre;
|
||||
final String url;
|
||||
final String endpoint;
|
||||
final String? hBiblioteca;
|
||||
|
||||
Biblioteca({
|
||||
this.id,
|
||||
required this.nombre,
|
||||
required this.url,
|
||||
required this.endpoint,
|
||||
this.hBiblioteca,
|
||||
});
|
||||
|
||||
String get fullUrl => '$url$endpoint';
|
||||
|
||||
factory Biblioteca.fromMap(Map<String, dynamic> map) => Biblioteca(
|
||||
id: map['id'] as int?,
|
||||
nombre: map['nombre'] as String,
|
||||
url: map['url'] as String,
|
||||
endpoint: map['endpoint'] as String,
|
||||
hBiblioteca: map['h_biblioteca'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
if (id != null) 'id': id,
|
||||
'nombre': nombre,
|
||||
'url': url,
|
||||
'endpoint': endpoint,
|
||||
'h_biblioteca': hBiblioteca,
|
||||
};
|
||||
}
|
||||
55
lib/domain/entities/contenedor.dart
Normal file
55
lib/domain/entities/contenedor.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
import 'archivo_adjunto.dart';
|
||||
import 'gps_location.dart';
|
||||
|
||||
class Contenedor {
|
||||
final String hash;
|
||||
final String? titulo;
|
||||
final String? descripcion;
|
||||
final List<ArchivoAdjunto> archivos;
|
||||
final GpsLocation? gps;
|
||||
final List<String> etiquetas;
|
||||
final DateTime createdAt;
|
||||
|
||||
Contenedor({
|
||||
required this.hash,
|
||||
this.titulo,
|
||||
this.descripcion,
|
||||
List<ArchivoAdjunto>? archivos,
|
||||
this.gps,
|
||||
List<String>? etiquetas,
|
||||
DateTime? createdAt,
|
||||
}) : archivos = archivos ?? [],
|
||||
etiquetas = etiquetas ?? [],
|
||||
createdAt = createdAt ?? DateTime.now();
|
||||
|
||||
Contenedor copyWith({
|
||||
String? hash,
|
||||
String? titulo,
|
||||
String? descripcion,
|
||||
List<ArchivoAdjunto>? archivos,
|
||||
GpsLocation? gps,
|
||||
List<String>? etiquetas,
|
||||
DateTime? createdAt,
|
||||
}) =>
|
||||
Contenedor(
|
||||
hash: hash ?? this.hash,
|
||||
titulo: titulo ?? this.titulo,
|
||||
descripcion: descripcion ?? this.descripcion,
|
||||
archivos: archivos ?? this.archivos,
|
||||
gps: gps ?? this.gps,
|
||||
etiquetas: etiquetas ?? this.etiquetas,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'hash': hash,
|
||||
if (titulo != null) 'titulo': titulo,
|
||||
if (descripcion != null) 'descripcion': descripcion,
|
||||
'etiquetas': etiquetas,
|
||||
if (gps != null) 'gps': gps!.toJson(),
|
||||
'archivos': archivos.map((a) => a.toJson()).toList(),
|
||||
};
|
||||
|
||||
bool get isEmpty => archivos.isEmpty && etiquetas.isEmpty && titulo == null;
|
||||
int get archivoCount => archivos.length;
|
||||
}
|
||||
46
lib/domain/entities/destino.dart
Normal file
46
lib/domain/entities/destino.dart
Normal file
@@ -0,0 +1,46 @@
|
||||
class Destino {
|
||||
final int? id;
|
||||
final String nombre;
|
||||
final String url;
|
||||
final String hash;
|
||||
final bool activo;
|
||||
|
||||
Destino({
|
||||
this.id,
|
||||
required this.nombre,
|
||||
required this.url,
|
||||
required this.hash,
|
||||
this.activo = true,
|
||||
});
|
||||
|
||||
factory Destino.fromMap(Map<String, dynamic> map) => Destino(
|
||||
id: map['id'] as int?,
|
||||
nombre: map['nombre'] as String,
|
||||
url: map['url'] as String,
|
||||
hash: map['hash'] as String,
|
||||
activo: (map['activo'] as int?) == 1,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
if (id != null) 'id': id,
|
||||
'nombre': nombre,
|
||||
'url': url,
|
||||
'hash': hash,
|
||||
'activo': activo ? 1 : 0,
|
||||
};
|
||||
|
||||
Destino copyWith({
|
||||
int? id,
|
||||
String? nombre,
|
||||
String? url,
|
||||
String? hash,
|
||||
bool? activo,
|
||||
}) =>
|
||||
Destino(
|
||||
id: id ?? this.id,
|
||||
nombre: nombre ?? this.nombre,
|
||||
url: url ?? this.url,
|
||||
hash: hash ?? this.hash,
|
||||
activo: activo ?? this.activo,
|
||||
);
|
||||
}
|
||||
49
lib/domain/entities/etiqueta.dart
Normal file
49
lib/domain/entities/etiqueta.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
class Etiqueta {
|
||||
final String hMaestro;
|
||||
final String hGlobal;
|
||||
final String? mrf;
|
||||
final String? ref;
|
||||
final String? nombreEs;
|
||||
final String? nombreEn;
|
||||
final String grupo;
|
||||
final bool activo;
|
||||
final int? bibliotecaId;
|
||||
|
||||
Etiqueta({
|
||||
required this.hMaestro,
|
||||
required this.hGlobal,
|
||||
this.mrf,
|
||||
this.ref,
|
||||
this.nombreEs,
|
||||
this.nombreEn,
|
||||
required this.grupo,
|
||||
this.activo = true,
|
||||
this.bibliotecaId,
|
||||
});
|
||||
|
||||
String get displayName => nombreEs ?? nombreEn ?? ref ?? hMaestro.substring(0, 8);
|
||||
|
||||
String? get imagenUrl => mrf != null ? 'https://tzrtech.org/$mrf.png' : null;
|
||||
|
||||
factory Etiqueta.fromJson(Map<String, dynamic> json) => Etiqueta(
|
||||
hMaestro: json['h_maestro'] as String,
|
||||
hGlobal: json['h_global'] as String,
|
||||
mrf: json['mrf'] as String?,
|
||||
ref: json['ref'] as String?,
|
||||
nombreEs: json['nombre_es'] as String?,
|
||||
nombreEn: json['nombre_en'] as String?,
|
||||
grupo: json['grupo'] as String? ?? 'default',
|
||||
activo: json['activo'] as bool? ?? true,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'h_maestro': hMaestro,
|
||||
'h_global': hGlobal,
|
||||
'mrf': mrf,
|
||||
'ref': ref,
|
||||
'nombre_es': nombreEs,
|
||||
'nombre_en': nombreEn,
|
||||
'grupo': grupo,
|
||||
'biblioteca_id': bibliotecaId,
|
||||
};
|
||||
}
|
||||
16
lib/domain/entities/gps_location.dart
Normal file
16
lib/domain/entities/gps_location.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
class GpsLocation {
|
||||
final double lat;
|
||||
final double long;
|
||||
|
||||
GpsLocation({required this.lat, required this.long});
|
||||
|
||||
Map<String, dynamic> toJson() => {'lat': lat, 'long': long};
|
||||
|
||||
factory GpsLocation.fromJson(Map<String, dynamic> json) => GpsLocation(
|
||||
lat: (json['lat'] as num).toDouble(),
|
||||
long: (json['long'] as num).toDouble(),
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => '${lat.toStringAsFixed(4)}, ${long.toStringAsFixed(4)}';
|
||||
}
|
||||
29
lib/domain/entities/pack.dart
Normal file
29
lib/domain/entities/pack.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
class Pack {
|
||||
final int? id;
|
||||
final String nombre;
|
||||
final String icono;
|
||||
final List<String> tags;
|
||||
|
||||
Pack({
|
||||
this.id,
|
||||
required this.nombre,
|
||||
this.icono = '📦',
|
||||
required this.tags,
|
||||
});
|
||||
|
||||
factory Pack.fromMap(Map<String, dynamic> map) => Pack(
|
||||
id: map['id'] as int?,
|
||||
nombre: map['nombre'] as String,
|
||||
icono: map['icono'] as String? ?? '📦',
|
||||
tags: (map['tags'] as String).split(',').where((t) => t.isNotEmpty).toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
if (id != null) 'id': id,
|
||||
'nombre': nombre,
|
||||
'icono': icono,
|
||||
'tags': tags.join(','),
|
||||
};
|
||||
|
||||
int get tagCount => tags.length;
|
||||
}
|
||||
55
lib/domain/entities/pendiente.dart
Normal file
55
lib/domain/entities/pendiente.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
class Pendiente {
|
||||
final String hash;
|
||||
final String? titulo;
|
||||
final Uint8List contenido;
|
||||
final int intentos;
|
||||
final DateTime? ultimoIntento;
|
||||
final DateTime? proximoIntento;
|
||||
final int? destinoId;
|
||||
|
||||
Pendiente({
|
||||
required this.hash,
|
||||
this.titulo,
|
||||
required this.contenido,
|
||||
this.intentos = 0,
|
||||
this.ultimoIntento,
|
||||
this.proximoIntento,
|
||||
this.destinoId,
|
||||
});
|
||||
|
||||
factory Pendiente.fromMap(Map<String, dynamic> map) => Pendiente(
|
||||
hash: map['hash'] as String,
|
||||
titulo: map['titulo'] as String?,
|
||||
contenido: map['contenido'] as Uint8List,
|
||||
intentos: map['intentos'] as int? ?? 0,
|
||||
ultimoIntento: map['ultimo_intento'] != null
|
||||
? DateTime.parse(map['ultimo_intento'] as String)
|
||||
: null,
|
||||
proximoIntento: map['proximo_intento'] != null
|
||||
? DateTime.parse(map['proximo_intento'] as String)
|
||||
: null,
|
||||
destinoId: map['destino_id'] as int?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toMap() => {
|
||||
'hash': hash,
|
||||
'titulo': titulo,
|
||||
'contenido': contenido,
|
||||
'intentos': intentos,
|
||||
'ultimo_intento': ultimoIntento?.toIso8601String(),
|
||||
'proximo_intento': proximoIntento?.toIso8601String(),
|
||||
'destino_id': destinoId,
|
||||
};
|
||||
|
||||
bool get puedeReintentar => intentos < 20;
|
||||
|
||||
String get estado {
|
||||
if (intentos >= 20) return 'agotado';
|
||||
if (proximoIntento != null && proximoIntento!.isAfter(DateTime.now())) {
|
||||
return 'esperando';
|
||||
}
|
||||
return 'listo';
|
||||
}
|
||||
}
|
||||
7
lib/main.dart
Normal file
7
lib/main.dart
Normal file
@@ -0,0 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'presentation/app.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(const PacketApp());
|
||||
}
|
||||
147
lib/presentation/app.dart
Normal file
147
lib/presentation/app.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../core/theme/app_theme.dart';
|
||||
import 'bloc/app/app_cubit.dart';
|
||||
import 'bloc/app/app_state.dart';
|
||||
import 'bloc/captura/captura_cubit.dart';
|
||||
import 'bloc/etiquetas/etiquetas_cubit.dart';
|
||||
import 'bloc/packs/packs_cubit.dart';
|
||||
import 'bloc/pendientes/pendientes_cubit.dart';
|
||||
import 'pages/captura_page.dart';
|
||||
import 'pages/etiquetas_page.dart';
|
||||
import 'pages/packs_page.dart';
|
||||
import 'pages/pendientes_page.dart';
|
||||
import 'pages/config_page.dart';
|
||||
|
||||
class PacketApp extends StatelessWidget {
|
||||
const PacketApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider(create: (_) => AppCubit()..init()),
|
||||
BlocProvider(create: (_) => CapturaCubit()),
|
||||
BlocProvider(create: (_) => EtiquetasCubit()..init()),
|
||||
BlocProvider(create: (_) => PacksCubit()..load()),
|
||||
BlocProvider(create: (_) => PendientesCubit()..load()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
title: 'Packet',
|
||||
theme: AppTheme.lightTheme,
|
||||
darkTheme: AppTheme.darkTheme,
|
||||
themeMode: ThemeMode.system,
|
||||
home: const MainScreen(),
|
||||
debugShowCheckedModeBanner: false,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MainScreen extends StatelessWidget {
|
||||
const MainScreen({super.key});
|
||||
|
||||
static const _pages = [
|
||||
CapturaPage(),
|
||||
EtiquetasPage(),
|
||||
PacksPage(),
|
||||
PendientesPage(),
|
||||
ConfigPage(),
|
||||
];
|
||||
|
||||
static const _titles = [
|
||||
'Captura',
|
||||
'Etiquetas',
|
||||
'Packs',
|
||||
'Pendientes',
|
||||
'Config',
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<AppCubit, AppState>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(_titles[state.currentIndex]),
|
||||
actions: [
|
||||
// Destino selector
|
||||
if (state.destinos.isNotEmpty)
|
||||
PopupMenuButton<int>(
|
||||
onSelected: (id) {
|
||||
final destino = state.destinos.firstWhere((d) => d.id == id);
|
||||
context.read<AppCubit>().setDestinoActivo(destino);
|
||||
},
|
||||
itemBuilder: (_) => state.destinos
|
||||
.map((d) => PopupMenuItem(
|
||||
value: d.id,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
state.destinoActivo?.id == d.id
|
||||
? Icons.check
|
||||
: Icons.cloud,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(d.nombre),
|
||||
],
|
||||
),
|
||||
))
|
||||
.toList(),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
state.destinoActivo?.nombre ?? 'Sin destino',
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const Icon(Icons.arrow_drop_down),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: IndexedStack(
|
||||
index: state.currentIndex,
|
||||
children: _pages,
|
||||
),
|
||||
bottomNavigationBar: NavigationBar(
|
||||
selectedIndex: state.currentIndex,
|
||||
onDestinationSelected: (i) => context.read<AppCubit>().setIndex(i),
|
||||
destinations: const [
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.camera_alt_outlined),
|
||||
selectedIcon: Icon(Icons.camera_alt),
|
||||
label: 'Captura',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.label_outline),
|
||||
selectedIcon: Icon(Icons.label),
|
||||
label: 'Tags',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.inventory_2_outlined),
|
||||
selectedIcon: Icon(Icons.inventory_2),
|
||||
label: 'Packs',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.pending_outlined),
|
||||
selectedIcon: Icon(Icons.pending),
|
||||
label: 'Pend.',
|
||||
),
|
||||
NavigationDestination(
|
||||
icon: Icon(Icons.settings_outlined),
|
||||
selectedIcon: Icon(Icons.settings),
|
||||
label: 'Config',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
53
lib/presentation/bloc/app/app_cubit.dart
Normal file
53
lib/presentation/bloc/app/app_cubit.dart
Normal file
@@ -0,0 +1,53 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../data/repositories/config_repository.dart';
|
||||
import '../../../domain/entities/destino.dart';
|
||||
import 'app_state.dart';
|
||||
|
||||
class AppCubit extends Cubit<AppState> {
|
||||
final ConfigRepository _configRepo = ConfigRepository();
|
||||
|
||||
AppCubit() : super(const AppState());
|
||||
|
||||
Future<void> init() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
final destinos = await _configRepo.getDestinos();
|
||||
final activo = await _configRepo.getDestinoActivo();
|
||||
emit(state.copyWith(
|
||||
destinos: destinos,
|
||||
destinoActivo: activo,
|
||||
isLoading: false,
|
||||
));
|
||||
}
|
||||
|
||||
void setIndex(int index) {
|
||||
emit(state.copyWith(currentIndex: index));
|
||||
}
|
||||
|
||||
Future<void> setDestinoActivo(Destino destino) async {
|
||||
if (destino.id != null) {
|
||||
await _configRepo.setDestinoActivo(destino.id!);
|
||||
emit(state.copyWith(destinoActivo: destino));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addDestino(Destino destino) async {
|
||||
final id = await _configRepo.insertDestino(destino);
|
||||
final newDestino = destino.copyWith(id: id);
|
||||
final destinos = [...state.destinos, newDestino];
|
||||
emit(state.copyWith(destinos: destinos));
|
||||
if (state.destinoActivo == null) {
|
||||
await setDestinoActivo(newDestino);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> removeDestino(int id) async {
|
||||
await _configRepo.deleteDestino(id);
|
||||
final destinos = state.destinos.where((d) => d.id != id).toList();
|
||||
emit(state.copyWith(destinos: destinos));
|
||||
if (state.destinoActivo?.id == id) {
|
||||
emit(state.copyWith(
|
||||
destinoActivo: destinos.isNotEmpty ? destinos.first : null,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
32
lib/presentation/bloc/app/app_state.dart
Normal file
32
lib/presentation/bloc/app/app_state.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../domain/entities/destino.dart';
|
||||
|
||||
class AppState extends Equatable {
|
||||
final int currentIndex;
|
||||
final Destino? destinoActivo;
|
||||
final List<Destino> destinos;
|
||||
final bool isLoading;
|
||||
|
||||
const AppState({
|
||||
this.currentIndex = 0,
|
||||
this.destinoActivo,
|
||||
this.destinos = const [],
|
||||
this.isLoading = false,
|
||||
});
|
||||
|
||||
AppState copyWith({
|
||||
int? currentIndex,
|
||||
Destino? destinoActivo,
|
||||
List<Destino>? destinos,
|
||||
bool? isLoading,
|
||||
}) =>
|
||||
AppState(
|
||||
currentIndex: currentIndex ?? this.currentIndex,
|
||||
destinoActivo: destinoActivo ?? this.destinoActivo,
|
||||
destinos: destinos ?? this.destinos,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [currentIndex, destinoActivo, destinos, isLoading];
|
||||
}
|
||||
191
lib/presentation/bloc/captura/captura_cubit.dart
Normal file
191
lib/presentation/bloc/captura/captura_cubit.dart
Normal file
@@ -0,0 +1,191 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import '../../../core/utils/hash_utils.dart';
|
||||
import '../../../data/repositories/contenedor_repository.dart';
|
||||
import '../../../domain/entities/archivo_adjunto.dart';
|
||||
import '../../../domain/entities/contenedor.dart';
|
||||
import '../../../domain/entities/destino.dart';
|
||||
import '../../../domain/entities/gps_location.dart';
|
||||
import 'captura_state.dart';
|
||||
|
||||
class CapturaCubit extends Cubit<CapturaState> {
|
||||
final ContenedorRepository _repo = ContenedorRepository();
|
||||
final ImagePicker _picker = ImagePicker();
|
||||
|
||||
CapturaCubit()
|
||||
: super(CapturaState(
|
||||
contenedor: Contenedor(hash: HashUtils.generateHash()),
|
||||
));
|
||||
|
||||
void regenerateHash() {
|
||||
emit(state.copyWith(
|
||||
contenedor: state.contenedor.copyWith(hash: HashUtils.generateHash()),
|
||||
));
|
||||
}
|
||||
|
||||
void setTitulo(String titulo) {
|
||||
emit(state.copyWith(
|
||||
contenedor: state.contenedor.copyWith(titulo: titulo.isEmpty ? null : titulo),
|
||||
));
|
||||
}
|
||||
|
||||
void setDescripcion(String descripcion) {
|
||||
emit(state.copyWith(
|
||||
contenedor: state.contenedor.copyWith(
|
||||
descripcion: descripcion.isEmpty ? null : descripcion,
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> capturePhoto() async {
|
||||
try {
|
||||
final image = await _picker.pickImage(source: ImageSource.camera);
|
||||
if (image == null) return;
|
||||
|
||||
final bytes = await image.readAsBytes();
|
||||
final archivo = ArchivoAdjunto(
|
||||
nombre: image.name,
|
||||
mimeType: 'image/jpeg',
|
||||
bytes: bytes,
|
||||
tipo: ArchivoTipo.image,
|
||||
hash: HashUtils.hashFromBytes(bytes),
|
||||
);
|
||||
emit(state.addArchivo(archivo));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
status: CapturaStatus.error,
|
||||
errorMessage: 'Error al capturar foto: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> captureVideo() async {
|
||||
try {
|
||||
final video = await _picker.pickVideo(source: ImageSource.camera);
|
||||
if (video == null) return;
|
||||
|
||||
final bytes = await video.readAsBytes();
|
||||
final archivo = ArchivoAdjunto(
|
||||
nombre: video.name,
|
||||
mimeType: 'video/mp4',
|
||||
bytes: bytes,
|
||||
tipo: ArchivoTipo.video,
|
||||
hash: HashUtils.hashFromBytes(bytes),
|
||||
);
|
||||
emit(state.addArchivo(archivo));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
status: CapturaStatus.error,
|
||||
errorMessage: 'Error al capturar video: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> pickFile() async {
|
||||
try {
|
||||
final result = await FilePicker.platform.pickFiles(withData: true);
|
||||
if (result == null || result.files.isEmpty) return;
|
||||
|
||||
final file = result.files.first;
|
||||
if (file.bytes == null) return;
|
||||
|
||||
final archivo = ArchivoAdjunto(
|
||||
nombre: file.name,
|
||||
mimeType: _getMimeType(file.extension),
|
||||
bytes: file.bytes!,
|
||||
tipo: ArchivoTipo.document,
|
||||
hash: HashUtils.hashFromBytes(file.bytes!),
|
||||
);
|
||||
emit(state.addArchivo(archivo));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
status: CapturaStatus.error,
|
||||
errorMessage: 'Error al seleccionar archivo: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void addAudioFile(Uint8List bytes, String nombre) {
|
||||
final archivo = ArchivoAdjunto(
|
||||
nombre: nombre,
|
||||
mimeType: 'audio/m4a',
|
||||
bytes: bytes,
|
||||
tipo: ArchivoTipo.audio,
|
||||
hash: HashUtils.hashFromBytes(bytes),
|
||||
);
|
||||
emit(state.addArchivo(archivo));
|
||||
}
|
||||
|
||||
void removeArchivo(int index) {
|
||||
emit(state.removeArchivo(index));
|
||||
}
|
||||
|
||||
Future<void> captureGps() async {
|
||||
try {
|
||||
final permission = await Geolocator.checkPermission();
|
||||
if (permission == LocationPermission.denied) {
|
||||
await Geolocator.requestPermission();
|
||||
}
|
||||
|
||||
final position = await Geolocator.getCurrentPosition();
|
||||
final gps = GpsLocation(lat: position.latitude, long: position.longitude);
|
||||
emit(state.setGps(gps));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
status: CapturaStatus.error,
|
||||
errorMessage: 'Error al obtener GPS: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void clearGps() {
|
||||
emit(state.setGps(null));
|
||||
}
|
||||
|
||||
void setEtiquetas(List<String> etiquetas) {
|
||||
emit(state.setEtiquetas(etiquetas));
|
||||
}
|
||||
|
||||
Future<void> enviar(Destino destino) async {
|
||||
emit(state.copyWith(status: CapturaStatus.sending));
|
||||
try {
|
||||
await _repo.enviar(state.contenedor, destino);
|
||||
emit(state.copyWith(status: CapturaStatus.success));
|
||||
reset();
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
status: CapturaStatus.error,
|
||||
errorMessage: 'Error al enviar: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void reset() {
|
||||
emit(CapturaState(
|
||||
contenedor: Contenedor(hash: HashUtils.generateHash()),
|
||||
));
|
||||
}
|
||||
|
||||
String _getMimeType(String? extension) {
|
||||
switch (extension?.toLowerCase()) {
|
||||
case 'pdf':
|
||||
return 'application/pdf';
|
||||
case 'doc':
|
||||
case 'docx':
|
||||
return 'application/msword';
|
||||
case 'xls':
|
||||
case 'xlsx':
|
||||
return 'application/vnd.ms-excel';
|
||||
case 'png':
|
||||
return 'image/png';
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return 'image/jpeg';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
}
|
||||
63
lib/presentation/bloc/captura/captura_state.dart
Normal file
63
lib/presentation/bloc/captura/captura_state.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../domain/entities/contenedor.dart';
|
||||
import '../../../domain/entities/archivo_adjunto.dart';
|
||||
import '../../../domain/entities/gps_location.dart';
|
||||
|
||||
enum CapturaStatus { idle, capturing, sending, success, error }
|
||||
|
||||
class CapturaState extends Equatable {
|
||||
final Contenedor contenedor;
|
||||
final CapturaStatus status;
|
||||
final String? errorMessage;
|
||||
final bool isRecording;
|
||||
|
||||
const CapturaState({
|
||||
required this.contenedor,
|
||||
this.status = CapturaStatus.idle,
|
||||
this.errorMessage,
|
||||
this.isRecording = false,
|
||||
});
|
||||
|
||||
CapturaState copyWith({
|
||||
Contenedor? contenedor,
|
||||
CapturaStatus? status,
|
||||
String? errorMessage,
|
||||
bool? isRecording,
|
||||
}) =>
|
||||
CapturaState(
|
||||
contenedor: contenedor ?? this.contenedor,
|
||||
status: status ?? this.status,
|
||||
errorMessage: errorMessage,
|
||||
isRecording: isRecording ?? this.isRecording,
|
||||
);
|
||||
|
||||
CapturaState addArchivo(ArchivoAdjunto archivo) {
|
||||
return copyWith(
|
||||
contenedor: contenedor.copyWith(
|
||||
archivos: [...contenedor.archivos, archivo],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
CapturaState removeArchivo(int index) {
|
||||
final archivos = [...contenedor.archivos]..removeAt(index);
|
||||
return copyWith(
|
||||
contenedor: contenedor.copyWith(archivos: archivos),
|
||||
);
|
||||
}
|
||||
|
||||
CapturaState setGps(GpsLocation? gps) {
|
||||
return copyWith(
|
||||
contenedor: contenedor.copyWith(gps: gps),
|
||||
);
|
||||
}
|
||||
|
||||
CapturaState setEtiquetas(List<String> etiquetas) {
|
||||
return copyWith(
|
||||
contenedor: contenedor.copyWith(etiquetas: etiquetas),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [contenedor, status, errorMessage, isRecording];
|
||||
}
|
||||
105
lib/presentation/bloc/etiquetas/etiquetas_cubit.dart
Normal file
105
lib/presentation/bloc/etiquetas/etiquetas_cubit.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/utils/hash_utils.dart';
|
||||
import '../../../data/repositories/config_repository.dart';
|
||||
import '../../../data/repositories/etiqueta_repository.dart';
|
||||
import 'etiquetas_state.dart';
|
||||
|
||||
class EtiquetasCubit extends Cubit<EtiquetasState> {
|
||||
final ConfigRepository _configRepo = ConfigRepository();
|
||||
final EtiquetaRepository _etiquetaRepo = EtiquetaRepository();
|
||||
|
||||
EtiquetasCubit() : super(const EtiquetasState());
|
||||
|
||||
Future<void> init() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
final bibliotecas = await _configRepo.getBibliotecas();
|
||||
final etiquetasPorBiblioteca = <int, List<dynamic>>{};
|
||||
|
||||
for (final bib in bibliotecas) {
|
||||
if (bib.id != null) {
|
||||
final etiquetas = await _etiquetaRepo.getEtiquetasByBiblioteca(bib.id!);
|
||||
etiquetasPorBiblioteca[bib.id!] = etiquetas;
|
||||
}
|
||||
}
|
||||
|
||||
emit(state.copyWith(
|
||||
bibliotecas: bibliotecas,
|
||||
etiquetasPorBiblioteca: etiquetasPorBiblioteca.cast(),
|
||||
isLoading: false,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
error: 'Error al cargar etiquetas: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> syncBiblioteca(int bibliotecaId) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
try {
|
||||
final biblioteca = state.bibliotecas.firstWhere((b) => b.id == bibliotecaId);
|
||||
await _etiquetaRepo.syncBiblioteca(biblioteca);
|
||||
final etiquetas = await _etiquetaRepo.getEtiquetasByBiblioteca(bibliotecaId);
|
||||
|
||||
final newMap = Map<int, List<dynamic>>.from(state.etiquetasPorBiblioteca);
|
||||
newMap[bibliotecaId] = etiquetas;
|
||||
|
||||
emit(state.copyWith(
|
||||
etiquetasPorBiblioteca: newMap.cast(),
|
||||
isLoading: false,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
error: 'Error al sincronizar: $e',
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void toggleEtiqueta(String hash) {
|
||||
final seleccionadas = List<String>.from(state.seleccionadas);
|
||||
if (seleccionadas.contains(hash)) {
|
||||
seleccionadas.remove(hash);
|
||||
} else {
|
||||
seleccionadas.add(hash);
|
||||
}
|
||||
emit(state.copyWith(seleccionadas: seleccionadas));
|
||||
}
|
||||
|
||||
void removeEtiqueta(String hash) {
|
||||
final seleccionadas = List<String>.from(state.seleccionadas)..remove(hash);
|
||||
emit(state.copyWith(seleccionadas: seleccionadas));
|
||||
}
|
||||
|
||||
void clearSeleccion() {
|
||||
emit(state.copyWith(seleccionadas: []));
|
||||
}
|
||||
|
||||
Future<void> addHashExterno(String input) async {
|
||||
final hashes = HashUtils.extractHashes(input);
|
||||
if (hashes.isEmpty) return;
|
||||
|
||||
final seleccionadas = List<String>.from(state.seleccionadas);
|
||||
final resolvedHashes = Map<String, dynamic>.from(state.resolvedHashes);
|
||||
|
||||
for (final hash in hashes) {
|
||||
if (!seleccionadas.contains(hash)) {
|
||||
seleccionadas.add(hash);
|
||||
// Try to resolve in background
|
||||
final etiqueta = await _etiquetaRepo.resolveHash(hash);
|
||||
resolvedHashes[hash] = etiqueta;
|
||||
}
|
||||
}
|
||||
|
||||
emit(state.copyWith(
|
||||
seleccionadas: seleccionadas,
|
||||
resolvedHashes: resolvedHashes.cast(),
|
||||
));
|
||||
}
|
||||
|
||||
void setSeleccionadas(List<String> etiquetas) {
|
||||
emit(state.copyWith(seleccionadas: etiquetas));
|
||||
}
|
||||
}
|
||||
50
lib/presentation/bloc/etiquetas/etiquetas_state.dart
Normal file
50
lib/presentation/bloc/etiquetas/etiquetas_state.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../domain/entities/etiqueta.dart';
|
||||
import '../../../domain/entities/biblioteca.dart';
|
||||
|
||||
class EtiquetasState extends Equatable {
|
||||
final List<Biblioteca> bibliotecas;
|
||||
final Map<int, List<Etiqueta>> etiquetasPorBiblioteca;
|
||||
final List<String> seleccionadas;
|
||||
final Map<String, Etiqueta?> resolvedHashes;
|
||||
final bool isLoading;
|
||||
final String? error;
|
||||
|
||||
const EtiquetasState({
|
||||
this.bibliotecas = const [],
|
||||
this.etiquetasPorBiblioteca = const {},
|
||||
this.seleccionadas = const [],
|
||||
this.resolvedHashes = const {},
|
||||
this.isLoading = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
EtiquetasState copyWith({
|
||||
List<Biblioteca>? bibliotecas,
|
||||
Map<int, List<Etiqueta>>? etiquetasPorBiblioteca,
|
||||
List<String>? seleccionadas,
|
||||
Map<String, Etiqueta?>? resolvedHashes,
|
||||
bool? isLoading,
|
||||
String? error,
|
||||
}) =>
|
||||
EtiquetasState(
|
||||
bibliotecas: bibliotecas ?? this.bibliotecas,
|
||||
etiquetasPorBiblioteca: etiquetasPorBiblioteca ?? this.etiquetasPorBiblioteca,
|
||||
seleccionadas: seleccionadas ?? this.seleccionadas,
|
||||
resolvedHashes: resolvedHashes ?? this.resolvedHashes,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
error: error,
|
||||
);
|
||||
|
||||
bool isSelected(String hash) => seleccionadas.contains(hash);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
bibliotecas,
|
||||
etiquetasPorBiblioteca,
|
||||
seleccionadas,
|
||||
resolvedHashes,
|
||||
isLoading,
|
||||
error,
|
||||
];
|
||||
}
|
||||
42
lib/presentation/bloc/packs/packs_cubit.dart
Normal file
42
lib/presentation/bloc/packs/packs_cubit.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../data/repositories/etiqueta_repository.dart';
|
||||
import '../../../domain/entities/pack.dart';
|
||||
|
||||
class PacksState extends Equatable {
|
||||
final List<Pack> packs;
|
||||
final bool isLoading;
|
||||
|
||||
const PacksState({this.packs = const [], this.isLoading = false});
|
||||
|
||||
PacksState copyWith({List<Pack>? packs, bool? isLoading}) => PacksState(
|
||||
packs: packs ?? this.packs,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [packs, isLoading];
|
||||
}
|
||||
|
||||
class PacksCubit extends Cubit<PacksState> {
|
||||
final EtiquetaRepository _repo = EtiquetaRepository();
|
||||
|
||||
PacksCubit() : super(const PacksState());
|
||||
|
||||
Future<void> load() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
final packs = await _repo.getPacks();
|
||||
emit(state.copyWith(packs: packs, isLoading: false));
|
||||
}
|
||||
|
||||
Future<void> addPack(String nombre, List<String> tags) async {
|
||||
final pack = Pack(nombre: nombre, tags: tags);
|
||||
await _repo.insertPack(pack);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> deletePack(int id) async {
|
||||
await _repo.deletePack(id);
|
||||
await load();
|
||||
}
|
||||
}
|
||||
66
lib/presentation/bloc/pendientes/pendientes_cubit.dart
Normal file
66
lib/presentation/bloc/pendientes/pendientes_cubit.dart
Normal file
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../../../data/repositories/contenedor_repository.dart';
|
||||
import '../../../domain/entities/pendiente.dart';
|
||||
import '../../../domain/entities/destino.dart';
|
||||
|
||||
class PendientesState extends Equatable {
|
||||
final List<Pendiente> pendientes;
|
||||
final bool isLoading;
|
||||
final bool queueFull;
|
||||
|
||||
const PendientesState({
|
||||
this.pendientes = const [],
|
||||
this.isLoading = false,
|
||||
this.queueFull = false,
|
||||
});
|
||||
|
||||
PendientesState copyWith({
|
||||
List<Pendiente>? pendientes,
|
||||
bool? isLoading,
|
||||
bool? queueFull,
|
||||
}) =>
|
||||
PendientesState(
|
||||
pendientes: pendientes ?? this.pendientes,
|
||||
isLoading: isLoading ?? this.isLoading,
|
||||
queueFull: queueFull ?? this.queueFull,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [pendientes, isLoading, queueFull];
|
||||
}
|
||||
|
||||
class PendientesCubit extends Cubit<PendientesState> {
|
||||
final ContenedorRepository _repo = ContenedorRepository();
|
||||
|
||||
PendientesCubit() : super(const PendientesState());
|
||||
|
||||
Future<void> load() async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
final pendientes = await _repo.getPendientes();
|
||||
emit(state.copyWith(
|
||||
pendientes: pendientes,
|
||||
isLoading: false,
|
||||
queueFull: pendientes.length >= 20,
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> reintentar(Pendiente pendiente, Destino destino) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
await _repo.reintentar(pendiente, destino);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> eliminar(String hash) async {
|
||||
await _repo.eliminarPendiente(hash);
|
||||
await load();
|
||||
}
|
||||
|
||||
Future<void> reintentarTodos(Destino destino) async {
|
||||
emit(state.copyWith(isLoading: true));
|
||||
for (final p in state.pendientes.where((p) => p.puedeReintentar)) {
|
||||
await _repo.reintentar(p, destino);
|
||||
}
|
||||
await load();
|
||||
}
|
||||
}
|
||||
311
lib/presentation/pages/captura_page.dart
Normal file
311
lib/presentation/pages/captura_page.dart
Normal file
@@ -0,0 +1,311 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../bloc/captura/captura_cubit.dart';
|
||||
import '../bloc/captura/captura_state.dart';
|
||||
import '../bloc/etiquetas/etiquetas_cubit.dart';
|
||||
import '../bloc/app/app_cubit.dart';
|
||||
import '../bloc/app/app_state.dart';
|
||||
import '../widgets/audio_recorder.dart';
|
||||
import '../../core/utils/hash_utils.dart';
|
||||
|
||||
class CapturaPage extends StatelessWidget {
|
||||
const CapturaPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<CapturaCubit, CapturaState>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// Hash section
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.tag, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Hash', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy, size: 20),
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: state.contenedor.hash));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Hash copiado')),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.refresh, size: 20),
|
||||
onPressed: () => context.read<CapturaCubit>().regenerateHash(),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
HashUtils.truncateHash(state.contenedor.hash, length: 32),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Title & Description
|
||||
TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Título (opcional)',
|
||||
prefixIcon: Icon(Icons.title),
|
||||
),
|
||||
onChanged: (v) => context.read<CapturaCubit>().setTitulo(v),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Descripción (opcional)',
|
||||
prefixIcon: Icon(Icons.description),
|
||||
),
|
||||
maxLines: 2,
|
||||
onChanged: (v) => context.read<CapturaCubit>().setDescripcion(v),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Capture buttons
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('Capturar', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
_CaptureButton(
|
||||
icon: Icons.camera_alt,
|
||||
label: 'Foto',
|
||||
onPressed: () => context.read<CapturaCubit>().capturePhoto(),
|
||||
),
|
||||
AudioRecorderButton(
|
||||
onRecorded: (bytes, name) {
|
||||
context.read<CapturaCubit>().addAudioFile(bytes, name);
|
||||
},
|
||||
),
|
||||
_CaptureButton(
|
||||
icon: Icons.videocam,
|
||||
label: 'Video',
|
||||
onPressed: () => context.read<CapturaCubit>().captureVideo(),
|
||||
),
|
||||
_CaptureButton(
|
||||
icon: Icons.attach_file,
|
||||
label: 'Archivo',
|
||||
onPressed: () => context.read<CapturaCubit>().pickFile(),
|
||||
),
|
||||
_CaptureButton(
|
||||
icon: state.contenedor.gps != null
|
||||
? Icons.location_on
|
||||
: Icons.location_off,
|
||||
label: 'GPS',
|
||||
onPressed: () {
|
||||
if (state.contenedor.gps != null) {
|
||||
context.read<CapturaCubit>().clearGps();
|
||||
} else {
|
||||
context.read<CapturaCubit>().captureGps();
|
||||
}
|
||||
},
|
||||
selected: state.contenedor.gps != null,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Attached files
|
||||
if (state.contenedor.archivos.isNotEmpty) ...[
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Archivos (${state.contenedor.archivos.length})',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
...state.contenedor.archivos.asMap().entries.map((e) {
|
||||
final archivo = e.value;
|
||||
return ListTile(
|
||||
leading: Icon(_getFileIcon(archivo.tipo)),
|
||||
title: Text(archivo.nombre),
|
||||
subtitle: Text(archivo.sizeFormatted),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: () =>
|
||||
context.read<CapturaCubit>().removeArchivo(e.key),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Etiquetas summary
|
||||
BlocBuilder<EtiquetasCubit, dynamic>(
|
||||
builder: (context, etState) {
|
||||
final seleccionadas = (etState as dynamic).seleccionadas as List<String>;
|
||||
if (seleccionadas.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Etiquetas (${seleccionadas.length})',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: seleccionadas
|
||||
.map((h) => Chip(
|
||||
label: Text(HashUtils.truncateHash(h)),
|
||||
onDeleted: () =>
|
||||
context.read<EtiquetasCubit>().removeEtiqueta(h),
|
||||
))
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
// GPS info
|
||||
if (state.contenedor.gps != null) ...[
|
||||
const SizedBox(height: 16),
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.location_on, color: Colors.green),
|
||||
title: const Text('Ubicación'),
|
||||
subtitle: Text(state.contenedor.gps!.toString()),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Send button
|
||||
BlocBuilder<AppCubit, AppState>(
|
||||
builder: (context, appState) {
|
||||
final destino = appState.destinoActivo;
|
||||
return FilledButton.icon(
|
||||
onPressed: destino != null && state.status != CapturaStatus.sending
|
||||
? () {
|
||||
final etiquetas = context
|
||||
.read<EtiquetasCubit>()
|
||||
.state
|
||||
.seleccionadas;
|
||||
context.read<CapturaCubit>().setEtiquetas(etiquetas);
|
||||
context.read<CapturaCubit>().enviar(destino);
|
||||
}
|
||||
: null,
|
||||
icon: state.status == CapturaStatus.sending
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.send),
|
||||
label: Text(state.status == CapturaStatus.sending
|
||||
? 'Enviando...'
|
||||
: 'Enviar'),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
if (state.status == CapturaStatus.error && state.errorMessage != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: Text(
|
||||
state.errorMessage!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
IconData _getFileIcon(dynamic tipo) {
|
||||
switch (tipo.toString()) {
|
||||
case 'FileType.image':
|
||||
return Icons.image;
|
||||
case 'FileType.audio':
|
||||
return Icons.audiotrack;
|
||||
case 'FileType.video':
|
||||
return Icons.videocam;
|
||||
default:
|
||||
return Icons.insert_drive_file;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _CaptureButton extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final VoidCallback onPressed;
|
||||
final bool selected;
|
||||
|
||||
const _CaptureButton({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onPressed,
|
||||
this.selected = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FilledButton.tonal(
|
||||
onPressed: onPressed,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: selected ? Theme.of(context).colorScheme.primaryContainer : null,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 18),
|
||||
const SizedBox(width: 4),
|
||||
Text(label),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
303
lib/presentation/pages/config_page.dart
Normal file
303
lib/presentation/pages/config_page.dart
Normal file
@@ -0,0 +1,303 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../bloc/app/app_cubit.dart';
|
||||
import '../bloc/app/app_state.dart';
|
||||
import '../bloc/etiquetas/etiquetas_cubit.dart';
|
||||
import '../bloc/etiquetas/etiquetas_state.dart';
|
||||
import '../../domain/entities/destino.dart';
|
||||
import '../../domain/entities/biblioteca.dart';
|
||||
import '../../data/repositories/config_repository.dart';
|
||||
|
||||
class ConfigPage extends StatelessWidget {
|
||||
const ConfigPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
// Destinos section
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.cloud_upload),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'Destinos',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: () => _showDestinoDialog(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
BlocBuilder<AppCubit, AppState>(
|
||||
builder: (context, state) {
|
||||
if (state.destinos.isEmpty) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No hay destinos configurados'),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: state.destinos.map((destino) {
|
||||
final isActive = state.destinoActivo?.id == destino.id;
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
isActive ? Icons.radio_button_checked : Icons.radio_button_off,
|
||||
color: isActive ? Theme.of(context).colorScheme.primary : null,
|
||||
),
|
||||
title: Text(destino.nombre),
|
||||
subtitle: Text(
|
||||
destino.url,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
onPressed: () => context.read<AppCubit>().removeDestino(destino.id!),
|
||||
),
|
||||
onTap: () => context.read<AppCubit>().setDestinoActivo(destino),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Bibliotecas section
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.library_books),
|
||||
const SizedBox(width: 8),
|
||||
const Text(
|
||||
'Bibliotecas',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: () => _showBibliotecaDialog(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
BlocBuilder<EtiquetasCubit, EtiquetasState>(
|
||||
builder: (context, state) {
|
||||
if (state.bibliotecas.isEmpty) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text('No hay bibliotecas configuradas'),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
children: state.bibliotecas.map((bib) {
|
||||
final etiquetas = state.etiquetasPorBiblioteca[bib.id] ?? [];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.folder),
|
||||
title: Text(bib.nombre),
|
||||
subtitle: Text(
|
||||
'${bib.url}${bib.endpoint}\n${etiquetas.length} etiquetas en cache',
|
||||
),
|
||||
isThreeLine: true,
|
||||
trailing: IconButton(
|
||||
icon: const Icon(Icons.sync),
|
||||
onPressed: () =>
|
||||
context.read<EtiquetasCubit>().syncBiblioteca(bib.id!),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// App info
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Información',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const ListTile(
|
||||
title: Text('Packet'),
|
||||
subtitle: Text('v1.0.0'),
|
||||
leading: Icon(Icons.apps),
|
||||
),
|
||||
const ListTile(
|
||||
title: Text('Biblioteca HST'),
|
||||
subtitle: Text('tzrtech.org'),
|
||||
leading: Icon(Icons.link),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showDestinoDialog(BuildContext context) {
|
||||
final nombreController = TextEditingController();
|
||||
final urlController = TextEditingController();
|
||||
final hashController = TextEditingController();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Nuevo Destino'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: nombreController,
|
||||
decoration: const InputDecoration(labelText: 'Nombre'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: urlController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'URL',
|
||||
hintText: 'https://api.example.com',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: hashController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Llave (hash 64 chars)',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
if (nombreController.text.isNotEmpty &&
|
||||
urlController.text.isNotEmpty &&
|
||||
hashController.text.length == 64) {
|
||||
context.read<AppCubit>().addDestino(Destino(
|
||||
nombre: nombreController.text,
|
||||
url: urlController.text,
|
||||
hash: hashController.text,
|
||||
));
|
||||
Navigator.pop(ctx);
|
||||
}
|
||||
},
|
||||
child: const Text('Guardar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showBibliotecaDialog(BuildContext context) {
|
||||
final nombreController = TextEditingController();
|
||||
final urlController = TextEditingController();
|
||||
final endpointController = TextEditingController(text: '/api/tags');
|
||||
final configRepo = ConfigRepository();
|
||||
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Nueva Biblioteca'),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextField(
|
||||
controller: nombreController,
|
||||
decoration: const InputDecoration(labelText: 'Nombre'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: urlController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'URL',
|
||||
hintText: 'https://example.com',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: endpointController,
|
||||
decoration: const InputDecoration(labelText: 'Endpoint'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
if (nombreController.text.isNotEmpty && urlController.text.isNotEmpty) {
|
||||
await configRepo.insertBiblioteca(Biblioteca(
|
||||
nombre: nombreController.text,
|
||||
url: urlController.text,
|
||||
endpoint: endpointController.text,
|
||||
));
|
||||
if (ctx.mounted) {
|
||||
Navigator.pop(ctx);
|
||||
context.read<EtiquetasCubit>().init();
|
||||
}
|
||||
}
|
||||
},
|
||||
child: const Text('Guardar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
235
lib/presentation/pages/etiquetas_page.dart
Normal file
235
lib/presentation/pages/etiquetas_page.dart
Normal file
@@ -0,0 +1,235 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import '../bloc/etiquetas/etiquetas_cubit.dart';
|
||||
import '../bloc/etiquetas/etiquetas_state.dart';
|
||||
import '../../core/utils/hash_utils.dart';
|
||||
|
||||
class EtiquetasPage extends StatefulWidget {
|
||||
const EtiquetasPage({super.key});
|
||||
|
||||
@override
|
||||
State<EtiquetasPage> createState() => _EtiquetasPageState();
|
||||
}
|
||||
|
||||
class _EtiquetasPageState extends State<EtiquetasPage> {
|
||||
final _hashController = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hashController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<EtiquetasCubit, EtiquetasState>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () async {
|
||||
for (final bib in state.bibliotecas) {
|
||||
if (bib.id != null) {
|
||||
await context.read<EtiquetasCubit>().syncBiblioteca(bib.id!);
|
||||
}
|
||||
}
|
||||
},
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
// External hash input
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Añadir hash externo',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _hashController,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Pegar URL o hash...',
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: () {
|
||||
context
|
||||
.read<EtiquetasCubit>()
|
||||
.addHashExterno(_hashController.text);
|
||||
_hashController.clear();
|
||||
},
|
||||
),
|
||||
),
|
||||
onSubmitted: (v) {
|
||||
context.read<EtiquetasCubit>().addHashExterno(v);
|
||||
_hashController.clear();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Selected tags
|
||||
if (state.seleccionadas.isNotEmpty) ...[
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
'Seleccionadas (${state.seleccionadas.length})',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.read<EtiquetasCubit>().clearSeleccion(),
|
||||
child: const Text('Limpiar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: state.seleccionadas.map((hash) {
|
||||
final resolved = state.resolvedHashes[hash];
|
||||
return Chip(
|
||||
avatar: resolved?.imagenUrl != null
|
||||
? CircleAvatar(
|
||||
backgroundImage: CachedNetworkImageProvider(
|
||||
resolved!.imagenUrl!,
|
||||
),
|
||||
)
|
||||
: const CircleAvatar(child: Icon(Icons.tag, size: 16)),
|
||||
label: Text(resolved?.displayName ??
|
||||
HashUtils.truncateHash(hash)),
|
||||
onDeleted: () =>
|
||||
context.read<EtiquetasCubit>().removeEtiqueta(hash),
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
|
||||
// Bibliotecas
|
||||
...state.bibliotecas.map((biblioteca) {
|
||||
final etiquetas = state.etiquetasPorBiblioteca[biblioteca.id] ?? [];
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
biblioteca.nombre,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
const Spacer(),
|
||||
if (etiquetas.isEmpty)
|
||||
TextButton.icon(
|
||||
onPressed: () => context
|
||||
.read<EtiquetasCubit>()
|
||||
.syncBiblioteca(biblioteca.id!),
|
||||
icon: const Icon(Icons.download, size: 18),
|
||||
label: const Text('Cargar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (etiquetas.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 4,
|
||||
crossAxisSpacing: 8,
|
||||
mainAxisSpacing: 8,
|
||||
),
|
||||
itemCount: etiquetas.length,
|
||||
itemBuilder: (context, index) {
|
||||
final etiqueta = etiquetas[index];
|
||||
final isSelected = state.isSelected(etiqueta.hMaestro);
|
||||
return InkWell(
|
||||
onTap: () => context
|
||||
.read<EtiquetasCubit>()
|
||||
.toggleEtiqueta(etiqueta.hMaestro),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: isSelected
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: Colors.grey.shade300,
|
||||
width: isSelected ? 2 : 1,
|
||||
),
|
||||
color: isSelected
|
||||
? Theme.of(context)
|
||||
.colorScheme
|
||||
.primaryContainer
|
||||
.withOpacity(0.3)
|
||||
: null,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (etiqueta.imagenUrl != null)
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: CachedNetworkImage(
|
||||
imageUrl: etiqueta.imagenUrl!,
|
||||
fit: BoxFit.contain,
|
||||
placeholder: (_, __) =>
|
||||
const Icon(Icons.image),
|
||||
errorWidget: (_, __, ___) =>
|
||||
const Icon(Icons.tag),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
const Icon(Icons.tag),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(4),
|
||||
child: Text(
|
||||
etiqueta.ref ?? etiqueta.displayName,
|
||||
style: const TextStyle(fontSize: 10),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
141
lib/presentation/pages/packs_page.dart
Normal file
141
lib/presentation/pages/packs_page.dart
Normal file
@@ -0,0 +1,141 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../bloc/packs/packs_cubit.dart';
|
||||
import '../bloc/etiquetas/etiquetas_cubit.dart';
|
||||
import '../bloc/etiquetas/etiquetas_state.dart';
|
||||
|
||||
class PacksPage extends StatelessWidget {
|
||||
const PacksPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<PacksCubit, PacksState>(
|
||||
builder: (context, state) {
|
||||
if (state.isLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
body: state.packs.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.inventory_2_outlined,
|
||||
size: 64, color: Colors.grey.shade400),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No hay packs',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text('Crea uno seleccionando etiquetas'),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: state.packs.length,
|
||||
itemBuilder: (context, index) {
|
||||
final pack = state.packs[index];
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: Text(pack.icono, style: const TextStyle(fontSize: 24)),
|
||||
title: Text(pack.nombre),
|
||||
subtitle: Text('${pack.tagCount} etiquetas'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.play_arrow),
|
||||
onPressed: () {
|
||||
context.read<EtiquetasCubit>().setSeleccionadas(pack.tags);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Pack "${pack.nombre}" aplicado'),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
onPressed: () => _confirmDelete(context, pack),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
floatingActionButton: BlocBuilder<EtiquetasCubit, EtiquetasState>(
|
||||
builder: (context, etState) {
|
||||
if (etState.seleccionadas.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return FloatingActionButton.extended(
|
||||
onPressed: () => _showCreateDialog(context, etState.seleccionadas),
|
||||
icon: const Icon(Icons.add),
|
||||
label: Text('Crear (${etState.seleccionadas.length})'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _showCreateDialog(BuildContext context, List<String> tags) {
|
||||
final controller = TextEditingController();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Nuevo Pack'),
|
||||
content: TextField(
|
||||
controller: controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nombre del pack',
|
||||
),
|
||||
autofocus: true,
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
if (controller.text.isNotEmpty) {
|
||||
context.read<PacksCubit>().addPack(controller.text, tags);
|
||||
Navigator.pop(ctx);
|
||||
}
|
||||
},
|
||||
child: const Text('Crear'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _confirmDelete(BuildContext context, dynamic pack) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Eliminar pack'),
|
||||
content: Text('¿Eliminar "${pack.nombre}"?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text('Cancelar'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
context.read<PacksCubit>().deletePack(pack.id);
|
||||
Navigator.pop(ctx);
|
||||
},
|
||||
child: const Text('Eliminar'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
223
lib/presentation/pages/pendientes_page.dart
Normal file
223
lib/presentation/pages/pendientes_page.dart
Normal file
@@ -0,0 +1,223 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../bloc/pendientes/pendientes_cubit.dart';
|
||||
import '../bloc/app/app_cubit.dart';
|
||||
import '../bloc/app/app_state.dart';
|
||||
import '../../core/utils/hash_utils.dart';
|
||||
import '../../core/utils/retry_utils.dart';
|
||||
|
||||
class PendientesPage extends StatelessWidget {
|
||||
const PendientesPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<PendientesCubit, PendientesState>(
|
||||
builder: (context, state) {
|
||||
if (state.isLoading) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
if (state.queueFull)
|
||||
Container(
|
||||
width: double.infinity,
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.warning,
|
||||
color: Theme.of(context).colorScheme.error),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Cola llena (20/20). Libera espacio para continuar.',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: state.pendientes.isEmpty
|
||||
? Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.check_circle_outline,
|
||||
size: 64, color: Colors.green.shade400),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Sin pendientes',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: RefreshIndicator(
|
||||
onRefresh: () => context.read<PendientesCubit>().load(),
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: state.pendientes.length,
|
||||
itemBuilder: (context, index) {
|
||||
final pendiente = state.pendientes[index];
|
||||
final dateFormat = DateFormat('HH:mm dd/MM');
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
pendiente.puedeReintentar
|
||||
? Icons.schedule
|
||||
: Icons.error,
|
||||
color: pendiente.puedeReintentar
|
||||
? Colors.orange
|
||||
: Colors.red,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment:
|
||||
CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
pendiente.titulo ?? 'Sin título',
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(
|
||||
HashUtils.truncateHash(
|
||||
pendiente.hash),
|
||||
style: TextStyle(
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 12,
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
_InfoChip(
|
||||
icon: Icons.repeat,
|
||||
label: '${pendiente.intentos}/20',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (pendiente.ultimoIntento != null)
|
||||
_InfoChip(
|
||||
icon: Icons.access_time,
|
||||
label: dateFormat
|
||||
.format(pendiente.ultimoIntento!),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
if (pendiente.proximoIntento != null)
|
||||
_InfoChip(
|
||||
icon: Icons.timer,
|
||||
label: RetryUtils.formatTimeRemaining(
|
||||
pendiente.proximoIntento!),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton.icon(
|
||||
onPressed: () => context
|
||||
.read<PendientesCubit>()
|
||||
.eliminar(pendiente.hash),
|
||||
icon: const Icon(Icons.download),
|
||||
label: const Text('Recuperar'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
BlocBuilder<AppCubit, AppState>(
|
||||
builder: (context, appState) {
|
||||
return FilledButton.icon(
|
||||
onPressed: pendiente.puedeReintentar &&
|
||||
appState.destinoActivo !=
|
||||
null
|
||||
? () => context
|
||||
.read<PendientesCubit>()
|
||||
.reintentar(
|
||||
pendiente,
|
||||
appState.destinoActivo!,
|
||||
)
|
||||
: null,
|
||||
icon: const Icon(Icons.replay),
|
||||
label: const Text('Reintentar'),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
floatingActionButton: state.pendientes.isNotEmpty
|
||||
? BlocBuilder<AppCubit, AppState>(
|
||||
builder: (context, appState) {
|
||||
return FloatingActionButton.extended(
|
||||
onPressed: appState.destinoActivo != null
|
||||
? () => context
|
||||
.read<PendientesCubit>()
|
||||
.reintentarTodos(appState.destinoActivo!)
|
||||
: null,
|
||||
icon: const Icon(Icons.replay),
|
||||
label: const Text('Reintentar todos'),
|
||||
);
|
||||
},
|
||||
)
|
||||
: null,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoChip extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
const _InfoChip({required this.icon, required this.label});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade200,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 14, color: Colors.grey.shade600),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
106
lib/presentation/widgets/audio_recorder.dart
Normal file
106
lib/presentation/widgets/audio_recorder.dart
Normal file
@@ -0,0 +1,106 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:record/record.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
class AudioRecorderButton extends StatefulWidget {
|
||||
final void Function(Uint8List bytes, String nombre) onRecorded;
|
||||
|
||||
const AudioRecorderButton({super.key, required this.onRecorded});
|
||||
|
||||
@override
|
||||
State<AudioRecorderButton> createState() => _AudioRecorderButtonState();
|
||||
}
|
||||
|
||||
class _AudioRecorderButtonState extends State<AudioRecorderButton> {
|
||||
final _recorder = AudioRecorder();
|
||||
bool _isRecording = false;
|
||||
int _seconds = 0;
|
||||
Timer? _timer;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
_recorder.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _toggleRecording() async {
|
||||
if (_isRecording) {
|
||||
await _stopRecording();
|
||||
} else {
|
||||
await _startRecording();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _startRecording() async {
|
||||
final hasPermission = await _recorder.hasPermission();
|
||||
if (!hasPermission) return;
|
||||
|
||||
final dir = await getTemporaryDirectory();
|
||||
final path = '${dir.path}/audio_${DateTime.now().millisecondsSinceEpoch}.m4a';
|
||||
|
||||
await _recorder.start(
|
||||
const RecordConfig(encoder: AudioEncoder.aacLc),
|
||||
path: path,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_isRecording = true;
|
||||
_seconds = 0;
|
||||
});
|
||||
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (t) {
|
||||
setState(() => _seconds++);
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _stopRecording() async {
|
||||
_timer?.cancel();
|
||||
final path = await _recorder.stop();
|
||||
|
||||
setState(() {
|
||||
_isRecording = false;
|
||||
_seconds = 0;
|
||||
});
|
||||
|
||||
if (path != null) {
|
||||
final file = File(path);
|
||||
final bytes = await file.readAsBytes();
|
||||
final nombre = 'audio_${DateTime.now().millisecondsSinceEpoch}.m4a';
|
||||
widget.onRecorded(bytes, nombre);
|
||||
await file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
String _formatDuration(int seconds) {
|
||||
final mins = seconds ~/ 60;
|
||||
final secs = seconds % 60;
|
||||
return '${mins.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FilledButton.tonal(
|
||||
onPressed: _toggleRecording,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor:
|
||||
_isRecording ? Theme.of(context).colorScheme.errorContainer : null,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_isRecording ? Icons.stop : Icons.mic,
|
||||
size: 18,
|
||||
color: _isRecording ? Theme.of(context).colorScheme.error : null,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(_isRecording ? _formatDuration(_seconds) : 'Audio'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user