Add notification replies, Android Auto support, and channel mute bell

- Message notifications use Android MessagingStyle with Reply, Mark as read,
  and Mute channel actions, so they work in Android Auto and on watches
- Replies go through the normal send path (length limits, SMAZ, Cyr2Lat,
  retries), split into up to 3 messages, and report failures
- Declare Android Auto notification support and register the action receiver
- Add a bell icon to channel chat to mute/unmute; unify the channel mute key
  so unnamed channels mute correctly
- Update README and docs for Android Auto support
This commit is contained in:
zjs81 committed 2026-09-27 21:55:43 -07:00
1 parent 5cfd26b3af
commit 25f8d6ae27
35 files changed
+1874 -199

No files matched your search

+148 -11
View File
@@ -40,6 +40,7 @@ import '../services/app_settings_service.dart';
import '../services/background_service.dart';
import '../services/timeout_prediction_service.dart';
import '../services/translation_service.dart';
import '../services/notification_reply.dart';
import '../services/notification_service.dart';
import 'meshcore_connector_usb.dart';
import 'meshcore_connector_tcp.dart';
@@ -231,6 +232,7 @@ class MeshCoreConnector extends ChangeNotifier {
StreamSubscription<bool>? _isScanningSubscription;
StreamSubscription<BluetoothConnectionState>? _connectionSubscription;
StreamSubscription<List<int>>? _notifySubscription;
StreamSubscription<NotificationReply>? _notificationReplySubscription;
Timer? _notifyListenersTimer;
Timer? _selfInfoRetryTimer;
Timer? _reconnectTimer;
@@ -987,6 +989,137 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
/// Handles a reply or mark-as-read action from a message notification
/// (notification shade, watch, or Android Auto).
Future<void> handleNotificationReply(NotificationReply reply) async {
if (reply.action == NotificationReplyAction.mute) {
await _appSettingsService?.muteChannel(
_channelDisplayName(reply.channelIndex!),
);
await _notificationService.clearChannelNotification(
reply.channelIndex!,
getTotalUnreadCount(),
);
return;
}
if (reply.action == NotificationReplyAction.markRead) {
// markXRead only clears the notification when there were unread
// messages; clear it here otherwise so the action always dismisses it.
if (reply.isChannel) {
final index = reply.channelIndex!;
final hadUnread = getUnreadCountForChannelIndex(index) > 0;
markChannelRead(index);
if (!hadUnread) {
await _notificationService.clearChannelNotification(
index,
getTotalUnreadCount(),
);
}
} else {
final key = reply.contactKeyHex!;
final hadUnread = getUnreadCountForContactKey(key) > 0;
markContactRead(key);
if (!hadUnread) {
await _notificationService.clearContactNotification(
key,
getTotalUnreadCount(),
);
}
}
return;
}
if (!isConnected) {
await _notificationService.showReplyFailed(
reply,
NotificationReplyFailure.notConnected,
badgeCount: getTotalUnreadCount(),
);
return;
}
final channel = reply.isChannel
? _findChannelByIndex(reply.channelIndex!)
: null;
final contact = reply.isChannel
? null
: getContactByPubKeyHex(reply.contactKeyHex!);
if (channel == null && contact == null) {
await _notificationService.showReplyFailed(
reply,
NotificationReplyFailure.unavailable,
badgeCount: getTotalUnreadCount(),
);
return;
}
// Same length limits and Cyr2Lat handling as the chat screens.
final parts = splitMessageToFit(reply.text, (part) {
if (channel != null) {
return utf8
.encode(prepareChannelOutboundText(channel.index, part))
.length <=
maxChannelMessageBytes(selfName);
}
return utf8.encode(prepareContactOutboundText(contact!, part)).length <=
maxContactMessageBytes();
});
if (parts == null) {
await _notificationService.showReplyFailed(
reply,
NotificationReplyFailure.tooLong,
badgeCount: getTotalUnreadCount(),
);
return;
}
_appDebugLogService?.info(
'Sending notification reply in ${parts.length} part(s)',
tag: 'Notification',
);
for (final part in parts) {
// sendMessage/sendChannelMessage silently do nothing when disconnected,
// so check before every part in case the link dropped mid-reply.
if (!isConnected) {
await _notificationService.showReplyFailed(
reply,
NotificationReplyFailure.notConnected,
badgeCount: getTotalUnreadCount(),
);
return;
}
var text = part;
try {
final cyr2lat = channel != null
? isChannelCyr2LatEnabled(channel.index)
: isContactCyr2LatEnabled(contact!.publicKeyHex);
if (cyr2lat) text = Cyr2Lat.encode(text);
} catch (_) {}
try {
if (channel != null) {
await sendChannelMessage(channel, text);
} else {
await sendMessage(contact!, text);
}
} catch (e) {
appLogger.warn('Notification reply send failed: $e');
await _notificationService.showReplyFailed(
reply,
isConnected
? NotificationReplyFailure.sendFailed
: NotificationReplyFailure.notConnected,
badgeCount: getTotalUnreadCount(),
);
return;
}
}
await _notificationService.showOwnReply(
reply,
reply.text,
badgeCount: getTotalUnreadCount(),
);
}
Future<void> setChannelSmazEnabled(int channelIndex, bool enabled) async {
_channelSmazEnabled[channelIndex] = enabled;
if (enabled) {
@@ -1137,6 +1270,13 @@ class MeshCoreConnector extends ChangeNotifier {
// Initialize notification service
_notificationService.initialize();
_notificationReplySubscription ??= _notificationService.replies.listen(
(reply) => unawaited(
handleNotificationReply(reply).catchError((Object e) {
appLogger.warn('Notification action failed: $e');
}),
),
);
_loadChannelOrder();
// Initialize retry service callbacks
@@ -4936,6 +5076,7 @@ class MeshCoreConnector extends ChangeNotifier {
_currentCr = reader.readByte();
_selfName = reader.readCString();
_notificationService.setSelfName(_selfName);
// The local public key only exists once SELF_INFO has arrived, so the
// image sender prefix (first 2 bytes, big-endian) is refreshed here.
@@ -6066,13 +6207,10 @@ class MeshCoreConnector extends ChangeNotifier {
return text;
}
String _channelDisplayName(int channelIndex) {
for (final channel in _channels) {
if (channel.index != channelIndex) continue;
return channel.name.isEmpty ? 'Channel $channelIndex' : channel.name;
}
return 'Channel $channelIndex';
}
// Falls back to the cached channel list, which stays populated while a
// channel refresh has temporarily emptied _channels.
String _channelDisplayName(int channelIndex) =>
_findChannelByIndex(channelIndex)?.muteKey ?? 'Channel $channelIndex';
void _maybeNotifyChannelMessage(
ChannelMessage message, {
@@ -6243,12 +6381,9 @@ class MeshCoreConnector extends ChangeNotifier {
channel.index,
message,
);
final label = channel.name.isEmpty
? 'Channel ${channel.index}'
: channel.name;
_maybeNotifyChannelMessage(
message,
channelName: label,
channelName: channel.muteKey,
translationResult: translationResult,
);
}());
@@ -7400,6 +7535,8 @@ class MeshCoreConnector extends ChangeNotifier {
_connectionSubscription?.cancel();
_usbFrameSubscription?.cancel();
_notifySubscription?.cancel();
_notificationReplySubscription?.cancel();
_notificationService.releaseReplyPort();
_notifyListenersTimer?.cancel();
_reconnectTimer?.cancel();
_batteryPollTimer?.cancel();
+11
View File
@@ -2606,6 +2606,17 @@
}
},
"notification_receivedNewMessage": "Received new message",
"notification_actionReply": "Reply",
"notification_actionMarkRead": "Mark as read",
"notification_actionMuteChannel": "Mute channel",
"notification_replyHint": "Message",
"notification_you": "You",
"notification_replyFailedTitle": "Reply not sent",
"notification_replyNotConnected": "Not connected to a radio. Reconnect in MeshCore Open and send your reply again.",
"notification_replyTooLong": "Your reply is too long to send from a notification. Send it from MeshCore Open instead.",
"notification_replyUnavailable": "This conversation is no longer on the connected radio.",
"notification_replySendFailed": "Your reply may not have been sent. Check in MeshCore Open and try again.",
"notification_replyAppNotRunning": "MeshCore Open isn't running. Open it and send your reply again.",
"settings_gpxExportRepeaters": "Export repeaters / room server to GPX",
"settings_gpxExportRepeatersSubtitle": "Exports repeaters / roomserver with a location to GPX file.",
"settings_gpxExportContacts": "Export companions to GPX",
+66
View File
@@ -7954,6 +7954,72 @@ abstract class AppLocalizations {
/// **'Received new message'**
String get notification_receivedNewMessage;
/// No description provided for @notification_actionReply.
///
/// In en, this message translates to:
/// **'Reply'**
String get notification_actionReply;
/// No description provided for @notification_actionMarkRead.
///
/// In en, this message translates to:
/// **'Mark as read'**
String get notification_actionMarkRead;
/// No description provided for @notification_actionMuteChannel.
///
/// In en, this message translates to:
/// **'Mute channel'**
String get notification_actionMuteChannel;
/// No description provided for @notification_replyHint.
///
/// In en, this message translates to:
/// **'Message'**
String get notification_replyHint;
/// No description provided for @notification_you.
///
/// In en, this message translates to:
/// **'You'**
String get notification_you;
/// No description provided for @notification_replyFailedTitle.
///
/// In en, this message translates to:
/// **'Reply not sent'**
String get notification_replyFailedTitle;
/// No description provided for @notification_replyNotConnected.
///
/// In en, this message translates to:
/// **'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.'**
String get notification_replyNotConnected;
/// No description provided for @notification_replyTooLong.
///
/// In en, this message translates to:
/// **'Your reply is too long to send from a notification. Send it from MeshCore Open instead.'**
String get notification_replyTooLong;
/// No description provided for @notification_replyUnavailable.
///
/// In en, this message translates to:
/// **'This conversation is no longer on the connected radio.'**
String get notification_replyUnavailable;
/// No description provided for @notification_replySendFailed.
///
/// In en, this message translates to:
/// **'Your reply may not have been sent. Check in MeshCore Open and try again.'**
String get notification_replySendFailed;
/// No description provided for @notification_replyAppNotRunning.
///
/// In en, this message translates to:
/// **'MeshCore Open isn\'t running. Open it and send your reply again.'**
String get notification_replyAppNotRunning;
/// No description provided for @settings_gpxExportRepeaters.
///
/// In en, this message translates to:
+38
View File
@@ -4638,6 +4638,44 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Получено ново съобщение';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Експортиране на повтарящи се устройства / сървър на стаята до GPX';
+38
View File
@@ -4648,6 +4648,44 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Neue Nachricht empfangen';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Repeater und Raumserver als GPX exportieren';
+38
View File
@@ -4574,6 +4574,44 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Received new message';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Export repeaters / room server to GPX';
+38
View File
@@ -4640,6 +4640,44 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nuevo mensaje recibido';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exportar repetidores / servidores de sala a GPX';
+38
View File
@@ -4659,6 +4659,44 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nouveau message reçu';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exporter les répéteurs / room servers au format GPX';
+38
View File
@@ -4638,6 +4638,44 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Új üzenet érkezett';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Ismétlők / szobaszerver exportálása GPX-be';
+38
View File
@@ -4645,6 +4645,44 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nuovo messaggio ricevuto';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Esporta ripetitori / server di stanza in GPX';
+38
View File
@@ -4423,6 +4423,44 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get notification_receivedNewMessage => '新しいメッセージを受信';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters => 'GPX へのエクスポート用リピータ/ルームサーバー';
+38
View File
@@ -4433,6 +4433,44 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get notification_receivedNewMessage => '새로운 메시지를 받았습니다';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters => 'GPX로 전송/방 관리 서버';
+38
View File
@@ -4616,6 +4616,44 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nieuw bericht ontvangen';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exporteer repeaters / roomserver naar GPX';
+38
View File
@@ -4666,6 +4666,44 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Otrzymano nową wiadomość';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Eksportuj przekaźniki / roomservery do GPX';
+38
View File
@@ -4641,6 +4641,44 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nova mensagem recebida';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exportar repetidores / servidor de sala para GPX';
+38
View File
@@ -4654,6 +4654,44 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Получено новое сообщение';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Экспортировать рипитеры / сервер комнаты в GPX';
+38
View File
@@ -4623,6 +4623,44 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Prijatá nová správa';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exportovať repeater / server miestnosti do GPX';
+38
View File
@@ -4624,6 +4624,44 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Prejeto novo sporočilo';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Izvoz ponoviteljev / strežnika sobe v GPX';
+38
View File
@@ -4598,6 +4598,44 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Nytt meddelande mottaget';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Exportera repeatrar/rumsservrar till GPX';
+38
View File
@@ -4654,6 +4654,44 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get notification_receivedNewMessage => 'Отримано нове повідомлення';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters =>
'Експорт ретрансляторів і серверів кімнат у GPX';
+38
View File
@@ -4323,6 +4323,44 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get notification_receivedNewMessage => '收到新消息';
@override
String get notification_actionReply => 'Reply';
@override
String get notification_actionMarkRead => 'Mark as read';
@override
String get notification_actionMuteChannel => 'Mute channel';
@override
String get notification_replyHint => 'Message';
@override
String get notification_you => 'You';
@override
String get notification_replyFailedTitle => 'Reply not sent';
@override
String get notification_replyNotConnected =>
'Not connected to a radio. Reconnect in MeshCore Open and send your reply again.';
@override
String get notification_replyTooLong =>
'Your reply is too long to send from a notification. Send it from MeshCore Open instead.';
@override
String get notification_replyUnavailable =>
'This conversation is no longer on the connected radio.';
@override
String get notification_replySendFailed =>
'Your reply may not have been sent. Check in MeshCore Open and try again.';
@override
String get notification_replyAppNotRunning =>
'MeshCore Open isn\'t running. Open it and send your reply again.';
@override
String get settings_gpxExportRepeaters => '导出转发节点/房间服务器到 GPX';
+3
View File
@@ -25,6 +25,9 @@ class Channel {
bool get isEmpty => name.isEmpty && psk.every((b) => b == 0);
/// Key used for per-channel notification muting.
String get muteKey => name.isEmpty ? 'Channel $index' : name;
bool get isPublicChannel => pskHex == publicChannelPsk;
bool get isHashtagChannel => name.startsWith('#');
+19
View File
@@ -361,6 +361,25 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
centerTitle: false,
bottom: const SyncProgressAppBarBottom(),
actions: [
Consumer<AppSettingsService>(
builder: (context, settings, _) {
final muteKey = widget.channel.muteKey;
final muted = settings.isChannelMuted(muteKey);
return IconButton(
tooltip: muted
? context.l10n.channels_unmuteChannel
: context.l10n.channels_muteChannel,
icon: Icon(
muted
? Icons.notifications_off_outlined
: Icons.notifications_outlined,
),
onPressed: () => muted
? settings.unmuteChannel(muteKey)
: settings.muteChannel(muteKey),
);
},
),
IconButton(
tooltip: context.l10n.channels_regionSelect_Title,
icon: const Icon(Icons.landscape),
+4 -4
View File
@@ -363,7 +363,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
}) {
final unreadCount = connector.getUnreadCountForChannel(channel);
final isMuted = context.watch<AppSettingsService>().isChannelMuted(
channel.name,
channel.muteKey,
);
final scheme = Theme.of(context).colorScheme;
@@ -623,7 +623,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
) {
final parentContext = context;
final settingsService = context.read<AppSettingsService>();
final isMuted = settingsService.isChannelMuted(channel.name);
final isMuted = settingsService.isChannelMuted(channel.muteKey);
showModalBottomSheet(
context: parentContext,
@@ -656,9 +656,9 @@ class _ChannelsScreenState extends State<ChannelsScreen>
onTap: () async {
Navigator.pop(sheetContext);
if (isMuted) {
await settingsService.unmuteChannel(channel.name);
await settingsService.unmuteChannel(channel.muteKey);
} else {
await settingsService.muteChannel(channel.name);
await settingsService.muteChannel(channel.muteKey);
}
},
),
+197
View File
@@ -0,0 +1,197 @@
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../l10n/app_localizations.dart';
/// Name under which the main isolate registers the port that receives
/// notification actions from the plugin's background isolate.
const notificationReplyPortName = 'meshcore.notification_reply';
const notificationReplyActionId = 'reply';
const notificationMarkReadActionId = 'mark_read';
const notificationMuteActionId = 'mute';
/// Preference holding the app's language code, so the background isolate can
/// localize its notices the same way the app does.
const notificationLanguagePrefsKey = 'notification_language';
enum NotificationReplyAction { reply, markRead, mute }
enum NotificationReplyFailure { notConnected, unavailable, tooLong, sendFailed }
/// A reply or mark-as-read action taken on a message notification, e.g. from
/// the notification shade, a watch, or Android Auto.
class NotificationReply {
final NotificationReplyAction action;
final String? contactKeyHex;
final int? channelIndex;
final String text;
const NotificationReply._({
required this.action,
this.contactKeyHex,
this.channelIndex,
this.text = '',
});
bool get isChannel => channelIndex != null;
/// Parses the plugin's action id, notification payload (`message:<keyHex>`
/// or `channel:<index>`) and reply input. Returns null for taps, unknown
/// actions, malformed payloads, and empty replies.
static NotificationReply? parse({
required String? actionId,
required String? payload,
String? input,
}) {
final NotificationReplyAction action;
if (actionId == notificationReplyActionId) {
action = NotificationReplyAction.reply;
} else if (actionId == notificationMarkReadActionId) {
action = NotificationReplyAction.markRead;
} else if (actionId == notificationMuteActionId) {
action = NotificationReplyAction.mute;
} else {
return null;
}
final text = input?.trim() ?? '';
if (action == NotificationReplyAction.reply && text.isEmpty) return null;
if (payload == null) return null;
final sep = payload.indexOf(':');
if (sep <= 0) return null;
final kind = payload.substring(0, sep);
final value = payload.substring(sep + 1);
if (kind == 'message' &&
value.isNotEmpty &&
value != 'null' &&
action != NotificationReplyAction.mute) {
return NotificationReply._(
action: action,
contactKeyHex: value,
text: text,
);
}
if (kind == 'channel') {
final index = int.tryParse(value);
if (index == null) return null;
return NotificationReply._(
action: action,
channelIndex: index,
text: text,
);
}
return null;
}
}
/// Splits [text] at word boundaries into at most [maxParts] pieces that each
/// satisfy [fits]. Words that are too long on their own are split by
/// character. Returns null when the text needs more than [maxParts] pieces,
/// or when a single character doesn't fit.
List<String>? splitMessageToFit(
String text,
bool Function(String part) fits, {
int maxParts = 3,
}) {
final trimmed = text.trim();
if (trimmed.isEmpty) return const [];
if (fits(trimmed)) return [trimmed];
final parts = <String>[];
var current = '';
for (final word in trimmed.split(RegExp(r'\s+'))) {
final candidate = current.isEmpty ? word : '$current $word';
if (fits(candidate)) {
current = candidate;
continue;
}
if (current.isNotEmpty) parts.add(current);
if (fits(word)) {
current = word;
continue;
}
current = '';
for (final char in word.characters) {
final next = '$current$char';
if (fits(next)) {
current = next;
} else {
if (current.isEmpty || !fits(char)) return null;
parts.add(current);
current = char;
}
}
}
if (current.isNotEmpty) parts.add(current);
return parts.length <= maxParts ? parts : null;
}
/// Runs in the plugin's background isolate when a notification action that
/// doesn't open the app is used. Forwards it to the main isolate, which owns
/// the radio connection; if the app isn't running, tells the user.
@pragma('vm:entry-point')
Future<void> notificationActionBackgroundHandler(
NotificationResponse response,
) async {
final port = IsolateNameServer.lookupPortByName(notificationReplyPortName);
if (port != null) {
port.send(<String, String?>{
'actionId': response.actionId,
'payload': response.payload,
'input': response.input,
});
return;
}
if (response.actionId != notificationReplyActionId) return;
try {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
final plugin = FlutterLocalNotificationsPlugin();
await plugin.initialize(
settings: const InitializationSettings(
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
),
);
final l10n = await _backgroundLocalizations();
await plugin.show(
id: 'reply_failed'.hashCode,
title: l10n.notification_replyFailedTitle,
body: l10n.notification_replyAppNotRunning,
notificationDetails: const NotificationDetails(
android: AndroidNotificationDetails(
'messages',
'Messages',
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
),
),
);
if (response.id != null) await plugin.cancel(id: response.id!);
} catch (e) {
debugPrint('Failed to report unsent notification reply: $e');
}
}
Future<AppLocalizations> _backgroundLocalizations() async {
String? code;
try {
code = (await SharedPreferences.getInstance()).getString(
notificationLanguagePrefsKey,
);
} catch (_) {}
for (final locale in [
if (code != null) Locale(code),
PlatformDispatcher.instance.locale,
]) {
try {
return lookupAppLocalizations(locale);
} catch (_) {}
}
return lookupAppLocalizations(const Locale('en'));
}
+356 -172
View File
@@ -1,4 +1,6 @@
import 'dart:async';
import 'dart:io' show Platform, File;
import 'dart:isolate';
import 'dart:ui';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
@@ -10,6 +12,7 @@ import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../storage/prefs_manager.dart';
import '../utils/platform_info.dart';
import 'notification_reply.dart';
class NotificationService {
static final NotificationService _instance = NotificationService._internal();
@@ -26,10 +29,48 @@ class NotificationService {
/// 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,
locale.languageCode,
);
} 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);
@@ -99,13 +140,48 @@ class NotificationService {
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;
@@ -234,12 +310,85 @@ class NotificationService {
}
}
Future<void> _showMessageNotificationImpl({
required String contactName,
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,
),
];
// Always MessagingStyle: Android Auto only handles messaging notifications
// in that style, so an image preview is shown as the large icon instead.
AndroidNotificationDetails _androidConversationDetails(
_Conversation conversation, {
int? badgeCount,
bool silent = false,
}) {
final imagePath = conversation.imagePath;
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: '@mipmap/ic_launcher',
number: badgeCount,
silent: silent,
category: AndroidNotificationCategory.message,
largeIcon: imagePath != null ? FilePathAndroidBitmap(imagePath) : null,
styleInformation: MessagingStyleInformation(
Person(key: 'self', name: _selfName ?? _l10n.notification_you),
conversationTitle: conversation.isChannel ? conversation.title : null,
groupConversation: conversation.isChannel,
messages: List<Message>.of(conversation.messages),
),
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? contactId,
String? senderName,
int? badgeCount,
bool silent = false,
}) async {
if (!await _ensureCanNotify()) return;
@@ -247,66 +396,158 @@ class NotificationService {
message,
urlImagesEnabled: urlImagesEnabled,
);
final preview = formatNotificationText(message.trim());
final body = preview.isEmpty
? _l10n.notification_receivedNewMessage
: preview;
final androidDetails = AndroidNotificationDetails(
'messages',
'Messages',
channelDescription: 'New message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
number: badgeCount,
styleInformation: imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
summaryText: formatNotificationText(message),
)
: null,
);
final iosDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
final conversation =
_conversations.putIfAbsent(
id,
() => _Conversation(
title: title,
payload: payload,
isChannel: isChannel,
),
)
..title = title
..badgeCount = badgeCount
..imagePath = imagePath;
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: androidDetails,
iOS: iosDetails,
macOS: macDetails,
android: _androidConversationDetails(
conversation,
badgeCount: badgeCount,
silent: silent,
),
iOS: _darwinDetails(imagePath, badgeCount),
macOS: _darwinDetails(imagePath, badgeCount),
);
try {
await _notifications.show(
id: contactId?.hashCode ?? 0,
title: contactName,
body: formatNotificationText(message),
id: id,
title: title,
body: _collapsedBody(conversation),
notificationDetails: notificationDetails,
payload: 'message:$contactId',
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: '@mipmap/ic_launcher',
),
),
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,
@@ -356,86 +597,6 @@ class NotificationService {
}
}
Future<void> _showChannelMessageNotificationImpl({
required String channelName,
required String message,
required bool urlImagesEnabled,
int? channelIndex,
int? badgeCount,
}) async {
if (!await _ensureCanNotify()) return;
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
final androidDetails = AndroidNotificationDetails(
'channel_messages',
'Channel Messages',
channelDescription: 'New channel message notifications',
importance: Importance.high,
priority: Priority.high,
icon: '@mipmap/ic_launcher',
number: badgeCount,
styleInformation: imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
summaryText: formatNotificationText(message),
)
: null,
);
final iosDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
presentAlert: true,
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final notificationDetails = NotificationDetails(
android: androidDetails,
iOS: iosDetails,
macOS: macDetails,
);
final preview = formatNotificationText(message.trim());
final body = preview.isEmpty
? _l10n.notification_receivedNewMessage
: preview;
try {
await _notifications.show(
id:
channelIndex?.hashCode ??
DateTime.now().millisecondsSinceEpoch & 0x7FFFFFFF,
title: channelName,
body: body,
notificationDetails: notificationDetails,
payload: 'channel:$channelIndex',
);
} catch (e) {
debugPrint('Failed to show channel 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)
@@ -461,6 +622,7 @@ class NotificationService {
}
Future<void> cancelAll() async {
_conversations.clear();
await _notifications.cancelAll();
}
@@ -474,6 +636,7 @@ class NotificationService {
int totalUnreadCount,
) async {
if (!await _ensureInitialized()) return;
_conversations.remove(contactId.hashCode);
await _notifications.cancel(id: contactId.hashCode);
await _updateBadge(totalUnreadCount);
}
@@ -484,6 +647,7 @@ class NotificationService {
int totalUnreadCount,
) async {
if (!await _ensureInitialized()) return;
_conversations.remove(channelIndex.hashCode);
await _notifications.cancel(id: channelIndex.hashCode);
await _updateBadge(totalUnreadCount);
}
@@ -579,7 +743,8 @@ class NotificationService {
_PendingNotification(
type: _NotificationType.channelMessage,
title: channelName,
body: '$senderName: $message',
body: message,
senderName: senderName,
urlImagesEnabled: urlImagesEnabled,
id: channelIndex?.toString(),
badgeCount: badgeCount,
@@ -589,10 +754,20 @@ class NotificationService {
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; during a burst they update silently.
if (notification.type != _NotificationType.advert) {
_showNotificationImmediately(notification, silent: throttled);
if (!throttled) _lastNotificationTime = now;
return;
}
// If we recently showed a notification, start batching
if (_lastNotificationTime != null &&
now.difference(_lastNotificationTime!) < _minNotificationInterval) {
if (throttled) {
_pendingNotifications.add(notification);
debugPrint(
'[Notification] queued: ${notification.type.name} (${_getNotificationIdentifier(notification)})',
@@ -634,17 +809,21 @@ class NotificationService {
}
Future<void> _showNotificationImmediately(
_PendingNotification notification,
) async {
_PendingNotification notification, {
bool silent = false,
}) async {
try {
switch (notification.type) {
case _NotificationType.message:
await _showMessageNotificationImpl(
contactName: notification.title,
await _showConversationNotificationImpl(
id: notification.id?.hashCode ?? 0,
payload: 'message:${notification.id}',
title: notification.title,
isChannel: false,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
contactId: notification.id,
badgeCount: notification.badgeCount,
silent: silent,
);
break;
case _NotificationType.advert:
@@ -655,12 +834,19 @@ class NotificationService {
);
break;
case _NotificationType.channelMessage:
await _showChannelMessageNotificationImpl(
channelName: notification.title,
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,
channelIndex: int.tryParse(notification.id ?? ''),
badgeCount: notification.badgeCount,
silent: silent,
);
break;
}
@@ -669,39 +855,15 @@ class NotificationService {
}
}
Future<void> _showBatchSummary(List<_PendingNotification> batch) async {
if (!await _ensureCanNotify()) return;
/// Only adverts are batched; messages always update their conversation
/// notification instead.
Future<void> _showBatchSummary(List<_PendingNotification> adverts) async {
if (adverts.isEmpty || !await _ensureCanNotify()) return;
// Group by type
final messages = batch
.where((n) => n.type == _NotificationType.message)
.toList();
final adverts = batch
.where((n) => n.type == _NotificationType.advert)
.toList();
final channelMsgs = batch
.where((n) => n.type == _NotificationType.channelMessage)
.toList();
// Build summary text using localized plurals
final parts = <String>[];
if (messages.isNotEmpty) {
parts.add(_l10n.notification_messagesCount(messages.length));
}
if (channelMsgs.isNotEmpty) {
parts.add(_l10n.notification_channelMessagesCount(channelMsgs.length));
}
if (adverts.isNotEmpty) {
parts.add(_l10n.notification_newNodesCount(adverts.length));
}
if (parts.isEmpty) return;
// Show first few device names in batch summary for debugging (only if adverts exist)
final deviceInfo = adverts.isNotEmpty
? ' (${adverts.take(5).map((n) => _logSafe(n.body)).join(', ')}${adverts.length > 5 ? ', ...' : ''})'
: '';
debugPrint('[Notification] batch summary: ${parts.join(", ")}$deviceInfo');
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',
@@ -718,7 +880,7 @@ class NotificationService {
await _notifications.show(
id: 'batch_summary'.hashCode,
title: _l10n.notification_activityTitle,
body: parts.join(', '),
body: summary,
notificationDetails: notificationDetails,
payload: 'batch',
);
@@ -735,6 +897,7 @@ class _PendingNotification {
final _NotificationType type;
final String title;
final String body;
final String? senderName;
final bool urlImagesEnabled;
final String? id;
final int? badgeCount;
@@ -743,8 +906,29 @@ class _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);
}
}