Merge remote-tracking branch 'origin/dev' into pr-593
# Conflicts: # lib/models/app_settings.dart # lib/screens/channel_chat_screen.dart # lib/screens/chat_screen.dart # untranslated.json
This commit is contained in:
commit
7e7e7a48db
87 files changed
+4822
-882
No files matched your search
@@ -3,6 +3,8 @@ import 'package:flutter/foundation.dart';
|
||||
import '../models/app_settings.dart';
|
||||
import '../models/image_codec_support.dart';
|
||||
import '../models/translation_support.dart';
|
||||
|
||||
export '../models/app_settings.dart' show ChannelNotificationMode;
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
import '../helpers/cyr2lat.dart';
|
||||
@@ -286,19 +288,24 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(unitSystem: value));
|
||||
}
|
||||
|
||||
bool isChannelMuted(String channelName) {
|
||||
return _settings.mutedChannels.contains(channelName);
|
||||
ChannelNotificationMode getChannelNotificationMode(String channelName) {
|
||||
return _settings.channelNotificationModes[channelName] ??
|
||||
ChannelNotificationMode.all;
|
||||
}
|
||||
|
||||
Future<void> muteChannel(String channelName) async {
|
||||
final updated = Set<String>.from(_settings.mutedChannels)..add(channelName);
|
||||
await updateSettings(_settings.copyWith(mutedChannels: updated));
|
||||
}
|
||||
|
||||
Future<void> unmuteChannel(String channelName) async {
|
||||
final updated = Set<String>.from(_settings.mutedChannels)
|
||||
..remove(channelName);
|
||||
await updateSettings(_settings.copyWith(mutedChannels: updated));
|
||||
Future<void> setChannelNotificationMode(
|
||||
String channelName,
|
||||
ChannelNotificationMode mode,
|
||||
) async {
|
||||
final updated = Map<String, ChannelNotificationMode>.from(
|
||||
_settings.channelNotificationModes,
|
||||
);
|
||||
if (mode == ChannelNotificationMode.all) {
|
||||
updated.remove(channelName);
|
||||
} else {
|
||||
updated[channelName] = mode;
|
||||
}
|
||||
await updateSettings(_settings.copyWith(channelNotificationModes: updated));
|
||||
}
|
||||
|
||||
Future<void> setTcpServerAddress(String value) async {
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
import '../storage/prefs_manager.dart';
|
||||
|
||||
/// DNS name whose TXT record configures the connect screen's "get a node"
|
||||
/// banner, e.g. `v=1;on=1;url=https%3A%2F%2F...;title=...`.
|
||||
const String nodeBannerRecordName = '_banner.meshcoreopen.org';
|
||||
|
||||
const String _dohEndpoint = 'https://cloudflare-dns.com/dns-query';
|
||||
const String _cacheRecordKey = 'node_banner_txt';
|
||||
const String _cacheExpiryKey = 'node_banner_expires_ms';
|
||||
const int _dnsTypeTxt = 16;
|
||||
|
||||
/// Banner content from the TXT record. Null text fields fall back to the
|
||||
/// app's localized strings.
|
||||
class NodeBannerConfig {
|
||||
final Uri url;
|
||||
final String? title;
|
||||
final String? body;
|
||||
final String? action;
|
||||
|
||||
const NodeBannerConfig({
|
||||
required this.url,
|
||||
this.title,
|
||||
this.body,
|
||||
this.action,
|
||||
});
|
||||
|
||||
/// Parses `key=value` pairs separated by `;`. Values may be plain text;
|
||||
/// percent-encoding is decoded when valid, so `%3B` can carry a `;`.
|
||||
/// Returns null when the banner is switched off (`on=0`), the version is
|
||||
/// unknown, or the link is missing or not https.
|
||||
static NodeBannerConfig? parse(String record) {
|
||||
final fields = <String, String>{};
|
||||
for (final pair in record.split(';')) {
|
||||
final eq = pair.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
final raw = pair.substring(eq + 1).trim();
|
||||
String value;
|
||||
try {
|
||||
value = Uri.decodeComponent(raw);
|
||||
} on ArgumentError {
|
||||
value = raw;
|
||||
}
|
||||
fields[pair.substring(0, eq).trim().toLowerCase()] = value;
|
||||
}
|
||||
if (fields['v'] != '1' || fields['on'] != '1') return null;
|
||||
final url = Uri.tryParse(fields['url'] ?? '');
|
||||
if (url == null || url.scheme != 'https' || url.host.isEmpty) return null;
|
||||
String? text(String key) {
|
||||
final value = fields[key]?.trim();
|
||||
return value == null || value.isEmpty ? null : value;
|
||||
}
|
||||
|
||||
return NodeBannerConfig(
|
||||
url: url,
|
||||
title: text('title'),
|
||||
body: text('body'),
|
||||
action: text('cta'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up the banner's TXT record over DNS-over-HTTPS and caches it for
|
||||
/// the record's TTL. Any failure means no banner.
|
||||
class NodeBannerService {
|
||||
final http.Client _client;
|
||||
final DateTime Function() _now;
|
||||
|
||||
NodeBannerService({http.Client? client, DateTime Function()? now})
|
||||
: _client = client ?? http.Client(),
|
||||
_now = now ?? DateTime.now;
|
||||
|
||||
Future<NodeBannerConfig?> load() async {
|
||||
try {
|
||||
final prefs = PrefsManager.instance;
|
||||
final expires = prefs.getInt(_cacheExpiryKey) ?? 0;
|
||||
final cached = prefs.getString(_cacheRecordKey);
|
||||
if (cached != null && _now().millisecondsSinceEpoch < expires) {
|
||||
return NodeBannerConfig.parse(cached);
|
||||
}
|
||||
|
||||
final response = await _client
|
||||
.get(
|
||||
Uri.parse(_dohEndpoint).replace(
|
||||
queryParameters: {'name': nodeBannerRecordName, 'type': 'TXT'},
|
||||
),
|
||||
headers: const {'accept': 'application/dns-json'},
|
||||
)
|
||||
.timeout(const Duration(seconds: 5));
|
||||
if (response.statusCode != 200) return null;
|
||||
final answer = txtFromDohJson(response.body);
|
||||
if (answer == null) return null;
|
||||
|
||||
final ttl = answer.ttl.clamp(60, 6 * 3600);
|
||||
await prefs.setString(_cacheRecordKey, answer.text);
|
||||
await prefs.setInt(
|
||||
_cacheExpiryKey,
|
||||
_now().add(Duration(seconds: ttl)).millisecondsSinceEpoch,
|
||||
);
|
||||
return NodeBannerConfig.parse(answer.text);
|
||||
} catch (e) {
|
||||
debugPrint('Node banner lookup failed: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// The first TXT answer in a DoH JSON response, with its character-strings
|
||||
/// joined, or null when the name has no TXT record.
|
||||
@visibleForTesting
|
||||
static ({String text, int ttl})? txtFromDohJson(String body) {
|
||||
final json = jsonDecode(body) as Map<String, dynamic>;
|
||||
if (json['Status'] != 0) return null;
|
||||
for (final answer in (json['Answer'] as List<dynamic>? ?? const [])) {
|
||||
final record = answer as Map<String, dynamic>;
|
||||
if (record['type'] != _dnsTypeTxt) continue;
|
||||
return (
|
||||
text: _joinCharacterStrings(record['data'] as String),
|
||||
ttl: (record['TTL'] as num?)?.toInt() ?? 300,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Joins the quoted character-strings of TXT presentation data
|
||||
/// (`"a" "b"` -> `ab`), undoing `\"`, `\\` and `\DDD` escapes.
|
||||
static String _joinCharacterStrings(String data) {
|
||||
if (!data.contains('"')) return data;
|
||||
final out = StringBuffer();
|
||||
var inQuotes = false;
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
final c = data[i];
|
||||
if (c == '"') {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (!inQuotes) {
|
||||
continue;
|
||||
} else if (c == r'\' && i + 1 < data.length) {
|
||||
final digits = i + 3 < data.length ? data.substring(i + 1, i + 4) : '';
|
||||
final code = int.tryParse(digits);
|
||||
if (digits.length == 3 && code != null) {
|
||||
out.writeCharCode(code);
|
||||
i += 3;
|
||||
} else {
|
||||
out.write(data[++i]);
|
||||
}
|
||||
} else {
|
||||
out.write(c);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ 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/marker_message.dart';
|
||||
import '../helpers/message_url_image_helper.dart';
|
||||
import '../helpers/reaction_helper.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
@@ -15,6 +17,7 @@ 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();
|
||||
@@ -284,15 +287,26 @@ class NotificationService {
|
||||
await requestPermissions();
|
||||
}
|
||||
|
||||
/// Format special message types for human-readable notifications.
|
||||
static String formatNotificationText(String text) {
|
||||
/// 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 'Reacted ${reaction.emoji}';
|
||||
return l10n.notification_reacted(reaction.emoji);
|
||||
}
|
||||
if (RegExp(r'^g:[A-Za-z0-9_-]+$').hasMatch(trimmed)) {
|
||||
return 'Sent a GIF';
|
||||
if (ReceivedImageRef.parse(trimmed) != null) {
|
||||
return l10n.notification_sentImage;
|
||||
}
|
||||
if (GifHelper.parseGif(trimmed) != null) {
|
||||
return l10n.notification_sentGif;
|
||||
}
|
||||
final marker = parseMarkerText(trimmed);
|
||||
if (marker != null) {
|
||||
return marker.label.isEmpty
|
||||
? l10n.notification_sharedLocation
|
||||
: l10n.notification_sharedLocationNamed(marker.label);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
@@ -406,7 +420,7 @@ class NotificationService {
|
||||
message,
|
||||
urlImagesEnabled: urlImagesEnabled,
|
||||
);
|
||||
final preview = formatNotificationText(message.trim());
|
||||
final preview = formatNotificationText(message.trim(), _l10n);
|
||||
final body = preview.isEmpty
|
||||
? _l10n.notification_receivedNewMessage
|
||||
: preview;
|
||||
@@ -607,6 +621,54 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: '@mipmap/ic_launcher',
|
||||
);
|
||||
|
||||
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)
|
||||
@@ -663,6 +725,26 @@ class NotificationService {
|
||||
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;
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../models/map_path_trace_draft.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/contact_search.dart';
|
||||
|
||||
@@ -33,6 +34,8 @@ class UiViewStateService extends ChangeNotifier {
|
||||
ChannelSortOption _channelsSortOption = ChannelSortOption.manual;
|
||||
MapSourceOption _mapSource = MapSourceOption.local;
|
||||
|
||||
final MapPathTraceDraft mapPathTrace = MapPathTraceDraft();
|
||||
|
||||
String get contactsSelectedGroupName => _contactsSelectedGroupName;
|
||||
String get contactsSearchText => _contactsSearchText;
|
||||
bool get contactsSearchExpanded => _contactsSearchExpanded;
|
||||
|
||||
Reference in new issue
Block a user