// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:unifiedpush_platform_interface/data/push_endpoint.dart'; import 'package:unifiedpush_platform_interface/data/push_message.dart'; import 'package:unifiedpush_platform_interface/unifiedpush_platform_interface.dart'; import 'api/docwell_api.dart' hide PushMessage; import 'l10n.dart'; /// Push notifications through UnifiedPush (Android). The phone's distributor /// app (ntfy, NextPush, …) gives this app an endpoint; docwell-server sends /// notifications there, encrypted to this app's Web Push keys. Messages that /// don't decrypt are dropped, so knowing the endpoint is not enough to send /// a notification. class PushService extends ChangeNotifier { PushService({FlutterSecureStorage? storage}) : _storage = storage ?? const FlutterSecureStorage(); static const _instance = 'docwell'; final FlutterSecureStorage _storage; final _local = FlutterLocalNotificationsPlugin(); DocwellApi? _api; void Function(String route)? _open; /// Whether this phone gets push notifications (it registered an endpoint). bool get enabled => _deviceId != null; String? _deviceId; /// Why push can't be turned on, e.g. no distributor installed. String? problem; bool get supported => !kIsWeb && Platform.isAndroid; /// Sets up the handlers. [open] receives the app route of a tapped /// notification. Future init(void Function(String route) open) async { _open = open; if (!supported) return; _deviceId = await _storage.read(key: 'push_device'); await _local.initialize( settings: const InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), ), onDidReceiveNotificationResponse: (r) { final route = r.payload; if (route != null && route.startsWith('/')) _open?.call(route); }, ); // A tap that started the app. final launch = await _local.getNotificationAppLaunchDetails(); final route = launch?.notificationResponse?.payload; if (launch?.didNotificationLaunchApp == true && route != null) { Future.microtask(() => _open?.call(route)); } await UnifiedPushPlatform.instance.initializeCallback( onNewEndpoint: (e, _) => _registerEndpoint(e), onUnregistered: (_) => _forget(), onMessage: (m, _) => _show(m), ); } /// The signed-in session: endpoints get registered with this server. set api(DocwellApi? api) { _api = api; // Endpoints can change; the connector reports them again on register. if (api != null && enabled) _register(); } /// Turns push on. Returns false (and sets [problem]) when the phone has /// no UnifiedPush distributor. Future enable() async { if (!supported) return false; problem = null; final ok = await UnifiedPushPlatform.instance .tryUseCurrentOrDefaultDistributor(); if (!ok) { final all = await UnifiedPushPlatform.instance.getDistributors(const []); if (all.isEmpty) { problem = tr('pushNoDistributor'); notifyListeners(); return false; } await UnifiedPushPlatform.instance.saveDistributor(all.first); } await _local .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin >() ?.requestNotificationsPermission(); await _register(); return true; } Future _register() => UnifiedPushPlatform.instance.register(_instance, const [], null, null); /// Turns push off on this phone and tells the server to stop. Future disable() async { final id = _deviceId; if (id != null) { try { await _api?.removeDevice(id); } catch (_) { // The server forgets endpoints that stop answering anyway. } } if (supported) await UnifiedPushPlatform.instance.unregister(_instance); await _forget(); } Future _registerEndpoint(PushEndpoint e) async { final keys = e.pubKeySet; final api = _api; if (keys == null || api == null) return; try { final device = await api.registerDevice( endpoint: e.url, p256dh: keys.pubKey, auth: keys.auth, name: 'Android', ); _deviceId = device.id; await _storage.write(key: 'push_device', value: device.id); notifyListeners(); } catch (err) { problem = tr('pushRefused', {'error': err}); notifyListeners(); } } Future _forget() async { _deviceId = null; await _storage.delete(key: 'push_device'); notifyListeners(); } Future _show(PushMessage m) async { if (!m.decrypted) return; final Map msg; try { msg = jsonDecode(utf8.decode(m.content)) as Map; } catch (_) { return; } await _local.show( id: DateTime.now().millisecondsSinceEpoch & 0x7fffffff, title: msg['title'] as String? ?? 'Docwell', body: msg['body'] as String? ?? '', notificationDetails: NotificationDetails( android: AndroidNotificationDetails( 'activity', tr('pushChannel'), channelDescription: tr('pushChannelHint'), importance: Importance.defaultImportance, ), ), payload: msg['route'] as String?, ); } }