Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions desktop-app/lib/app.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:quantus_desktop_wallet/constants.dart';
import 'package:quantus_desktop_wallet/providers/notifications_provider.dart';
import 'package:quantus_desktop_wallet/services/own_activity_notifications.dart';
import 'package:quantus_desktop_wallet/ui/shell/desktop_shell.dart';
import 'package:quantus_sdk/quantus_sdk.dart';
import 'package:wallet_core/l10n/app_localizations.dart';
Expand All @@ -11,6 +13,8 @@ class QuantusDesktopApp extends ConsumerWidget {

@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(notificationsStartupProvider);
ref.watch(ownActivityNotificationsProvider);
final theme = AppTheme.darkTheme(context, text: const AppTextThemeV3.desktop());

return MaterialApp(
Expand Down
4 changes: 2 additions & 2 deletions desktop-app/lib/bootstrap/app_bootstrap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/misc.dart';
import 'package:quantus_desktop_wallet/app.dart';
import 'package:quantus_desktop_wallet/providers/notifications_provider.dart';
import 'package:quantus_desktop_wallet/providers/shell_providers.dart';
import 'package:quantus_desktop_wallet/services/desktop_local_notifications.dart';
import 'package:quantus_desktop_wallet/services/desktop_push_registration.dart';
import 'package:quantus_desktop_wallet/services/desktop_telemetry.dart';
import 'package:quantus_desktop_wallet/services/user_approval.dart';
Expand All @@ -23,7 +23,7 @@ List<Override> desktopWalletCoreOverrides() => [
...walletCoreOverrides(
telemetry: (_) => const DesktopTelemetry(),
pushRegistration: (_) => const DesktopPushRegistration(),
localNotifications: (_) => const DesktopLocalNotifications(),
localNotifications: (ref) => ref.watch(desktopLocalNotificationsProvider.notifier),
userApproval: (ref) => ref.watch(systemApprovalProvider),
),
// The sidebar shows every account's balance, so each refresh of the active
Expand Down
32 changes: 32 additions & 0 deletions desktop-app/lib/models/notification_status.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/// What the system lets the app do with notifications.
sealed class NotificationStatus {
const NotificationStatus();
}

/// The system's notifications have not been started yet.
final class NotificationsStarting extends NotificationStatus {
const NotificationsStarting();
}

/// macOS: started, but the person has not been asked yet whether the app may
/// show notifications.
final class NotificationsNotAsked extends NotificationStatus {
const NotificationsNotAsked();
}

/// The app may show notifications.
final class NotificationsAllowed extends NotificationStatus {
const NotificationsAllowed();
}

/// macOS: the person said no, when asked or later in System Settings.
final class NotificationsDenied extends NotificationStatus {
const NotificationsDenied();
}

/// The system's notifications could not be used; [reason] says why.
final class NotificationsUnavailable extends NotificationStatus {
const NotificationsUnavailable(this.reason);

final String reason;
}
179 changes: 179 additions & 0 deletions desktop-app/lib/providers/notifications_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import 'dart:async';
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:quantus_desktop_wallet/constants.dart';
import 'package:quantus_desktop_wallet/models/notification_status.dart';
import 'package:quantus_desktop_wallet/models/wallet_presence.dart';
import 'package:quantus_desktop_wallet/providers/shell_providers.dart';
import 'package:quantus_desktop_wallet/providers/wallet_presence_provider.dart';
import 'package:quantus_desktop_wallet/services/notification_plugin.dart';
import 'package:quantus_desktop_wallet/services/window_chrome.dart';
import 'package:quantus_sdk/quantus_sdk.dart';
import 'package:wallet_core/models/notification_models.dart';
import 'package:wallet_core/providers/account_providers.dart';
import 'package:wallet_core/providers/l10n_provider.dart';
import 'package:wallet_core/services/local_notifications.dart';
import 'package:wallet_core/services/telemetry.dart';

/// The desktop's system notifications: wallet_core's [LocalNotifications],
/// and what the system lets the app do with them.
///
/// Notifications that cannot be shown never stop the app: the status says
/// why, for Settings to tell the person.
class DesktopLocalNotifications extends Notifier<NotificationStatus> implements LocalNotifications {
/// Who the app is to Windows, which files its notifications under them.
static const windowsAppUserModelId = 'Quantus.DesktopWallet';

/// The app's notification activator on Windows. It must never change: the
/// system keeps it registered for the app.
static const windowsActivatorGuid = '745d2a45-cfdc-4f29-91c2-0c8a985a2e19';

Future<void>? _started;

@override
NotificationStatus build() => const NotificationsStarting();

/// Starts the system's notifications. Started once, however often called.
Future<void> start() => _started ??= _start();

Future<void> _start() async {
final settings = InitializationSettings(
macOS: const DarwinInitializationSettings(
requestAlertPermission: false,
requestSoundPermission: false,
requestBadgePermission: false,
),
windows: const WindowsInitializationSettings(
appName: appTitle,
appUserModelId: windowsAppUserModelId,
guid: windowsActivatorGuid,
),
linux: LinuxInitializationSettings(defaultActionName: ref.read(l10nProvider).desktopNotificationOpenAction),
);
try {
await ref.read(notificationPluginProvider).initialize(settings, onClick: _open);
} catch (e) {
_unavailable(e);
return;
}
state = defaultTargetPlatform == TargetPlatform.macOS
? const NotificationsNotAsked()
: const NotificationsAllowed();
await _openLaunchClick();
}

/// Opens what the click that launched the app was about, if one did: such
/// a click comes before the notifications were started, so not through
/// [_open] as a click on the running app does.
Future<void> _openLaunchClick() async {
final String? payload;
try {
payload = await ref.read(notificationPluginProvider).launchPayload();
} catch (e) {
quantusPrint('The click that launched the app could not be read: $e');
ref.read(telemetryProvider).sendError('desktop_notification_launch_unreadable', error: e);
return;
}
if (payload != null) _open(payload);
}

/// Asks macOS whether the app may show notifications. Windows and Linux do
/// not ask, and nothing can be asked of notifications that are unavailable.
Future<void> requestPermission() async {
await start();
if (defaultTargetPlatform != TargetPlatform.macOS || state is NotificationsUnavailable) return;
try {
final allowed = await ref.read(notificationPluginProvider).requestMacOSPermission();
state = allowed ? const NotificationsAllowed() : const NotificationsDenied();
} catch (e) {
_unavailable(e);
}
}

/// The account a click asked for, until the wallet's accounts and its
/// active account have loaded, as at launch.
String? _clickedAccountId;
final _untilLoaded = <ProviderSubscription<Object?>>[];

/// Opens what a clicked notification was about: the window comes to the
/// front, on the account the notification named when it is still there.
void _open(String? payload) {
unawaited(const WindowChrome().bringToFront());
final String accountId;
try {
accountId = (jsonDecode(payload!) as Map<String, dynamic>)['accountId'] as String;
} catch (e) {
quantusPrint('A clicked notification could not be read: $e');
ref.read(telemetryProvider).sendError('desktop_notification_click_unreadable', error: e);
return;
}
_clickedAccountId = accountId;
if (_openClickedAccount() || _untilLoaded.isNotEmpty) return;
_untilLoaded
..add(ref.listen(sidebarAccountsProvider, (_, _) => _openClickedAccount()))
..add(ref.listen(activeAccountProvider, (_, _) => _openClickedAccount()));
}

/// Selects the clicked account once the accounts and the active account
/// have loaded: before that, restoring the saved active account would undo
/// it. Returns whether the click is done with.
bool _openClickedAccount() {
final accountId = _clickedAccountId;
if (accountId == null) return true;
final accounts = ref.read(sidebarAccountsProvider);
if (accounts.isEmpty || !ref.read(activeAccountProvider).hasValue) return false;
_clickedAccountId = null;
for (final subscription in _untilLoaded) {
subscription.close();
}
_untilLoaded.clear();
final account = accounts.where((display) => display.account.accountId == accountId).firstOrNull;
if (account != null) unawaited(ref.read(sidebarSelectionProvider.notifier).showAccount(account));
return true;
}

void _unavailable(Object error) {
quantusPrint('Desktop notifications are unavailable: $error');
ref.read(telemetryProvider).sendError('desktop_notifications_unavailable', error: error);
state = NotificationsUnavailable('$error');
}

/// Shows [notification] now. Callers check [state] first: showing one the
/// system does not allow fails.
@override
Future<void> showOrScheduleNotification(NotificationData notification) async {
if (notification.hasValidScheduleTime) {
throw UnsupportedError('Desktop notifications cannot be scheduled: no desktop feature schedules one yet');
}
final status = state;
if (status is! NotificationsAllowed) {
throw StateError('Desktop notifications are not allowed: ${status.runtimeType}');
}
await ref
.read(notificationPluginProvider)
.show(
// The plugins take a 32-bit id.
id: notification.id.hashCode & 0x7fffffff,
title: notification.title,
body: notification.message,
payload: jsonEncode({'accountId': notification.accountId}),
);
}
}

final desktopLocalNotificationsProvider = NotifierProvider<DesktopLocalNotifications, NotificationStatus>(
DesktopLocalNotifications.new,
);

/// Starts the system's notifications with the app, and asks for permission
/// once there is a wallet to notify about.
final notificationsStartupProvider = Provider<void>((ref) {
final notifications = ref.watch(desktopLocalNotificationsProvider.notifier);
unawaited(notifications.start());
ref.listen(walletPresenceProvider, (_, presence) {
if (presence.value == WalletPresence.present) unawaited(notifications.requestPermission());
}, fireImmediately: true);
});
14 changes: 0 additions & 14 deletions desktop-app/lib/services/desktop_local_notifications.dart

This file was deleted.

70 changes: 70 additions & 0 deletions desktop-app/lib/services/notification_plugin.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// The system's notifications, as the app uses them. The plugin sits behind
/// this so that tests can stand in for the system.
abstract interface class NotificationPlugin {
/// Starts the system's notifications with [settings], calling [onClick]
/// with a notification's payload when the person clicks it. Throws when the
/// system's notification service does not start.
Future<void> initialize(InitializationSettings settings, {required void Function(String? payload) onClick});

/// The payload of the notification whose click launched the app, if one
/// did. Such a click comes before the app has started its notifications,
/// so it never reaches [initialize]'s `onClick`.
Future<String?> launchPayload();

/// Asks macOS whether the app may show notifications, with sounds and a
/// badge. Returns whether it may. macOS asks the person only the first
/// time; after that it answers with what they chose.
Future<bool> requestMacOSPermission();

/// Shows a notification now. One shown with the same [id] replaces it.
Future<void> show({required int id, required String title, required String body, required String payload});
}

/// The system's notifications through flutter_local_notifications.
class SystemNotificationPlugin implements NotificationPlugin {
final _plugin = FlutterLocalNotificationsPlugin();

@override
Future<void> initialize(InitializationSettings settings, {required void Function(String? payload) onClick}) async {
final started = await _plugin.initialize(
settings: settings,
onDidReceiveNotificationResponse: (response) => onClick(response.payload),
);
// Null: the plugin has nothing for this platform.
if (started == null) throw StateError('There are no system notifications on $defaultTargetPlatform');
// On macOS the answer is whether permission was granted, which starting
// does not ask for; Windows and Linux answer whether their service started.
if (!started && defaultTargetPlatform != TargetPlatform.macOS) {
throw StateError("The system's notification service did not start");
}
}

/// Asked of macOS only. Linux has no launch details, and Windows cannot
/// launch this app for a click: the plugin registers the app's activator
/// with Windows only while the app is running.
@override
Future<String?> launchPayload() async {
if (defaultTargetPlatform != TargetPlatform.macOS) return null;
final details = await _plugin.getNotificationAppLaunchDetails();
if (details == null || !details.didNotificationLaunchApp) return null;
return details.notificationResponse?.payload;
}

@override
Future<bool> requestMacOSPermission() async {
final macOS = _plugin.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>();
if (macOS == null) throw StateError('There are no macOS notifications on $defaultTargetPlatform');
return await macOS.requestPermissions(alert: true, sound: true, badge: true) ?? false;
}

@override
Future<void> show({required int id, required String title, required String body, required String payload}) {
return _plugin.show(id: id, title: title, body: body, payload: payload);
}
}

final notificationPluginProvider = Provider<NotificationPlugin>((ref) => SystemNotificationPlugin());
Loading
Loading