From 832be3d797ac52312c0a1a3fb478be3d6d6e0e15 Mon Sep 17 00:00:00 2001 From: Mark-cachy Date: Sat, 19 Sep 2026 18:42:34 +0200 Subject: [PATCH] feat: supporto latest_version, riga AppImage e gestione aggiornamento facoltativo/obbligatorio --- .gitea/workflows/release.yaml | 31 +++- lib/core/utils/version_check_service.dart | 155 ++++++++++++------- lib/main.dart | 172 ++++++++++++++++------ pubspec.yaml | 2 +- 4 files changed, 258 insertions(+), 102 deletions(-) diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index 6207f52..e817784 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -51,13 +51,17 @@ jobs: - name: Aggiorna Link Windows su Supabase run: | + $TagVersion = "${{ github.ref_name }}".TrimStart('v') $headers = @{ "apikey" = "${{ secrets.SUPABASE_SERVICE_KEY }}" "Authorization" = "Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" "Content-Type" = "application/json" } - $body = '{"download_url": "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe"}' - Invoke-RestMethod -Uri "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.1f888b30-5cbf-4a16-820c-5036a3af0cf8" -Method Patch -Headers $headers -Body $body + $body = (@{ + download_url = "https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/FluxInstaller.exe" + latest_version = $TagVersion + } | ConvertTo-Json) + Invoke-RestMethod -Uri "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.windows" -Method Patch -Headers $headers -Body $body - name: Pulisci Workspace Windows if: always() @@ -90,6 +94,15 @@ jobs: run: | npx wrangler pages deploy build/web --project-name="flux" --branch="main" + - name: Aggiorna Versione Web su Supabase + run: | + TagVersion="${GITHUB_REF_NAME#v}" + curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.web" \ + -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Content-Type: application/json" \ + -d "{\"latest_version\": \"$TagVersion\"}" + # ----------------------------------------------------------------- # JOB 4: LINUX APPIMAGE (Gira sul tuo PC Fedora / Linux Runner) # ----------------------------------------------------------------- @@ -151,7 +164,12 @@ jobs: - name: Aggiorna Link Linux su Supabase run: | - curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.linux" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\"}" + TagVersion="${GITHUB_REF_NAME#v}" + curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.AppImage" \ + -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Content-Type: application/json" \ + -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-x86_64.AppImage\", \"latest_version\": \"$TagVersion\"}" # ----------------------------------------------------------------- # JOB 5: MACOS (Gira sul tuo Mac / macos-runner) @@ -191,4 +209,9 @@ jobs: - name: Aggiorna Link macOS su Supabase run: | - curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" -H "Content-Type: application/json" -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\"}" \ No newline at end of file + TagVersion="${GITHUB_REF_NAME#v}" + curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?platform=eq.macos" \ + -H "apikey: ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Authorization: Bearer ${{ secrets.SUPABASE_SERVICE_KEY }}" \ + -H "Content-Type: application/json" \ + -d "{\"download_url\": \"https://gitea.catelli.it/brontomark/flux/releases/download/${{ github.ref_name }}/Flux-macOS.dmg\", \"latest_version\": \"$TagVersion\"}" \ No newline at end of file diff --git a/lib/core/utils/version_check_service.dart b/lib/core/utils/version_check_service.dart index 2a4f051..4ce9123 100644 --- a/lib/core/utils/version_check_service.dart +++ b/lib/core/utils/version_check_service.dart @@ -3,46 +3,86 @@ import 'package:flutter/foundation.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; +enum UpdateType { + none, + optional, + mandatory, +} + +class UpdateInfo { + final UpdateType type; + final String latestVersion; + final String minVersion; + final String downloadUrl; + + const UpdateInfo({ + required this.type, + required this.latestVersion, + required this.minVersion, + required this.downloadUrl, + }); + + bool get isMandatory => type == UpdateType.mandatory; + bool get isOptional => type == UpdateType.optional; + bool get hasUpdate => type != UpdateType.none; +} + class VersionCheckService { - Future checkForceUpdate() async { + Future checkUpdate() async { try { - // 1. Capiamo su che piattaforma sta girando l'app in questo istante - String currentPlatform = _getCurrentPlatform(); + final platformAliases = _getPlatformAliases(); - // 2. Recuperiamo SOLO la riga corrispondente alla nostra piattaforma final dbResponse = await Supabase.instance.client .from('app_config') - .select('min_version, download_url') - .eq('platform', currentPlatform) - .maybeSingle(); // Usiamo maybeSingle così se non c'è la riga non crasha + .select('platform, min_version, latest_version, download_url'); - if (dbResponse == null) { - return null; // Nessuna regola per questa piattaforma + if (dbResponse.isEmpty) { + return null; } - String minVersionFromDb = dbResponse['min_version'] as String; - String downloadUrl = dbResponse['download_url'] as String; + final rows = List>.from(dbResponse); + final config = rows.firstWhere( + (r) { + final p = (r['platform'] as String?)?.toLowerCase().trim() ?? ''; + return platformAliases.any((alias) => alias.toLowerCase() == p); + }, + orElse: () => {}, + ); - // 3. Recuperiamo la versione locale di Flutter - PackageInfo packageInfo = await PackageInfo.fromPlatform(); - String localVersionRaw = packageInfo.version; + if (config.isEmpty) { + return null; + } - // 🥷 TRUCCO 1: Pulizia totale dai build number (+37) o tag "v" - String cleanLocal = localVersionRaw - .split('+') - .first - .replaceAll('v', '') - .trim(); - String cleanDb = minVersionFromDb - .split('+') - .first - .replaceAll('v', '') - .trim(); + final minVersionRaw = (config['min_version'] as String?) ?? '0.0.0'; + final latestVersionRaw = + (config['latest_version'] as String?) ?? minVersionRaw; + final downloadUrl = (config['download_url'] as String?) ?? ''; - // 🥷 TRUCCO 2: Confronto Semantico Reale - if (_isVersionLower(current: cleanLocal, minimum: cleanDb)) { - // Ritorna il link VERO per questa specifica piattaforma preso dal CSV! - return downloadUrl; + final packageInfo = await PackageInfo.fromPlatform(); + final localVersionRaw = packageInfo.version; + + final cleanLocal = _cleanVersion(localVersionRaw); + final cleanMin = _cleanVersion(minVersionRaw); + final cleanLatest = _cleanVersion(latestVersionRaw); + + // Se la versione locale è inferiore alla minima ammessa -> obbligatorio + if (_isVersionLower(current: cleanLocal, target: cleanMin)) { + return UpdateInfo( + type: UpdateType.mandatory, + latestVersion: latestVersionRaw, + minVersion: minVersionRaw, + downloadUrl: downloadUrl, + ); + } + + // Se è >= della minima ma inferiore all'ultima disponibile -> facoltativo + if (_isVersionLower(current: cleanLocal, target: cleanLatest)) { + return UpdateInfo( + type: UpdateType.optional, + latestVersion: latestVersionRaw, + minVersion: minVersionRaw, + downloadUrl: downloadUrl, + ); } return null; @@ -52,43 +92,48 @@ class VersionCheckService { } } - // Helper ninja per mappare le piattaforme in base alle stringhe del tuo DB - String _getCurrentPlatform() { - if (kIsWeb) return 'web'; - if (Platform.isAndroid) return 'android'; - if (Platform.isIOS) return 'ios'; - if (Platform.isWindows) return 'windows'; - if (Platform.isMacOS) return 'macos'; - if (Platform.isLinux) return 'linux'; - return 'unknown'; + Future checkForceUpdate() async { + final info = await checkUpdate(); + return info?.isMandatory == true ? info?.downloadUrl : null; } - // Il motore matematico (resta invariato) - bool _isVersionLower({required String current, required String minimum}) { - if (current == minimum) return false; + String _cleanVersion(String raw) { + return raw.split('+').first.replaceAll('v', '').trim(); + } - List currentParts = current + List _getPlatformAliases() { + if (kIsWeb) return const ['web']; + if (Platform.isAndroid) return const ['android']; + if (Platform.isIOS) return const ['ios']; + if (Platform.isWindows) return const ['windows']; + if (Platform.isMacOS) return const ['macos']; + if (Platform.isLinux) return const ['AppImage', 'linux']; + return const ['unknown']; + } + + bool _isVersionLower({required String current, required String target}) { + if (current == target) return false; + + final currentParts = current .split('.') .map((e) => int.tryParse(e) ?? 0) .toList(); - List minParts = minimum + final targetParts = target .split('.') .map((e) => int.tryParse(e) ?? 0) .toList(); - while (currentParts.length < 3) { - currentParts.add(0); - } - while (minParts.length < 3) { - minParts.add(0); - } + final maxLength = currentParts.length > targetParts.length + ? currentParts.length + : targetParts.length; - if (currentParts[0] != minParts[0]) { - return currentParts[0] < minParts[0]; + for (int i = 0; i < maxLength; i++) { + final c = i < currentParts.length ? currentParts[i] : 0; + final t = i < targetParts.length ? targetParts[i] : 0; + if (c != t) { + return c < t; + } } - if (currentParts[1] != minParts[1]) { - return currentParts[1] < minParts[1]; - } - return currentParts[2] < minParts[2]; + return false; } } diff --git a/lib/main.dart b/lib/main.dart index 21e8290..08c33b3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -237,8 +237,9 @@ class GlobalUpdateChecker extends StatefulWidget { class _GlobalUpdateCheckerState extends State with WidgetsBindingObserver { - bool _mustUpdate = false; - String? _updateUrl; + UpdateInfo? _updateInfo; + bool _isDismissed = false; + String? _dismissedVersion; StreamSubscription? _versionSubscription; bool _isUpdating = false; double _downloadProgress = 0.0; @@ -285,7 +286,7 @@ class _GlobalUpdateCheckerState extends State // Riapriamo il rubinetto di Supabase _versionSubscription = GetIt.I() - .from('app_config') // <-- Sostituisci col nome reale della tua tabella + .from('app_config') .stream(primaryKey: ['id']) .listen((_) { _checkVersion(); @@ -299,18 +300,24 @@ class _GlobalUpdateCheckerState extends State } Future _checkVersion() async { - final updateUrl = await VersionCheckService().checkForceUpdate(); + final updateInfo = await VersionCheckService().checkUpdate(); - if (updateUrl != null && mounted) { + if (mounted) { setState(() { - _mustUpdate = true; - _updateUrl = updateUrl; + _updateInfo = updateInfo; + // Se arriva una versione diversa da quella già rimandata, azzeriamo il dismiss + if (updateInfo != null && + updateInfo.latestVersion != _dismissedVersion) { + _isDismissed = false; + } }); } } Future _startAutoUpdate() async { - if (_updateUrl == null) return; + final updateUrl = _updateInfo?.downloadUrl; + if (updateUrl == null || updateUrl.isEmpty) return; + setState(() { _isUpdating = true; _errorMessage = null; @@ -320,7 +327,7 @@ class _GlobalUpdateCheckerState extends State try { await AutoUpdateService.downloadAndApplyUpdate( - downloadUrl: _updateUrl!, + downloadUrl: updateUrl, onProgress: (progress, status) { if (mounted) { setState(() { @@ -342,7 +349,14 @@ class _GlobalUpdateCheckerState extends State @override Widget build(BuildContext context) { - if (!_mustUpdate) return widget.child; + final updateInfo = _updateInfo; + final showOverlay = updateInfo != null && + updateInfo.hasUpdate && + (updateInfo.isMandatory || !_isDismissed); + + if (!showOverlay) return widget.child; + + final isMandatory = updateInfo.isMandatory; return Stack( children: [ @@ -356,7 +370,7 @@ class _GlobalUpdateCheckerState extends State child: Container( margin: const EdgeInsets.all(24), padding: const EdgeInsets.all(24), - constraints: const BoxConstraints(maxWidth: 420), + constraints: const BoxConstraints(maxWidth: 440), decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.circular(16), @@ -375,29 +389,50 @@ class _GlobalUpdateCheckerState extends State mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( - kIsWeb ? Icons.cached : Icons.system_update, - color: Colors.orange, + isMandatory + ? Icons.warning_amber_rounded + : (kIsWeb ? Icons.cached : Icons.system_update), + color: + isMandatory ? Colors.amber[700] : Colors.blue, size: 32, ), const SizedBox(width: 12), - Flexible( + Expanded( child: Text( - kIsWeb - ? "Aggiornamento" - : "Aggiornamento Obbligatorio", - style: Theme.of(context).textTheme.titleLarge + isMandatory + ? "Aggiornamento Obbligatorio" + : (kIsWeb + ? "Aggiornamento Disponibile" + : "Nuova Versione Disponibile"), + style: Theme.of(context) + .textTheme + .titleLarge ?.copyWith(fontWeight: FontWeight.bold), ), ), + if (!isMandatory && !_isUpdating) + IconButton( + icon: const Icon(Icons.close), + tooltip: "Chiudi e rimanda", + onPressed: () { + setState(() { + _isDismissed = true; + _dismissedVersion = + updateInfo.latestVersion; + }); + }, + ), ], ), const SizedBox(height: 16), Text( kIsWeb - ? "È stata rilasciata una nuova versione dell'applicazione. Ricarica la pagina per scaricare il nuovo codice." - : "Per continuare ad utilizzare l'applicazione è necessario aggiornare all'ultima versione disponibile.", + ? "È stata rilasciata una nuova versione dell'applicazione (${updateInfo.latestVersion}). Ricarica la pagina per scaricare il nuovo codice." + : (isMandatory + ? "La versione attuale non è più supportata (minima richiesta: ${updateInfo.minVersion}). È necessario aggiornare all'ultima versione (${updateInfo.latestVersion}) per continuare a lavorare." + : "È disponibile la nuova versione ${updateInfo.latestVersion}. Puoi aggiornare subito oppure rimandare."), textAlign: TextAlign.center, - style: const TextStyle(fontSize: 16), + style: const TextStyle(fontSize: 15), ), const SizedBox(height: 24), if (_errorMessage != null) ...[ @@ -425,7 +460,9 @@ class _GlobalUpdateCheckerState extends State ClipRRect( borderRadius: BorderRadius.circular(8), child: LinearProgressIndicator( - value: _downloadProgress > 0 ? _downloadProgress : null, + value: _downloadProgress > 0 + ? _downloadProgress + : null, minHeight: 10, ), ), @@ -434,11 +471,14 @@ class _GlobalUpdateCheckerState extends State _statusMessage, style: TextStyle( fontSize: 13, - color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.7), + color: Theme.of(context) + .colorScheme + .onSurface + .withValues(alpha: 0.7), ), textAlign: TextAlign.center, ), - ] else if (kIsWeb) + ] else if (kIsWeb) ...[ FilledButton.icon( icon: const Icon(Icons.refresh), label: const Text("RICARICA ORA"), @@ -449,8 +489,24 @@ class _GlobalUpdateCheckerState extends State // Hard reload aggirando la cache! html.window.location.reload(); }, - ) - else if (AutoUpdateService.isAutoUpdateSupported) + ), + if (!isMandatory) ...[ + const SizedBox(height: 10), + OutlinedButton( + style: OutlinedButton.styleFrom( + minimumSize: const Size(double.infinity, 44), + ), + onPressed: () { + setState(() { + _isDismissed = true; + _dismissedVersion = + updateInfo.latestVersion; + }); + }, + child: const Text("PIÙ TARDI"), + ), + ], + ] else if (AutoUpdateService.isAutoUpdateSupported) ...[ FilledButton.icon( icon: const Icon(Icons.system_update_alt), label: const Text("AGGIORNA ORA"), @@ -459,8 +515,24 @@ class _GlobalUpdateCheckerState extends State backgroundColor: Colors.blue, ), onPressed: _startAutoUpdate, - ) - else + ), + if (!isMandatory) ...[ + const SizedBox(height: 10), + OutlinedButton( + style: OutlinedButton.styleFrom( + minimumSize: const Size(double.infinity, 44), + ), + onPressed: () { + setState(() { + _isDismissed = true; + _dismissedVersion = + updateInfo.latestVersion; + }); + }, + child: const Text("PIÙ TARDI"), + ), + ], + ] else ...[ FilledButton.icon( icon: const Icon(Icons.download), label: const Text("SCARICA AGGIORNAMENTO"), @@ -469,27 +541,43 @@ class _GlobalUpdateCheckerState extends State backgroundColor: Colors.blue, ), onPressed: () async { - if (_updateUrl != null) { - final url = Uri.parse(_updateUrl!); - await launchUrl( - url, - mode: LaunchMode.externalApplication, - ); - } + final url = Uri.parse(updateInfo.downloadUrl); + await launchUrl( + url, + mode: LaunchMode.externalApplication, + ); }, ), - if (!_isUpdating && AutoUpdateService.isAutoUpdateSupported && _errorMessage != null) ...[ + if (!isMandatory) ...[ + const SizedBox(height: 10), + OutlinedButton( + style: OutlinedButton.styleFrom( + minimumSize: const Size(double.infinity, 44), + ), + onPressed: () { + setState(() { + _isDismissed = true; + _dismissedVersion = + updateInfo.latestVersion; + }); + }, + child: const Text("PIÙ TARDI"), + ), + ], + ], + if (!_isUpdating && + AutoUpdateService.isAutoUpdateSupported && + _errorMessage != null) ...[ const SizedBox(height: 10), TextButton.icon( icon: const Icon(Icons.open_in_browser, size: 16), label: const Text("Scarica manualmente dal browser"), onPressed: () async { - if (_updateUrl != null) { - await launchUrl( - Uri.parse(_updateUrl!), - mode: LaunchMode.externalApplication, - ); - } + final url = Uri.parse(updateInfo.downloadUrl); + await launchUrl( + url, + mode: LaunchMode.externalApplication, + ); }, ), ], diff --git a/pubspec.yaml b/pubspec.yaml index 247fc79..759c5dc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.0.7+63 +version: 2.0.8+64 environment: sdk: ^3.11.3