implemented user backups

This commit is contained in:
Fabian Freund
2025-12-18 18:38:06 +01:00
parent 2f1ecd50e1
commit 018915298a
19 changed files with 1172 additions and 78 deletions
@@ -18,6 +18,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/filesystem.dart';
@@ -47,36 +48,74 @@ class SelectProfileDialog extends HookConsumerWidget {
title: Text(profile.name),
subtitle: isSelected ? const Text('Active') : null,
onTap: () async {
final result = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Switch User'),
content: Text(
"Switching to User '${profile.name}' will require a restart of the Browser",
),
actions: [
TextButton(
onPressed: () {
context.pop(false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
context.pop(true);
},
child: const Text('Switch Profile'),
),
],
),
);
final duplicateMozillaProfile = await filesystem
.checkForDuplicateMozillaProfile(profile.uuidValue);
if (result == true) {
await ref
.read(profileRepositoryProvider.notifier)
.switchProfile(profile.id);
await exitApp(ref.container);
if (context.mounted) {
final result = await showDialog<(bool, bool)>(
context: context,
builder: (context) => HookBuilder(
builder: (context) {
final clearCache = useState(false);
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Switch User'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
"Switching to User '${profile.name}' will require a restart of the Browser.",
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
if (duplicateMozillaProfile != null)
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: clearCache.value,
title: const Text('Clear Shared Cache'),
subtitle: const Text(
'This User has been created based on an exisiting Mozilla Profile Identifier. Clearing cache will affect all linked accounts.',
),
onChanged: (value) {
clearCache.value = value;
},
),
],
),
actions: [
TextButton(
onPressed: () {
context.pop((false, false));
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
context.pop((true, clearCache.value));
},
child: const Text('Switch Profile'),
),
],
);
},
),
);
if (result?.$1 == true) {
if (duplicateMozillaProfile != null && result?.$2 == true) {
await filesystem.clearMozillaProfileCache(
duplicateMozillaProfile,
);
}
await ref
.read(profileRepositoryProvider.notifier)
.switchProfile(profile.id);
await exitApp(ref.container);
}
}
},
);
@@ -0,0 +1,187 @@
import 'package:fancy_password_field/fancy_password_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/domain/entities/profile.dart';
import 'package:weblibre/features/user/domain/services/user_backup.dart';
import 'package:weblibre/utils/ui_helper.dart';
class ProfileBackupScreen extends HookConsumerWidget {
final Profile profile;
const ProfileBackupScreen({required this.profile});
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final passwordTextController = useTextEditingController();
final passwordController = useMemoized(() => FancyPasswordController());
final integrityVerification = useState(true);
final skipPasswordConfirmation = useState(false);
final backupFuture = useState<Future<bool>?>(null);
final backupState = useFuture(backupFuture.value);
useEffect(() {
if (backupState.hasError) {
WidgetsBinding.instance.addPostFrameCallback((_) {
showErrorMessage(context, backupState.error!.toString());
});
} else if (backupState.hasData) {
WidgetsBinding.instance.addPostFrameCallback((_) {
showInfoMessage(context, 'Backup created successfully');
ProfileListRoute().go(context);
});
}
return null;
}, [backupState.hasError, backupState.hasData, backupState.error]);
final disableInteraction =
backupState.connectionState == ConnectionState.waiting;
return Scaffold(
appBar: AppBar(title: const Text('Create Backup')),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8),
child: Form(
key: formKey,
child: ListView(
children: [
FancyPasswordField(
controller: passwordTextController,
enabled: !disableInteraction,
passwordController: passwordController,
enableSuggestions: false,
autocorrect: false,
enableIMEPersonalizedLearning: false,
keyboardType: TextInputType.visiblePassword,
decoration: const InputDecoration(
labelText: 'Password',
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validationRules: {MinCharactersValidationRule(5)},
validator: (value) {
//Make sure since onChange is sometimes unreliable
passwordController.onChange(value ?? '');
return passwordController.areAllRulesValidated
? null
: 'Not Validated';
},
),
const SizedBox(height: 16),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: integrityVerification.value,
onChanged: disableInteraction
? null
: (value) {
integrityVerification.value = value;
},
title: const Text('Verify Backup Integrity'),
subtitle: const Text(
'Automatically check that backups are complete and restorable',
),
),
ExpansionTile(
enabled: !disableInteraction,
childrenPadding: EdgeInsets.zero,
tilePadding: EdgeInsets.zero,
title: const Text('Advanced'),
children: [
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: skipPasswordConfirmation.value,
onChanged: disableInteraction
? null
: (value) {
skipPasswordConfirmation.value = value;
},
title: const Text('Skip Password Confirmation Prompt'),
),
],
),
const SizedBox(height: 16),
if (disableInteraction)
const Column(
children: [
LinearProgressIndicator(),
Text('Creating Backup'),
],
)
else
FilledButton.icon(
icon: const Icon(MdiIcons.safe),
onPressed: () async {
if (formKey.currentState?.validate() ?? false) {
if (!skipPasswordConfirmation.value) {
final confirmation = await showDialog<String>(
context: context,
builder: (context) {
final controller = TextEditingController();
return AlertDialog(
title: const Text('Password Confirmation'),
content: TextField(
controller: controller,
enableSuggestions: false,
autocorrect: false,
enableIMEPersonalizedLearning: false,
keyboardType: TextInputType.visiblePassword,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
floatingLabelBehavior:
FloatingLabelBehavior.always,
),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(controller.text);
},
child: const Text('Confirm'),
),
],
);
},
);
if (confirmation != passwordTextController.text) {
if (context.mounted) {
showErrorMessage(context, 'Passwords do not match');
}
return;
}
}
backupFuture.value = ref
.read(userBackupServiceProvider.notifier)
.createUserBackup(
profile,
password: passwordTextController.text,
integrityCheck: integrityVerification.value,
);
}
},
label: const Text('Backup'),
),
],
),
),
),
);
}
}
@@ -0,0 +1,79 @@
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:path/path.dart' as p;
import 'package:weblibre/core/providers/format.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/user/domain/providers.dart';
import 'package:weblibre/features/user/domain/services/user_backup.dart';
import 'package:weblibre/presentation/widgets/failure_widget.dart';
final _filenamePattern = RegExp(
r'^backup_(?<profile>.+?)_(?<timestamp>\d{4}-\d{2}-\d{2}_\d{6})\.weblibre$',
);
class ProfileBackupListScreen extends HookConsumerWidget {
const ProfileBackupListScreen();
@override
Widget build(BuildContext context, WidgetRef ref) {
final backupListAsync = ref.watch(backupListProvider);
return Scaffold(
appBar: AppBar(title: const Text('Backups')),
body: backupListAsync.when(
data: (backupList) {
return ListView.builder(
itemCount: backupList.length,
itemBuilder: (context, index) {
final file = backupList[index];
final match = _filenamePattern.firstMatch(p.basename(file.path));
if (match != null) {
final profileName = match.group(1)!;
final datePart = match.group(2)!;
// Reparse into DateTime
final dateTime = UserBackupService.dateFormatter.decode(
datePart,
);
return ListTile(
key: ValueKey(file.path),
title: Text(profileName),
subtitle: Text(
ref
.read(formatProvider.notifier)
.fullDateTimeWithTimezone(dateTime),
),
onTap: () async {
await RestoreProfileRoute(
backupFilePath: file.path,
).push(context);
},
);
} else {
return ListTile(
key: ValueKey(file.path),
title: Text(p.basename(file.path)),
onTap: () async {
await RestoreProfileRoute(
backupFilePath: file.path,
).push(context);
},
);
}
},
);
},
error: (error, stackTrace) => FailureWidget(
title: 'Failed to get backups',
exception: error,
onRetry: () {
ref.invalidate(backupListProvider);
},
),
loading: () => const Center(child: CircularProgressIndicator()),
),
);
}
}
@@ -17,10 +17,14 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/domain/entities/profile.dart';
import 'package:weblibre/features/user/domain/repositories/profile.dart';
import 'package:weblibre/utils/form_validators.dart';
@@ -81,62 +85,76 @@ class ProfileEditScreen extends HookConsumerWidget {
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateRequired,
validator: validateProfileName,
),
const SizedBox(height: 16),
if (profile != null)
if (profile != null) ...[
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
label: const Text('Backup'),
icon: const Icon(MdiIcons.safe),
onPressed: () async {
final result = await showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Delete User'),
content: const Text(
'Are you sure you want to delete this User including all data?',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Delete'),
),
],
);
},
);
if (result == true) {
await ref
.read(profileRepositoryProvider.notifier)
.deleteProfile(profile!.uuidValue.uuid);
if (context.mounted) {
context.pop();
}
}
await BackupProfileRoute(
profile: jsonEncode(profile!.toJson()),
).push(context);
},
),
),
],
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
style: OutlinedButton.styleFrom(
side: BorderSide(
color: Theme.of(context).colorScheme.error,
),
foregroundColor: Theme.of(context).colorScheme.error,
iconColor: Theme.of(context).colorScheme.error,
),
label: const Text('Delete'),
icon: const Icon(Icons.delete),
onPressed: () async {
final result = await showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Delete User'),
content: const Text(
'Are you sure you want to delete this User including all data?',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Delete'),
),
],
);
},
);
if (result == true) {
await ref
.read(profileRepositoryProvider.notifier)
.deleteProfile(profile!.uuidValue.uuid);
if (context.mounted) {
context.pop();
}
}
},
),
),
],
),
),
@@ -20,6 +20,7 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/filesystem.dart';
import 'package:weblibre/core/routing/routes.dart';
@@ -34,7 +35,17 @@ class ProfileListScreen extends HookConsumerWidget {
final usersAsync = ref.watch(profileRepositoryProvider);
return Scaffold(
appBar: AppBar(title: const Text('Users')),
appBar: AppBar(
title: const Text('Users'),
actions: [
IconButton(
onPressed: () async {
await ProfileBackupListRoute().push(context);
},
icon: const Icon(MdiIcons.backupRestore),
),
],
),
body: usersAsync.when(
skipLoadingOnReload: true,
data: (profiles) => ListView.builder(
@@ -0,0 +1,183 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:weblibre/core/routing/routes.dart';
import 'package:weblibre/features/user/domain/services/user_backup.dart';
import 'package:weblibre/utils/form_validators.dart';
import 'package:weblibre/utils/ui_helper.dart';
enum RestoreTarget { createOrOverride, createNew }
class ProfileRestoreScreen extends HookConsumerWidget {
final File backupFile;
const ProfileRestoreScreen({super.key, required this.backupFile});
@override
Widget build(BuildContext context, WidgetRef ref) {
final formKey = useMemoized(() => GlobalKey<FormState>());
final passwordTextController = useTextEditingController();
final nameTextController = useTextEditingController();
final restoreFuture = useState<Future<bool>?>(null);
final restoreState = useFuture(restoreFuture.value);
final restoreTarget = useState(RestoreTarget.createNew);
useEffect(() {
if (restoreState.hasError) {
WidgetsBinding.instance.addPostFrameCallback((_) {
showErrorMessage(context, restoreState.error!.toString());
});
} else if (restoreState.hasData) {
WidgetsBinding.instance.addPostFrameCallback((_) {
showInfoMessage(context, 'Backup restored successfully');
ProfileListRoute().go(context);
});
}
return null;
}, [restoreState.hasError, restoreState.hasData, restoreState.error]);
final disableInteraction =
restoreState.connectionState == ConnectionState.waiting;
return Scaffold(
appBar: AppBar(title: const Text('Restore Backup')),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8),
child: Form(
key: formKey,
child: ListView(
children: [
TextFormField(
controller: passwordTextController,
enabled: !disableInteraction,
enableSuggestions: false,
autocorrect: false,
enableIMEPersonalizedLearning: false,
keyboardType: TextInputType.visiblePassword,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: (value) {
return validateRequired(value, message: 'Password required');
},
),
const SizedBox(height: 16),
RadioGroup(
groupValue: restoreTarget.value,
onChanged: (value) {
if (value != null) {
restoreTarget.value = value;
}
},
child: Column(
children: [
RadioListTile(
enabled: !disableInteraction,
value: RestoreTarget.createNew,
title: const Text('Create New User'),
subtitle: const Text('Restore backup as a new user'),
),
RadioListTile(
enabled: !disableInteraction,
value: RestoreTarget.createOrOverride,
title: const Text('Restore & Replace'),
subtitle: const Text(
'Restore backup and overwrite existing user if present',
),
),
],
),
),
if (restoreTarget.value == RestoreTarget.createNew)
TextFormField(
controller: nameTextController,
enabled: !disableInteraction,
decoration: const InputDecoration(
label: Text('Name'),
floatingLabelBehavior: FloatingLabelBehavior.always,
),
validator: validateProfileName,
),
const SizedBox(height: 16),
if (disableInteraction)
const Column(
children: [
LinearProgressIndicator(),
Text('Restoring Backup'),
],
)
else
FilledButton.icon(
icon: const Icon(MdiIcons.backupRestore),
onPressed: () {
if (formKey.currentState?.validate() ?? false) {
restoreFuture.value = switch (restoreTarget.value) {
RestoreTarget.createOrOverride =>
ref
.read(userBackupServiceProvider.notifier)
.restoreAndCreateOrOverride(
backupFile,
password: passwordTextController.text,
confirmOverrideCallback: () {
if (context.mounted) {
return showDialog<bool?>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
icon: const Icon(Icons.warning),
title: const Text('Override User'),
content: const Text(
'Are you sure you want to override the exisiting User?',
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('Cancel'),
),
TextButton(
onPressed: () {
Navigator.pop(context, true);
},
child: const Text('Override'),
),
],
);
},
);
} else {
throw Exception('Override failed');
}
},
),
RestoreTarget.createNew =>
ref
.read(userBackupServiceProvider.notifier)
.restoreAndCreateNew(
backupFile,
profileName: nameTextController.text,
password: passwordTextController.text,
),
};
}
},
label: const Text('Restore'),
),
],
),
),
),
);
}
}