17 Commits
Author SHA1 Message Date
brontomark 0fbcbe5146 v
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Successful in 1m8s
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Failing after 1m41s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Failing after 3s
2026-11-22 10:48:19 +01:00
brontomark 58b9a8543f ci 2026-11-22 10:47:38 +01:00
brontomark 08aeaa3f42 rc
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Canceled after 0s
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Canceled after 0s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Canceled after 22s
2026-11-21 08:18:01 +01:00
brontomark 57e75068ac v 2026-11-15 14:39:15 +01:00
brontomark 8bfe077108 test ads 2026-11-15 13:25:45 +01:00
brontomark 28009867d8 fix 2026-11-15 12:18:00 +01:00
brontomark 1f2fcb68ea fix 2026-11-15 12:02:40 +01:00
brontomark dfe5dd6eb7 admob e icone 2026-11-15 11:30:43 +01:00
brontomark 119cc4993a fix modalità normale e precisione 2026-11-15 10:04:39 +01:00
brontomark b0f19ec5c7 fix overlay multipli x stesso codice 2026-11-15 09:40:29 +01:00
brontomark 579ddadeff fix code detection 2026-11-15 09:27:26 +01:00
brontomark 466f2f759e v 2026-11-14 09:46:24 +01:00
brontomark bda61b07b8 fix server 2026-11-13 19:32:31 +01:00
brontomark dbd53c17e7 fix: add certifi bundle and custom SSL context for reliable updates in bundled builds
Build and Release Barcode Reader Server (Multi-Platform) / build-linux (push) Successful in 48s
Build and Release Barcode Reader Server (Multi-Platform) / build-windows (push) Successful in 3m39s
Build and Release Barcode Reader Server (Multi-Platform) / build-macos (push) Failing after 10m57s
2026-11-13 09:44:33 +01:00
brontomark 2d94be87ae feat: add android multicast lock, network config, and connection ack handling 2026-11-13 09:25:16 +01:00
brontomark 6a8729a147 feat: configure release signing config with key.properties in android build gradle 2026-11-12 08:18:11 +01:00
brontomark fd83f6fc75 feat: add audio and vibration feedback alongside configurable scan cooldowns 2026-11-11 21:45:38 +01:00
59 changed files with 2930 additions and 156 deletions

No files matched your search

+104 -20
View File
@@ -69,14 +69,49 @@ jobs:
}
}
- name: Upload Windows Installer Asset
- name: Upload Windows Installer Asset su Gitea Release
uses: https://gitea.com/actions/release-action@main
with:
files: "server/dist/installer/BarcodeServerSetup.exe"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica Windows Installer su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if ([string]::IsNullOrWhiteSpace($env:VPS_SSH_KEY)) {
Write-Host "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
}
$VpsHost = if ([string]::IsNullOrWhiteSpace($env:VPS_HOST)) { "vps.catelli.it" } else { $env:VPS_HOST }
$VpsUser = if ([string]::IsNullOrWhiteSpace($env:VPS_USER)) { "mark" } else { $env:VPS_USER }
$Port = if ([string]::IsNullOrWhiteSpace($env:VPS_PORT)) { "22" } else { $env:VPS_PORT }
$DestDir = if ([string]::IsNullOrWhiteSpace($env:VPS_APPS_DOWNLOADS_DIR)) { "/home/mark/caddy-docker/apps.catelli.it/downloads" } else { $env:VPS_APPS_DOWNLOADS_DIR.TrimEnd('/') }
$KeyFile = Join-Path $env:TEMP ("vps_deploy_key_" + [guid]::NewGuid().ToString("N"))
try {
$NormalizedKey = $env:VPS_SSH_KEY.Replace("`r`n", "`n").TrimEnd() + "`n"
[System.IO.File]::WriteAllText($KeyFile, $NormalizedKey, (New-Object System.Text.UTF8Encoding($false)))
& icacls $KeyFile /inheritance:r /grant:r "$($env:USERNAME):(R)" | Out-Null
$SshOpts = @("-i", $KeyFile, "-o", "StrictHostKeyChecking=accept-new", "-o", "BatchMode=yes")
& ssh.exe @SshOpts -p $Port "$VpsUser@$VpsHost" "mkdir -p '$DestDir' && chmod 755 '$DestDir'"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& scp.exe @SshOpts -P $Port "server\dist\installer\BarcodeServerSetup.exe" "$VpsUser@$VpsHost`:$DestDir/BarcodeServerSetup.exe.tmp"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
& ssh.exe @SshOpts -p $Port "$VpsUser@$VpsHost" "chmod 644 '$DestDir/BarcodeServerSetup.exe.tmp' && mv -f '$DestDir/BarcodeServerSetup.exe.tmp' '$DestDir/BarcodeServerSetup.exe'"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
} finally {
if (Test-Path $KeyFile) { Remove-Item -Force $KeyFile }
}
# -----------------------------------------------------------------
# JOB 2: LINUX APPIMAGE (.AppImage)
# JOB 2: LINUX APPIMAGE (.AppImage via Docker Ubuntu 22.04)
# -----------------------------------------------------------------
build-linux:
runs-on: linux-runner
@@ -84,31 +119,53 @@ jobs:
- name: Checkout del codice
uses: actions/checkout@v3
- name: Compila binario e AppDir PySide6
- name: Prepara immagine Docker (Ubuntu 22.04 / glibc compatibile)
run: |
docker build -t barcode-linux-builder -f docker/linux-appimage.Dockerfile .
- name: Build Server Linux e Genera AppImage nel container
run: |
TagVersion="${GITHUB_REF_NAME#v}"
python3 server/build_binary.py --onedir --windowed --appdir --version "$TagVersion"
docker run --rm \
-e HOST_UID="$(id -u)" \
-e HOST_GID="$(id -g)" \
-e APP_VERSION="$TagVersion" \
-v "$PWD:/workspace" \
barcode-linux-builder
- name: Scarica appimagetool se non presente
run: |
if [ ! -x /tmp/appimagetool-x86_64.AppImage ] || ! head -c 4 /tmp/appimagetool-x86_64.AppImage | grep -q "ELF"; then
rm -f /tmp/appimagetool-x86_64.AppImage
curl -fSL -o /tmp/appimagetool-x86_64.AppImage https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
chmod +x /tmp/appimagetool-x86_64.AppImage
fi
- name: Genera AppImage
run: |
ARCH=x86_64 APPIMAGE_EXTRACT_AND_RUN=1 /tmp/appimagetool-x86_64.AppImage server/dist/BarcodeServer.AppDir BarcodeServer-x86_64.AppImage
chmod +x BarcodeServer-x86_64.AppImage
APPIMAGE_EXTRACT_AND_RUN=1 ./BarcodeServer-x86_64.AppImage --version
- name: Upload Linux AppImage Asset
- name: Upload Linux AppImage Asset su Gitea Release
uses: https://gitea.com/actions/release-action@main
with:
files: "BarcodeServer-x86_64.AppImage"
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica Linux AppImage su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if [ -z "${VPS_SSH_KEY:-}" ]; then
echo "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
fi
HOST="${VPS_HOST:-vps.catelli.it}"
USER="${VPS_USER:-mark}"
PORT="${VPS_PORT:-22}"
DEST_DIR="${VPS_APPS_DOWNLOADS_DIR:-/home/mark/caddy-docker/apps.catelli.it/downloads}"
DEST_DIR="${DEST_DIR%/}"
KEY_FILE="$(mktemp)"
trap 'rm -f "$KEY_FILE"' EXIT
printf '%s\n' "$VPS_SSH_KEY" > "$KEY_FILE"
chmod 600 "$KEY_FILE"
SSH_OPTS=(-i "$KEY_FILE" -o StrictHostKeyChecking=accept-new -o BatchMode=yes)
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "mkdir -p '${DEST_DIR}' && chmod 755 '${DEST_DIR}'"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-x86_64.AppImage" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp"
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "chmod 644 '${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp' && mv -f '${DEST_DIR}/BarcodeServer-x86_64.AppImage.tmp' '${DEST_DIR}/BarcodeServer-x86_64.AppImage'"
# -----------------------------------------------------------------
# JOB 3: MACOS (.dmg e .zip per auto-update)
# -----------------------------------------------------------------
@@ -129,7 +186,7 @@ jobs:
hdiutil create -volname "Barcode Reader Server" -srcfolder "server/dist/BarcodeServer.app" -ov -format UDZO "BarcodeServer-macOS.dmg"
ditto -c -k --sequesterRsrc --keepParent "server/dist/BarcodeServer.app" "BarcodeServer-macOS.zip"
- name: Upload macOS Assets
- name: Upload macOS Assets su Gitea Release
uses: https://gitea.com/actions/release-action@main
with:
files: |
@@ -137,3 +194,30 @@ jobs:
BarcodeServer-macOS.zip
api_key: ${{ secrets.MYRELEASE_TOKEN }}
- name: Pubblica macOS DMG e ZIP su apps.catelli.it
env:
VPS_HOST: ${{ secrets.VPS_HOST }}
VPS_USER: ${{ secrets.VPS_USER }}
VPS_PORT: ${{ secrets.VPS_PORT }}
VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
VPS_APPS_DOWNLOADS_DIR: ${{ secrets.VPS_APPS_DOWNLOADS_DIR }}
run: |
if [ -z "${VPS_SSH_KEY:-}" ]; then
echo "[!] Secret VPS_SSH_KEY non configurato: salto deploy su apps.catelli.it."
exit 0
fi
HOST="${VPS_HOST:-vps.catelli.it}"
USER="${VPS_USER:-mark}"
PORT="${VPS_PORT:-22}"
DEST_DIR="${VPS_APPS_DOWNLOADS_DIR:-/home/mark/caddy-docker/apps.catelli.it/downloads}"
DEST_DIR="${DEST_DIR%/}"
KEY_FILE="$(mktemp)"
trap 'rm -f "$KEY_FILE"' EXIT
printf '%s\n' "$VPS_SSH_KEY" > "$KEY_FILE"
chmod 600 "$KEY_FILE"
SSH_OPTS=(-i "$KEY_FILE" -o StrictHostKeyChecking=accept-new -o BatchMode=yes)
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "mkdir -p '${DEST_DIR}' && chmod 755 '${DEST_DIR}'"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-macOS.dmg" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-macOS.dmg.tmp"
scp "${SSH_OPTS[@]}" -P "$PORT" "BarcodeServer-macOS.zip" "${USER}@${HOST}:${DEST_DIR}/BarcodeServer-macOS.zip.tmp"
ssh "${SSH_OPTS[@]}" -p "$PORT" "${USER}@${HOST}" "chmod 644 '${DEST_DIR}/BarcodeServer-macOS.dmg.tmp' '${DEST_DIR}/BarcodeServer-macOS.zip.tmp' && mv -f '${DEST_DIR}/BarcodeServer-macOS.dmg.tmp' '${DEST_DIR}/BarcodeServer-macOS.dmg' && mv -f '${DEST_DIR}/BarcodeServer-macOS.zip.tmp' '${DEST_DIR}/BarcodeServer-macOS.zip'"
+32 -3
View File
@@ -1,9 +1,18 @@
import java.io.FileInputStream
import java.util.Properties
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
val keystoreProperties = Properties()
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
FileInputStream(keystorePropertiesFile).use { keystoreProperties.load(it) }
}
android {
namespace = "com.catellisrl.barcode_reader_app"
compileSdk = flutter.compileSdkVersion
@@ -21,6 +30,7 @@ android {
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
multiDexEnabled = true
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
@@ -29,11 +39,26 @@ android {
versionName = flutter.versionName
}
signingConfigs {
if (keystorePropertiesFile.exists()) {
create("release") {
keyAlias = keystoreProperties.getProperty("keyAlias")
keyPassword = keystoreProperties.getProperty("keyPassword")
storeFile = keystoreProperties.getProperty("storeFile")?.let { file(it) }
storePassword = keystoreProperties.getProperty("storePassword")
}
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
signingConfig = if (keystorePropertiesFile.exists()) {
signingConfigs.getByName("release")
} else {
signingConfigs.getByName("debug")
}
isMinifyEnabled = false
isShrinkResources = false
}
}
}
@@ -44,6 +69,10 @@ kotlin {
}
}
tasks.matching { it.name.contains("AarMetadata") }.configureEach {
enabled = false
}
flutter {
source = "../.."
}
+38
View File
@@ -0,0 +1,38 @@
# 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.** { *; }
# Google Mobile Ads (AdMob)
-keep public class com.google.android.gms.ads.** {
public *;
}
-keep public class com.google.ads.** {
public *;
}
-keep class com.google.android.gms.common.** { *; }
-keep class com.google.android.gms.internal.ads.** { *; }
-dontwarn com.google.android.gms.ads.**
-dontwarn com.google.android.gms.internal.ads.**
# WebView (required by AdMob / Google Mobile Ads)
-keepclassmembers class * extends android.webkit.WebView {
public *;
}
-keep class android.webkit.** { *; }
-dontwarn android.webkit.**
+8 -1
View File
@@ -3,13 +3,15 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:label="Barcode Reader"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="true">
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name=".MainActivity"
android:exported="true"
@@ -37,6 +39,11 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- Google AdMob Application ID -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-8592989118033227~7564566063" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
@@ -1,5 +1,57 @@
package com.catellisrl.barcode_reader_app
import android.content.Context
import android.net.wifi.WifiManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
private val CHANNEL = "com.catellisrl.barcode_reader/multicast"
private var multicastLock: WifiManager.MulticastLock? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
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()
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 544 B

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 442 B

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 721 B

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 38 KiB

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
Binary file not shown.

After

Width:  |  Height:  |  Size: 898 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 595 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.
Binary file not shown.
@@ -20,6 +20,7 @@ class AppConstants {
static const String keyInactivityTimeout = 'inactivity_timeout_minutes';
static const String keySuffix = 'server_suffix';
static const String keyContinuous = 'continuous_mode';
static const String keyScanCooldownMs = 'scan_cooldown_ms';
static const String keyVibrate = 'vibrate_enabled';
static const String keySound = 'sound_enabled';
static const String keyAimMode = 'scan_aim_mode';
@@ -32,4 +33,7 @@ class AppConstants {
// Default timeout in minutes
static const int defaultInactivityTimeoutMinutes = 5;
// Default post-scan cooldown pause in milliseconds (2.5 seconds)
static const int defaultScanCooldownMs = 2500;
}
+174
View File
@@ -0,0 +1,174 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
/// Service managing Google AdMob SDK initialization and Rewarded Ads.
class AdService {
AdService();
static const String androidProductionRewardedAdUnitId =
'ca-app-pub-8592989118033227/7181422681';
// Official Google demo ad unit ID for testing rewarded video ads safely
static const String androidTestRewardedAdUnitId =
'ca-app-pub-3940256099942544/5224354917';
// Set to true only when publishing the final public release to production.
// Kept false during development and closed testing to guarantee 100% fill rate
// and prevent accidental invalid traffic strikes on the AdMob account.
static const bool useProductionAds = false;
RewardedAd? _rewardedAd;
bool _isLoading = false;
bool _isInitialized = false;
Completer<RewardedAd?>? _loadCompleter;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
String get rewardedAdUnitId {
if (useProductionAds && kReleaseMode) {
return androidProductionRewardedAdUnitId;
}
return androidTestRewardedAdUnitId;
}
bool get isInitialized => _isInitialized;
bool get isAdReady => _rewardedAd != null;
bool get isLoading => _isLoading;
Future<void> initialize() async {
if (_isFlutterTest || kIsWeb) return;
try {
await MobileAds.instance.initialize();
_isInitialized = true;
// Preload after the first UI frames have settled
Future.delayed(const Duration(seconds: 1), () {
loadRewardedAd();
});
} catch (e) {
debugPrint('AdService initialize error: $e');
}
}
Future<RewardedAd?> _requestAd(String unitId) {
final completer = Completer<RewardedAd?>();
try {
RewardedAd.load(
adUnitId: unitId,
request: const AdRequest(),
rewardedAdLoadCallback: RewardedAdLoadCallback(
onAdLoaded: (ad) {
debugPrint('RewardedAd loaded successfully with unit: $unitId');
completer.complete(ad);
},
onAdFailedToLoad: (error) {
debugPrint('RewardedAd failed for $unitId: ${error.message} (code: ${error.code})');
completer.complete(null);
},
),
);
} catch (e) {
debugPrint('RewardedAd request exception for $unitId: $e');
completer.complete(null);
}
return completer.future;
}
Future<bool> loadRewardedAd() async {
if (_isFlutterTest || kIsWeb) return true;
if (_rewardedAd != null) return true;
if (_loadCompleter != null) {
final ad = await _loadCompleter!.future;
return ad != null;
}
_loadCompleter = Completer<RewardedAd?>();
_isLoading = true;
try {
// 1. Try preferred unit (production in release, test in debug)
var ad = await _requestAd(rewardedAdUnitId);
// 2. If production has No Fill (brand new unit taking up to 24h to activate),
// fallback to Google Test Unit so testers and reviewers are never blocked!
if (ad == null && rewardedAdUnitId != androidTestRewardedAdUnitId) {
debugPrint('Production ad unit has no inventory yet. Falling back to test unit...');
ad = await _requestAd(androidTestRewardedAdUnitId);
}
_rewardedAd = ad;
_isLoading = false;
_loadCompleter?.complete(ad);
_loadCompleter = null;
return ad != null;
} catch (e) {
debugPrint('loadRewardedAd top-level error: $e');
_rewardedAd = null;
_isLoading = false;
_loadCompleter?.complete(null);
_loadCompleter = null;
return false;
}
}
Future<bool> showRewardedAd({required VoidCallback onUserEarnedReward}) async {
if (_isFlutterTest) {
onUserEarnedReward();
return true;
}
// If ad is not preloaded yet, wait up to 8s for it to load
if (_rewardedAd == null) {
debugPrint('Ad not preloaded yet, awaiting load on demand...');
final loaded = await loadRewardedAd().timeout(
const Duration(seconds: 8),
onTimeout: () => false,
);
if (!loaded || _rewardedAd == null) {
debugPrint('Ad load failed or timed out');
return false;
}
}
final completer = Completer<bool>();
final ad = _rewardedAd!;
_rewardedAd = null;
ad.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
ad.dispose();
loadRewardedAd();
if (!completer.isCompleted) completer.complete(true);
},
onAdFailedToShowFullScreenContent: (ad, error) {
debugPrint('Ad failed to show: ${error.message}');
ad.dispose();
loadRewardedAd();
if (!completer.isCompleted) completer.complete(false);
},
);
try {
await ad.show(
onUserEarnedReward: (_, reward) {
debugPrint('User earned reward: ${reward.amount} ${reward.type}');
onUserEarnedReward();
},
);
} catch (e) {
debugPrint('Exception showing ad: $e');
if (!completer.isCompleted) completer.complete(false);
}
return completer.future;
}
void dispose() {
_rewardedAd?.dispose();
_rewardedAd = null;
}
}
+133 -12
View File
@@ -1,29 +1,151 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/services.dart';
import 'package:vibration/vibration.dart';
class FeedbackService {
const FeedbackService();
Future<void> triggerScanFeedback({required bool sound, required bool vibrate}) async {
static AudioPlayer? _successPlayer;
static AudioPlayer? _errorPlayer;
static bool _audioConfigured = false;
static bool? _hasVibrator;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
static Future<void> _ensureAudioConfigured() async {
if (_audioConfigured || _isFlutterTest) return;
_audioConfigured = true;
try {
if (vibrate) {
await HapticFeedback.mediumImpact();
await AudioPlayer.global.setAudioContext(
AudioContext(
iOS: AudioContextIOS(
category: AVAudioSessionCategory.playback,
options: {AVAudioSessionOptions.mixWithOthers},
),
android: AudioContextAndroid(
isSpeakerphoneOn: false,
stayAwake: false,
contentType: AndroidContentType.sonification,
usageType: AndroidUsageType.assistanceSonification,
audioFocus: AndroidAudioFocus.none,
),
),
);
} catch (_) {}
}
static Future<AudioPlayer?> _getPlayer({required bool isError}) async {
if (_isFlutterTest) return null;
try {
await _ensureAudioConfigured();
if (isError) {
_errorPlayer ??= AudioPlayer()
..setReleaseMode(ReleaseMode.stop)
..setPlayerMode(PlayerMode.lowLatency);
return _errorPlayer;
} else {
_successPlayer ??= AudioPlayer()
..setReleaseMode(ReleaseMode.stop)
..setPlayerMode(PlayerMode.lowLatency);
return _successPlayer;
}
if (sound) {
await SystemSound.play(SystemSoundType.click);
} catch (_) {
return null;
}
}
Future<void> _playBeep({required bool isError}) async {
if (_isFlutterTest) return;
try {
final player = await _getPlayer(isError: isError);
if (player != null) {
await player.stop();
await player.play(
AssetSource(
isError ? 'sounds/beep_error.wav' : 'sounds/beep_success.wav',
),
volume: 1.0,
);
return;
}
} catch (_) {
// Fallback to system sound if asset player is unavailable
try {
await SystemSound.play(
isError ? SystemSoundType.alert : SystemSoundType.click,
);
} catch (_) {}
}
}
Future<void> _vibrate({required bool isError}) async {
if (_isFlutterTest) return;
try {
_hasVibrator ??= await Vibration.hasVibrator();
if (_hasVibrator == true) {
if (isError) {
await Vibration.vibrate(pattern: [0, 75, 65, 120]);
} else {
await Vibration.vibrate(duration: 110, amplitude: 220);
}
return;
}
} catch (_) {}
// Fallback to Flutter HapticFeedback
try {
if (isError) {
await HapticFeedback.vibrate();
} else {
await HapticFeedback.heavyImpact();
}
} catch (_) {}
}
/// Feedback confermato quando il codice è stato inviato con successo al PC.
Future<void> triggerSentSuccess({
required bool sound,
required bool vibrate,
}) async {
final futures = <Future<void>>[];
if (vibrate) futures.add(_vibrate(isError: false));
if (sound) futures.add(_playBeep(isError: false));
if (futures.isNotEmpty) {
await Future.wait(futures);
}
}
/// Feedback distinto quando l'invio al PC non è riuscito (es. PC disconnesso).
Future<void> triggerSentError({
required bool sound,
required bool vibrate,
}) async {
final futures = <Future<void>>[];
if (vibrate) futures.add(_vibrate(isError: true));
if (sound) futures.add(_playBeep(isError: true));
if (futures.isNotEmpty) {
await Future.wait(futures);
}
}
Future<void> triggerScanFeedback({
required bool sound,
required bool vibrate,
}) async {
await triggerSentSuccess(sound: sound, vibrate: vibrate);
}
Future<void> triggerSuccess() async {
try {
await HapticFeedback.heavyImpact();
} catch (_) {}
await _vibrate(isError: false);
}
Future<void> triggerError() async {
try {
await HapticFeedback.vibrate();
} catch (_) {}
await _vibrate(isError: true);
}
Future<void> triggerSelection() async {
@@ -32,4 +154,3 @@ class FeedbackService {
} catch (_) {}
}
}
@@ -0,0 +1,151 @@
import 'dart:async';
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart';
import 'package:purchases_flutter/purchases_flutter.dart';
import 'package:purchases_ui_flutter/purchases_ui_flutter.dart';
/// Service managing RevenueCat In-App Purchases, Subscriptions, Paywalls and Customer Center.
class SubscriptionService {
SubscriptionService();
// RevenueCat Google / Android API Key
static const String apiKey = 'test_WfBStIXoLdiBaGJjDFgiLQSPjnl';
// Entitlement ID granting unlimited scanning
static const String entitlementId = 'barcode_reader_pc_unlimited';
// Product IDs configured in RevenueCat
static const String productLifetime = 'lifetime';
static const String productYearly = 'yearly';
static const String productMonthly = 'monthly';
bool _isConfigured = false;
final _customerInfoController = StreamController<CustomerInfo>.broadcast();
Stream<CustomerInfo> get customerInfoStream => _customerInfoController.stream;
static bool get _isFlutterTest =>
!kIsWeb && Platform.environment.containsKey('FLUTTER_TEST');
bool get isConfigured => _isConfigured;
Future<void> initialize() async {
if (_isFlutterTest || kIsWeb) return;
try {
if (kDebugMode) {
await Purchases.setLogLevel(LogLevel.debug);
} else {
await Purchases.setLogLevel(LogLevel.info);
}
final configuration = PurchasesConfiguration(apiKey);
await Purchases.configure(configuration);
_isConfigured = true;
// Listen for real-time customer info changes (renewals, cancellations, purchases)
Purchases.addCustomerInfoUpdateListener((customerInfo) {
_customerInfoController.add(customerInfo);
});
} catch (e, stack) {
debugPrint('SubscriptionService initialize error: $e\n$stack');
}
}
/// Checks whether the user has the active premium entitlement.
Future<bool> isEntitled() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return false;
try {
final customerInfo = await Purchases.getCustomerInfo();
return isCustomerEntitled(customerInfo);
} catch (e) {
debugPrint('Error checking customer entitlement: $e');
return false;
}
}
/// Helper to verify entitlement from a [CustomerInfo] snapshot.
bool isCustomerEntitled(CustomerInfo? customerInfo) {
if (customerInfo == null) return false;
final entitlement = customerInfo.entitlements.all[entitlementId];
return entitlement != null && entitlement.isActive;
}
/// Fetches available offerings and subscription packages from RevenueCat.
Future<Offerings?> getOfferings() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return null;
try {
return await Purchases.getOfferings();
} catch (e) {
debugPrint('Error fetching offerings: $e');
return null;
}
}
/// Restores existing purchases (e.g. after reinstalling the app or switching devices).
Future<CustomerInfo?> restorePurchases() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return null;
try {
final customerInfo = await Purchases.restorePurchases();
_customerInfoController.add(customerInfo);
return customerInfo;
} catch (e) {
debugPrint('Error restoring purchases: $e');
rethrow;
}
}
/// Presents the official RevenueCat Paywall UI.
Future<PaywallResult> presentPaywall({Offering? offering}) async {
if (_isFlutterTest || kIsWeb || !_isConfigured) {
return PaywallResult.notPresented;
}
try {
final result = await RevenueCatUI.presentPaywall(offering: offering);
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
}
return result;
} catch (e) {
debugPrint('Error presenting Paywall: $e');
return PaywallResult.error;
}
}
/// Presents the Paywall only if the user does NOT have the active entitlement.
Future<PaywallResult> presentPaywallIfNeeded() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) {
return PaywallResult.notPresented;
}
try {
final result = await RevenueCatUI.presentPaywallIfNeeded(entitlementId);
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
}
return result;
} catch (e) {
debugPrint('Error presenting Paywall if needed: $e');
return PaywallResult.error;
}
}
/// Presents the official RevenueCat Customer Center to manage or cancel subscriptions.
Future<void> presentCustomerCenter() async {
if (_isFlutterTest || kIsWeb || !_isConfigured) return;
try {
await RevenueCatUI.presentCustomerCenter();
final info = await Purchases.getCustomerInfo();
_customerInfoController.add(info);
} catch (e) {
debugPrint('Error presenting Customer Center: $e');
}
}
void dispose() {
_customerInfoController.close();
}
}
@@ -18,6 +18,8 @@ class ConnectionRemoteDataSource {
final StreamController<String> _serverNameController =
StreamController<String>.broadcast();
final Map<String, Completer<bool>> _pendingAcks = {};
ConnectionStatus _status = ConnectionStatus.disconnected;
Stream<ConnectionStatus> 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<bool>();
_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();
}
}
@@ -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<List<DiscoveredServer>> discover({
@@ -12,21 +16,71 @@ class UdpDiscoveryDataSource {
}) async {
final Map<String, DiscoveredServer> 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>{
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<List<DiscoveredServer>>();
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();
}
}
}
@@ -0,0 +1,187 @@
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_ui_flutter/purchases_ui_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../../../core/services/ad_service.dart';
import '../../../../core/services/subscription_service.dart';
import 'monetization_state.dart';
class MonetizationCubit extends Cubit<MonetizationState> {
late final SharedPreferences _prefs;
late final AdService _adService;
late final SubscriptionService _subscriptionService;
Timer? _countdownTimer;
StreamSubscription? _customerInfoSub;
static const String _keyExpiresAt = 'monetization_unlimited_expires_at';
static const String _keyFreeScans = 'monetization_free_scans_remaining';
MonetizationCubit({
required SharedPreferences prefs,
required AdService adService,
required SubscriptionService subscriptionService,
}) : super(const MonetizationState()) {
_prefs = prefs;
_adService = adService;
_subscriptionService = subscriptionService;
_init();
}
void _init() {
_loadState();
_checkInitialEntitlement();
// Real-time listener for RevenueCat purchases, renewals, restorations
_customerInfoSub = _subscriptionService.customerInfoStream.listen((customerInfo) {
final isEntitled = _subscriptionService.isCustomerEntitled(customerInfo);
if (isEntitled != state.isPremium) {
emit(state.copyWith(isPremium: isEntitled));
}
});
}
Future<void> _checkInitialEntitlement() async {
final isEntitled = await _subscriptionService.isEntitled();
if (isEntitled && !isClosed) {
emit(state.copyWith(isPremium: true));
}
}
void _loadState() {
final rawExpires = _prefs.getInt(_keyExpiresAt);
final freeScans = _prefs.getInt(_keyFreeScans) ?? 15;
DateTime? expiresAt;
int seconds = 0;
if (rawExpires != null) {
final date = DateTime.fromMillisecondsSinceEpoch(rawExpires);
if (date.isAfter(DateTime.now())) {
expiresAt = date;
seconds = date.difference(DateTime.now()).inSeconds;
}
}
emit(MonetizationState(
unlimitedExpiresAt: expiresAt,
freeScansRemaining: freeScans,
remainingSeconds: seconds,
));
if (expiresAt != null && seconds > 0) {
_startCountdownTimer();
}
}
void _startCountdownTimer() {
_countdownTimer?.cancel();
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (isClosed) {
timer.cancel();
return;
}
final expires = state.unlimitedExpiresAt;
if (expires == null) {
timer.cancel();
emit(state.copyWith(clearUnlimited: true));
return;
}
final diffSeconds = expires.difference(DateTime.now()).inSeconds;
if (diffSeconds <= 0) {
timer.cancel();
emit(state.copyWith(clearUnlimited: true));
_prefs.remove(_keyExpiresAt);
} else {
emit(state.copyWith(remainingSeconds: diffSeconds));
}
});
}
/// Verifies if a scan can proceed.
/// If the user is Premium or in an active unlimited session, returns `true` immediately.
/// If using free scans, decrements count and returns `true`.
/// Returns `false` when all scans/sessions are expired.
bool tryConsumeScan() {
if (state.isPremium || state.isUnlimited) {
return true;
}
if (state.freeScansRemaining > 0) {
final nextCount = state.freeScansRemaining - 1;
emit(state.copyWith(freeScansRemaining: nextCount));
_prefs.setInt(_keyFreeScans, nextCount);
return true;
}
return false;
}
/// Grants a block of unlimited scanning (default 15 minutes) via Rewarded Ad.
Future<void> grantRewardedMinutes([int minutes = 15]) async {
final newExpires = DateTime.now().add(Duration(minutes: minutes));
await _prefs.setInt(_keyExpiresAt, newExpires.millisecondsSinceEpoch);
final seconds = newExpires.difference(DateTime.now()).inSeconds;
emit(state.copyWith(
unlimitedExpiresAt: newExpires,
remainingSeconds: seconds,
isAdLoading: false,
));
_startCountdownTimer();
}
/// Triggers the Rewarded Ad display and unlocks 15 minutes upon completion.
Future<bool> watchAdAndUnlock() async {
emit(state.copyWith(isAdLoading: true));
final success = await _adService.showRewardedAd(
onUserEarnedReward: () {
grantRewardedMinutes(15);
},
);
if (!success) {
emit(state.copyWith(isAdLoading: false));
}
return success;
}
/// Presents the official RevenueCat Paywall UI.
Future<PaywallResult> presentPaywall() async {
final result = await _subscriptionService.presentPaywall();
if (result == PaywallResult.purchased || result == PaywallResult.restored) {
emit(state.copyWith(isPremium: true));
}
return result;
}
/// Presents the RevenueCat Customer Center to view/manage subscription.
Future<void> presentCustomerCenter() async {
await _subscriptionService.presentCustomerCenter();
final isEntitled = await _subscriptionService.isEntitled();
emit(state.copyWith(isPremium: isEntitled));
}
/// Restores previous purchases across device reinstalls.
Future<bool> restorePurchases() async {
try {
final info = await _subscriptionService.restorePurchases();
final isEntitled = _subscriptionService.isCustomerEntitled(info);
emit(state.copyWith(isPremium: isEntitled));
return isEntitled;
} catch (_) {
return false;
}
}
@override
Future<void> close() {
_countdownTimer?.cancel();
_customerInfoSub?.cancel();
return super.close();
}
}
@@ -0,0 +1,65 @@
import 'package:equatable/equatable.dart';
class MonetizationState extends Equatable {
final DateTime? unlimitedExpiresAt;
final int freeScansRemaining;
final bool isAdLoading;
final int remainingSeconds;
final bool isPremium;
const MonetizationState({
this.unlimitedExpiresAt,
this.freeScansRemaining = 15, // 15 initial free scans for new users to test immediately
this.isAdLoading = false,
this.remainingSeconds = 0,
this.isPremium = false,
});
bool get isUnlimited {
if (isPremium) return true;
final expires = unlimitedExpiresAt;
if (expires == null) return false;
return expires.isAfter(DateTime.now()) && remainingSeconds > 0;
}
bool get canScan => isPremium || isUnlimited || freeScansRemaining > 0;
Duration get remainingDuration => Duration(seconds: remainingSeconds);
String get formattedRemainingTime {
if (isPremium) return 'Premium';
final m = remainingSeconds ~/ 60;
final s = remainingSeconds % 60;
return '${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
}
MonetizationState copyWith({
DateTime? unlimitedExpiresAt,
bool clearUnlimited = false,
int? freeScansRemaining,
bool? isAdLoading,
int? remainingSeconds,
bool? isPremium,
}) {
return MonetizationState(
unlimitedExpiresAt: clearUnlimited
? null
: (unlimitedExpiresAt ?? this.unlimitedExpiresAt),
freeScansRemaining: freeScansRemaining ?? this.freeScansRemaining,
isAdLoading: isAdLoading ?? this.isAdLoading,
remainingSeconds: clearUnlimited
? 0
: (remainingSeconds ?? this.remainingSeconds),
isPremium: isPremium ?? this.isPremium,
);
}
@override
List<Object?> get props => [
unlimitedExpiresAt,
freeScansRemaining,
isAdLoading,
remainingSeconds,
isPremium,
];
}
@@ -0,0 +1,219 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:purchases_ui_flutter/purchases_ui_flutter.dart';
import '../../../../core/theme/app_theme.dart';
import '../cubit/monetization_cubit.dart';
import '../cubit/monetization_state.dart';
/// Bottom sheet dialog prompting user to watch a rewarded video for 15 min unlimited scanning.
class RewardSessionDialog extends StatelessWidget {
const RewardSessionDialog({super.key});
static Future<bool?> show(BuildContext context) {
return showModalBottomSheet<bool>(
context: context,
backgroundColor: Colors.transparent,
isScrollControlled: true,
builder: (_) => BlocProvider.value(
value: context.read<MonetizationCubit>(),
child: const RewardSessionDialog(),
),
);
}
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(
24,
20,
24,
MediaQuery.paddingOf(context).bottom + 24,
),
decoration: const BoxDecoration(
color: AppTheme.darkCard,
borderRadius: BorderRadius.vertical(top: Radius.circular(28)),
border: Border(
top: BorderSide(color: AppTheme.darkBorder, width: 1.5),
),
),
child: BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, state) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// Drag handle
Container(
width: 40,
height: 4,
margin: const EdgeInsets.only(bottom: 20),
decoration: BoxDecoration(
color: AppTheme.darkTextSecondary.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(2),
),
),
// Icon badge
Container(
width: 64,
height: 64,
decoration: BoxDecoration(
color: AppTheme.primary.withValues(alpha: 0.15),
shape: BoxShape.circle,
border: Border.all(
color: AppTheme.primary.withValues(alpha: 0.4),
width: 2,
),
),
child: const Icon(
Icons.play_circle_fill_rounded,
color: AppTheme.primary,
size: 34,
),
),
const SizedBox(height: 16),
const Text(
'Scansioni Illimitate',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
letterSpacing: -0.4,
),
),
const SizedBox(height: 8),
Text(
'Guarda un breve video per sbloccare 15 minuti di scansioni illimitate al PC senza interruzioni.',
textAlign: TextAlign.center,
style: TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 14,
height: 1.4,
),
),
const SizedBox(height: 24),
// Watch video CTA button
SizedBox(
width: double.infinity,
height: 52,
child: FilledButton.icon(
onPressed: state.isAdLoading
? null
: () async {
final cubit = context.read<MonetizationCubit>();
final success = await cubit.watchAdAndUnlock();
if (context.mounted) {
if (success) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'15 minuti di scansioni illimitate sbloccati!',
),
duration: Duration(milliseconds: 1600),
backgroundColor: AppTheme.success,
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Caricamento video in corso... Riprova tra pochi istanti.',
),
duration: Duration(milliseconds: 1800),
backgroundColor: AppTheme.darkCard,
),
);
}
}
},
style: FilledButton.styleFrom(
backgroundColor: AppTheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
icon: state.isAdLoading
? const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Icon(Icons.ondemand_video_rounded, size: 22),
label: Text(
state.isAdLoading ? 'Caricamento video...' : 'Guarda Video (+15 min)',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Upgrade to Premium button (RevenueCat Paywall)
SizedBox(
width: double.infinity,
height: 50,
child: OutlinedButton.icon(
onPressed: () async {
final cubit = context.read<MonetizationCubit>();
final result = await cubit.presentPaywall();
if (context.mounted &&
(result == PaywallResult.purchased ||
result == PaywallResult.restored)) {
Navigator.of(context).pop(true);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('🎉 Benvenuto in Premium Illimitato!'),
backgroundColor: AppTheme.success,
duration: Duration(milliseconds: 2000),
),
);
}
},
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFFFBBF24),
side: const BorderSide(color: Color(0xFFFBBF24), width: 1.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
),
icon: const Icon(Icons.workspace_premium_rounded, size: 22),
label: const Text(
'Passa a Premium Illimitato',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
),
),
),
),
const SizedBox(height: 12),
// Cancel button
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text(
'Più tardi',
style: TextStyle(
color: AppTheme.darkTextSecondary,
fontSize: 14,
),
),
),
],
);
},
),
);
}
}
@@ -1,3 +1,6 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/services/feedback_service.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart';
@@ -12,6 +15,8 @@ class ScannerCubit extends Cubit<ScannerState> {
final HistoryCubit historyCubit;
final FeedbackService feedbackService;
Timer? _cooldownTimer;
ScannerCubit({
required this.connectionCubit,
required this.settingsCubit,
@@ -33,34 +38,48 @@ class ScannerCubit extends Cubit<ScannerState> {
emit(state.copyWith(zoomScale: clamped));
}
void clearCooldown() {
_cooldownTimer?.cancel();
_cooldownTimer = null;
if (!isClosed && (state.cooldownUntil != null || state.cooldownTotalMs != 0)) {
emit(state.copyWith(clearCooldown: true));
}
}
Future<void> processBarcode(
String rawValue, {
String format = 'Barcode',
}) async {
final cleanCode = rawValue.trim();
if (cleanCode.isEmpty) return;
if (state.isProcessing || state.isInCooldown) return;
final now = DateTime.now();
final isSameCode = cleanCode == state.lastScannedValue;
final durationSinceLast = now.difference(state.lastScannedTime);
final continuous = settingsCubit.state.settings.continuousMode;
final settings = settingsCubit.state.settings;
// Minimum debounce interval for live camera stream
final minInterval = isSameCode
? (continuous
? const Duration(milliseconds: 1000)
: const Duration(milliseconds: 1800))
: const Duration(milliseconds: 600);
// Post-scan cooldown pause: gives the operator time (default 2.5s) to
// move the camera away before the next automatic read.
final configuredCooldownMs = settings.scanCooldownMs;
final effectiveCooldownMs = (settings.continuousMode && !isSameCode)
? math.min(configuredCooldownMs, 1000)
: configuredCooldownMs;
if (durationSinceLast < minInterval || state.isProcessing) {
if (durationSinceLast < Duration(milliseconds: effectiveCooldownMs)) {
return;
}
await _sendAndRecord(cleanCode, format: format, timestamp: now);
await _sendAndRecord(
cleanCode,
format: format,
timestamp: now,
cooldownMs: effectiveCooldownMs,
);
}
/// Sends a barcode explicitly chosen by the user (e.g. from AR badge or frozen picker),
/// bypassing the live-camera debounce so rapid multi-code picking feels instant.
/// bypassing the live-camera cooldown so rapid multi-code picking feels instant.
Future<bool> sendSelectedBarcode(
String rawValue, {
String format = 'Barcode',
@@ -93,6 +112,7 @@ class ScannerCubit extends Cubit<ScannerState> {
required DateTime timestamp,
String? idOverride,
bool updateDebounceTracker = true,
int cooldownMs = 0,
}) async {
emit(state.copyWith(
isProcessing: true,
@@ -101,18 +121,23 @@ class ScannerCubit extends Cubit<ScannerState> {
));
final settings = settingsCubit.state.settings;
await feedbackService.triggerScanFeedback(
sound: settings.sound,
vibrate: settings.vibrate,
);
final success = await connectionCubit.sendCode(
code: cleanCode,
suffix: settings.suffix,
);
// Distinct audio + vibration confirmation right when the code is sent
if (success) {
await feedbackService.triggerSuccess();
await feedbackService.triggerSentSuccess(
sound: settings.sound,
vibrate: settings.vibrate,
);
} else {
await feedbackService.triggerSentError(
sound: settings.sound,
vibrate: settings.vibrate,
);
}
final record = ScanRecord(
@@ -125,11 +150,32 @@ class ScannerCubit extends Cubit<ScannerState> {
await historyCubit.addScan(record);
emit(state.copyWith(
isProcessing: false,
lastScan: record,
));
DateTime? cooldownUntil;
var activeCooldownTotalMs = 0;
if (cooldownMs > 0) {
_cooldownTimer?.cancel();
cooldownUntil = DateTime.now().add(Duration(milliseconds: cooldownMs));
activeCooldownTotalMs = cooldownMs;
_cooldownTimer = Timer(Duration(milliseconds: cooldownMs), clearCooldown);
}
if (!isClosed) {
emit(state.copyWith(
isProcessing: false,
lastScan: record,
cooldownUntil: cooldownUntil,
cooldownTotalMs: activeCooldownTotalMs,
));
}
return record;
}
@override
Future<void> close() {
_cooldownTimer?.cancel();
_cooldownTimer = null;
return super.close();
}
}
@@ -9,6 +9,8 @@ class ScannerState extends Equatable {
final String? lastScannedValue;
final DateTime lastScannedTime;
final double zoomScale;
final DateTime? cooldownUntil;
final int cooldownTotalMs;
ScannerState({
this.lastScan,
@@ -18,9 +20,14 @@ class ScannerState extends Equatable {
this.lastScannedValue,
DateTime? lastScannedTime,
this.zoomScale = 0.0,
this.cooldownUntil,
this.cooldownTotalMs = 0,
}) : lastScannedTime =
lastScannedTime ?? DateTime.fromMillisecondsSinceEpoch(0);
bool get isInCooldown =>
cooldownUntil != null && DateTime.now().isBefore(cooldownUntil!);
ScannerState copyWith({
ScanRecord? lastScan,
bool? isTorchOn,
@@ -29,6 +36,9 @@ class ScannerState extends Equatable {
String? lastScannedValue,
DateTime? lastScannedTime,
double? zoomScale,
DateTime? cooldownUntil,
int? cooldownTotalMs,
bool clearCooldown = false,
}) {
return ScannerState(
lastScan: lastScan ?? this.lastScan,
@@ -38,6 +48,10 @@ class ScannerState extends Equatable {
lastScannedValue: lastScannedValue ?? this.lastScannedValue,
lastScannedTime: lastScannedTime ?? this.lastScannedTime,
zoomScale: zoomScale ?? this.zoomScale,
cooldownUntil:
clearCooldown ? null : (cooldownUntil ?? this.cooldownUntil),
cooldownTotalMs:
clearCooldown ? 0 : (cooldownTotalMs ?? this.cooldownTotalMs),
);
}
@@ -50,5 +64,7 @@ class ScannerState extends Equatable {
lastScannedValue,
lastScannedTime,
zoomScale,
cooldownUntil,
cooldownTotalMs,
];
}
@@ -9,6 +9,9 @@ import '../../../../core/theme/app_theme.dart';
import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/widgets/connection_status_chip.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../monetization/presentation/widgets/reward_session_dialog.dart';
import '../../../settings/presentation/cubit/settings_cubit.dart';
import '../../../settings/presentation/cubit/settings_state.dart';
import '../../../settings/presentation/screens/settings_screen.dart';
@@ -27,6 +30,16 @@ import '../widgets/scanner_controls_bar.dart';
import '../widgets/scanner_overlay.dart';
import 'history_screen.dart';
class _TrackedBarcodeEntry {
DetectedBarcodeItem item;
DateTime lastSeen;
_TrackedBarcodeEntry({
required this.item,
required this.lastSeen,
});
}
class ScannerScreen extends StatefulWidget {
const ScannerScreen({super.key});
@@ -45,6 +58,9 @@ class _ScannerScreenState extends State<ScannerScreen>
bool _autoZoomedForPrecision = false;
// Live AR & Precision targeting state
final Map<String, _TrackedBarcodeEntry> _trackedArItems = {};
final Set<String> _sentLiveKeys = <String>{};
Timer? _arPruneTimer;
List<DetectedBarcodeItem> _liveArItems = const [];
int? _precisionTargetIndex;
Timer? _arDecayTimer;
@@ -66,14 +82,16 @@ class _ScannerScreenState extends State<ScannerScreen>
super.initState();
WidgetsBinding.instance.addObserver(this);
_scannerController = MobileScannerController(
detectionSpeed: DetectionSpeed.normal,
detectionTimeoutMs: 180,
cameraResolution: const Size(1920, 1080),
detectionSpeed: DetectionSpeed.unrestricted,
facing: CameraFacing.back,
torchEnabled: false,
returnImage: true,
);
_arPruneTimer = Timer.periodic(const Duration(milliseconds: 200), (_) {
_pruneExpiredArItems();
});
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkStartupConnection();
_applyInitialModeZoom();
@@ -117,6 +135,7 @@ class _ScannerScreenState extends State<ScannerScreen>
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_arDecayTimer?.cancel();
_arPruneTimer?.cancel();
_focusRingTimer?.cancel();
_scannerController.dispose();
super.dispose();
@@ -192,6 +211,8 @@ class _ScannerScreenState extends State<ScannerScreen>
if (!mounted) return;
_arDecayTimer?.cancel();
_trackedArItems.clear();
_sentLiveKeys.clear();
setState(() {
_liveArItems = const [];
_precisionTargetIndex = null;
@@ -227,13 +248,47 @@ class _ScannerScreenState extends State<ScannerScreen>
_precisionTargetIndex = null;
});
}
final barcodes = capture.barcodes;
if (barcodes.isEmpty) return;
final first = barcodes.first;
final rawValue = first.rawValue ?? first.displayValue;
if (rawValue == null || rawValue.trim().isEmpty) return;
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
final standardReticle = ScannerReticleGeometry.scanRect(
_viewportSize,
ScanAimMode.standard,
);
final items = BarcodeGeometry.mapCaptureToItems(
capture: capture,
widgetSize: _viewportSize,
deviceOrientation: deviceOrientation,
);
if (items.isNotEmpty && standardReticle != null) {
// Check barcodes whose center or bounding box falls inside the reticle
final inside = items.where((item) =>
standardReticle.contains(item.center) ||
standardReticle.overlaps(item.boundingRect)).toList();
if (inside.isEmpty) return;
// Pick the barcode closest to the reticle center
inside.sort((a, b) =>
(a.center - standardReticle.center).distanceSquared.compareTo(
(b.center - standardReticle.center).distanceSquared));
final best = inside.first;
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(
best.code,
format: best.format,
);
} else {
// Fallback if geometric mapping is unavailable
final barcodes = capture.barcodes;
if (barcodes.isEmpty) return;
final first = barcodes.first;
final rawValue = first.rawValue ?? first.displayValue;
if (rawValue == null || rawValue.trim().isEmpty) return;
final formatName = first.format.name.replaceAll('BarcodeFormat.', '');
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(rawValue, format: formatName);
}
case ScanAimMode.precision:
final items = BarcodeGeometry.mapCaptureToItems(
@@ -248,12 +303,13 @@ class _ScannerScreenState extends State<ScannerScreen>
final target = BarcodeGeometry.selectPrecisionTarget(
items: items,
crosshairCenter: crosshairCenter,
hitRadius: 16.0,
hitRadius: 24.0,
);
_updateLiveArItems(items, precisionTargetIndex: target?.index);
if (target != null) {
if (!_ensureCanScan()) return;
context.read<ScannerCubit>().processBarcode(
target.code,
format: target.format,
@@ -266,9 +322,45 @@ class _ScannerScreenState extends State<ScannerScreen>
widgetSize: _viewportSize,
deviceOrientation: deviceOrientation,
);
if (items.isEmpty) return;
_updateLiveArItems(items);
final now = DateTime.now();
// 1. Update/Add detected items into sticky cache - key is unique code to prevent duplicate badges
for (final item in items) {
final code = item.code;
if (_trackedArItems.containsKey(code)) {
final entry = _trackedArItems[code]!;
entry.item = item; // Update coordinates for smooth live tracking
entry.lastSeen = now;
} else {
_trackedArItems[code] = _TrackedBarcodeEntry(
item: item,
lastSeen: now,
);
}
}
// 2. Prune items that haven't been seen for > 2200ms
_trackedArItems.removeWhere((key, entry) =>
now.difference(entry.lastSeen) > const Duration(milliseconds: 2200));
final activeItems = _trackedArItems.values.map((e) => e.item).toList();
// Sort predictably and assign 1-based indices
final reindexed = <DetectedBarcodeItem>[];
for (var i = 0; i < activeItems.length; i++) {
final it = activeItems[i];
reindexed.add(it.copyWith(
index: i + 1,
color: kArBarcodePalette[i % kArBarcodePalette.length],
));
}
if (mounted && _frozenSnapshot == null) {
setState(() {
_liveArItems = reindexed;
});
}
final imageBytes = capture.image;
if (imageBytes != null && imageBytes.isNotEmpty) {
@@ -277,12 +369,12 @@ class _ScannerScreenState extends State<ScannerScreen>
imageSize: capture.size,
viewportSize: _viewportSize,
deviceOrientation: deviceOrientation,
items: items,
timestamp: DateTime.now(),
items: reindexed.isNotEmpty ? reindexed : items,
timestamp: now,
);
_latestArSnapshot = snapshot;
if (_pendingFreeze) {
if (_pendingFreeze && reindexed.isNotEmpty) {
_pendingFreeze = false;
_freezeWithSnapshot(snapshot);
}
@@ -290,6 +382,33 @@ class _ScannerScreenState extends State<ScannerScreen>
}
}
void _pruneExpiredArItems() {
if (!mounted || _frozenSnapshot != null) return;
final aimMode = context.read<SettingsCubit>().state.settings.aimMode;
if (aimMode != ScanAimMode.arMulti) return;
if (_trackedArItems.isEmpty && _liveArItems.isEmpty) return;
final now = DateTime.now();
final beforeCount = _trackedArItems.length;
_trackedArItems.removeWhere((key, entry) =>
now.difference(entry.lastSeen) > const Duration(milliseconds: 2200));
if (_trackedArItems.length != beforeCount) {
final activeItems = _trackedArItems.values.map((e) => e.item).toList();
final reindexed = <DetectedBarcodeItem>[];
for (var i = 0; i < activeItems.length; i++) {
final it = activeItems[i];
reindexed.add(it.copyWith(
index: i + 1,
color: kArBarcodePalette[i % kArBarcodePalette.length],
));
}
setState(() {
_liveArItems = reindexed;
});
}
}
void _updateLiveArItems(
List<DetectedBarcodeItem> items, {
int? precisionTargetIndex,
@@ -311,12 +430,21 @@ class _ScannerScreenState extends State<ScannerScreen>
void _requestFreeze() {
final snapshot = _latestArSnapshot;
final now = DateTime.now();
final isFresh = snapshot != null &&
DateTime.now().difference(snapshot.timestamp) <=
const Duration(milliseconds: 1500);
now.difference(snapshot.timestamp) <= const Duration(milliseconds: 3000);
if (isFresh) {
_freezeWithSnapshot(snapshot);
if (isFresh && (_liveArItems.isNotEmpty || snapshot.items.isNotEmpty)) {
final finalItems = _liveArItems.isNotEmpty ? _liveArItems : snapshot.items;
final readySnapshot = ArCaptureSnapshot(
imageBytes: snapshot.imageBytes,
imageSize: snapshot.imageSize,
viewportSize: snapshot.viewportSize,
deviceOrientation: snapshot.deviceOrientation,
items: finalItems,
timestamp: now,
);
_freezeWithSnapshot(readySnapshot);
return;
}
@@ -351,18 +479,37 @@ class _ScannerScreenState extends State<ScannerScreen>
});
}
bool _ensureCanScan() {
final monetization = context.read<MonetizationCubit>();
if (!monetization.tryConsumeScan()) {
RewardSessionDialog.show(context);
return false;
}
return true;
}
Future<void> _onTapArBarcode(DetectedBarcodeItem item) async {
if (!_ensureCanScan()) return;
final success = await context.read<ScannerCubit>().sendSelectedBarcode(
item.code,
format: item.format,
);
if (!mounted) return;
if (_frozenSnapshot != null && success) {
if (success) {
setState(() {
_sentFrozenKeys.add(item.selectionKey);
if (_frozenSnapshot != null) {
_sentFrozenKeys.add(item.code);
_sentFrozenKeys.add(item.selectionKey);
} else {
_sentLiveKeys.add(item.code);
_sentLiveKeys.add(item.selectionKey);
}
});
} else if (_frozenSnapshot == null) {
}
if (_frozenSnapshot == null) {
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
..showSnackBar(
@@ -379,7 +526,7 @@ class _ScannerScreenState extends State<ScannerScreen>
}
}
Future<void> _handleTapToFocus(TapUpDetails details) async {
void _handleTapToFocus(TapUpDetails details) {
if (_frozenSnapshot != null ||
_viewportSize.isEmpty ||
!_scannerController.value.isRunning) {
@@ -387,9 +534,6 @@ class _ScannerScreenState extends State<ScannerScreen>
}
final local = details.localPosition;
final rx = (local.dx / _viewportSize.width).clamp(0.0, 1.0);
final ry = (local.dy / _viewportSize.height).clamp(0.0, 1.0);
_focusRingTimer?.cancel();
setState(() {
_focusRingPosition = local;
@@ -400,9 +544,7 @@ class _ScannerScreenState extends State<ScannerScreen>
}
});
try {
await _scannerController.setFocusPoint(Offset(rx, ry));
} catch (_) {}
_feedbackService.triggerSelection();
}
void _toggleTorch() {
@@ -439,10 +581,6 @@ class _ScannerScreenState extends State<ScannerScreen>
return LayoutBuilder(
builder: (context, constraints) {
_viewportSize = constraints.biggest;
final scanWindow = ScannerReticleGeometry.scanRect(
_viewportSize,
aimMode,
);
final topSafe = MediaQuery.paddingOf(context).top + 124.0;
final bottomReserved = (lastScan != null ? 250.0 : 165.0) +
@@ -477,8 +615,6 @@ class _ScannerScreenState extends State<ScannerScreen>
},
child: MobileScanner(
controller: _scannerController,
scanWindow: scanWindow,
scanWindowUpdateThreshold: 4.0,
onDetect: _onDetect,
),
),
@@ -487,6 +623,9 @@ class _ScannerScreenState extends State<ScannerScreen>
ScannerOverlay(
aimMode: aimMode,
hasPrecisionTarget: _precisionTargetIndex != null,
cooldownUntil: scannerState.cooldownUntil,
cooldownTotalMs: scannerState.cooldownTotalMs,
lastScanSucceeded: lastScan?.sentSuccessfully ?? true,
),
// 3. Live AR Overlay (outlines in Precisione, badges in AR Multi)
@@ -497,6 +636,8 @@ class _ScannerScreenState extends State<ScannerScreen>
items: _liveArItems,
safeBounds: arSafeBounds,
showBadges: aimMode == ScanAimMode.arMulti,
allowBoxTap: true,
sentKeys: _sentLiveKeys,
highlightedIndex: aimMode == ScanAimMode.precision
? _precisionTargetIndex
: null,
@@ -522,7 +663,16 @@ class _ScannerScreenState extends State<ScannerScreen>
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Center(child: ConnectionStatusChip()),
Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 6,
children: const [
ConnectionStatusChip(),
_SessionStatusChip(),
],
),
const SizedBox(height: 10),
Row(
mainAxisAlignment:
@@ -748,3 +898,100 @@ class _CircleGlassButton extends StatelessWidget {
);
}
}
class _SessionStatusChip extends StatelessWidget {
const _SessionStatusChip();
@override
Widget build(BuildContext context) {
return BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, state) {
if (state.isPremium) {
const premiumColor = Color(0xFFFBBF24); // Gold amber
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => context.read<MonetizationCubit>().presentCustomerCenter(),
borderRadius: BorderRadius.circular(16),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: premiumColor.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: premiumColor.withValues(alpha: 0.4),
width: 1,
),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.workspace_premium_rounded,
color: premiumColor,
size: 14,
),
SizedBox(width: 5),
Text(
'💎 Premium',
style: TextStyle(
color: premiumColor,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
}
final isUnlimited = state.isUnlimited;
final color = isUnlimited
? AppTheme.success
: (state.freeScansRemaining > 0 ? AppTheme.primary : AppTheme.warning);
final label = isUnlimited
? '${state.formattedRemainingTime} Illimitati'
: (state.freeScansRemaining > 0
? '${state.freeScansRemaining} libere'
: 'Sblocca 15 min');
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () => RewardSessionDialog.show(context),
borderRadius: BorderRadius.circular(16),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: color.withValues(alpha: 0.4), width: 1),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isUnlimited ? Icons.timer_outlined : Icons.ondemand_video_rounded,
color: color,
size: 14,
),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(
color: color,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
);
},
);
}
}
@@ -35,7 +35,8 @@ class ArBarcodeOverlay extends StatelessWidget {
safeBounds: safeBounds,
measureBadge: (item) => _measureBadge(
item,
isSent: sentKeys.contains(item.selectionKey),
isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
),
)
: const <int, Rect>{};
@@ -71,7 +72,8 @@ class ArBarcodeOverlay extends StatelessWidget {
rect: rect,
child: _ArCodeBadge(
item: item,
isSent: sentKeys.contains(item.selectionKey),
isSent: sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey),
onTap: onTapBarcode != null ? () => onTapBarcode!(item) : null,
),
),
@@ -197,7 +199,8 @@ class _ArPolygonPainter extends CustomPainter {
final isPrecisionMode = !showBadges;
final isHighlighted = highlightedIndex == item.index;
final isSent = sentKeys.contains(item.selectionKey);
final isSent = sentKeys.contains(item.code) ||
sentKeys.contains(item.selectionKey);
final Color strokeColor;
final double strokeWidth;
@@ -250,7 +250,7 @@ class _ArFrozenPickerState extends State<ArFrozenPicker> {
const SizedBox(height: 8),
itemBuilder: (context, index) {
final item = snapshot.items[index];
final isSent =
final isSent = widget.sentKeys.contains(item.code) ||
widget.sentKeys.contains(item.selectionKey);
return _FrozenCodeRow(
item: item,
@@ -142,6 +142,7 @@ class _ZoomPresetsBar extends StatelessWidget {
static const _presets = [
(label: '1x', scale: 0.0),
(label: '1.5x', scale: 0.125),
(label: '2x', scale: 0.25),
(label: '3x', scale: 0.50),
];
@@ -174,7 +175,7 @@ class _ZoomPresetsBar extends StatelessWidget {
for (final preset in _presets)
_ZoomChip(
label: preset.label,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.09,
selected: !isExtraZoom && (zoomScale - preset.scale).abs() < 0.06,
onTap: () => onSelect(preset.scale),
),
if (isExtraZoom)
@@ -6,11 +6,17 @@ import '../utils/barcode_geometry.dart';
class ScannerOverlay extends StatefulWidget {
final ScanAimMode aimMode;
final bool hasPrecisionTarget;
final DateTime? cooldownUntil;
final int cooldownTotalMs;
final bool lastScanSucceeded;
const ScannerOverlay({
super.key,
this.aimMode = ScanAimMode.standard,
this.hasPrecisionTarget = false,
this.cooldownUntil,
this.cooldownTotalMs = 0,
this.lastScanSucceeded = true,
});
@override
@@ -55,10 +61,20 @@ class _ScannerOverlayState extends State<ScannerOverlay>
return const SizedBox.expand();
}
final cooldownUntil = widget.cooldownUntil;
final remainingMs = cooldownUntil != null
? cooldownUntil.difference(DateTime.now()).inMilliseconds
: 0;
final isCoolingDown = remainingMs > 0;
final cooldownColor =
widget.lastScanSucceeded ? AppTheme.success : AppTheme.warning;
final isPrecision = widget.aimMode == ScanAimMode.precision;
final accentColor = isPrecision && widget.hasPrecisionTarget
? AppTheme.success
: AppTheme.primary;
final accentColor = isCoolingDown
? cooldownColor
: (isPrecision && widget.hasPrecisionTarget
? AppTheme.success
: AppTheme.primary);
final maskAlpha = isPrecision ? 0.72 : 0.62;
final radius = isPrecision ? 14.0 : 18.0;
@@ -93,15 +109,19 @@ class _ScannerOverlayState extends State<ScannerOverlay>
),
),
// Outer border
// Outer border (+ subtle confirmation tint during cooldown)
Positioned.fromRect(
rect: scanRect,
child: Container(
child: AnimatedContainer(
duration: const Duration(milliseconds: 160),
decoration: BoxDecoration(
color: isCoolingDown
? cooldownColor.withValues(alpha: 0.14)
: Colors.transparent,
borderRadius: BorderRadius.circular(radius),
border: Border.all(
color: accentColor.withValues(alpha: 0.4),
width: 1.5,
color: accentColor.withValues(alpha: isCoolingDown ? 0.85 : 0.4),
width: isCoolingDown ? 2.0 : 1.5,
),
),
),
@@ -114,7 +134,34 @@ class _ScannerOverlayState extends State<ScannerOverlay>
radius: radius,
),
if (isPrecision)
if (isCoolingDown)
Positioned.fromRect(
rect: scanRect,
child: Center(
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: cooldownColor.withValues(alpha: 0.9),
shape: BoxShape.circle,
boxShadow: [
BoxShadow(
color: cooldownColor.withValues(alpha: 0.5),
blurRadius: 14,
spreadRadius: 2,
),
],
),
child: Icon(
widget.lastScanSucceeded
? Icons.check_rounded
: Icons.priority_high_rounded,
color: Colors.white,
size: 28,
),
),
),
)
else if (isPrecision)
_PrecisionCrosshair(
scanRect: scanRect,
accentColor: accentColor,
@@ -157,26 +204,38 @@ class _ScannerOverlayState extends State<ScannerOverlay>
},
),
// Helper text below reticle
// Cooldown pill or helper text below reticle
Positioned(
left: 20,
right: 20,
top: scanRect.bottom + 14,
child: Text(
isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco'
: 'Inquadra codice a barre o QR • Pizzica per zoomare',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
shadows: [
Shadow(color: Colors.black, blurRadius: 6),
],
),
),
child: isCoolingDown
? Center(
child: _CooldownStatusPill(
key: ValueKey(cooldownUntil),
remainingMs: remainingMs,
totalMs: widget.cooldownTotalMs > 0
? widget.cooldownTotalMs
: remainingMs,
succeeded: widget.lastScanSucceeded,
color: cooldownColor,
),
)
: Text(
isPrecision
? 'Centra il mirino sul codice • Tocca per mettere a fuoco'
: 'Inquadra codice a barre o QR • Pizzica per zoomare',
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white70,
fontSize: 12,
fontWeight: FontWeight.w500,
letterSpacing: 0.2,
shadows: [
Shadow(color: Colors.black, blurRadius: 6),
],
),
),
),
],
);
@@ -372,3 +431,89 @@ class _CornersPainter extends CustomPainter {
bool shouldRepaint(covariant _CornersPainter oldDelegate) =>
oldDelegate.color != color || oldDelegate.radius != radius;
}
class _CooldownStatusPill extends StatelessWidget {
final int remainingMs;
final int totalMs;
final bool succeeded;
final Color color;
const _CooldownStatusPill({
super.key,
required this.remainingMs,
required this.totalMs,
required this.succeeded,
required this.color,
});
@override
Widget build(BuildContext context) {
final startFraction = (remainingMs / totalMs).clamp(0.0, 1.0);
return TweenAnimationBuilder<double>(
tween: Tween(begin: startFraction, end: 0.0),
duration: Duration(milliseconds: remainingMs),
builder: (context, fraction, _) {
final secsLeft = (fraction * totalMs / 1000.0).clamp(0.0, 99.9);
final label = succeeded
? 'Inviato • Pausa ${secsLeft.toStringAsFixed(1)}s'
: 'Non inviato • Pausa ${secsLeft.toStringAsFixed(1)}s';
return Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: AppTheme.darkBackground.withValues(alpha: 0.88),
borderRadius: BorderRadius.circular(14),
border: Border.all(color: color.withValues(alpha: 0.65), width: 1.2),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.4),
blurRadius: 10,
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
succeeded
? Icons.check_circle_rounded
: Icons.warning_amber_rounded,
size: 15,
color: color,
),
const SizedBox(width: 6),
Text(
label,
style: TextStyle(
color: color,
fontSize: 12,
fontWeight: FontWeight.w700,
letterSpacing: 0.2,
),
),
],
),
const SizedBox(height: 6),
SizedBox(
width: 150,
child: ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: fraction,
minHeight: 3,
backgroundColor: color.withValues(alpha: 0.2),
valueColor: AlwaysStoppedAnimation<Color>(color),
),
),
),
],
),
);
},
);
}
}
@@ -12,6 +12,8 @@ class SettingsLocalDataSource {
final suffix =
_prefs.getString(AppConstants.keySuffix) ?? AppConstants.suffixEnter;
final continuous = _prefs.getBool(AppConstants.keyContinuous) ?? false;
final scanCooldownMs = _prefs.getInt(AppConstants.keyScanCooldownMs) ??
AppConstants.defaultScanCooldownMs;
final vibrate = _prefs.getBool(AppConstants.keyVibrate) ?? true;
final sound = _prefs.getBool(AppConstants.keySound) ?? true;
final autoConnect = _prefs.getBool(AppConstants.keyAutoConnect) ?? false;
@@ -24,6 +26,7 @@ class SettingsLocalDataSource {
return AppSettings(
suffix: suffix,
continuousMode: continuous,
scanCooldownMs: scanCooldownMs,
vibrate: vibrate,
sound: sound,
autoConnect: autoConnect,
@@ -40,6 +43,10 @@ class SettingsLocalDataSource {
await _prefs.setBool(AppConstants.keyContinuous, enabled);
}
Future<void> saveScanCooldownMs(int cooldownMs) async {
await _prefs.setInt(AppConstants.keyScanCooldownMs, cooldownMs);
}
Future<void> saveFeedbackToggles(
{required bool vibrate, required bool sound}) async {
await _prefs.setBool(AppConstants.keyVibrate, vibrate);
@@ -23,6 +23,11 @@ class SettingsRepositoryImpl implements SettingsRepository {
await _localDataSource.saveContinuousMode(enabled);
}
@override
Future<void> saveScanCooldownMs(int cooldownMs) async {
await _localDataSource.saveScanCooldownMs(cooldownMs);
}
@override
Future<void> saveFeedbackToggles(
{required bool vibrate, required bool sound}) async {
@@ -5,6 +5,7 @@ import '../../../scanner/domain/entities/scan_aim_mode.dart';
class AppSettings extends Equatable {
final String suffix; // 'enter', 'tab', 'none'
final bool continuousMode;
final int scanCooldownMs; // Default: 2500ms (2.5s pause between scans)
final bool vibrate;
final bool sound;
final bool autoConnect; // Default: false (ideal for multi-PC store)
@@ -14,6 +15,7 @@ class AppSettings extends Equatable {
const AppSettings({
this.suffix = 'enter',
this.continuousMode = false,
this.scanCooldownMs = AppConstants.defaultScanCooldownMs,
this.vibrate = true,
this.sound = true,
this.autoConnect = false,
@@ -24,6 +26,7 @@ class AppSettings extends Equatable {
AppSettings copyWith({
String? suffix,
bool? continuousMode,
int? scanCooldownMs,
bool? vibrate,
bool? sound,
bool? autoConnect,
@@ -33,6 +36,7 @@ class AppSettings extends Equatable {
return AppSettings(
suffix: suffix ?? this.suffix,
continuousMode: continuousMode ?? this.continuousMode,
scanCooldownMs: scanCooldownMs ?? this.scanCooldownMs,
vibrate: vibrate ?? this.vibrate,
sound: sound ?? this.sound,
autoConnect: autoConnect ?? this.autoConnect,
@@ -46,6 +50,7 @@ class AppSettings extends Equatable {
List<Object?> get props => [
suffix,
continuousMode,
scanCooldownMs,
vibrate,
sound,
autoConnect,
@@ -5,6 +5,7 @@ abstract class SettingsRepository {
Future<AppSettings> loadSettings();
Future<void> saveSuffix(String suffix);
Future<void> saveContinuousMode(bool enabled);
Future<void> saveScanCooldownMs(int cooldownMs);
Future<void> saveFeedbackToggles({required bool vibrate, required bool sound});
Future<void> saveAutoConnect(bool enabled);
Future<void> saveInactivityTimeout(int minutes);
@@ -30,6 +30,12 @@ class SettingsCubit extends Cubit<SettingsState> {
await _settingsRepository.saveContinuousMode(enabled);
}
Future<void> updateScanCooldownMs(int cooldownMs) async {
final updated = state.settings.copyWith(scanCooldownMs: cooldownMs);
emit(state.copyWith(settings: updated));
await _settingsRepository.saveScanCooldownMs(cooldownMs);
}
Future<void> updateFeedback({bool? vibrate, bool? sound}) async {
final updated = state.settings.copyWith(
vibrate: vibrate ?? state.settings.vibrate,
@@ -6,6 +6,8 @@ import '../../../connection/presentation/cubit/connection_cubit.dart';
import '../../../connection/presentation/cubit/connection_state.dart';
import '../../../connection/presentation/screens/connect_screen.dart';
import '../../../connection/presentation/widgets/server_selection_sheet.dart';
import '../../../monetization/presentation/cubit/monetization_cubit.dart';
import '../../../monetization/presentation/cubit/monetization_state.dart';
import '../../../scanner/domain/entities/scan_aim_mode.dart';
import '../cubit/settings_cubit.dart';
import '../cubit/settings_state.dart';
@@ -26,6 +28,99 @@ class SettingsScreen extends StatelessWidget {
return ListView(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
children: [
// Subscription & Premium Section (RevenueCat)
const _SectionHeader(title: 'PIANO & ABBONAMENTO'),
BlocBuilder<MonetizationCubit, MonetizationState>(
builder: (context, monState) {
final isPremium = monState.isPremium;
return Card(
child: Column(
children: [
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: (isPremium
? const Color(0xFFFBBF24)
: AppTheme.primary)
.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(8),
),
child: Icon(
isPremium
? Icons.workspace_premium_rounded
: Icons.lock_open_rounded,
color: isPremium
? const Color(0xFFFBBF24)
: AppTheme.primary,
size: 22,
),
),
title: Text(
isPremium ? 'Piano Premium Attivo' : 'Versione Base Gratuita',
style: const TextStyle(fontWeight: FontWeight.w600),
),
subtitle: Text(
isPremium
? 'Scansioni illimitate e zero pubblicità'
: (monState.isUnlimited
? 'Sessione attiva: ${monState.formattedRemainingTime}'
: '${monState.freeScansRemaining} scansioni libere rimanenti'),
),
trailing: isPremium
? OutlinedButton(
onPressed: () => context
.read<MonetizationCubit>()
.presentCustomerCenter(),
child: const Text('Gestisci'),
)
: FilledButton(
onPressed: () => context
.read<MonetizationCubit>()
.presentPaywall(),
style: FilledButton.styleFrom(
backgroundColor: const Color(0xFFFBBF24),
foregroundColor: Colors.black87,
),
child: const Text('Passa a Premium'),
),
),
if (!isPremium) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.restore_rounded),
title: const Text('Ripristina Acquisti'),
subtitle: const Text(
'Hai già acquistato su un altro dispositivo o reinstallato?',
),
onTap: () async {
final restored = await context
.read<MonetizationCubit>()
.restorePurchases();
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
restored
? 'Acquisti ripristinati con successo!'
: 'Nessun acquisto attivo trovato da ripristinare.',
),
backgroundColor: restored
? AppTheme.success
: AppTheme.darkCard,
),
);
}
},
),
],
],
),
);
},
),
const SizedBox(height: 14),
// PC Connection Section
const _SectionHeader(title: 'CONNESSIONE PC & NEGOZIO'),
Card(
@@ -302,6 +397,47 @@ class SettingsScreen extends StatelessWidget {
),
),
const Divider(height: 1),
ListTile(
leading: Container(
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: AppTheme.primary.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(8),
),
child: const Icon(Icons.hourglass_bottom_rounded,
color: AppTheme.primary, size: 22),
),
title: const Text('Pausa dopo scansione'),
subtitle: Text(
'Attesa di ${(settings.scanCooldownMs / 1000).toStringAsFixed(1).replaceAll('.', ',')}s prima della prossima lettura',
style: const TextStyle(fontSize: 12),
),
trailing: DropdownButton<int>(
value: settings.scanCooldownMs,
dropdownColor: AppTheme.darkCard,
style: const TextStyle(
color: AppTheme.darkTextPrimary,
fontWeight: FontWeight.bold,
),
underline: const SizedBox.shrink(),
items: const [
DropdownMenuItem(value: 1000, child: Text('1,0 sec (Rapida)')),
DropdownMenuItem(value: 2000, child: Text('2,0 sec')),
DropdownMenuItem(value: 2500, child: Text('2,5 sec (Consigliata)')),
DropdownMenuItem(value: 3000, child: Text('3,0 sec')),
DropdownMenuItem(value: 4000, child: Text('4,0 sec')),
DropdownMenuItem(value: 5000, child: Text('5,0 sec')),
],
onChanged: (val) {
if (val != null) {
context
.read<SettingsCubit>()
.updateScanCooldownMs(val);
}
},
),
),
const Divider(height: 1),
SwitchListTile(
secondary: Container(
padding: const EdgeInsets.all(8),
@@ -314,8 +450,8 @@ class SettingsScreen extends StatelessWidget {
),
title: const Text('Scansione Continua'),
subtitle: const Text(
'Continua a leggere codici in sequenza senza pause',
style: TextStyle(fontSize: 13),
'Riduce la pausa a 1,0s quando inquadri codici diversi in serie',
style: TextStyle(fontSize: 12),
),
value: settings.continuousMode,
onChanged: (val) {
+32
View File
@@ -3,7 +3,9 @@ import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'core/services/ad_service.dart';
import 'core/services/feedback_service.dart';
import 'core/services/subscription_service.dart';
import 'core/theme/app_theme.dart';
import 'features/connection/data/datasources/connection_local_datasource.dart';
import 'features/connection/data/datasources/connection_remote_datasource.dart';
@@ -12,6 +14,7 @@ import 'features/connection/data/repositories/connection_repository_impl.dart';
import 'features/connection/domain/repositories/connection_repository.dart';
import 'features/connection/presentation/cubit/connection_cubit.dart';
import 'features/connection/presentation/cubit/discovery_cubit.dart';
import 'features/monetization/presentation/cubit/monetization_cubit.dart';
import 'features/scanner/data/datasources/scan_history_datasource.dart';
import 'features/scanner/data/repositories/scan_repository_impl.dart';
import 'features/scanner/domain/repositories/scan_repository.dart';
@@ -36,6 +39,19 @@ void main() async {
// Core services
const feedbackService = FeedbackService();
final adService = AdService();
try {
await adService.initialize();
} catch (e) {
debugPrint('AdService init error: $e');
}
final subscriptionService = SubscriptionService();
try {
await subscriptionService.initialize();
} catch (e) {
debugPrint('SubscriptionService init error: $e');
}
// Repositories
final SettingsRepository settingsRepository = SettingsRepositoryImpl(
@@ -58,6 +74,9 @@ void main() async {
connectionRepository: connectionRepository,
scanRepository: scanRepository,
feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
),
);
}
@@ -67,6 +86,9 @@ class BarcodeReaderApp extends StatelessWidget {
final ConnectionRepository connectionRepository;
final ScanRepository scanRepository;
final FeedbackService feedbackService;
final AdService adService;
final SubscriptionService subscriptionService;
final SharedPreferences prefs;
const BarcodeReaderApp({
super.key,
@@ -74,12 +96,22 @@ class BarcodeReaderApp extends StatelessWidget {
required this.connectionRepository,
required this.scanRepository,
required this.feedbackService,
required this.adService,
required this.subscriptionService,
required this.prefs,
});
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<MonetizationCubit>(
create: (_) => MonetizationCubit(
prefs: prefs,
adService: adService,
subscriptionService: subscriptionService,
),
),
BlocProvider<SettingsCubit>(
create: (_) => SettingsCubit(settingsRepository)..loadSettings(),
),
@@ -6,6 +6,10 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_linux/audioplayers_linux_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin");
audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar);
}
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
@@ -5,10 +5,18 @@
import FlutterMacOS
import Foundation
import audioplayers_darwin
import device_info_plus
import mobile_scanner
import purchases_flutter
import shared_preferences_foundation
import webview_flutter_wkwebview
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin"))
PurchasesFlutterPlugin.register(with: registry.registrar(forPlugin: "PurchasesFlutterPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin"))
}
+281 -1
View File
@@ -17,6 +17,62 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.13.1"
audioplayers:
dependency: "direct main"
description:
name: audioplayers
sha256: "2ba4bb2944baacbdd5372ff8254a8e7feb8c10d7739545e392f5605a8f618745"
url: "https://pub.dev"
source: hosted
version: "6.8.1"
audioplayers_android:
dependency: transitive
description:
name: audioplayers_android
sha256: f5ff5b15620fbab8cb0849e9636c48e2b96c3f0f71723bbbe2ad3c761b205f05
url: "https://pub.dev"
source: hosted
version: "5.3.0"
audioplayers_darwin:
dependency: transitive
description:
name: audioplayers_darwin
sha256: "1ca553add991384ecf421b9569da850f3ab2472ffb83f6970b0416365abc51be"
url: "https://pub.dev"
source: hosted
version: "6.5.0"
audioplayers_linux:
dependency: transitive
description:
name: audioplayers_linux
sha256: "15178b726b7cdee5364d0463c8d445630c4e0fb7d26612b73c767e7d25de9417"
url: "https://pub.dev"
source: hosted
version: "4.3.0"
audioplayers_platform_interface:
dependency: transitive
description:
name: audioplayers_platform_interface
sha256: "765f6f0e6dca55cb471c9483fc77700564b3484d19198aca4ebb5147c6c85acb"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
audioplayers_web:
dependency: transitive
description:
name: audioplayers_web
sha256: ae1e0103c865a03e273f6d13d97b93f5595eac09915729cd5e37ef96e2857319
url: "https://pub.dev"
source: hosted
version: "5.3.0"
audioplayers_windows:
dependency: transitive
description:
name: audioplayers_windows
sha256: a70ae82bba2dfcb6eb03dd4815d737a2d46d33ea5a96a03f535cfcaac490e413
url: "https://pub.dev"
source: hosted
version: "4.4.1"
bloc:
dependency: transitive
description:
@@ -49,6 +105,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.3"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.1"
collection:
dependency: transitive
description:
@@ -73,6 +137,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.9"
device_info_plus:
dependency: transitive
description:
name: device_info_plus
sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa
url: "https://pub.dev"
source: hosted
version: "13.3.0"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46"
url: "https://pub.dev"
source: hosted
version: "8.1.0"
equatable:
dependency: "direct main"
description:
@@ -97,6 +177,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
file:
dependency: transitive
description:
@@ -105,6 +193,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -136,6 +232,22 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
google_mobile_ads:
dependency: "direct main"
description:
name: google_mobile_ads
sha256: "439e018d73b47565d1cf21410e893a8f46d5fb95110c41c266a6fb78449d7106"
url: "https://pub.dev"
source: hosted
version: "9.2.0"
hooks:
dependency: transitive
description:
name: hooks
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
http:
dependency: "direct main"
description:
@@ -160,6 +272,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
url: "https://pub.dev"
source: hosted
version: "1.0.4+1"
jni_util:
dependency: transitive
description:
@@ -200,6 +320,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.0"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
@@ -240,6 +368,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.0"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.5.0"
package_config:
dependency: transitive
description:
@@ -256,6 +392,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: transitive
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
@@ -304,6 +464,38 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
purchases_flutter:
dependency: "direct main"
description:
name: purchases_flutter
sha256: "273a98e9fe3d6a763c9c23ef1fc466b055311d40c3c87b09aef605ec398fd85f"
url: "https://pub.dev"
source: hosted
version: "11.0.3"
purchases_ui_flutter:
dependency: "direct main"
description:
name: purchases_ui_flutter
sha256: "9931ffb9729b61b667f41da213de299cff9993ecaf95f18e455aef78b02b17a8"
url: "https://pub.dev"
source: hosted
version: "11.0.3"
record_use:
dependency: transitive
description:
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
shared_preferences:
dependency: "direct main"
description:
@@ -397,6 +589,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
synchronized:
dependency: transitive
description:
name: synchronized
sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94
url: "https://pub.dev"
source: hosted
version: "3.6.1+1"
term_glyph:
dependency: transitive
description:
@@ -421,6 +621,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
uuid:
dependency: transitive
description:
name: uuid
sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd"
url: "https://pub.dev"
source: hosted
version: "4.6.0"
vector_math:
dependency: transitive
description:
@@ -429,6 +637,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.4.0"
vibration:
dependency: "direct main"
description:
name: vibration
sha256: "3424f7856b971a2ce94d22be3a3abfb5b9b5984562fdedd621f4e67574be7254"
url: "https://pub.dev"
source: hosted
version: "3.2.1"
vibration_platform_interface:
dependency: transitive
description:
name: vibration_platform_interface
sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
vm_service:
dependency: transitive
description:
@@ -461,6 +685,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.3"
webview_flutter:
dependency: transitive
description:
name: webview_flutter
sha256: d53e1ccf5516f25017e3c9d44c39034db352d20fa34fe200674270242c2c5111
url: "https://pub.dev"
source: hosted
version: "4.14.1"
webview_flutter_android:
dependency: transitive
description:
name: webview_flutter_android
sha256: "4de8b3d1ff4ebe1bdb42e68a5e4f809194a3cb0117a8f495f590004f00da3964"
url: "https://pub.dev"
source: hosted
version: "4.14.1"
webview_flutter_platform_interface:
dependency: transitive
description:
name: webview_flutter_platform_interface
sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04"
url: "https://pub.dev"
source: hosted
version: "2.15.1"
webview_flutter_wkwebview:
dependency: transitive
description:
name: webview_flutter_wkwebview
sha256: acac45e0a8d7beb1d0805521f44842f406c46eb5a69410f53d935e3c62138afc
url: "https://pub.dev"
source: hosted
version: "3.27.2"
win32:
dependency: transitive
description:
name: win32
sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d
url: "https://pub.dev"
source: hosted
version: "6.4.0"
win32_registry:
dependency: transitive
description:
name: win32_registry
sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904"
url: "https://pub.dev"
source: hosted
version: "3.0.3"
xdg_directories:
dependency: transitive
description:
@@ -469,6 +741,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.13.4 <4.0.0"
flutter: ">=3.44.0"
flutter: ">=3.47.0"
+9 -1
View File
@@ -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.10+11
environment:
sdk: ^3.13.4
@@ -40,6 +40,11 @@ dependencies:
shared_preferences: ^2.5.6
flutter_bloc: ^9.1.1
equatable: ^3.0.0
audioplayers: ^6.8.1
vibration: ^3.2.1
google_mobile_ads: ^9.2.0
purchases_flutter: ^11.0.3
purchases_ui_flutter: ^11.0.3
dev_dependencies:
flutter_test:
@@ -63,6 +68,9 @@ flutter:
# the material Icons class.
uses-material-design: true
assets:
- assets/sounds/
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
+107
View File
@@ -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();
});
});
}
+1
View File
@@ -307,6 +307,7 @@ void main() {
expect(find.text('Blocca frame (2 codici)'), findsOneWidget);
expect(find.text('1x'), findsOneWidget);
expect(find.text('1.5x'), findsOneWidget);
expect(find.text('2x'), findsOneWidget);
expect(find.text('3x'), findsOneWidget);
expect(find.text('Standard'), findsOneWidget);
@@ -0,0 +1,222 @@
import 'package:barcode_reader_app/core/services/feedback_service.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/repositories/connection_repository_impl.dart';
import 'package:barcode_reader_app/features/connection/domain/entities/discovered_server.dart';
import 'package:barcode_reader_app/features/connection/domain/entities/server_connection_info.dart';
import 'package:barcode_reader_app/features/connection/domain/repositories/connection_repository.dart';
import 'package:barcode_reader_app/features/connection/presentation/cubit/connection_cubit.dart';
import 'package:barcode_reader_app/features/scanner/data/datasources/scan_history_datasource.dart';
import 'package:barcode_reader_app/features/scanner/data/repositories/scan_repository_impl.dart';
import 'package:barcode_reader_app/features/scanner/domain/entities/scan_aim_mode.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/history_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/cubit/scanner_cubit.dart';
import 'package:barcode_reader_app/features/scanner/presentation/widgets/scanner_overlay.dart';
import 'package:barcode_reader_app/features/settings/data/datasources/settings_local_datasource.dart';
import 'package:barcode_reader_app/features/settings/data/repositories/settings_repository_impl.dart';
import 'package:barcode_reader_app/features/settings/presentation/cubit/settings_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _SpyFeedbackService extends FeedbackService {
int successCalls = 0;
int errorCalls = 0;
bool? lastSound;
bool? lastVibrate;
@override
Future<void> triggerSentSuccess({
required bool sound,
required bool vibrate,
}) async {
successCalls++;
lastSound = sound;
lastVibrate = vibrate;
}
@override
Future<void> triggerSentError({
required bool sound,
required bool vibrate,
}) async {
errorCalls++;
lastSound = sound;
lastVibrate = vibrate;
}
}
class _FakeConnectionRepository implements ConnectionRepository {
bool nextSendResult = true;
@override
ConnectionStatus get currentStatus => ConnectionStatus.connected;
@override
Stream<String> get messageStream => const Stream.empty();
@override
Stream<ConnectionStatus> get statusStream => const Stream.empty();
@override
Future<void> connect(ServerConnectionInfo info) async {}
@override
Future<void> disconnect() async {}
@override
Future<List<DiscoveredServer>> discoverServers({
Duration timeout = const Duration(seconds: 3),
}) async =>
const [];
@override
Future<List<ServerConnectionInfo>> loadFavoriteServers() async => const [];
@override
Future<ServerConnectionInfo> loadSavedConnection() async =>
const ServerConnectionInfo();
@override
Future<void> removeFavoriteServer(String id) async {}
@override
Future<void> saveConnection(ServerConnectionInfo info) async {}
@override
Future<void> saveFavoriteServer(ServerConnectionInfo server) async {}
@override
Future<bool> sendCode({
required String code,
required String suffix,
required String pin,
String? ip,
int? port,
}) async =>
nextSendResult;
@override
void dispose() {}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Scan Feedback & Cooldown Pause', () {
late SharedPreferences prefs;
late SettingsRepositoryImpl settingsRepo;
late ScanRepositoryImpl scanRepo;
late _FakeConnectionRepository fakeConnectionRepo;
late ConnectionRepositoryImpl realConnectionRepo;
setUp(() async {
SharedPreferences.setMockInitialValues({});
prefs = await SharedPreferences.getInstance();
settingsRepo = SettingsRepositoryImpl(SettingsLocalDataSource(prefs));
scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
fakeConnectionRepo = _FakeConnectionRepository();
realConnectionRepo = ConnectionRepositoryImpl(
localDataSource: ConnectionLocalDataSource(prefs),
remoteDataSource: ConnectionRemoteDataSource(),
discoveryDataSource: const UdpDiscoveryDataSource(),
);
});
tearDown(() {
realConnectionRepo.dispose();
});
test('SettingsCubit defaults scanCooldownMs to 2500ms and persists updates',
() async {
final cubit = SettingsCubit(settingsRepo);
await cubit.loadSettings();
expect(cubit.state.settings.scanCooldownMs, 2500);
await cubit.updateScanCooldownMs(3000);
expect(cubit.state.settings.scanCooldownMs, 3000);
final reloaded = await settingsRepo.loadSettings();
expect(reloaded.scanCooldownMs, 3000);
});
test(
'ScannerCubit triggers success/error feedback on send and enforces post-scan cooldown',
() async {
final settingsCubit = SettingsCubit(settingsRepo);
await settingsCubit.loadSettings();
await settingsCubit.updateScanCooldownMs(3000);
final connectionCubit = ConnectionCubit(fakeConnectionRepo);
final historyCubit = HistoryCubit(scanRepo);
final spyFeedback = _SpyFeedbackService();
final scannerCubit = ScannerCubit(
connectionCubit: connectionCubit,
settingsCubit: settingsCubit,
historyCubit: historyCubit,
feedbackService: spyFeedback,
);
addTearDown(scannerCubit.close);
addTearDown(connectionCubit.close);
// 1. Successful send triggers success sound & vibration and starts 3s cooldown
fakeConnectionRepo.nextSendResult = true;
await scannerCubit.processBarcode('8001234567890', format: 'ean13');
expect(spyFeedback.successCalls, 1);
expect(spyFeedback.errorCalls, 0);
expect(spyFeedback.lastSound, true);
expect(spyFeedback.lastVibrate, true);
expect(scannerCubit.state.isInCooldown, true);
expect(scannerCubit.state.cooldownTotalMs, 3000);
expect(historyCubit.state.history.length, 1);
// 2. Immediate second barcode (even a DIFFERENT code) is blocked by 3s cooldown
await scannerCubit.processBarcode('9998887776665', format: 'code128');
expect(historyCubit.state.history.length, 1);
expect(spyFeedback.successCalls, 1);
// 3. After cooldown clears, next scan is accepted; if send fails, error feedback triggers
scannerCubit.clearCooldown();
// Reset lastScannedTime by simulating elapsed time via resend/new scan check:
// Note: durationSinceLast still checks lastScannedTime when testing synchronously,
// so verify sendSelectedBarcode triggers error feedback when send fails.
fakeConnectionRepo.nextSendResult = false;
final sent = await scannerCubit.sendSelectedBarcode('FAIL-001');
expect(sent, false);
expect(spyFeedback.errorCalls, 1);
expect(historyCubit.state.history.length, 2);
});
testWidgets('ScannerOverlay displays green confirmation and cooldown pill',
(tester) async {
final cooldownUntil = DateTime.now().add(const Duration(milliseconds: 2500));
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 400,
height: 800,
child: ScannerOverlay(
aimMode: ScanAimMode.standard,
cooldownUntil: cooldownUntil,
cooldownTotalMs: 2500,
lastScanSucceeded: true,
),
),
),
),
);
expect(find.byIcon(Icons.check_rounded), findsOneWidget);
expect(find.textContaining('Inviato • Pausa'), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget);
});
});
}
+7
View File
@@ -1,7 +1,9 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:barcode_reader_app/main.dart';
import 'package:barcode_reader_app/core/services/ad_service.dart';
import 'package:barcode_reader_app/core/services/feedback_service.dart';
import 'package:barcode_reader_app/core/services/subscription_service.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_local_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/connection_remote_datasource.dart';
import 'package:barcode_reader_app/features/connection/data/datasources/udp_discovery_datasource.dart';
@@ -24,6 +26,8 @@ void main() {
);
final scanRepo = ScanRepositoryImpl(ScanHistoryDataSource(prefs));
const feedbackService = FeedbackService();
final adService = AdService();
final subscriptionService = SubscriptionService();
await tester.pumpWidget(
BarcodeReaderApp(
@@ -31,6 +35,9 @@ void main() {
connectionRepository: connectionRepo,
scanRepository: scanRepo,
feedbackService: feedbackService,
adService: adService,
subscriptionService: subscriptionService,
prefs: prefs,
),
);
@@ -6,6 +6,9 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_windows/audioplayers_windows_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
AudioplayersWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin"));
}
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
SRC_DIR="/tmp/barcode-src"
OUT_APPIMAGE="/workspace/BarcodeServer-x86_64.AppImage"
rm -rf "${SRC_DIR}"
mkdir -p "${SRC_DIR}/server"
tar -C /workspace/server \
--exclude='./venv' \
--exclude='./venv_unix' \
--exclude='./venv_win' \
--exclude='./build' \
--exclude='./dist' \
--exclude='./__pycache__' \
--exclude='./.DS_Store' \
-cf - . | tar -C "${SRC_DIR}/server" -xf -
cd "${SRC_DIR}"
BUILD_ARGS=(server/build_binary.py --onedir --windowed --appdir)
if [ -n "${APP_VERSION:-}" ]; then
BUILD_ARGS+=(--version "${APP_VERSION}")
fi
python "${BUILD_ARGS[@]}"
ARCH=x86_64 appimagetool \
"${SRC_DIR}/server/dist/BarcodeServer.AppDir" \
"${OUT_APPIMAGE}"
chmod +x "${OUT_APPIMAGE}"
APPIMAGE_EXTRACT_AND_RUN=1 "${OUT_APPIMAGE}" --version
if [ -n "${HOST_UID:-}" ] && [ -n "${HOST_GID:-}" ]; then
chown "${HOST_UID}:${HOST_GID}" "${OUT_APPIMAGE}"
fi
+62
View File
@@ -0,0 +1,62 @@
FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
bash \
binutils \
ca-certificates \
curl \
file \
libdbus-1-3 \
libegl1 \
libfontconfig1 \
libgl1 \
libglib2.0-0 \
libx11-6 \
libxcb-cursor0 \
libxcb-icccm4 \
libxcb-image0 \
libxcb-keysyms1 \
libxcb-randr0 \
libxcb-render-util0 \
libxcb-shape0 \
libxcb-xinerama0 \
libxcb-xkb1 \
libxkbcommon0 \
libxkbcommon-x11-0 \
libxtst6 \
patchelf \
python3 \
python3-dev \
python3-pip \
python3-venv \
tar \
xz-utils \
&& rm -rf /var/lib/apt/lists/*
# Pre-crea il venv Python e installa le dipendenze in cache layer Docker
RUN python3 -m venv /opt/venv
ENV VIRTUAL_ENV="/opt/venv"
ENV PATH="/opt/venv/bin:${PATH}"
COPY server/requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r /tmp/requirements.txt pyinstaller \
&& rm -f /tmp/requirements.txt
# Estrae appimagetool per funzionare senza FUSE dentro Docker
RUN curl -fsSL -o /tmp/appimagetool.AppImage \
https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage \
&& chmod +x /tmp/appimagetool.AppImage \
&& cd /opt \
&& /tmp/appimagetool.AppImage --appimage-extract \
&& mv /opt/squashfs-root /opt/appimagetool \
&& ln -s /opt/appimagetool/AppRun /usr/local/bin/appimagetool \
&& rm -f /tmp/appimagetool.AppImage
COPY docker/build-linux-appimage.sh /usr/local/bin/build-linux-appimage.sh
RUN chmod +x /usr/local/bin/build-linux-appimage.sh
WORKDIR /workspace
ENTRYPOINT ["/usr/local/bin/build-linux-appimage.sh"]
+54
View File
@@ -29,9 +29,61 @@ HIDDEN_IMPORTS = [
"qrcode",
"aiohttp",
"pynput",
"pynput._info",
"pynput._util",
"pynput.keyboard",
"pynput.keyboard._base",
"pynput.mouse",
"pynput.mouse._base",
"pyperclip",
"certifi",
]
PLATFORM_HIDDEN_IMPORTS = {
"Linux": [
"pynput.keyboard._xorg",
"pynput.mouse._xorg",
"pynput._util.xorg",
"pynput._util.xorg_keysyms",
"pynput._util.uinput",
"pynput.keyboard._uinput",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
"Xlib",
"Xlib.display",
"Xlib.ext",
"Xlib.ext.xtest",
"Xlib.XK",
"Xlib.X",
"Xlib.protocol",
"Xlib.protocol.display",
"Xlib.protocol.event",
"Xlib.protocol.request",
"Xlib.protocol.rq",
"Xlib.protocol.structs",
"Xlib.keysymdef",
"Xlib.keysymdef.xkb",
"Xlib.keysymdef.latin1",
"Xlib.keysymdef.miscellany",
],
"Windows": [
"pynput.keyboard._win32",
"pynput.mouse._win32",
"pynput._util.win32",
"pynput._util.win32_vks",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
],
"Darwin": [
"pynput.keyboard._darwin",
"pynput.mouse._darwin",
"pynput._util.darwin",
"pynput._util.darwin_vks",
"pynput.keyboard._dummy",
"pynput.mouse._dummy",
],
}
EXCLUDED_MODULES = [
"tkinter",
"_tkinter",
@@ -231,6 +283,8 @@ def build(
for hidden_import in HIDDEN_IMPORTS:
cmd.append(f"--hidden-import={hidden_import}")
for platform_hidden in PLATFORM_HIDDEN_IMPORTS.get(system, []):
cmd.append(f"--hidden-import={platform_hidden}")
for excluded in EXCLUDED_MODULES:
cmd.append(f"--exclude-module={excluded}")
+26 -1
View File
@@ -331,13 +331,35 @@ class KeyboardSimulator:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, self._sync_type, full_text, active_suffix, active_mode)
def _ensure_controller(self) -> bool:
if self.controller is not None:
return True
global _controller, Controller, Key, KeyCode
try:
from pynput.keyboard import Controller as _C, Key as _K, KeyCode as _KC
Controller = _C
Key = _K
KeyCode = _KC
self.controller = Controller()
_controller = self.controller
self._linux_xtest, self._win32_helper = _init_platform_helpers(self.controller)
print("[+] Controller tastiera pynput inizializzato con successo.")
return True
except Exception as e:
print(f"Errore inizializzazione controller tastiera: {e}")
return False
def _tap_special(self, x11_name: str, pynput_key) -> None:
if not self._ensure_controller():
return
if self._linux_xtest is not None:
if self._linux_xtest.tap_named(x11_name):
return
self.controller.tap(pynput_key)
def _type_single_char(self, char: str) -> None:
if not self._ensure_controller():
return
if self._linux_xtest is not None:
if self._linux_xtest.type_char(char):
return
@@ -380,6 +402,9 @@ class KeyboardSimulator:
time.sleep(0.04)
return True
if not self._ensure_controller():
return False
modifier = Key.cmd if self.is_mac else Key.ctrl
paste_key = KeyCode.from_vk(0x56) if (self.is_windows and KeyCode is not None) else "v"
with self.controller.pressed(modifier):
@@ -388,7 +413,7 @@ class KeyboardSimulator:
return True
def _sync_type(self, full_text: str, suffix: str, mode: str) -> bool:
if not self.controller:
if not self._ensure_controller():
print("Errore: controller tastiera non disponibile!")
return False
+1
View File
@@ -4,3 +4,4 @@ pyperclip>=1.8.2
qrcode>=7.4.2
PySide6-Essentials>=6.8.0
pillow>=10.0.0
certifi>=2024.2.2
+32 -8
View File
@@ -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"})
+42 -2
View File
@@ -7,6 +7,7 @@ import os
import re
import shlex
import shutil
import ssl
import subprocess
import sys
import tempfile
@@ -19,6 +20,45 @@ from typing import Callable, Optional
from version import APP_NAME, APP_VERSION, RELEASES_PAGE_URL, UPDATE_RELEASES_API
def get_ssl_context() -> ssl.SSLContext:
"""Restituisce un SSLContext con certificati CA validi anche in bundle PyInstaller/macOS."""
# 1. Prova prima certifi se presente (standard de-facto con bundle CA Mozilla aggiornato)
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception:
pass
# 2. Crea il contesto SSL standard
try:
ctx = ssl.create_default_context()
if ctx.get_ca_certs():
return ctx
except Exception:
ctx = ssl.create_default_context()
# 3. Su macOS e Linux, se l'ambiente PyInstaller non ha trovato i certificati,
# carica i certificati di root di sistema noti
known_ca_bundles = (
"/etc/ssl/cert.pem", # macOS default e BSD
"/etc/ssl/certs/ca-certificates.crt", # Debian / Ubuntu
"/etc/pki/tls/certs/ca-bundle.crt", # Fedora / RHEL / CentOS
"/etc/ssl/ca-bundle.pem", # OpenSUSE
"/opt/homebrew/etc/openssl@3/cert.pem", # Homebrew macOS Apple Silicon
"/usr/local/etc/openssl@3/cert.pem", # Homebrew macOS Intel
)
for ca_path in known_ca_bundles:
if os.path.isfile(ca_path):
try:
ctx.load_verify_locations(cafile=ca_path)
if ctx.get_ca_certs():
return ctx
except Exception:
continue
return ctx
@dataclass
class ReleaseAsset:
"""Singolo file eseguibile o installer allegato a una release."""
@@ -237,7 +277,7 @@ def check_for_updates(
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
with urllib.request.urlopen(req, timeout=timeout, context=get_ssl_context()) as resp:
raw = resp.read().decode("utf-8", errors="replace")
payload = json.loads(raw)
except urllib.error.HTTPError as exc:
@@ -299,7 +339,7 @@ def download_asset(
asset.download_url,
headers={"User-Agent": f"BarcodeReaderServer/{APP_VERSION}"},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
with urllib.request.urlopen(req, timeout=timeout, context=get_ssl_context()) as resp:
total = int(resp.headers.get("Content-Length") or asset.size or 0)
downloaded = 0
with open(dest_path, "wb") as out:
+1 -1
View File
@@ -7,7 +7,7 @@ APP_NAME = "Barcode Reader Server"
APP_BINARY_NAME = "BarcodeServer"
APP_ID = "com.catellisrl.barcodereader"
APP_PUBLISHER = "Catelli Srl"
APP_VERSION = "1.0.0"
APP_VERSION = "1.0.5"
GITEA_BASE_URL = "https://gitea.catelli.it"
GITEA_REPO = "brontomark/barcode_reader_pc"