Merge upstream/dev: Android Auto as opt-in flavor, decluttered map overlay
build / build (push) Failing after 3m2s

Conflicts: the manifest keeps our unread widget receiver and drops the
Android Auto meta-data, which upstream moved to the androidAuto source set
(fe7e72a). Rename detection had moved our unread_widget_info.xml into that
source set with it; it stays in main. _mapChip is gone upstream with the
map overlay declutter (ed5884e), so our terminal-theme restyle of it goes
too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-10-25 19:00:11 +01:00
commit 9489dee1c3
114 files changed
+11506 -1027

No files matched your search

+48 -15
View File
@@ -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 {
@@ -313,10 +320,6 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(jumpToOldestUnread: value));
}
Future<void> setImageMessagesEnabled(bool value) async {
await updateSettings(_settings.copyWith(imageMessagesEnabled: value));
}
Future<void> setNetworkMapUploadEnabled(bool value) async {
await updateSettings(_settings.copyWith(networkMapUploadEnabled: value));
}
@@ -325,6 +328,36 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(networkMapPromptShown: value));
}
Future<void> setLoadLinkImages(bool value) async {
await updateSettings(_settings.copyWith(loadLinkImages: value));
}
Future<void> setShowLinkImagesByDefault(bool value) async {
await updateSettings(_settings.copyWith(showLinkImagesByDefault: value));
}
Future<void> setIpfsImageSettings({
required String publicGateway,
required String uploadGateway,
required String uploadEndpoint,
required String uploadApiKey,
}) async {
final normalizedPublicGateway = normalizeIpfsGateway(publicGateway);
final normalizedUploadGateway = normalizeIpfsGateway(uploadGateway);
await updateSettings(
_settings.copyWith(
publicIpfsGateway: normalizedPublicGateway,
uploadIpfsGateway: normalizedUploadGateway,
uploadIpfsEndpoint: uploadEndpoint.trim(),
uploadIpfsApiKey: uploadApiKey.trim(),
),
);
}
Future<void> setImageMessagesEnabled(bool value) async {
await updateSettings(_settings.copyWith(imageMessagesEnabled: value));
}
/// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into
/// `ReceivedImageStore.processAutomatically` on every settings change; the
/// store applies it to future arrivals only, so flipping it does not
+155
View File
@@ -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();
}
}
+98 -7
View File
@@ -8,12 +8,16 @@ 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';
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();
@@ -26,6 +30,11 @@ class NotificationService {
// 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) {
@@ -278,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;
}
@@ -297,7 +317,10 @@ class NotificationService {
}) async {
if (!urlImagesEnabled) return null;
final imageUrl = await MessageUrlImageHelper.parseVerified(text);
final imageUrl = await MessageUrlImageHelper.parseVerified(
text,
publicGateway: _publicIpfsGateway,
);
if (imageUrl == null) return null;
try {
@@ -397,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;
@@ -598,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)
@@ -654,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;
+31 -1
View File
@@ -1,7 +1,10 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/contact.dart';
import '../models/path_history.dart';
import '../models/path_selection.dart';
import '../utils/coalesced_writes.dart';
import 'storage_service.dart';
class PathHistoryService extends ChangeNotifier {
@@ -10,6 +13,10 @@ class PathHistoryService extends ChangeNotifier {
final Map<String, int> _autoRotationIndex = {};
final Map<String, _FloodStats> _floodStats = {};
final Map<String, Future<void>> _pendingLoads = {};
// A path record lands for most received messages, so saves are batched.
final CoalescedWrites _writes = CoalescedWrites(
delay: const Duration(seconds: 5),
);
// LRU cache eviction tracking
static const int _maxCachedContacts = 50;
@@ -23,6 +30,9 @@ class PathHistoryService extends ChangeNotifier {
PathHistoryService(this._storage);
void setDevicePublicKey(String publicKeyHex) {
// Queued saves use the storage key on entry, so they still land under
// the previous radio's key.
unawaited(_writes.flush());
_storage.setPublicKeyHex = publicKeyHex;
_cache.clear();
_cacheAccessOrder.clear();
@@ -361,7 +371,12 @@ class PathHistoryService extends ChangeNotifier {
_cache[contactPubKeyHex] = updatedHistory;
_trackAccess(contactPubKeyHex);
_evictIfNeeded();
_storage.savePathHistory(contactPubKeyHex, updatedHistory);
// The snapshot is written, not the cache entry: the LRU may evict it
// before the batch runs.
_writes.schedule(
contactPubKeyHex,
() => _storage.savePathHistory(contactPubKeyHex, updatedHistory),
);
notifyListeners();
}
@@ -404,6 +419,9 @@ class PathHistoryService extends ChangeNotifier {
Future<ContactPathHistory?> _loadHistoryFromStorage(
String contactPubKeyHex,
) async {
// An evicted contact may still have a queued save; it reaches the prefs
// cache synchronously, so the load below reads it.
unawaited(_writes.flush());
return await _storage.loadPathHistory(contactPubKeyHex);
}
@@ -445,6 +463,7 @@ class PathHistoryService extends ChangeNotifier {
_cacheAccessOrder.remove(contactPubKeyHex);
_autoRotationIndex.remove(contactPubKeyHex);
_floodStats.remove(contactPubKeyHex);
_writes.cancel(contactPubKeyHex);
await _storage.clearPathHistory(contactPubKeyHex);
_version++;
notifyListeners();
@@ -465,6 +484,7 @@ class PathHistoryService extends ChangeNotifier {
recentPaths: updatedPaths,
);
_writes.cancel(contactPubKeyHex);
await _storage.savePathHistory(contactPubKeyHex, _cache[contactPubKeyHex]!);
_version++;
notifyListeners();
@@ -588,11 +608,21 @@ class PathHistoryService extends ChangeNotifier {
}
}
/// Runs queued saves now, e.g. before the app is backgrounded.
Future<void> flushPendingWrites() => _writes.flush();
@override
void dispose() {
unawaited(_writes.flush());
super.dispose();
}
void clearAllHistories() {
_cache.clear();
_cacheAccessOrder.clear();
_autoRotationIndex.clear();
_floodStats.clear();
_writes.dispose();
_storage.clearAllPathHistories();
_version = 0;
notifyListeners();
+3
View File
@@ -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;