CW-1000 Background sync improvements (#2142)

* feat: background sync improvements

- dev options on ci build cherrypick
- add permissions for background sync to AndroidManifestBase
- enable desugaring + update java compatibility to 17
- update walletconnect_flutter_v2
- update ens_dart
- update nostr_tools
- add notification for new transactions found in background
- expose more settings from flutter_daemon in UI
- remove battery optimization setting when it's already disabled
- fix notification permission handling
- fix background sync last trigger saving
- prevent notifications from being duplicated

* potential fix for multiple notifications firing for the same tx

* improve logging in background sync

* ui improvements to ignore battery optimization popup

* feat: logs for bg sync
disable decred bgsync

* fix: call store() directly to be sure that it is writing the data

* chore: rename logs to background sync logs

* Update lib/view_model/dashboard/dashboard_view_model.dart

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* chore: remove unused key

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
This commit is contained in:
cyan
2025-04-24 19:06:43 +02:00
committed by GitHub
co-authored by Omar Hatem
parent e6c9cf54fb
commit 02e74b5997
48 changed files with 1373 additions and 68 deletions
+104 -8
View File
@@ -1,26 +1,101 @@
import 'dart:async';
import 'dart:math';
import 'dart:io';
import 'package:cake_wallet/core/key_service.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_item.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_view_model.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
class BackgroundSync {
final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin();
bool _isInitialized = false;
Future<void> _initializeNotifications() async {
if (_isInitialized) return;
const androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const initializationSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
);
await _notificationsPlugin.initialize(initializationSettings);
_isInitialized = true;
}
Future<bool> requestPermissions() async {
if (Platform.isIOS || Platform.isMacOS) {
return await _notificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
) ?? false;
} else if (Platform.isAndroid) {
return await _notificationsPlugin
.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()
?.areNotificationsEnabled() ?? false;
}
return false;
}
Future<void> showNotification(String title, String content) async {
await _initializeNotifications();
final hasPermission = await requestPermissions();
if (!hasPermission) {
printV('Notification permissions not granted');
return;
}
const androidDetails = AndroidNotificationDetails(
'transactions',
'Transactions',
channelDescription: 'Channel for notifications about transactions',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
);
const iosDetails = DarwinNotificationDetails();
const notificationDetails = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
);
await _notificationsPlugin.show(
DateTime.now().millisecondsSinceEpoch.hashCode,
title,
content,
notificationDetails,
);
}
Future<void> sync() async {
printV("Background sync started");
await _syncMonero();
await _syncWallets();
printV("Background sync completed");
}
Future<void> _syncMonero() async {
Future<void> _syncWallets() async {
final walletLoadingService = getIt.get<WalletLoadingService>();
final walletListViewModel = getIt.get<WalletListViewModel>();
final settingsStore = getIt.get<SettingsStore>();
@@ -28,10 +103,10 @@ class BackgroundSync {
final List<WalletListItem> moneroWallets = walletListViewModel.wallets
.where((element) => !element.isHardware)
.where((element) => [WalletType.monero].contains(element.type))
.where((element) => ![WalletType.haven, WalletType.decred].contains(element.type))
.toList();
for (int i = 0; i < moneroWallets.length; i++) {
final wallet = await walletLoadingService.load(moneroWallets[i].type, moneroWallets[i].name);
final wallet = await walletLoadingService.load(moneroWallets[i].type, moneroWallets[i].name, isBackground: true);
int syncedTicks = 0;
final keyService = getIt.get<KeyService>();
@@ -75,7 +150,7 @@ class BackgroundSync {
} else {
syncedTicks = 0;
}
if (kDebugMode) {
if (FeatureFlag.hasDevOptions) {
if (syncStatus is SyncingSyncStatus) {
final blocksLeft = syncStatus.blocksLeft;
printV("$blocksLeft Blocks Left");
@@ -100,6 +175,27 @@ class BackgroundSync {
}
}
}
final txs = wallet.transactionHistory;
final sortedTxs = txs.transactions.values.toList()..sort((a, b) => a.date.compareTo(b.date));
final sharedPreferences = await SharedPreferences.getInstance();
for (final tx in sortedTxs) {
final lastTriggerString = sharedPreferences.getString(PreferencesKey.backgroundSyncLastTrigger(wallet.name));
final lastTriggerDate = lastTriggerString != null
? DateTime.parse(lastTriggerString)
: DateTime.now();
final keys = sharedPreferences.getKeys();
if (tx.date.isBefore(lastTriggerDate)) {
printV("w: ${wallet.name}, tx: ${tx.date} is before $lastTriggerDate (lastTriggerString: $lastTriggerString) (k: ${keys.length})");
continue;
}
await sharedPreferences.setString(PreferencesKey.backgroundSyncLastTrigger(wallet.name), tx.date.add(Duration(minutes: 1)).toIso8601String());
final action = tx.direction == TransactionDirection.incoming ? "Received" : "Sent";
if (sharedPreferences.getBool(PreferencesKey.backgroundSyncNotificationsEnabled) ?? false) {
await showNotification("$action ${wallet.currency.fullName} in ${wallet.name}", "${tx.amountFormatted()}");
}
printV("${wallet.currency.fullName} in ${wallet.name}: TX: ${tx.date} ${tx.amount} ${tx.direction}");
}
wallet.id;
await wallet.stopBackgroundSync(await keyService.getWalletPassword(walletName: wallet.name));
await wallet.close(shouldCleanup: true);
}
+4 -1
View File
@@ -52,8 +52,11 @@ class WalletLoadingService {
}
}
Future<WalletBase> load(WalletType type, String name, {String? password}) async {
Future<WalletBase> load(WalletType type, String name, {String? password, bool isBackground = false}) async {
try {
if (!isBackground) {
await sharedPreferences.setString(PreferencesKey.backgroundSyncLastTrigger(name), DateTime.now().toIso8601String());
}
final walletService = walletServiceFactory.call(type);
final walletPassword = password ?? (await keyService.getWalletPassword(walletName: name));
final wallet = await walletService.openWallet(name, walletPassword);
+23 -12
View File
@@ -33,11 +33,13 @@ import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/haven/cw_haven.dart';
import 'package:cake_wallet/src/screens/dev/monero_background_sync.dart';
import 'package:cake_wallet/src/screens/dev/moneroc_call_profiler.dart';
import 'package:cake_wallet/src/screens/dev/shared_preferences_page.dart';
import 'package:cake_wallet/src/screens/settings/background_sync_page.dart';
import 'package:cake_wallet/src/screens/wallet_connect/services/bottom_sheet_service.dart';
import 'package:cake_wallet/src/screens/wallet_connect/services/key_service/wallet_connect_key_service.dart';
import 'package:cake_wallet/src/screens/wallet_connect/services/walletkit_service.dart';
import 'package:cake_wallet/view_model/dev/monero_background_sync.dart';
import 'package:cake_wallet/view_model/dev/shared_preferences.dart';
import 'package:cake_wallet/view_model/link_view_model.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/src/screens/transaction_details/rbf_details_page.dart';
@@ -266,6 +268,8 @@ import 'buy/kryptonim/kryptonim.dart';
import 'buy/meld/meld_buy_provider.dart';
import 'src/screens/buy/buy_sell_page.dart';
import 'cake_pay/cake_pay_payment_credantials.dart';
import 'package:cake_wallet/view_model/dev/background_sync_logs_view_model.dart';
import 'package:cake_wallet/src/screens/dev/background_sync_logs_page.dart';
final getIt = GetIt.instance;
@@ -883,9 +887,8 @@ Future<void> setup({
nanoAccountCreationViewModel:
getIt.get<NanoAccountEditOrCreateViewModel>(param1: account)));
getIt.registerFactory(() {
return DisplaySettingsViewModel(getIt.get<SettingsStore>());
});
getIt.registerFactory(() =>
DisplaySettingsViewModel(getIt.get<SettingsStore>()));
getIt.registerFactory(() =>
SilentPaymentsSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
@@ -893,22 +896,20 @@ Future<void> setup({
getIt.registerFactory(
() => MwebSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(() {
return PrivacySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!);
});
getIt.registerFactory(() =>
PrivacySettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!));
getIt.registerFactory(() => TrocadorExchangeProvider());
getIt.registerFactory(() => TrocadorProvidersViewModel(
getIt.get<SettingsStore>(), getIt.get<TrocadorExchangeProvider>()));
getIt.registerFactory(() {
return OtherSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!,
getIt.get<SendViewModel>());});
getIt.registerFactory(() =>
OtherSettingsViewModel(getIt.get<SettingsStore>(), getIt.get<AppStore>().wallet!,
getIt.get<SendViewModel>()));
getIt.registerFactory(() {
return SecuritySettingsViewModel(getIt.get<SettingsStore>());
});
getIt.registerFactory(() =>
SecuritySettingsViewModel(getIt.get<SettingsStore>()));
getIt.registerFactory(() => WalletSeedViewModel(getIt.get<AppStore>().wallet!));
@@ -916,6 +917,8 @@ Future<void> setup({
getIt.registerFactory(() => DevMoneroBackgroundSync(getIt.get<AppStore>().wallet!));
getIt.registerFactory(() => DevSharedPreferences());
getIt.registerFactoryParam<WalletSeedPage, bool, void>((bool isWalletCreated, _) =>
WalletSeedPage(getIt.get<WalletSeedViewModel>(), isNewWalletCreated: isWalletCreated));
@@ -1456,6 +1459,14 @@ Future<void> setup({
getIt.registerFactory(() => SeedVerificationPage(getIt.get<WalletSeedViewModel>()));
getIt.registerFactory(() => DevMoneroBackgroundSyncPage(getIt.get<DevMoneroBackgroundSync>()));
getIt.registerFactory(() => DevMoneroCallProfilerPage());
getIt.registerFactory(() => DevSharedPreferencesPage(getIt.get<DevSharedPreferences>()));
getIt.registerFactory(() => BackgroundSyncLogsViewModel());
getIt.registerFactory(() => DevBackgroundSyncLogsPage(getIt.get<BackgroundSyncLogsViewModel>()));
_isSetupFinished = true;
}
+2
View File
@@ -105,4 +105,6 @@ class PreferencesKey {
static const walletConnectPairingTopicsList = 'wallet_connect_pairing_topics_list';
static String walletConnectPairingTopicsListForWallet(String publicKey) =>
'${PreferencesKey.walletConnectPairingTopicsList}_${publicKey}';
static String backgroundSyncLastTrigger(String walletId) => 'background_sync_last_trigger_${walletId}';
static const backgroundSyncNotificationsEnabled = 'background_sync_notifications_enabled';
}
+11
View File
@@ -36,6 +36,8 @@ import 'package:cake_wallet/src/screens/dashboard/pages/transactions_page.dart';
import 'package:cake_wallet/src/screens/dashboard/sign_page.dart';
import 'package:cake_wallet/src/screens/dev/monero_background_sync.dart';
import 'package:cake_wallet/src/screens/dev/moneroc_call_profiler.dart';
import 'package:cake_wallet/src/screens/dev/shared_preferences_page.dart';
import 'package:cake_wallet/src/screens/dev/background_sync_logs_page.dart';
import 'package:cake_wallet/src/screens/disclaimer/disclaimer_page.dart';
import 'package:cake_wallet/src/screens/exchange/exchange_page.dart';
import 'package:cake_wallet/src/screens/exchange/exchange_template_page.dart';
@@ -836,6 +838,15 @@ Route<dynamic> createRoute(RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (_) => getIt.get<DevMoneroBackgroundSyncPage>(),
);
case Routes.devSharedPreferences:
return MaterialPageRoute<void>(
builder: (_) => getIt.get<DevSharedPreferencesPage>(),
);
case Routes.devBackgroundSyncLogs:
return MaterialPageRoute<void>(
builder: (_) => getIt.get<DevBackgroundSyncLogsPage>(),
);
case Routes.devMoneroCallProfiler:
return MaterialPageRoute<void>(
+4
View File
@@ -111,8 +111,12 @@ class Routes {
static const importNFTPage = '/import_nft_page';
static const torPage = '/tor_page';
static const backgroundSync = '/background_sync';
static const devMoneroBackgroundSync = '/dev/monero_background_sync';
static const devMoneroCallProfiler = '/dev/monero_call_profiler';
static const devSharedPreferences = '/dev/shared_preferences';
static const devBackgroundSyncLogs = '/dev/background_sync_logs';
static const signPage = '/sign_page';
static const connectDevices = '/device/connect';
static const urqrAnimatedPage = '/urqr/animated_page';
@@ -0,0 +1,314 @@
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/view_model/dev/background_sync_logs_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:intl/intl.dart';
class DevBackgroundSyncLogsPage extends BasePage {
final BackgroundSyncLogsViewModel viewModel;
DevBackgroundSyncLogsPage(this.viewModel) {
viewModel.loadLogs();
}
@override
String? get title => "[dev] background sync logs";
@override
Widget? trailing(BuildContext context) {
return IconButton(
icon: Icon(Icons.refresh),
onPressed: () => viewModel.loadLogs(),
);
}
@override
Widget body(BuildContext context) {
return Observer(
builder: (_) {
if (viewModel.isLoading) {
return Center(child: CircularProgressIndicator());
}
if (viewModel.error != null) {
return Center(child: Text("Error: ${viewModel.error}"));
}
if (viewModel.logData == null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("No logs loaded"),
SizedBox(height: 16),
ElevatedButton(
onPressed: () => viewModel.loadLogs(),
child: Text("Load Logs"),
),
],
),
);
}
return DefaultTabController(
length: 2,
child: Column(
children: [
TabBar(
tabs: [
Tab(text: "Logs (${viewModel.logs.length})"),
Tab(text: "Sessions (${viewModel.sessions.length})"),
],
),
Expanded(
child: TabBarView(
children: [
_buildLogsTab(context),
_buildSessionsTab(context),
],
),
),
_buildActionButtons(context),
],
),
);
},
);
}
Widget _buildLogsTab(BuildContext context) {
final logs = viewModel.logs;
if (logs.isEmpty) {
return Center(child: Text("No logs available"));
}
final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss.SSS');
return ListView.builder(
itemCount: logs.length,
itemBuilder: (context, index) {
final log = logs[index];
return ListTile(
title: Text(
log.message,
style: TextStyle(
fontSize: 14,
fontFamily: 'Monospace',
),
),
subtitle: Text(
'${dateFormat.format(log.timestamp)} | ${log.level}' +
(log.sessionId != null ? ' | Session: ${log.sessionId}' : ''),
style: TextStyle(
fontSize: 12,
color: _getLevelColor(log.level),
),
),
dense: true,
onTap: () {
Clipboard.setData(ClipboardData(text: log.message));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Log message copied to clipboard')),
);
},
onLongPress: () {
Clipboard.setData(ClipboardData(
text: '${dateFormat.format(log.timestamp)} [${log.level}] ${log.message}'));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Full log entry copied to clipboard')),
);
},
tileColor: index % 2 == 0 ? Colors.transparent : Colors.black.withOpacity(0.03),
);
},
);
}
Widget _buildSessionsTab(BuildContext context) {
final sessions = viewModel.sessions;
if (sessions.isEmpty) {
return Center(child: Text("No sessions available"));
}
final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');
return ListView.builder(
itemCount: sessions.length,
itemBuilder: (context, index) {
final session = sessions[index];
final isActive = session.endTime == null;
return ExpansionTile(
title: Text(
session.name,
style: TextStyle(
fontWeight: FontWeight.bold,
color: isActive ? Colors.green : null,
),
),
subtitle: Text(
'ID: ${session.id} | Started: ${dateFormat.format(session.startTime)}',
style: TextStyle(fontSize: 12),
),
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Start: ${session.startTime.toString()}'),
if (session.endTime != null)
Text('End: ${session.endTime.toString()}'),
if (session.duration != null)
Text('Duration: ${_formatDuration(session.duration!)}'),
SizedBox(height: 8),
_buildSessionLogs(context, session.id),
],
),
),
],
);
},
);
}
Widget _buildSessionLogs(BuildContext context, int sessionId) {
final sessionLogs = viewModel.logs
.where((log) => log.sessionId == sessionId)
.toList();
if (sessionLogs.isEmpty) {
return Text('No logs for this session');
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Session Logs (${sessionLogs.length}):',
style: TextStyle(fontWeight: FontWeight.bold)),
SizedBox(height: 8),
Container(
height: 200,
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.05),
borderRadius: BorderRadius.circular(4),
),
child: ListView.builder(
itemCount: sessionLogs.length,
itemBuilder: (context, index) {
final log = sessionLogs[index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
child: Text(
'[${log.level}] ${log.message}',
style: TextStyle(
fontSize: 12,
fontFamily: 'Monospace',
color: _getLevelColor(log.level),
),
),
);
},
),
),
],
);
}
Widget _buildActionButtons(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
icon: Icon(Icons.refresh),
label: Text('Refresh'),
onPressed: () => viewModel.loadLogs(),
),
ElevatedButton.icon(
icon: Icon(Icons.copy),
label: Text('Copy All'),
onPressed: () => _copyAllLogs(context),
),
ElevatedButton.icon(
icon: Icon(Icons.delete),
label: Text('Clear'),
onPressed: () => _confirmClearLogs(context),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
),
],
),
);
}
void _copyAllLogs(BuildContext context) {
if (viewModel.logData == null) return;
final buffer = StringBuffer();
final dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss.SSS');
for (final log in viewModel.logs) {
buffer.writeln('${dateFormat.format(log.timestamp)} [${log.level}] ${log.message}');
}
Clipboard.setData(ClipboardData(text: buffer.toString()));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('All logs copied to clipboard')),
);
}
void _confirmClearLogs(BuildContext context) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Clear Logs'),
content: Text('Are you sure you want to clear the logs display?'),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: Text('Clear'),
style: TextButton.styleFrom(foregroundColor: Colors.red),
onPressed: () {
viewModel.clearLogs();
Navigator.of(context).pop();
},
),
],
);
},
);
}
Color _getLevelColor(String level) {
switch (level.toLowerCase()) {
case 'error':
return Colors.red;
case 'warning':
return Colors.orange;
case 'info':
return Colors.blue;
case 'debug':
return Colors.green;
case 'trace':
return Colors.purple;
default:
return Colors.grey;
}
}
String _formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
return '${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds';
}
}
@@ -0,0 +1,404 @@
import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/view_model/dev/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
class DevSharedPreferencesPage extends BasePage {
final DevSharedPreferences viewModel;
DevSharedPreferencesPage(this.viewModel);
@override
String? get title => "[dev] shared preferences";
@override
Widget? trailing(BuildContext context) {
return IconButton(
icon: Icon(Icons.add),
onPressed: () => _showCreateDialog(context),
);
}
@override
Widget body(BuildContext context) {
return Observer(
builder: (_) {
if (viewModel.sharedPreferences == null) {
return Center(child: Text("No shared preferences found"));
}
final keys = viewModel.keys;
Map<String, dynamic> values = {};
for (final key in keys) {
values[key] = viewModel.get(key);
}
Map<String, PreferenceType> types = {};
for (final key in keys) {
types[key] = viewModel.getPreferenceType(key);
}
return ListView.builder(
itemCount: keys.length,
itemBuilder: (context, index) {
final key = keys[index];
final type = types[key]!;
return ListTile(
onTap: () {
Clipboard.setData(ClipboardData(text: key + ": " + values[key].toString()));
},
onLongPress: () {
_showEditDialog(context, key, type, values[key]);
},
title: switch (type) {
PreferenceType.bool => Text(key, style: TextStyle(color: Colors.blue)),
PreferenceType.int => Text(key, style: TextStyle(color: Colors.green)),
PreferenceType.double => Text(key, style: TextStyle(color: Colors.yellow)),
PreferenceType.listString => Text(key, style: TextStyle(color: Colors.purple)),
PreferenceType.string => Text(key),
PreferenceType.unknown => Text(key),
},
subtitle: switch (type) {
PreferenceType.bool => Text("bool: ${values[key]}"),
PreferenceType.int => Text("int: ${values[key]}"),
PreferenceType.double => Text("double: ${values[key]}"),
PreferenceType.listString => values[key].isEmpty as bool ? Text("listString: []") : Text("listString:\n- ${values[key].join("\n- ")}"),
PreferenceType.string => Text("string: ${values[key]}"),
PreferenceType.unknown => Text("UNKNOWN(${values[key].runtimeType}): ${values[key]}"),
},
);
},
);
},
);
}
void _showEditDialog(BuildContext context, String key, PreferenceType type, dynamic currentValue) {
dynamic newValue = currentValue;
bool isListString = type == PreferenceType.listString;
List<String> listItems = isListString ? List<String>.from(currentValue as Iterable<dynamic>) : [];
TextEditingController textController = TextEditingController(
text: isListString ? '' : currentValue?.toString() ?? '');
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text('Edit $key'),
content: SizedBox(
width: double.maxFinite,
height: double.maxFinite,
child: SingleChildScrollView(
child: _buildDialogContent(
type,
newValue,
listItems,
textController,
(value) => setState(() => newValue = value),
(items) => setState(() => listItems = items),
),
),
),
actions: <Widget>[
TextButton(
child: Text('Delete'),
style: TextButton.styleFrom(foregroundColor: Colors.red),
onPressed: () {
_showDeleteConfirmation(context, key);
},
),
TextButton(
child: Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: Text('Save'),
onPressed: () async {
if (_validateAndUpdateValue(
context,
type,
textController,
listItems,
(value) => newValue = value
)) {
await viewModel.set(key, type, newValue);
Navigator.of(context).pop();
}
},
),
],
);
},
);
},
);
}
void _showDeleteConfirmation(BuildContext context, String key) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Delete Preference'),
content: Text('Are you sure you want to delete "$key"?'),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: Text('Delete'),
style: TextButton.styleFrom(foregroundColor: Colors.red),
onPressed: () {
viewModel.delete(key);
Navigator.of(context).pop();
Navigator.of(context).pop();
},
),
],
);
},
);
}
Widget _buildDialogContent(
PreferenceType type,
dynamic value,
List<String> listItems,
TextEditingController textController,
Function(dynamic) onValueChanged,
Function(List<String>) onListChanged,
) {
return switch (type) {
PreferenceType.bool => _buildBoolEditor(value as bool, onValueChanged),
PreferenceType.int => _buildNumberEditor(textController, 'Integer value', true),
PreferenceType.double => _buildNumberEditor(textController, 'Double value', false),
PreferenceType.string => _buildTextEditor(textController),
PreferenceType.listString => _buildListEditor(listItems, textController, onListChanged),
PreferenceType.unknown => Text('Cannot edit unknown type'),
};
}
Widget _buildBoolEditor(bool value, Function(bool) onChanged) {
return CheckboxListTile(
title: Text('Value'),
value: value,
onChanged: (newValue) {
if (newValue != null) onChanged(newValue);
},
);
}
Widget _buildTextEditor(TextEditingController controller) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
decoration: InputDecoration(labelText: 'String value'),
maxLines: null,
),
],
);
}
Widget _buildNumberEditor(TextEditingController controller, String label, bool isInteger) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
decoration: InputDecoration(labelText: label),
keyboardType: isInteger
? TextInputType.number
: TextInputType.numberWithOptions(decimal: true),
inputFormatters: isInteger
? [FilteringTextInputFormatter.digitsOnly]
: [FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*$'))],
),
],
);
}
Widget _buildListEditor(
List<String> items,
TextEditingController controller,
Function(List<String>) onListChanged,
) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: 200,
child: ReorderableListView(
shrinkWrap: true,
children: [
for (int i = 0; i < items.length; i++)
ListTile(
key: Key('$i'),
title: Text(items[i]),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () {
final newList = List<String>.from(items);
newList.removeAt(i);
onListChanged(newList);
},
),
)
],
onReorder: (int oldIndex, int newIndex) {
final newList = List<String>.from(items);
if (oldIndex < newIndex) {
newIndex -= 1;
}
final item = newList.removeAt(oldIndex);
newList.insert(newIndex, item);
onListChanged(newList);
},
),
),
Row(
children: [
Expanded(
child: TextField(
controller: controller,
decoration: InputDecoration(labelText: 'New item'),
),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () {
if (controller.text.isNotEmpty) {
final newList = List<String>.from(items);
newList.add(controller.text);
onListChanged(newList);
controller.clear();
}
},
),
],
),
],
);
}
bool _validateAndUpdateValue(
BuildContext context,
PreferenceType type,
TextEditingController controller,
List<String> listItems,
Function(dynamic) setNewValue,
) {
switch (type) {
case PreferenceType.int:
if (controller.text.isNotEmpty) {
try {
setNewValue(int.parse(controller.text));
} catch (e) {
_showErrorMessage(context, 'Invalid integer value');
return false;
}
}
break;
case PreferenceType.double:
if (controller.text.isNotEmpty) {
try {
setNewValue(double.parse(controller.text));
} catch (e) {
_showErrorMessage(context, 'Invalid double value');
return false;
}
}
break;
case PreferenceType.string:
setNewValue(controller.text);
break;
case PreferenceType.listString:
setNewValue(listItems);
break;
default:
break;
}
return true;
}
void _showErrorMessage(BuildContext context, String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
}
void _showCreateDialog(BuildContext context) {
PreferenceType selectedType = PreferenceType.string;
TextEditingController keyController = TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Text('Create Preference'),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: keyController,
decoration: InputDecoration(labelText: 'Preference Key'),
),
SizedBox(height: 16),
DropdownButtonFormField<PreferenceType>(
value: selectedType,
decoration: InputDecoration(labelText: 'Type'),
items: [
DropdownMenuItem(value: PreferenceType.string, child: Text('String')),
DropdownMenuItem(value: PreferenceType.bool, child: Text('Boolean')),
DropdownMenuItem(value: PreferenceType.int, child: Text('Integer')),
DropdownMenuItem(value: PreferenceType.double, child: Text('Double')),
DropdownMenuItem(value: PreferenceType.listString, child: Text('List of Strings')),
],
onChanged: (value) {
if (value != null) {
setState(() {
selectedType = value;
});
}
},
),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
TextButton(
child: Text('Create'),
onPressed: () {
if (keyController.text.isEmpty) {
_showErrorMessage(context, 'Key cannot be empty');
return;
}
viewModel.set(keyController.text, selectedType, switch (selectedType) {
PreferenceType.bool => false,
PreferenceType.int => 0,
PreferenceType.double => 0.0,
PreferenceType.string => '',
PreferenceType.listString => [],
PreferenceType.unknown => null,
});
Navigator.of(context).pop();
},
),
],
);
},
);
},
);
}
}
@@ -12,6 +12,7 @@ import 'package:cake_wallet/view_model/dashboard/dashboard_view_model.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:permission_handler/permission_handler.dart';
class BackgroundSyncPage extends BasePage {
BackgroundSyncPage(this.dashboardViewModel);
@@ -28,30 +29,30 @@ class BackgroundSyncPage extends BasePage {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (dashboardViewModel.hasBatteryOptimization)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.unrestricted_background_service,
value: !dashboardViewModel.batteryOptimizationEnabled,
onValueChange: (_, bool value) {
dashboardViewModel.disableBatteryOptimization();
},
);
}),
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync,
value: dashboardViewModel.backgroundSyncEnabled,
onValueChange: (dashboardViewModel.batteryOptimizationEnabled && dashboardViewModel.hasBatteryOptimization) ? (_, bool value) {
unawaited(showPopUp(context: context, builder: (context) => AlertWithOneAction(
alertTitle: S.current.background_sync,
alertContent: S.current.unrestricted_background_service_notice,
buttonText: S.current.ok,
buttonAction: () => Navigator.of(context).pop(),
)));
} : (_, bool value) {
onValueChange: (_, bool value) async {
if (value) {
dashboardViewModel.enableBackgroundSync();
if (dashboardViewModel.batteryOptimizationEnabled) {
await showPopUp(context: context, builder: (context) => AlertWithOneAction(
alertTitle: S.current.background_sync,
alertContent: S.current.unrestricted_background_service_notice,
buttonText: S.current.ok,
buttonAction: () => Navigator.of(context).pop(),
));
await dashboardViewModel.disableBatteryOptimization();
for (var i = 0; i < 4 * 60; i++) {
await Future.delayed(Duration(milliseconds: 250));
if (!dashboardViewModel.batteryOptimizationEnabled) {
await dashboardViewModel.enableBackgroundSync();
return;
}
}
} else {
dashboardViewModel.enableBackgroundSync();
}
} else {
dashboardViewModel.disableBackgroundSync();
}
@@ -68,22 +69,58 @@ class BackgroundSyncPage extends BasePage {
dashboardViewModel.setSyncMode(syncMode);
});
}),
// Observer(builder: (context) {
// return SettingsSwitcherCell(
// title: S.current.background_sync_on_battery,
// value: dashboardViewModel.backgroundSyncOnBattery,
// onValueChange: (_, bool value) =>
// dashboardViewModel.setBackgroundSyncOnBattery(value),
// );
// }),
// Observer(builder: (context) {
// return SettingsSwitcherCell(
// title: S.current.background_sync_on_data,
// value: dashboardViewModel.backgroundSyncOnData,
// onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncOnData(value),
// );
// }),
if (dashboardViewModel.hasBgsyncNetworkConstraints)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync_on_unmetered_network,
value: dashboardViewModel.backgroundSyncNetworkUnmetered,
onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncNetworkUnmetered(value),
);
}),
if (dashboardViewModel.hasBgsyncBatteryNotLowConstraints)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync_on_battery_low,
value: !dashboardViewModel.backgroundSyncBatteryNotLow,
onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncBatteryNotLow(!value),
);
}),
if (dashboardViewModel.hasBgsyncChargingConstraints)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync_on_charging,
value: dashboardViewModel.backgroundSyncCharging,
onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncCharging(value),
);
}),
if (dashboardViewModel.hasBgsyncDeviceIdleConstraints)
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.background_sync_on_device_idle,
value: dashboardViewModel.backgroundSyncDeviceIdle,
onValueChange: (_, bool value) => dashboardViewModel.setBackgroundSyncDeviceIdle(value),
);
}),
Observer(builder: (context) {
return SettingsSwitcherCell(
title: S.current.new_transactions_notifications,
value: dashboardViewModel.backgroundSyncNotificationsEnabled,
onValueChange: (_, bool value) {
try {
dashboardViewModel.setBackgroundSyncNotificationsEnabled(value);
} catch (e) {
showPopUp(context: context, builder: (context) => AlertWithOneAction(
alertTitle: S.current.error,
alertContent: S.current.notification_permission_denied,
buttonText: S.current.ok,
buttonAction: () {
Navigator.of(context).pop();
},
));
}
},
);
}),
],
),
);
@@ -49,7 +49,7 @@ class ConnectionSyncPage extends BasePage {
title: S.current.manage_nodes,
handler: (context) => Navigator.of(context).pushNamed(Routes.manageNodes),
),
if (dashboardViewModel.hasBackgroundSync && Platform.isAndroid && FeatureFlag.isBackgroundSyncEnabled) ...[
if (Platform.isAndroid && FeatureFlag.isBackgroundSyncEnabled) ...[
SettingsCellWithArrow(
title: S.current.background_sync,
handler: (context) => Navigator.of(context).pushNamed(Routes.backgroundSync),
@@ -6,12 +6,10 @@ import 'package:cake_wallet/src/screens/base_page.dart';
import 'package:cake_wallet/src/screens/settings/widgets/setting_priority_picker_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_cell_with_arrow.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_picker_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_switcher_cell.dart';
import 'package:cake_wallet/src/screens/settings/widgets/settings_version_cell.dart';
import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/view_model/settings/other_settings_view_model.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
@@ -77,6 +75,18 @@ class OtherSettingsPage extends BasePage {
handler: (BuildContext context) =>
Navigator.of(context).pushNamed(Routes.devMoneroCallProfiler),
),
if (FeatureFlag.hasDevOptions)
SettingsCellWithArrow(
title: '[dev] shared preferences',
handler: (BuildContext context) =>
Navigator.of(context).pushNamed(Routes.devSharedPreferences),
),
if (FeatureFlag.hasDevOptions)
SettingsCellWithArrow(
title: '[dev] background sync logs',
handler: (BuildContext context) =>
Navigator.of(context).pushNamed(Routes.devBackgroundSyncLogs),
),
Spacer(),
SettingsVersionCell(
title: S.of(context).version(_otherSettingsViewModel.currentVersion)),
@@ -51,6 +51,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_daemon/flutter_daemon.dart';
import 'package:http/http.dart' as http;
import 'package:mobx/mobx.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../themes/theme_base.dart';
@@ -180,7 +181,7 @@ abstract class DashboardViewModelBase with Store {
isShowThirdYatIntroduction = false;
unawaited(isBackgroundSyncEnabled());
unawaited(isBatteryOptimizationEnabled());
unawaited(_loadConstraints());
final _wallet = wallet;
if (_wallet.type == WalletType.monero) {
@@ -536,6 +537,88 @@ abstract class DashboardViewModelBase with Store {
return resp;
}
@observable
late bool backgroundSyncNotificationsEnabled = sharedPreferences.getBool(PreferencesKey.backgroundSyncNotificationsEnabled) ?? false;
@action
Future<void> setBackgroundSyncNotificationsEnabled(bool value) async {
if (!value) {
backgroundSyncNotificationsEnabled = false;
sharedPreferences.setBool(PreferencesKey.backgroundSyncNotificationsEnabled, false);
return;
}
PermissionStatus permissionStatus = await Permission.notification.status;
if (permissionStatus != PermissionStatus.granted) {
final resp = await Permission.notification.request();
if (resp == PermissionStatus.denied) {
throw Exception("Notification permission denied");
}
}
backgroundSyncNotificationsEnabled = value;
await sharedPreferences.setBool(PreferencesKey.backgroundSyncNotificationsEnabled, value);
}
bool get hasBgsyncNetworkConstraints => Platform.isAndroid;
bool get hasBgsyncBatteryNotLowConstraints => Platform.isAndroid;
bool get hasBgsyncChargingConstraints => Platform.isAndroid;
bool get hasBgsyncDeviceIdleConstraints => Platform.isAndroid;
@observable
bool backgroundSyncNetworkUnmetered = false;
@observable
bool backgroundSyncBatteryNotLow = false;
@observable
bool backgroundSyncCharging = false;
@observable
bool backgroundSyncDeviceIdle = false;
Future<void> _loadConstraints() async {
backgroundSyncNetworkUnmetered = await FlutterDaemon().getNetworkType();
backgroundSyncBatteryNotLow = await FlutterDaemon().getBatteryNotLow();
backgroundSyncCharging = await FlutterDaemon().getRequiresCharging();
backgroundSyncDeviceIdle = await FlutterDaemon().getDeviceIdle();
}
@action
Future<void> setBackgroundSyncNetworkUnmetered(bool value) async {
backgroundSyncNetworkUnmetered = value;
await FlutterDaemon().setNetworkType(value);
if (await isBackgroundSyncEnabled()) {
await enableBackgroundSync();
}
}
@action
Future<void> setBackgroundSyncBatteryNotLow(bool value) async {
backgroundSyncBatteryNotLow = value;
await FlutterDaemon().setBatteryNotLow(value);
if (await isBackgroundSyncEnabled()) {
await enableBackgroundSync();
}
}
@action
Future<void> setBackgroundSyncCharging(bool value) async {
backgroundSyncCharging = value;
await FlutterDaemon().setRequiresCharging(value);
if (await isBackgroundSyncEnabled()) {
await enableBackgroundSync();
}
}
@action
Future<void> setBackgroundSyncDeviceIdle(bool value) async {
backgroundSyncDeviceIdle = value;
await FlutterDaemon().setDeviceIdle(value);
if (await isBackgroundSyncEnabled()) {
await enableBackgroundSync();
}
}
bool get hasBatteryOptimization => Platform.isAndroid;
@observable
@@ -0,0 +1,44 @@
import 'package:flutter_daemon/flutter_daemon.dart';
import 'package:mobx/mobx.dart';
part 'background_sync_logs_view_model.g.dart';
class BackgroundSyncLogsViewModel = BackgroundSyncLogsViewModelBase with _$BackgroundSyncLogsViewModel;
abstract class BackgroundSyncLogsViewModelBase with Store {
final FlutterDaemon _daemon = FlutterDaemon();
@observable
LogData? logData;
@observable
bool isLoading = false;
@observable
String? error;
@computed
List<LogEntry> get logs => logData?.logs ?? [];
@computed
List<LogSession> get sessions => logData?.sessions ?? [];
@action
Future<void> loadLogs() async {
isLoading = true;
error = null;
try {
logData = await _daemon.getLogs();
} catch (e) {
error = e.toString();
} finally {
isLoading = false;
}
}
@action
Future<void> clearLogs() async {
await _daemon.clearLogs();
await loadLogs();
}
}
@@ -0,0 +1,92 @@
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'shared_preferences.g.dart';
class DevSharedPreferences = DevSharedPreferencesBase with _$DevSharedPreferences;
enum PreferenceType {
unknown,
string,
int,
double,
bool,
listString
}
abstract class DevSharedPreferencesBase with Store {
DevSharedPreferencesBase() {
SharedPreferences.getInstance().then((value) {
sharedPreferences = value;
});
}
@observable
SharedPreferences? sharedPreferences;
@computed
List<String> get keys => (sharedPreferences?.getKeys().toList()?..sort()) ?? [];
@action
Future<void> delete(String key) async {
if (sharedPreferences == null) {
return;
}
await sharedPreferences!.remove(key);
}
dynamic get(String key) {
if (sharedPreferences == null) {
return null;
}
return sharedPreferences!.get(key);
}
Future<void> set(String key, PreferenceType type, dynamic value) async {
if (sharedPreferences == null) {
return;
}
switch (type) {
case PreferenceType.string:
await sharedPreferences!.setString(key, value as String);
break;
case PreferenceType.bool:
await sharedPreferences!.setBool(key, value as bool);
break;
case PreferenceType.int:
await sharedPreferences!.setInt(key, value as int);
break;
case PreferenceType.double:
await sharedPreferences!.setDouble(key, value as double);
break;
case PreferenceType.listString:
await sharedPreferences!.setStringList(key, List<String>.from(value as Iterable<dynamic>));
break;
default:
throw Exception("Unknown preference type: $type");
}
}
PreferenceType getPreferenceType(String key) {
if (sharedPreferences == null) {
return PreferenceType.unknown;
}
final value = sharedPreferences!.get(key);
if (value is String) {
return PreferenceType.string;
}
if (value is bool) {
return PreferenceType.bool;
}
if (value is int) {
return PreferenceType.int;
}
if (value is double) {
return PreferenceType.double;
}
if (value is List<String>) {
return PreferenceType.listString;
}
return PreferenceType.unknown;
}
}
+4
View File
@@ -14,6 +14,7 @@ import 'package:cake_wallet/entities/evm_transaction_error_fees_handler.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/entities/parsed_address.dart';
import 'package:cake_wallet/entities/template.dart';
import 'package:cake_wallet/entities/preferences_key.dart';
import 'package:cake_wallet/entities/transaction_description.dart';
import 'package:cake_wallet/entities/wallet_contact.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
@@ -52,6 +53,7 @@ import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'send_view_model.g.dart';
@@ -587,6 +589,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
transactionNote: note,
));
}
final sharedPreferences = await SharedPreferences.getInstance();
await sharedPreferences.setString(PreferencesKey.backgroundSyncLastTrigger(wallet.name), DateTime.now().add(Duration(minutes: 1)).toIso8601String());
state = TransactionCommitted();
} catch (e) {