Files
meshcore-open/lib/services/notification_service.dart
T
zjs81 462159e803 Tester feedback: offline mode, pt-PT, menus, layout and translations
Offline (read-only) mode
- The last connected radio is remembered; with no radio the app opens on
  its saved contacts, channels, messages and unread counts.
- Main screens stay open on disconnect. A Connect button replaces the
  battery and signal indicators, with a sheet to reconnect, choose a
  radio or stop a pending reconnect.
- While disconnected everything is read-only: the composer becomes a
  "connect to send" bar (drafts kept) and controls that change the radio
  or stored history are disabled or hidden.
- Resending while disconnected no longer deletes the message; a
  different radio no longer shows the previous radio's channels.
- Notification taps open the saved chat while offline.

Chats and menus
- Channel chat menu: notifications, edit channel, delete channel; the
  filter row lines up with the others; bell moved out of the app bar.
- DM and room menus: remove from contacts; rooms get room management.
- Search field uses the full app bar; long-press a result to copy.
- Hashtag channel titles no longer read "# #name"; more room around the
  radio activity dot.
- Repeat filter: short messages from one sender are caught at the same
  count as long ones.

Layout
- Shared menu row (wraps to two lines) and segment label (never splits
  a word) used across the app.
- One Scan button on the scanner; consistent settings tile titles;
  contact "last seen" wraps instead of truncating; unfetched repeater
  settings are dimmed.

Localization
- New European Portuguese locale (pt_PT); regional locales are handled
  by the language picker, notifications and the background service.
- Fill 67 missing strings per locale, including backup and restore.
- Keep "Flood" and "Zero Hop" untranslated, shorten "last seen" and
  routing labels, and fix mistranslated scan, theme and hop strings.
- Received-image strings, badge and caption come from translations.
- Regenerate the Czech localizations, which were missing strings.

Docs
- Add documentation/design.md (UI reference) and offline-mode.md;
  update channel, chat, navigation and scanner docs.
2026-11-09 21:18:29 -07:00

1187 lines
39 KiB
Dart

import 'dart:async';
import 'dart:io' show Platform, File;
import 'dart:isolate';
import 'dart:ui';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../helpers/gif_helper.dart';
import '../helpers/contact_share_message.dart';
import '../helpers/marker_message.dart';
import '../helpers/message_url_image_helper.dart';
import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../l10n/locale_tag.dart';
import '../models/app_settings.dart';
import '../storage/prefs_manager.dart';
import '../utils/platform_info.dart';
import 'notification_reply.dart';
import 'received_image_store.dart' show ReceivedImageRef;
class NotificationService {
static final NotificationService _instance = NotificationService._internal();
factory NotificationService() => _instance;
NotificationService._internal();
final FlutterLocalNotificationsPlugin _notifications =
FlutterLocalNotificationsPlugin();
bool _isInitialized = false;
// Locale for localized notification strings
Locale _locale = const Locale('en');
String _publicIpfsGateway = AppSettings.defaultPublicIpfsGateway;
void setPublicIpfsGateway(String gateway) {
_publicIpfsGateway = gateway.trim();
}
/// Set the locale for notification strings (call when app locale changes)
void setLocale(Locale locale) {
_locale = locale;
// The background action isolate reads this to localize its notices.
try {
PrefsManager.instance.setString(
notificationLanguagePrefsKey,
localeTag(locale),
);
} catch (_) {}
}
AppLocalizations get _l10n => lookupAppLocalizations(_locale);
String? _selfName;
/// Name of the connected radio, shown as the sender of your own replies.
void setSelfName(String? name) {
_selfName = name;
}
// Recent messages per conversation notification id, so each notification
// shows the conversation (Android MessagingStyle, used by Android Auto).
static const _maxConversationMessages = 6;
final Map<int, _Conversation> _conversations = {};
// Single-subscription so actions that arrive before the connector listens
// (e.g. during startup) are buffered instead of dropped.
final StreamController<NotificationReply> _replies =
StreamController<NotificationReply>();
ReceivePort? _replyPort;
/// Reply, mark-as-read and mute actions taken on message notifications.
/// Has a single listener (the connector).
Stream<NotificationReply> get replies => _replies.stream;
/// Stops receiving notification actions. The background handler then tells
/// the user the app isn't running instead of forwarding to nobody.
void releaseReplyPort() {
if (_replyPort == null) return;
IsolateNameServer.removePortNameMapping(notificationReplyPortName);
_replyPort!.close();
_replyPort = null;
}
String _logSafe(String value) {
final sanitized = value.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), ' ');
return Uri.encodeComponent(sanitized);
}
// Rate limiting to prevent notification storms
// (Added after getting notification-flooded while evaluating RF flood management. The irony.)
static const _minNotificationInterval = Duration(seconds: 3);
static const _batchWindow = Duration(seconds: 5);
/// Messages for the same conversation that arrive within this window are
/// posted as one notification update. A queue sync can deliver hundreds of
/// messages in seconds; posting each one floods the shade and makes the
/// phone sluggish (Android also drops updates past its rate limit).
static const _coalesceDelay = Duration(milliseconds: 800);
/// While the radio's offline queue is syncing, sound/vibrate at most this
/// often instead of every [_minNotificationInterval].
static const _bulkSyncAlertInterval = Duration(seconds: 60);
/// Reports whether the connector is draining the radio's message queue.
bool Function()? isBulkSyncActive;
/// Current unread total for the app badge. Coalesced conversation updates
/// flush on independent timers, so a count captured when a message was
/// queued can be older than one already posted by another conversation.
int Function()? unreadTotalProvider;
/// Newest badge count seen on any queued message, when no provider is set.
int? _latestQueuedBadgeCount;
final Map<String, List<_PendingNotification>> _pendingConversationUpdates =
{};
final Map<String, Timer> _conversationUpdateTimers = {};
/// Bumped whenever a conversation notification is cleared, so a post still
/// awaiting permission/image lookup does not bring a read chat back.
final Map<int, int> _clearGenerations = {};
int _cancelAllGeneration = 0;
(int, int) _clearGenerationOf(int id) =>
(_cancelAllGeneration, _clearGenerations[id] ?? 0);
void _bumpClearGeneration(int id) =>
_clearGenerations[id] = (_clearGenerations[id] ?? 0) + 1;
DateTime? _lastNotificationTime;
final List<_PendingNotification> _pendingNotifications = [];
bool _isBatchingActive = false;
bool _suppressNotifications = false;
/// Temporarily suppress all notifications (e.g., during sync)
void suppressNotifications(bool suppress) {
_suppressNotifications = suppress;
if (suppress) {
_pendingNotifications.clear();
_dropAllPendingConversationUpdates();
}
}
Future<void> initialize() async {
if (_isInitialized) return;
const androidSettings = AndroidInitializationSettings(
'@drawable/ic_stat_notification',
);
const iosSettings = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const macSettings = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);
const windowsSettings = WindowsInitializationSettings(
appName: 'MeshCore Open',
appUserModelId: 'org.meshcore.open.app',
guid: 'e7ea8f85-72f5-4f36-91f6-038f740ccf86',
);
const linuxSettings = LinuxInitializationSettings(
defaultActionName: 'Open notification',
);
const initSettings = InitializationSettings(
android: androidSettings,
iOS: iosSettings,
macOS: macSettings,
windows: windowsSettings,
linux: linuxSettings,
);
// On Linux, the notifications plugin opens a D-Bus session bus
// connection whose async subscription can throw an unhandled
// SocketException when the bus socket is missing (e.g. running as
// root or inside a container without a session bus).
if (PlatformInfo.isLinux && !_isDbusSessionAvailable()) {
debugPrint('Skipping notification init: D-Bus session bus unavailable');
return;
}
try {
await _notifications.initialize(
settings: initSettings,
onDidReceiveNotificationResponse: _onNotificationTapped,
onDidReceiveBackgroundNotificationResponse:
notificationActionBackgroundHandler,
);
_registerReplyPort();
_isInitialized = true;
} catch (e) {
debugPrint('Error initializing notifications: $e');
}
}
void _registerReplyPort() {
if (kIsWeb || _replyPort != null) return;
final port = ReceivePort();
IsolateNameServer.removePortNameMapping(notificationReplyPortName);
IsolateNameServer.registerPortWithName(
port.sendPort,
notificationReplyPortName,
);
port.listen((dynamic message) {
if (message is! Map) return;
_dispatchAction(
actionId: message['actionId'] as String?,
payload: message['payload'] as String?,
input: message['input'] as String?,
);
});
_replyPort = port;
}
void _dispatchAction({
required String? actionId,
required String? payload,
String? input,
}) {
final reply = NotificationReply.parse(
actionId: actionId,
payload: payload,
input: input,
);
if (reply != null) _replies.add(reply);
}
static bool _isDbusSessionAvailable() {
final addr = Platform.environment['DBUS_SESSION_BUS_ADDRESS'];
if (addr != null && addr.isNotEmpty) return true;
// Fallback: check the default socket for the current user.
final uid = Platform.environment['UID'] ?? Platform.environment['EUID'];
final path = '/run/user/${uid ?? '1000'}/bus';
return File(path).existsSync();
}
Future<bool> _ensureInitialized() async {
if (!_isInitialized) {
await initialize();
}
return _isInitialized;
}
// Cached "are we allowed to post notifications" result. Null = not yet
// determined. Avoids calling _notifications.show() when it would only throw
// "You must request notifications permissions first" (every web build).
// Android denials are never cached so a later grant in system settings is
// picked up without restarting the app.
bool? _canNotify;
static const _permissionRequestedKey = 'notification_permission_requested';
Future<bool> _ensureCanNotify() async {
if (!await _ensureInitialized()) return false;
final cached = _canNotify;
if (cached != null) return cached;
// flutter_local_notifications has no web backend, so show() always throws.
// Skip silently instead of logging an error per incoming message.
if (kIsWeb) return _canNotify = false;
// On Android 13+ notifications require an explicit grant; reflect the real
// OS state so we don't spam failed show() calls when denied.
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidPlugin != null) {
final enabled = await androidPlugin.areNotificationsEnabled() ?? false;
if (enabled) _canNotify = true;
return enabled;
}
// iOS/macOS request permission during initialize(); desktop has no gate.
return _canNotify = true;
}
Future<bool> requestPermissions() async {
if (!_isInitialized) {
await initialize();
}
// Request Android 13+ notification permission
final androidPlugin = _notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>();
if (androidPlugin != null) {
final granted = await androidPlugin.requestNotificationsPermission();
if (granted == true) _canNotify = true;
return granted ?? false;
}
// iOS permissions are requested during initialization
final iosPlugin = _notifications
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin
>();
if (iosPlugin != null) {
final granted = await iosPlugin.requestPermissions(
alert: true,
badge: true,
sound: true,
);
if (granted == true) _canNotify = true;
return granted ?? false;
}
return true;
}
/// Asks for the Android 13+ notification permission the first time it is
/// needed. Never re-prompts after the user has answered once; iOS/macOS
/// already prompt during [initialize].
Future<void> requestPermissionsOnce() async {
if (!PlatformInfo.isAndroid || !await _ensureInitialized()) return;
final prefs = PrefsManager.instance;
if (prefs.getBool(_permissionRequestedKey) ?? false) return;
if (await _ensureCanNotify()) return;
await prefs.setBool(_permissionRequestedKey, true);
await requestPermissions();
}
/// Summarizes structured payloads (reactions, images, GIFs, shared
/// locations) with the same parsers the chat bubbles use; other text is
/// returned unchanged.
static String formatNotificationText(String text, AppLocalizations l10n) {
final trimmed = text.trim();
final reaction = ReactionHelper.parseReaction(trimmed);
if (reaction != null) {
return l10n.notification_reacted(reaction.emoji);
}
if (ReceivedImageRef.parse(trimmed) != null) {
return l10n.notification_sentImage;
}
if (GifHelper.parseGif(trimmed) != null) {
return l10n.notification_sentGif;
}
final contactShare = parseContactShare(trimmed);
if (contactShare != null) {
return l10n.contactShare_notification(
contactShare.name.isEmpty ? contactShare.shortKey : contactShare.name,
);
}
final marker = parseMarkerText(trimmed);
if (marker != null) {
return marker.label.isEmpty
? l10n.notification_sharedLocation
: l10n.notification_sharedLocationNamed(marker.label);
}
return text;
}
Future<String?> _resolveNotificationImagePath(
String text, {
required bool urlImagesEnabled,
}) async {
if (!urlImagesEnabled) return null;
final imageUrl = await MessageUrlImageHelper.parseVerified(
text,
publicGateway: _publicIpfsGateway,
);
if (imageUrl == null) return null;
try {
// Cache the image so notification platforms can read it from disk.
final imageFile = await DefaultCacheManager().getSingleFile(imageUrl);
if (!imageFile.existsSync()) return null;
return imageFile.path;
} catch (e) {
debugPrint('Failed to resolve notification image: $e');
return null;
}
}
List<AndroidNotificationAction> _conversationActions(bool isChannel) => [
AndroidNotificationAction(
notificationReplyActionId,
_l10n.notification_actionReply,
inputs: [
AndroidNotificationActionInput(label: _l10n.notification_replyHint),
],
semanticAction: SemanticAction.reply,
allowGeneratedReplies: true,
cancelNotification: false,
),
AndroidNotificationAction(
notificationMarkReadActionId,
_l10n.notification_actionMarkRead,
semanticAction: SemanticAction.markAsRead,
invisible: true,
),
if (isChannel)
AndroidNotificationAction(
notificationMuteActionId,
_l10n.notification_actionMuteChannel,
semanticAction: SemanticAction.mute,
),
];
AndroidNotificationDetails _androidConversationDetails(
_Conversation conversation, {
int? badgeCount,
bool silent = false,
}) {
final imagePath = conversation.imagePath;
final styleInformation = imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
contentTitle: conversation.title,
summaryText: _collapsedBody(conversation),
showBigPictureWhenCollapsed: true,
)
: MessagingStyleInformation(
Person(key: 'self', name: _selfName ?? _l10n.notification_you),
conversationTitle: conversation.isChannel
? conversation.title
: null,
groupConversation: conversation.isChannel,
messages: List<Message>.of(conversation.messages),
);
return AndroidNotificationDetails(
conversation.isChannel ? 'channel_messages' : 'messages',
conversation.isChannel ? 'Channel Messages' : 'Messages',
channelDescription: conversation.isChannel
? 'New channel message notifications'
: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@drawable/ic_stat_notification',
number: badgeCount,
silent: silent,
category: AndroidNotificationCategory.message,
styleInformation: styleInformation,
actions: _conversationActions(conversation.isChannel),
);
}
DarwinNotificationDetails _darwinDetails(String? imagePath, int? badge) =>
DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: badge,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
Future<void> _showConversationNotificationImpl({
required int id,
required String payload,
required String title,
required bool isChannel,
required String message,
required bool urlImagesEnabled,
String? senderName,
int? badgeCount,
bool silent = false,
List<_PendingNotification> earlier = const [],
}) async {
final generation = _clearGenerationOf(id);
if (!await _ensureCanNotify()) return;
// Only the newest messages fit in the notification anyway.
final skipped = earlier.length > _maxConversationMessages
? earlier.length - _maxConversationMessages
: 0;
final history = earlier.skip(skipped);
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
if (_clearGenerationOf(id) != generation) return;
final preview = formatNotificationText(message.trim(), _l10n);
final body = preview.isEmpty
? _l10n.notification_receivedNewMessage
: preview;
final conversation =
_conversations.putIfAbsent(
id,
() => _Conversation(
title: title,
payload: payload,
isChannel: isChannel,
),
)
..title = title
..badgeCount = badgeCount
..imagePath = imagePath;
for (final prior in history) {
final priorPreview = formatNotificationText(prior.body.trim(), _l10n);
final priorSender = isChannel ? (prior.senderName ?? title) : title;
conversation.add(
Message(
priorPreview.isEmpty
? _l10n.notification_receivedNewMessage
: priorPreview,
DateTime.now(),
Person(
key: isChannel ? 'sender:$priorSender' : payload,
name: priorSender,
),
),
_maxConversationMessages,
);
}
final sender = isChannel ? (senderName ?? title) : title;
conversation.add(
Message(
body,
DateTime.now(),
Person(key: isChannel ? 'sender:$sender' : payload, name: sender),
),
_maxConversationMessages,
);
final notificationDetails = NotificationDetails(
android: _androidConversationDetails(
conversation,
badgeCount: badgeCount,
silent: silent,
),
iOS: _darwinDetails(imagePath, badgeCount),
macOS: _darwinDetails(imagePath, badgeCount),
);
try {
await _notifications.show(
id: id,
title: title,
body: _collapsedBody(conversation),
notificationDetails: notificationDetails,
payload: payload,
);
} catch (e) {
debugPrint('Failed to show message notification: $e');
}
}
/// Text shown when the notification is collapsed. Channel messages keep
/// the sender prefix, including after your own reply.
String _collapsedBody(_Conversation conversation) {
final last = conversation.messages.last;
if (!conversation.isChannel) return last.text;
final sender = last.person?.name ?? _selfName ?? _l10n.notification_you;
return '$sender: ${last.text}';
}
int _conversationId(NotificationReply reply) => reply.isChannel
? reply.channelIndex!.hashCode
: reply.contactKeyHex!.hashCode;
/// Adds the user's reply to the conversation notification. Android keeps
/// showing a progress spinner on a replied notification until it is updated.
/// Pass the current [badgeCount]: an update replaces the whole notification,
/// and the Android launcher badge comes from the notification number.
Future<void> showOwnReply(
NotificationReply reply,
String text, {
int? badgeCount,
}) async {
if (!await _ensureInitialized()) return;
final id = _conversationId(reply);
final conversation = _conversations[id];
if (conversation == null) {
await _notifications.cancel(id: id);
return;
}
conversation.badgeCount = badgeCount ?? conversation.badgeCount;
conversation.add(
Message(text, DateTime.now(), null),
_maxConversationMessages,
);
await _repostConversation(id, conversation);
}
/// Tells the user a notification reply could not be sent.
Future<void> showReplyFailed(
NotificationReply reply,
NotificationReplyFailure failure, {
int? badgeCount,
}) async {
if (!await _ensureInitialized()) return;
final reason = switch (failure) {
NotificationReplyFailure.notConnected =>
_l10n.notification_replyNotConnected,
NotificationReplyFailure.unavailable =>
_l10n.notification_replyUnavailable,
NotificationReplyFailure.tooLong => _l10n.notification_replyTooLong,
NotificationReplyFailure.sendFailed => _l10n.notification_replySendFailed,
};
final id = _conversationId(reply);
final conversation = _conversations[id];
if (conversation != null) {
conversation.badgeCount = badgeCount ?? conversation.badgeCount;
await _repostConversation(id, conversation);
} else {
await _notifications.cancel(id: id);
}
try {
await _notifications.show(
id: 'reply_failed:$id'.hashCode,
title: _l10n.notification_replyFailedTitle,
body: reason,
notificationDetails: const NotificationDetails(
android: AndroidNotificationDetails(
'messages',
'Messages',
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@drawable/ic_stat_notification',
),
),
payload: conversation?.payload,
);
} catch (e) {
debugPrint('Failed to show reply failure notification: $e');
}
}
Future<void> _repostConversation(int id, _Conversation conversation) async {
try {
await _notifications.show(
id: id,
title: conversation.title,
body: _collapsedBody(conversation),
notificationDetails: NotificationDetails(
android: _androidConversationDetails(
conversation,
badgeCount: conversation.badgeCount,
silent: true,
),
),
payload: conversation.payload,
);
} catch (e) {
debugPrint('Failed to update message notification: $e');
}
}
Future<void> _showAdvertNotificationImpl({
required String contactName,
required String contactType,
String? contactId,
}) async {
if (!await _ensureCanNotify()) return;
const androidDetails = AndroidNotificationDetails(
'adverts',
'Advertisements',
channelDescription: 'New node advertisement notifications',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@drawable/ic_stat_notification',
);
const iosDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
);
const macDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
);
const notificationDetails = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
macOS: macDetails,
);
try {
await _notifications.show(
id: contactId != null
? 'advert:$contactId'.hashCode
: DateTime.now().millisecondsSinceEpoch & 0x7FFFFFFF,
title: _l10n.notification_newTypeDiscovered(contactType),
body: contactName,
notificationDetails: notificationDetails,
payload: 'advert:$contactId',
);
} catch (e) {
debugPrint('Failed to show advert notification: $e');
}
}
/// Posts a low-battery alert for the connected device.
///
/// Uses a per-device, per-threshold notification id so each alert level
/// updates its own notification instead of stacking, and alerts for
/// different radios don't overwrite each other. Bypasses the rate-limit
/// queue, which only handles message and advert notifications.
Future<void> showLowBatteryNotification({
required String deviceKey,
required String deviceName,
required int batteryPercent,
required int threshold,
}) async {
if (!await _ensureCanNotify()) return;
const androidDetails = AndroidNotificationDetails(
'low_battery',
'Low Battery',
channelDescription: 'Low battery alerts for the connected device',
importance: Importance.high,
priority: Priority.high,
icon: '@drawable/ic_stat_notification',
);
const darwinDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: false,
presentSound: true,
);
const notificationDetails = NotificationDetails(
android: androidDetails,
iOS: darwinDetails,
macOS: darwinDetails,
);
try {
await _notifications.show(
id: _lowBatteryNotificationId(deviceKey, threshold),
title: _l10n.notification_lowBatteryTitle,
body: _l10n.notification_lowBatteryBody(deviceName, batteryPercent),
notificationDetails: notificationDetails,
payload: 'low_battery',
);
} catch (e) {
debugPrint('Failed to show low battery notification: $e');
}
}
/// Returns a privacy-safe identifier for debug logging.
/// - advert: shows device name (body contains contactName)
/// - message: shows "from: sender" (avoids logging message content)
/// - channelMessage: shows "in: channel" (avoids logging message content)
String _getNotificationIdentifier(_PendingNotification n) {
switch (n.type) {
case _NotificationType.advert:
return _logSafe(n.body);
case _NotificationType.message:
return 'from: ${_logSafe(n.title)}';
case _NotificationType.channelMessage:
return 'in: ${_logSafe(n.title)}';
}
}
/// Payload (`message:<key>` or `channel:<index>`) of the last tapped
/// conversation notification, until [NotificationNavigator] consumes it.
final ValueNotifier<String?> pendingTap = ValueNotifier<String?>(null);
void _onNotificationTapped(NotificationResponse response) {
final payload = response.payload;
// Action buttons (reply, mark read, mute) are handled elsewhere; only a
// tap on the notification body should open the conversation. Use the
// response type, not actionId: the Windows plugin fills actionId with the
// payload even for plain body clicks.
if (payload == null ||
response.notificationResponseType !=
NotificationResponseType.selectedNotification) {
return;
}
debugPrint('Notification tapped: $payload');
if (payload.startsWith('message:') || payload.startsWith('channel:')) {
pendingTap.value = payload;
}
}
static const String _radioKeyPrefsKey = 'notifications_radio_key';
/// Called when a radio connects. Notifications name conversations by
/// contact key and channel *slot*; after switching radios a leftover
/// channel notification would open (and mark read) whatever channel the
/// new radio keeps in that slot, so a different radio clears them all.
/// The key is persisted so this also holds across app restarts.
Future<void> bindRadio(String radioKeyHex) async {
String? previous;
try {
previous = PrefsManager.instance.getString(_radioKeyPrefsKey);
await PrefsManager.instance.setString(_radioKeyPrefsKey, radioKeyHex);
} catch (_) {}
if (previous == null || previous == radioKeyHex) return;
if (!await _ensureInitialized()) return;
await cancelAll();
}
Future<void> cancelAll() async {
_cancelAllGeneration++;
_dropAllPendingConversationUpdates();
_conversations.clear();
await _notifications.cancelAll();
await _updateBadge(0);
}
Future<void> cancel(int id) async {
await _notifications.cancel(id: id);
}
/// Cancel the notification for a specific contact and update the app badge.
Future<void> clearContactNotification(
String contactId,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(_NotificationType.message, contactId);
_bumpClearGeneration(contactId.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(contactId.hashCode);
await _notifications.cancel(id: contactId.hashCode);
await _updateBadge(totalUnreadCount);
}
/// Cancel the notification for a specific channel and update the app badge.
Future<void> clearChannelNotification(
int channelIndex,
int totalUnreadCount,
) async {
_dropPendingConversationUpdate(
_NotificationType.channelMessage,
channelIndex.toString(),
);
_bumpClearGeneration(channelIndex.hashCode);
if (!await _ensureInitialized()) return;
_conversations.remove(channelIndex.hashCode);
await _notifications.cancel(id: channelIndex.hashCode);
await _updateBadge(totalUnreadCount);
}
static int _lowBatteryNotificationId(String deviceKey, int threshold) =>
'low_battery:$deviceKey:$threshold'.hashCode;
/// Cancel a device's low-battery notifications for the given thresholds.
Future<void> clearLowBatteryNotifications(
String deviceKey,
Iterable<int> thresholds,
) async {
if (!await _ensureInitialized()) return;
for (final threshold in thresholds) {
try {
await _notifications.cancel(
id: _lowBatteryNotificationId(deviceKey, threshold),
);
} catch (e) {
debugPrint('Failed to clear low battery notification: $e');
}
}
}
/// Cancel advert notifications for the given contact public key hexes.
Future<void> clearAdvertNotifications(List<String> contactIds) async {
if (!await _ensureInitialized()) return;
for (final id in contactIds) {
await _notifications.cancel(id: 'advert:$id'.hashCode);
}
}
static const MethodChannel _badgeChannel = MethodChannel(
'meshcore_open/app_badge',
);
/// Sets the app icon badge to the current unread total.
Future<void> setAppBadge(int count) => _updateBadge(count);
Future<void> _updateBadge(int count) async {
if (PlatformInfo.isIOS || PlatformInfo.isMacOS) {
// Set natively: a silent notification cancelled right after show() is
// removed before iOS delivers it, so its badge number never applied.
try {
await _badgeChannel.invokeMethod<void>('setBadgeCount', count);
} catch (e) {
debugPrint('Failed to update app badge: $e');
}
}
// On Android, badge count is derived from active notifications,
// so cancelling the specific notification above is sufficient.
}
// ─────────────────────────────────────────────────────────────────
// Public notification methods (rate limiting is enforced automatically)
// ─────────────────────────────────────────────────────────────────
Future<void> showMessageNotification({
required String contactName,
required String message,
required bool urlImagesEnabled,
String? contactId,
int? badgeCount,
}) async {
if (_suppressNotifications) return;
_queueNotification(
_PendingNotification(
type: _NotificationType.message,
title: contactName,
body: message,
urlImagesEnabled: urlImagesEnabled,
id: contactId,
badgeCount: badgeCount,
),
);
}
Future<void> showAdvertNotification({
required String contactName,
required String contactType,
String? contactId,
}) async {
if (_suppressNotifications) return;
_queueNotification(
_PendingNotification(
type: _NotificationType.advert,
title: contactType,
body: contactName,
id: contactId,
),
);
}
Future<void> showChannelMessageNotification({
required String channelName,
required String senderName,
required String message,
required bool urlImagesEnabled,
int? channelIndex,
int? badgeCount,
}) async {
if (_suppressNotifications) return;
_queueNotification(
_PendingNotification(
type: _NotificationType.channelMessage,
title: channelName,
body: message,
senderName: senderName,
urlImagesEnabled: urlImagesEnabled,
id: channelIndex?.toString(),
badgeCount: badgeCount,
),
);
}
void _queueNotification(_PendingNotification notification) {
final now = DateTime.now();
final throttled =
_lastNotificationTime != null &&
now.difference(_lastNotificationTime!) < _minNotificationInterval;
// Messages always update their conversation notification so the reply
// action stays available; bursts are coalesced and update silently.
if (notification.type != _NotificationType.advert) {
_latestQueuedBadgeCount =
notification.badgeCount ?? _latestQueuedBadgeCount;
final key = _conversationKey(notification.type, notification.id);
(_pendingConversationUpdates[key] ??= []).add(notification);
_conversationUpdateTimers[key] ??= Timer(
_coalesceDelay,
() => unawaited(_flushConversationUpdate(key)),
);
return;
}
// If we recently showed a notification, start batching
if (throttled) {
_pendingNotifications.add(notification);
debugPrint(
'[Notification] queued: ${notification.type.name} (${_getNotificationIdentifier(notification)})',
);
// Start batch timer if not already running
if (!_isBatchingActive) {
_isBatchingActive = true;
Future.delayed(_batchWindow, _processBatch);
}
return;
}
// Show immediately if enough time has passed
debugPrint(
'[Notification] sent immediately: ${notification.type.name} (${_getNotificationIdentifier(notification)})',
);
_showNotificationImmediately(notification);
_lastNotificationTime = now;
}
static String _conversationKey(_NotificationType type, String? id) =>
'${type.name}:$id';
void _dropPendingConversationUpdate(_NotificationType type, String id) {
final key = _conversationKey(type, id);
_conversationUpdateTimers.remove(key)?.cancel();
_pendingConversationUpdates.remove(key);
}
void _dropAllPendingConversationUpdates() {
for (final timer in _conversationUpdateTimers.values) {
timer.cancel();
}
_conversationUpdateTimers.clear();
_pendingConversationUpdates.clear();
}
Future<void> _flushConversationUpdate(String key) async {
_conversationUpdateTimers.remove(key);
final batch = _pendingConversationUpdates.remove(key);
if (batch == null || batch.isEmpty) return;
final now = DateTime.now();
final alertGap = (isBulkSyncActive?.call() ?? false)
? _bulkSyncAlertInterval
: _minNotificationInterval;
final silent =
_lastNotificationTime != null &&
now.difference(_lastNotificationTime!) < alertGap;
if (!silent) _lastNotificationTime = now;
await _showNotificationImmediately(
batch.last,
silent: silent,
earlier: batch.sublist(0, batch.length - 1),
badgeCount: unreadTotalProvider?.call() ?? _latestQueuedBadgeCount,
);
}
Future<void> _processBatch() async {
_isBatchingActive = false;
if (_pendingNotifications.isEmpty) return;
final batch = List<_PendingNotification>.from(_pendingNotifications);
_pendingNotifications.clear();
if (batch.length == 1) {
// Single notification, show normally
_showNotificationImmediately(batch.first);
} else {
// Multiple notifications, show summary
await _showBatchSummary(batch);
}
_lastNotificationTime = DateTime.now();
}
Future<void> _showNotificationImmediately(
_PendingNotification notification, {
bool silent = false,
List<_PendingNotification> earlier = const [],
int? badgeCount,
}) async {
final badge = badgeCount ?? notification.badgeCount;
try {
switch (notification.type) {
case _NotificationType.message:
await _showConversationNotificationImpl(
id: notification.id?.hashCode ?? 0,
payload: 'message:${notification.id}',
title: notification.title,
isChannel: false,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
case _NotificationType.advert:
await _showAdvertNotificationImpl(
contactName: notification.body,
contactType: notification.title,
contactId: notification.id,
);
break;
case _NotificationType.channelMessage:
final channelIndex = int.tryParse(notification.id ?? '');
await _showConversationNotificationImpl(
id:
channelIndex?.hashCode ??
DateTime.now().millisecondsSinceEpoch & 0x7FFFFFFF,
payload: 'channel:$channelIndex',
title: notification.title,
isChannel: true,
message: notification.body,
senderName: notification.senderName,
urlImagesEnabled: notification.urlImagesEnabled,
badgeCount: badge,
silent: silent,
earlier: earlier,
);
break;
}
} catch (e) {
debugPrint('Failed to show immediate notification: $e');
}
}
/// Only adverts are batched; messages always update their conversation
/// notification instead.
Future<void> _showBatchSummary(List<_PendingNotification> adverts) async {
if (adverts.isEmpty || !await _ensureCanNotify()) return;
final summary = _l10n.notification_newNodesCount(adverts.length);
final deviceInfo =
' (${adverts.take(5).map((n) => _logSafe(n.body)).join(', ')}${adverts.length > 5 ? ', ...' : ''})';
debugPrint('[Notification] batch summary: $summary$deviceInfo');
const androidDetails = AndroidNotificationDetails(
'batch_summary',
'Activity Summary',
channelDescription: 'Batched notification summaries',
importance: Importance.defaultImportance,
priority: Priority.defaultPriority,
icon: '@drawable/ic_stat_notification',
);
const notificationDetails = NotificationDetails(android: androidDetails);
try {
await _notifications.show(
id: 'batch_summary'.hashCode,
title: _l10n.notification_activityTitle,
body: summary,
notificationDetails: notificationDetails,
payload: 'batch',
);
} catch (e) {
debugPrint('Failed to show batch summary notification: $e');
}
}
}
// Helper class for pending notifications
enum _NotificationType { message, advert, channelMessage }
class _PendingNotification {
final _NotificationType type;
final String title;
final String body;
final String? senderName;
final bool urlImagesEnabled;
final String? id;
final int? badgeCount;
_PendingNotification({
required this.type,
required this.title,
required this.body,
this.senderName,
this.urlImagesEnabled = false,
this.id,
this.badgeCount,
});
}
class _Conversation {
String title;
int? badgeCount;
String? imagePath;
final String payload;
final bool isChannel;
final List<Message> messages = [];
_Conversation({
required this.title,
required this.payload,
required this.isChannel,
});
void add(Message message, int max) {
messages.add(message);
if (messages.length > max) messages.removeRange(0, messages.length - max);
}
}