π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Schedule daily backups and streamline manual flow
Prateek Sunal2c7c6c1e7a3a
diff --git a/mobile/apps/auth/lib/services/local_backup_service.dart b/mobile/apps/auth/lib/services/local_backup_service.dartindex f48c5f7147..9f27b85f72 100644--- a/mobile/apps/auth/lib/services/local_backup_service.dart+++ b/mobile/apps/auth/lib/services/local_backup_service.dart@@ -19,21 +19,27 @@ class LocalBackupService {LocalBackupService._privateConstructor();static const int _maxBackups = 5;+ static const _lastBackupDayKey = 'lastBackupDay';// to create an encrypted backup file if the toggle is on- Future<void> triggerAutomaticBackup() async {+ Future<bool> triggerAutomaticBackup({bool isManual = false}) async {+ bool success = false;try {final prefs = await SharedPreferences.getInstance();final isEnabled = prefs.getBool('isAutoBackupEnabled') ?? false;if (!isEnabled) {- return;+ return false;}final backupPath = prefs.getString('autoBackupPath');final backupTreeUri = prefs.getString('autoBackupTreeUri');if (backupPath == null && (backupTreeUri == null || backupTreeUri.isEmpty)) {- return;+ return false;+ }++ if (!isManual && _hasBackedUpToday(prefs)) {+ return false;}Directory? backupDirectory;@@ -46,7 +52,7 @@ class LocalBackupService {final password = await storage.read(key: 'autoBackupPassword');if (password == null || password.isEmpty) {_logger.warning("Automatic backup skipped: password not set.");- return;+ return false;}_logger.info("Change detected, triggering automatic encrypted backup...");@@ -75,7 +81,7 @@ class LocalBackupService {final plainTextContent = cleanedLines.join('\n');if (plainTextContent.trim().isEmpty) {- return;+ return false;}final kekSalt = CryptoUtil.getSaltToDeriveKey();@@ -108,7 +114,9 @@ class LocalBackupService {final now = DateTime.now();final formatter = DateFormat('yyyy-MM-dd_HH-mm-ss');final formattedDate = formatter.format(now);- final fileName = 'ente-auth-auto-backup-$formattedDate.json';+ final fileName = isManual+ ? 'ente-auth-manual-backup-$formattedDate.json'+ : 'ente-auth-daily-backup-$formattedDate.json';if (backupTreeUri != null && backupTreeUri.isNotEmpty) {await _writeBackupWithSaf(@@ -116,6 +124,7 @@ class LocalBackupService {fileName,encryptedJson,);+ success = true;} else if (backupDirectory != null) {final filePath = '${backupDirectory.path}/$fileName';final backupFile = File(filePath);@@ -125,10 +134,23 @@ class LocalBackupService {_logger.info('Automatic encrypted backup successful! Saved to: $filePath',);+ success = true;+ }+ if (success && !isManual) {+ await _recordBackupDay(prefs, now);}} catch (e, s) {_logger.severe('Silent error during automatic backup', e, s);}+ return success;+ }++ Future<bool> triggerDailyBackupIfNeeded() async {+ final prefs = await SharedPreferences.getInstance();+ if (_hasBackedUpToday(prefs)) {+ return false;+ }+ return triggerAutomaticBackup();}Future<void> _writeBackupWithSaf(@@ -161,12 +183,14 @@ class LocalBackupService {final files = directory.listSync().where((entity) =>entity is File &&- entity.path.split('/').last.startsWith('ente-auth-auto-backup-'),)+ _isBackupFile(entity.path.split('/').last),).map((entity) => entity as File).toList();- // sort the fetched files in asc order (oldest first because the name is a timestamp)- files.sort((a, b) => a.path.compareTo(b.path));+ // sort by last modified (oldest first)+ files.sort(+ (a, b) => a.lastModifiedSync().compareTo(b.lastModifiedSync()),+ );// if we have more files than our limit, delete the oldest ones (current limit=_maxBackups)while (files.length > _maxBackups) {@@ -195,7 +219,7 @@ _logger.info('Backup count is now ${files.length}. Cleanup complete.');final files = directory.listSync().where((entity) =>entity is File &&- entity.path.split('/').last.startsWith('ente-auth-auto-backup-'),)+ _isBackupFile(entity.path.split('/').last),).map((entity) => entity as File).toList();@@ -214,4 +238,21 @@ _logger.info('Backup count is now ${files.length}. Cleanup complete.');_logger.severe('Error during full backup cleanup of old directory', e, s);}}++ bool _hasBackedUpToday(SharedPreferences prefs) {+ final todayKey = DateFormat('yyyy-MM-dd').format(DateTime.now());+ final last = prefs.getString(_lastBackupDayKey);+ return last == todayKey;+ }++ Future<void> _recordBackupDay(SharedPreferences prefs, DateTime now) async {+ final dayKey = DateFormat('yyyy-MM-dd').format(now);+ await prefs.setString(_lastBackupDayKey, dayKey);+ }++ bool _isBackupFile(String fileName) {+ return fileName.startsWith('ente-auth-daily-backup-') ||+ fileName.startsWith('ente-auth-manual-backup-') ||+ fileName.startsWith('ente-auth-auto-backup-');+ }}diff --git a/mobile/apps/auth/lib/ui/code_widget.dart b/mobile/apps/auth/lib/ui/code_widget.dartindex 6fc9bb3b9b..e93a0fc660 100644--- a/mobile/apps/auth/lib/ui/code_widget.dart+++ b/mobile/apps/auth/lib/ui/code_widget.dart@@ -964,7 +964,7 @@ class _CodeWidgetState extends State<CodeWidget> {firstButtonOnTap: () async {try {await CodeStore.instance.removeCode(widget.code);- LocalBackupService.instance.triggerAutomaticBackup().ignore();+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();} catch (e, s) {logger.severe('Failed to delete code', e, s);showGenericErrorDialog(context: context, error: e).ignore();diff --git a/mobile/apps/auth/lib/ui/home_page.dart b/mobile/apps/auth/lib/ui/home_page.dartindex 1a22ea88c9..c04cac9065 100644--- a/mobile/apps/auth/lib/ui/home_page.dart+++ b/mobile/apps/auth/lib/ui/home_page.dart@@ -110,6 +110,7 @@ class _HomePageState extends State<HomePage> {_codeSortKey = PreferenceService.instance.codeSortKey();_textController.addListener(_applyFilteringAndRefresh);_loadCodes();+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();_streamSubscription = Bus.instance.on<CodesUpdatedEvent>().listen((event) {_loadCodes();});@@ -1186,7 +1187,7 @@ class _HomePageState extends State<HomePage> {if ((_allCodes?.where((e) => !e.hasError).length ?? 0) > 2) {_focusNewCode(newCode);}- LocalBackupService.instance.triggerAutomaticBackup().ignore();+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();} finally {_isImportingFromGallery = false;}@@ -1209,7 +1210,7 @@ class _HomePageState extends State<HomePage> {if ((_allCodes?.where((e) => !e.hasError).length ?? 0) > 2) {_focusNewCode(result.code);}- LocalBackupService.instance.triggerAutomaticBackup().ignore();+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();}}@@ -1223,7 +1224,7 @@ class _HomePageState extends State<HomePage> {);if (code != null) {await CodeStore.instance.addCode(code);- LocalBackupService.instance.triggerAutomaticBackup().ignore();+ LocalBackupService.instance.triggerDailyBackupIfNeeded().ignore();}}diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dartindex f714b34617..731869bc3a 100644--- a/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup/local_backup_experience.dart@@ -158,7 +158,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {setState(() {_isBackupEnabled = true;});- await LocalBackupService.instance.triggerAutomaticBackup();+ await LocalBackupService.instance.triggerAutomaticBackup(isManual: true);_showSnackBar(context.l10n.initialBackupCreated);return true;}@@ -199,7 +199,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {}}- await LocalBackupService.instance.triggerAutomaticBackup();+ await LocalBackupService.instance.triggerAutomaticBackup(isManual: true);if (showSnackBar) {_showSnackBar(context.l10n.initialBackupCreated);}@@ -577,7 +577,7 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {if (Platform.isAndroid) {final saved = await _pickAndPersistAndroidLocation();if (saved) {- await LocalBackupService.instance.triggerAutomaticBackup();+ await LocalBackupService.instance.triggerAutomaticBackup(isManual: true);} else if (requireSelection) {_showSnackBar('Select a folder to continue');}@@ -592,7 +592,9 @@ class _LocalBackupExperienceState extends State<LocalBackupExperience> {successMessage ?? context.l10n.locationUpdatedAndBackupCreated,);if (saved) {- await LocalBackupService.instance.triggerAutomaticBackup();+ await LocalBackupService.instance.triggerAutomaticBackup(+ isManual: true,+ );}return saved;}diff --git a/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart b/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dartindex d00d44adc2..48d85127de 100644--- a/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart+++ b/mobile/apps/auth/lib/ui/settings/data/local_backup_settings_page.dart@@ -8,7 +8,7 @@ import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';const _autoBackupToggleCopy =- 'Backs up your 2FA codes locally. The backup updates automatically whenever you add, edit, or delete a code.';+ 'Creates one local backup per day when you open the app. Use "Backup now" to run an extra manual backup at any time. Backups are retained up to 5 files.';class LocalBackupSettingsPage extends StatelessWidget {const LocalBackupSettingsPage({super.key});@@ -56,7 +56,7 @@ class LocalBackupAppLockVariantPage extends StatelessWidget {Padding(padding: const EdgeInsets.only(top: 12, left: 12, right: 12),child: Text(- '$_autoBackupToggleCopy\n\nBackups are retained up to 5 files.',+ _autoBackupToggleCopy,style: textTheme.miniFaint,),),@@ -149,30 +149,29 @@ class LocalBackupAppLockVariantPage extends StatelessWidget {),),),- if (kDebugMode) ...[- const SizedBox(height: 12),- SizedBox(- width: double.infinity,- child: TextButton(- onPressed: () async {- await controller.runManualBackup();- },- style: TextButton.styleFrom(- foregroundColor: colorScheme.textBase,- backgroundColor: colorScheme.fillFaint,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12),- ),- padding:- const EdgeInsets.symmetric(vertical: 12),+ const SizedBox(height: 12),+ SizedBox(+ width: double.infinity,+ child: TextButton(+ onPressed: () async {+ await controller.runManualBackup();+ },+ style: TextButton.styleFrom(+ foregroundColor: colorScheme.textBase,+ backgroundColor: colorScheme.fillFaint,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),),- child: Text(- 'Backup now',- style: textTheme.bodyBold,+ padding: const EdgeInsets.symmetric(+ vertical: 12,),),+ child: Text(+ 'Backup now (manual)',+ style: textTheme.bodyBold,+ ),),- ],+ ),],): (kDebugMode