diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml index 185e1d3..6207f52 100644 --- a/.gitea/workflows/release.yaml +++ b/.gitea/workflows/release.yaml @@ -49,44 +49,20 @@ jobs: files: "build/windows/installer/FluxInstaller.exe" api_key: ${{ secrets.MYRELEASE_TOKEN }} + - name: Aggiorna Link Windows su Supabase + run: | + $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 + - name: Pulisci Workspace Windows if: always() run: Remove-Item -Recurse -Force ./* - # ----------------------------------------------------------------- - # JOB 2: ANDROID APPBUNDLE (Gira sul runner Fedora o Mac) - # ----------------------------------------------------------------- - build-android: - runs-on: cross-runner - steps: - - name: Checkout del codice - uses: actions/checkout@v3 - - # Logica Bash per Mac/Linux: usiamo le virgolette singole forti per evitare escape strani - - name: Crea file .env - run: | - cat << 'EOF' > .env - ${{ secrets.ENV_FILE_CONTENT }} - EOF - - - name: Build Flutter AppBundle - run: flutter build appbundle --release - - # Carichiamo l'AAB nelle release di Gitea per poi caricarlo su Google Play Console - - name: Upload Android Asset - uses: https://gitea.com/actions/release-action@main - with: - files: "build/app/outputs/bundle/release/app-release.aab" - api_key: ${{ secrets.MYRELEASE_TOKEN }} - - - name: Aggiorna Link Android su Supabase - run: | - curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.49f18b19-2129-46c0-b690-a97db725b5a8" -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 }}/app-release.aab\"}" - - - name: Aggiorna Link Windows su Supabase - run: | - curl -X PATCH "https://pvqpjloswwvtfoxbkfbh.supabase.co/rest/v1/app_config?id=eq.1f888b30-5cbf-4a16-820c-5036a3af0cf8" -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 }}/FluxInstaller.exe\"}" - # ----------------------------------------------------------------- # JOB 3: WEB & CLOUDFLARE DEPLOY (Gira sul runner Fedora o Mac) diff --git a/lib/core/utils/auto_update_service.dart b/lib/core/utils/auto_update_service.dart new file mode 100644 index 0000000..edc9387 --- /dev/null +++ b/lib/core/utils/auto_update_service.dart @@ -0,0 +1,164 @@ +import 'dart:async'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; + +class AutoUpdateService { + /// Verifica se la piattaforma corrente supporta l'aggiornamento automatico trasparente + static bool get isAutoUpdateSupported { + if (kIsWeb) return false; + if (Platform.isWindows) return true; + if (Platform.isLinux && Platform.environment['APPIMAGE'] != null) { + return true; + } + return false; + } + + /// Scarica l'aggiornamento e lo applica in modo silenzioso + static Future downloadAndApplyUpdate({ + required String downloadUrl, + required void Function(double progress, String status) onProgress, + }) async { + if (kIsWeb) { + throw UnsupportedError("L'auto-update non è supportato su Web."); + } + + if (Platform.isWindows) { + await _updateWindows(downloadUrl, onProgress); + } else if (Platform.isLinux) { + await _updateLinux(downloadUrl, onProgress); + } else { + throw UnsupportedError("Piattaforma non supportata per l'auto-update."); + } + } + + /// Gestione aggiornamento Windows + static Future _updateWindows( + String downloadUrl, + void Function(double progress, String status) onProgress, + ) async { + final tempDir = Directory.systemTemp; + final installerFile = File('${tempDir.path}\\FluxInstaller_Update.exe'); + + if (installerFile.existsSync()) { + try { + installerFile.deleteSync(); + } catch (_) {} + } + + onProgress(0.0, "Download aggiornamento in corso..."); + await _downloadFile(downloadUrl, installerFile, onProgress); + + onProgress(1.0, "Installazione e riavvio in corso..."); + await Future.delayed(const Duration(milliseconds: 500)); + + // Lancia l'installer in modalità silenziosa per utente singolo + // /VERYSILENT: nessuna interfaccia + // /SUPPRESSMSGBOXES: nessun popup + // /NORESTART: non riavvia il PC + await Process.start( + installerFile.path, + ['/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'], + mode: ProcessStartMode.detached, + ); + + // Chiude l'applicazione per consentire la sostituzione dei file + exit(0); + } + + /// Gestione aggiornamento Linux (AppImage in-place) + static Future _updateLinux( + String downloadUrl, + void Function(double progress, String status) onProgress, + ) async { + final currentAppImagePath = Platform.environment['APPIMAGE']; + if (currentAppImagePath == null) { + throw StateError( + "L'applicazione non è in esecuzione come AppImage.", + ); + } + + final newAppImageFile = File('$currentAppImagePath.new'); + if (newAppImageFile.existsSync()) { + try { + newAppImageFile.deleteSync(); + } catch (_) {} + } + + onProgress(0.0, "Download nuova versione in corso..."); + await _downloadFile(downloadUrl, newAppImageFile, onProgress); + + onProgress(1.0, "Finalizzazione e riavvio..."); + await Future.delayed(const Duration(milliseconds: 300)); + + // Assegna il permesso di esecuzione + await Process.run('chmod', ['+x', newAppImageFile.path]); + + // Sostituzione atomica del vecchio file AppImage con il nuovo + newAppImageFile.renameSync(currentAppImagePath); + + // Rilancia la nuova versione + await Process.start( + currentAppImagePath, + [], + mode: ProcessStartMode.detached, + ); + + // Termina il processo attuale + exit(0); + } + + /// Download in streaming con tracciamento del progresso + static Future _downloadFile( + String url, + File destinationFile, + void Function(double progress, String status) onProgress, + ) async { + final client = HttpClient(); + client.autoUncompress = true; + + try { + final uri = Uri.parse(url); + final request = await client.getUrl(uri); + final response = await request.close(); + + if (response.statusCode < 200 || response.statusCode >= 300) { + throw HttpException( + 'Download fallito con codice di stato ${response.statusCode}', + uri: uri, + ); + } + + final contentLength = response.contentLength; + int downloadedBytes = 0; + + final sink = destinationFile.openWrite(); + + await for (final chunk in response) { + sink.add(chunk); + downloadedBytes += chunk.length; + + if (contentLength > 0) { + final progress = (downloadedBytes / contentLength).clamp(0.0, 1.0); + final percent = (progress * 100).toStringAsFixed(0); + final downloadedMb = + (downloadedBytes / (1024 * 1024)).toStringAsFixed(1); + final totalMb = (contentLength / (1024 * 1024)).toStringAsFixed(1); + + onProgress( + progress, + 'Scaricamento: $percent% ($downloadedMb MB di $totalMb MB)', + ); + } else { + final downloadedMb = + (downloadedBytes / (1024 * 1024)).toStringAsFixed(1); + onProgress(0.5, 'Scaricamento in corso ($downloadedMb MB)...'); + } + } + + await sink.flush(); + await sink.close(); + } finally { + client.close(); + } + } +} diff --git a/lib/main.dart b/lib/main.dart index 9e3a9d6..21e8290 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -32,6 +32,7 @@ import 'package:flux/features/master_data/store/bloc/store_cubit.dart'; import 'package:flutter_web_plugins/url_strategy.dart'; import 'package:universal_html/html.dart' as html; import 'package:url_launcher/url_launcher.dart'; +import 'package:flux/core/utils/auto_update_service.dart'; String? initialRecoveryFragment; void main() async { @@ -239,6 +240,10 @@ class _GlobalUpdateCheckerState extends State bool _mustUpdate = false; String? _updateUrl; StreamSubscription? _versionSubscription; + bool _isUpdating = false; + double _downloadProgress = 0.0; + String _statusMessage = ""; + String? _errorMessage; @override void initState() { @@ -304,6 +309,37 @@ class _GlobalUpdateCheckerState extends State } } + Future _startAutoUpdate() async { + if (_updateUrl == null) return; + setState(() { + _isUpdating = true; + _errorMessage = null; + _downloadProgress = 0.0; + _statusMessage = "Avvio aggiornamento in corso..."; + }); + + try { + await AutoUpdateService.downloadAndApplyUpdate( + downloadUrl: _updateUrl!, + onProgress: (progress, status) { + if (mounted) { + setState(() { + _downloadProgress = progress; + _statusMessage = status; + }); + } + }, + ); + } catch (e) { + if (mounted) { + setState(() { + _isUpdating = false; + _errorMessage = "Errore durante l'aggiornamento automatico: $e"; + }); + } + } + } + @override Widget build(BuildContext context) { if (!_mustUpdate) return widget.child; @@ -320,7 +356,7 @@ class _GlobalUpdateCheckerState extends State child: Container( margin: const EdgeInsets.all(24), padding: const EdgeInsets.all(24), - constraints: const BoxConstraints(maxWidth: 400), + constraints: const BoxConstraints(maxWidth: 420), decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.circular(16), @@ -359,12 +395,50 @@ class _GlobalUpdateCheckerState extends State Text( kIsWeb ? "È stata rilasciata una nuova versione dell'applicazione. Ricarica la pagina per scaricare il nuovo codice." - : "Per continuare ad utilizzare l'applicazione è necessario scaricare e installare l'ultimo aggiornamento.", + : "Per continuare ad utilizzare l'applicazione è necessario aggiornare all'ultima versione disponibile.", textAlign: TextAlign.center, style: const TextStyle(fontSize: 16), ), const SizedBox(height: 24), - if (kIsWeb) + if (_errorMessage != null) ...[ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Colors.red.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: Colors.red.withValues(alpha: 0.3), + ), + ), + child: Text( + _errorMessage!, + style: const TextStyle( + color: Colors.red, + fontSize: 13, + ), + textAlign: TextAlign.center, + ), + ), + const SizedBox(height: 16), + ], + if (_isUpdating) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: LinearProgressIndicator( + value: _downloadProgress > 0 ? _downloadProgress : null, + minHeight: 10, + ), + ), + const SizedBox(height: 12), + Text( + _statusMessage, + style: TextStyle( + fontSize: 13, + color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.7), + ), + textAlign: TextAlign.center, + ), + ] else if (kIsWeb) FilledButton.icon( icon: const Icon(Icons.refresh), label: const Text("RICARICA ORA"), @@ -376,6 +450,16 @@ class _GlobalUpdateCheckerState extends State html.window.location.reload(); }, ) + else if (AutoUpdateService.isAutoUpdateSupported) + FilledButton.icon( + icon: const Icon(Icons.system_update_alt), + label: const Text("AGGIORNA ORA"), + style: FilledButton.styleFrom( + minimumSize: const Size(double.infinity, 50), + backgroundColor: Colors.blue, + ), + onPressed: _startAutoUpdate, + ) else FilledButton.icon( icon: const Icon(Icons.download), @@ -394,6 +478,21 @@ class _GlobalUpdateCheckerState extends State } }, ), + 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, + ); + } + }, + ), + ], ], ), ), diff --git a/pubspec.yaml b/pubspec.yaml index 82125ea..247fc79 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.6+62 +version: 2.0.7+63 environment: sdk: ^3.11.3 diff --git a/win_installer.iss b/win_installer.iss index a029147..d3443db 100644 --- a/win_installer.iss +++ b/win_installer.iss @@ -4,7 +4,7 @@ AppName=Flux AppVersion={#MyAppVersion} VersionInfoVersion={#MyAppVersion} AppPublisher=Catelli -DefaultDirName={autopf}\Flux +DefaultDirName={autolocalappdata}\Programs\Flux ; DefaultGroupName=Programs ; Cartella di output dell'installer e nome del file generato @@ -16,11 +16,13 @@ Compression=lzma2/max SolidCompression=yes WizardStyle=modern -; Icona dell'installer (opzionale, decommenta se hai il file .ico) +; Icona dell'installer SetupIconFile=windows\runner\resources\app_icon.ico -; Richiede privilegi di amministratore per installare nella cartella Programmi -PrivilegesRequired=admin +; Installazione utente (senza richiesta di privilegi amministratore UAC) +PrivilegesRequired=lowest +PrivilegesRequiredOverridesAllowed=dialog +CloseApplications=force [Files] ; 1. L'eseguibile principale di Flutter @@ -31,12 +33,12 @@ Source: "build\windows\x64\runner\Release\*"; DestDir: "{app}"; Flags: ignorever [Icons] ; Scorciatoie nel menu Start e sul Desktop -Name: "{autoprograms}\LaMiaApp"; Filename: "{app}\Flux.exe" -Name: "{autodesktop}\LaMiaApp"; Filename: "{app}\Flux.exe"; Tasks: desktopicon +Name: "{autoprograms}\Flux"; Filename: "{app}\Flux.exe" +Name: "{autodesktop}\Flux"; Filename: "{app}\Flux.exe"; Tasks: desktopicon [Tasks] Name: "desktopicon"; Description: "Crea un'icona sul &Desktop"; GroupDescription: "Icone aggiuntive:"; Flags: unchecked [Run] ; Opzione per avviare l'app subito dopo la fine dell'installazione -Filename: "{app}\Flux.exe"; Description: "Avvia LaMiaApp"; Flags: nowait postinstall skipifsilent \ No newline at end of file +Filename: "{app}\Flux.exe"; Description: "Avvia Flux"; Flags: nowait postinstall \ No newline at end of file