diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts index 61d1d9f..620de1a 100644 --- a/app/android/app/build.gradle.kts +++ b/app/android/app/build.gradle.kts @@ -56,6 +56,10 @@ android { } else { signingConfigs.getByName("debug") } + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) } } } diff --git a/app/android/app/proguard-rules.pro b/app/android/app/proguard-rules.pro new file mode 100644 index 0000000..e8c5a0f --- /dev/null +++ b/app/android/app/proguard-rules.pro @@ -0,0 +1,19 @@ +# Flutter ProGuard Rules +-keep class io.flutter.app.** { *; } +-keep class io.flutter.plugin.** { *; } +-keep class io.flutter.util.** { *; } +-keep class io.flutter.view.** { *; } +-keep class io.flutter.** { *; } +-keep class io.flutter.plugins.** { *; } + +# Flutter Play Core Deferred Components +-dontwarn com.google.android.play.core.** + +# Keep MainActivity +-keep class com.catellisrl.barcode_reader_app.** { *; } + +# Networking, Sockets & Wi-Fi +-keep class java.net.** { *; } +-keep class android.net.** { *; } +-keep class android.net.wifi.** { *; } + diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml index b212264..972e0cf 100644 --- a/app/android/app/src/main/AndroidManifest.xml +++ b/app/android/app/src/main/AndroidManifest.xml @@ -3,13 +3,15 @@ + + android:usesCleartextTraffic="true" + android:networkSecurityConfig="@xml/network_security_config"> + when (call.method) { + "acquireMulticastLock" -> { + try { + if (multicastLock == null) { + val wifi = applicationContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + multicastLock = wifi?.createMulticastLock("barcode_reader_multicast_lock")?.apply { + setReferenceCounted(true) + } + } + if (multicastLock?.isHeld == false) { + multicastLock?.acquire() + } + result.success(true) + } catch (e: Exception) { + result.error("LOCK_ERROR", e.message, null) + } + } + "releaseMulticastLock" -> { + try { + if (multicastLock?.isHeld == true) { + multicastLock?.release() + } + result.success(true) + } catch (e: Exception) { + result.error("LOCK_ERROR", e.message, null) + } + } + else -> result.notImplemented() + } + } + } + + override fun onDestroy() { + try { + if (multicastLock?.isHeld == true) { + multicastLock?.release() + } + } catch (_: Exception) {} + super.onDestroy() + } +} diff --git a/app/android/app/src/main/res/xml/network_security_config.xml b/app/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..a364976 --- /dev/null +++ b/app/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/app/lib/features/connection/data/datasources/connection_remote_datasource.dart b/app/lib/features/connection/data/datasources/connection_remote_datasource.dart index a061f6a..0a313ac 100644 --- a/app/lib/features/connection/data/datasources/connection_remote_datasource.dart +++ b/app/lib/features/connection/data/datasources/connection_remote_datasource.dart @@ -18,6 +18,8 @@ class ConnectionRemoteDataSource { final StreamController _serverNameController = StreamController.broadcast(); + final Map> _pendingAcks = {}; + ConnectionStatus _status = ConnectionStatus.disconnected; Stream get statusStream => _statusController.stream; @@ -80,9 +82,27 @@ class ConnectionRemoteDataSource { _serverNameController.add(serverName); _setStatus(ConnectionStatus.connected, 'Connesso a $serverName'); } - } else if (type == 'auth_error') { - _setStatus(ConnectionStatus.error, 'PIN errato: autenticazione fallita'); - _disconnectInternal(); + } else if (type == 'ack') { + final reqId = json['req_id'] as String?; + final success = json['success'] == true; + if (reqId != null && _pendingAcks.containsKey(reqId)) { + _pendingAcks.remove(reqId)?.complete(success); + } else if (_pendingAcks.isNotEmpty) { + final firstKey = _pendingAcks.keys.first; + _pendingAcks.remove(firstKey)?.complete(success); + } + } else if (type == 'paused' || type == 'auth_error' || type == 'error') { + final reqId = json['req_id'] as String?; + if (reqId != null && _pendingAcks.containsKey(reqId)) { + _pendingAcks.remove(reqId)?.complete(false); + } else if (_pendingAcks.isNotEmpty) { + final firstKey = _pendingAcks.keys.first; + _pendingAcks.remove(firstKey)?.complete(false); + } + if (type == 'auth_error') { + _setStatus(ConnectionStatus.error, 'PIN errato: autenticazione fallita'); + _disconnectInternal(); + } } } catch (_) {} } @@ -99,20 +119,36 @@ class ConnectionRemoteDataSource { // 1. Try WebSocket if connected if (_status == ConnectionStatus.connected && _channel != null) { + final reqId = 'scan_${DateTime.now().microsecondsSinceEpoch}'; + final completer = Completer(); + _pendingAcks[reqId] = completer; + try { _channel!.sink.add(jsonEncode({ 'type': 'scan', 'code': cleanCode, 'suffix': suffix, 'pin': pin, + 'req_id': reqId, })); - return true; + + final ackReceived = await completer.future.timeout( + const Duration(milliseconds: 1500), + onTimeout: () { + _pendingAcks.remove(reqId); + return false; + }, + ); + + if (ackReceived) { + return true; + } } catch (_) { - // Fallback to HTTP + _pendingAcks.remove(reqId); } } - // 2. HTTP Fallback + // 2. HTTP Fallback if WebSocket not connected or failed/timed out if (ip.isNotEmpty) { try { final uri = Uri.parse('http://$ip:$port/api/type'); @@ -125,10 +161,13 @@ class ConnectionRemoteDataSource { 'pin': pin, 'source': Platform.isAndroid ? 'Android (HTTP)' : 'iOS (HTTP)', }), - ).timeout(const Duration(seconds: 2)); + ).timeout(const Duration(milliseconds: 1500)); if (response.statusCode == 200) { - return true; + final body = jsonDecode(response.body); + if (body is Map && body['success'] == true) { + return true; + } } } catch (_) { return false; @@ -148,6 +187,14 @@ class ConnectionRemoteDataSource { _pingTimer = null; _channelSub?.cancel(); _channelSub = null; + + for (final completer in _pendingAcks.values) { + if (!completer.isCompleted) { + completer.complete(false); + } + } + _pendingAcks.clear(); + try { _channel?.sink.close(); } catch (_) {} @@ -178,4 +225,3 @@ class ConnectionRemoteDataSource { _serverNameController.close(); } } - diff --git a/app/lib/features/connection/data/datasources/udp_discovery_datasource.dart b/app/lib/features/connection/data/datasources/udp_discovery_datasource.dart index 3027b16..74b8399 100644 --- a/app/lib/features/connection/data/datasources/udp_discovery_datasource.dart +++ b/app/lib/features/connection/data/datasources/udp_discovery_datasource.dart @@ -1,10 +1,14 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'package:flutter/services.dart'; import '../../../../core/constants/app_constants.dart'; import '../../domain/entities/discovered_server.dart'; class UdpDiscoveryDataSource { + static const MethodChannel _multicastChannel = + MethodChannel('com.catellisrl.barcode_reader/multicast'); + const UdpDiscoveryDataSource(); Future> discover({ @@ -12,21 +16,71 @@ class UdpDiscoveryDataSource { }) async { final Map found = {}; RawDatagramSocket? socket; + StreamSubscription? sub; + Timer? pulseTimer1; + Timer? pulseTimer2; + + if (Platform.isAndroid) { + try { + await _multicastChannel.invokeMethod('acquireMulticastLock'); + } catch (_) {} + } + + void cleanup() { + pulseTimer1?.cancel(); + pulseTimer2?.cancel(); + sub?.cancel(); + socket?.close(); + if (Platform.isAndroid) { + try { + _multicastChannel.invokeMethod('releaseMulticastLock'); + } catch (_) {} + } + } try { socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0); socket.broadcastEnabled = true; final data = utf8.encode(AppConstants.udpDiscoveryMessage); - socket.send( - data, + + // Collect global broadcast and subnet-directed broadcast addresses + final broadcastTargets = { InternetAddress('255.255.255.255'), - AppConstants.defaultUdpDiscoveryPort, - ); + }; + + try { + final interfaces = await NetworkInterface.list( + type: InternetAddressType.IPv4, + includeLoopback: false, + ); + for (final iface in interfaces) { + for (final addr in iface.addresses) { + final parts = addr.address.split('.'); + if (parts.length == 4) { + broadcastTargets.add( + InternetAddress('${parts[0]}.${parts[1]}.${parts[2]}.255'), + ); + } + } + } + } catch (_) {} + + void sendPulse() { + for (final target in broadcastTargets) { + try { + socket?.send(data, target, AppConstants.defaultUdpDiscoveryPort); + } catch (_) {} + } + } + + sendPulse(); + pulseTimer1 = Timer(const Duration(milliseconds: 250), sendPulse); + pulseTimer2 = Timer(const Duration(milliseconds: 550), sendPulse); final completer = Completer>(); - final sub = socket.listen((event) { + sub = socket.listen((event) { if (event == RawSocketEvent.read) { final datagram = socket?.receive(); if (datagram != null) { @@ -46,17 +100,15 @@ class UdpDiscoveryDataSource { Timer(timeout, () { if (!completer.isCompleted) { - sub.cancel(); - socket?.close(); + cleanup(); completer.complete(found.values.toList()); } }); return await completer.future; } catch (_) { - socket?.close(); + cleanup(); return found.values.toList(); } } } - diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 78a4808..e72729b 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.0+1 +version: 1.0.1+2 environment: sdk: ^3.13.4 diff --git a/app/test/ack_verification_test.dart b/app/test/ack_verification_test.dart new file mode 100644 index 0000000..52c808c --- /dev/null +++ b/app/test/ack_verification_test.dart @@ -0,0 +1,107 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + HttpOverrides.global = null; + + group('ACK Verification and Timeout Tests', () { + test('sendCode returns false when server is unreachable or offline', () async { + final remote = ConnectionRemoteDataSource(); + + final result = await remote.sendCode( + code: '1234567890', + suffix: 'enter', + pin: '', + ip: '127.0.0.1', + port: 59999, // Unused port + ); + + expect(result, isFalse); + remote.dispose(); + }); + + test('sendCode returns true only when server responds with success: true', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((HttpRequest request) async { + await request.drain(); + if (request.uri.path == '/api/type') { + request.response.statusCode = 200; + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode({'status': 'ok', 'success': true})); + await request.response.close(); + } + }); + + final remote = ConnectionRemoteDataSource(); + final result = await remote.sendCode( + code: 'TEST-CODE', + suffix: 'enter', + pin: '', + ip: '127.0.0.1', + port: server.port, + ); + + expect(result, isTrue); + + await server.close(force: true); + remote.dispose(); + }); + + test('sendCode returns false when server responds with success: false (e.g. paused/error)', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((HttpRequest request) async { + await request.drain(); + if (request.uri.path == '/api/type') { + request.response.statusCode = 200; + request.response.headers.contentType = ContentType.json; + request.response.write(jsonEncode({'status': 'paused', 'success': false})); + await request.response.close(); + } + }); + + final remote = ConnectionRemoteDataSource(); + final result = await remote.sendCode( + code: 'TEST-PAUSED', + suffix: 'enter', + pin: '', + ip: '127.0.0.1', + port: server.port, + ); + + expect(result, isFalse); + + await server.close(force: true); + remote.dispose(); + }); + + test('sendCode returns false when server response times out', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((HttpRequest request) async { + await request.drain(); + await Future.delayed(const Duration(milliseconds: 2000)); + request.response.statusCode = 200; + await request.response.close(); + }); + + final remote = ConnectionRemoteDataSource(); + final stopwatch = Stopwatch()..start(); + final result = await remote.sendCode( + code: 'TEST-TIMEOUT', + suffix: 'enter', + pin: '', + ip: '127.0.0.1', + port: server.port, + ); + stopwatch.stop(); + + expect(result, isFalse); + expect(stopwatch.elapsedMilliseconds, lessThan(3500)); + + await server.close(force: true); + remote.dispose(); + }); + }); +} diff --git a/server/server_core.py b/server/server_core.py index b7b2820..217536d 100644 --- a/server/server_core.py +++ b/server/server_core.py @@ -230,7 +230,7 @@ class BarcodeServerCore: async def handle_type_post(request: web.Request) -> web.Response: if not self.is_listening: - return web.json_response({"status": "paused", "message": "Server in pausa"}, status=503) + return web.json_response({"status": "paused", "message": "Server in pausa", "success": False}, status=503) try: data = await request.json() @@ -240,10 +240,10 @@ class BarcodeServerCore: required_pin = str(self.config.get("pin", "")).strip() if required_pin and pin != required_pin: - return web.json_response({"status": "error", "message": "PIN errato"}, status=401) + return web.json_response({"status": "error", "message": "PIN errato", "success": False}, status=401) if not code: - return web.json_response({"status": "error", "message": "Nessun codice fornito"}, status=400) + return web.json_response({"status": "error", "message": "Nessun codice fornito", "success": False}, status=400) suffix = data.get("suffix") or self.config.get("suffix", "enter") success = await self.kb.type_text(code, suffix=suffix) @@ -259,7 +259,7 @@ class BarcodeServerCore: return web.json_response({"status": "ok", "typed": code, "success": success}) except Exception as e: - return web.json_response({"status": "error", "message": str(e)}, status=500) + return web.json_response({"status": "error", "message": str(e), "success": False}, status=500) async def handle_websocket(request: web.Request) -> web.WebSocketResponse: ws = web.WebSocketResponse(heartbeat=25.0) @@ -301,12 +301,23 @@ class BarcodeServerCore: }) elif msg_type == "scan": + req_id = payload.get("req_id") if not authenticated: - await ws.send_json({"type": "auth_error", "message": "Autenticazione richiesta"}) + await ws.send_json({ + "type": "auth_error", + "message": "Autenticazione richiesta", + "req_id": req_id, + }) continue if not self.is_listening: - await ws.send_json({"type": "paused", "message": "Server in pausa"}) + await ws.send_json({ + "type": "ack", + "code": payload.get("code", ""), + "success": False, + "message": "Server in pausa", + "req_id": req_id, + }) continue code = str(payload.get("code", "")).strip() @@ -323,12 +334,25 @@ class BarcodeServerCore: if self.on_scan: self.on_scan(code, client_name, success) - await ws.send_json({ + ack_data = { "type": "ack", "code": code, "success": success, "time": timestamp, - }) + } + if req_id is not None: + ack_data["req_id"] = req_id + await ws.send_json(ack_data) + else: + ack_data = { + "type": "ack", + "code": "", + "success": False, + "message": "Codice vuoto", + } + if req_id is not None: + ack_data["req_id"] = req_id + await ws.send_json(ack_data) elif msg_type == "ping": await ws.send_json({"type": "pong"})