mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
Fix RX advert data parsing
This commit is contained in:
@@ -34,8 +34,6 @@ class ContactsTab extends StatefulWidget {
|
||||
|
||||
class _ContactsTabState extends State<ContactsTab> {
|
||||
Position? _currentPosition;
|
||||
final Set<String> _resolvingAdvertKeys = <String>{};
|
||||
bool _isResolvingPendingBatch = false;
|
||||
final Map<ContactSection, String> _sectionFilters = {
|
||||
ContactSection.teamMembers: '',
|
||||
ContactSection.repeaters: '',
|
||||
@@ -99,57 +97,6 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
await _getCurrentLocation();
|
||||
}
|
||||
|
||||
Future<void> _handleResolveAdvert(PendingAdvert advert) async {
|
||||
final keyHex = advert.publicKeyHex;
|
||||
if (_resolvingAdvertKeys.contains(keyHex)) return;
|
||||
|
||||
setState(() {
|
||||
_resolvingAdvertKeys.add(keyHex);
|
||||
});
|
||||
|
||||
try {
|
||||
await context.read<ConnectionProvider>().getContact(advert.publicKey);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_resolvingAdvertKeys.remove(keyHex);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _schedulePendingAdvertResolution(
|
||||
List<PendingAdvert> pendingAdverts,
|
||||
ConnectionProvider connectionProvider,
|
||||
) {
|
||||
if (_isResolvingPendingBatch ||
|
||||
!connectionProvider.deviceInfo.isConnected ||
|
||||
pendingAdverts.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
final advertsToResolve = pendingAdverts
|
||||
.where((advert) => !_resolvingAdvertKeys.contains(advert.publicKeyHex))
|
||||
.toList();
|
||||
if (advertsToResolve.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) async {
|
||||
if (!mounted || _isResolvingPendingBatch) return;
|
||||
|
||||
_isResolvingPendingBatch = true;
|
||||
try {
|
||||
for (final advert in advertsToResolve) {
|
||||
if (!mounted) break;
|
||||
await _handleResolveAdvert(advert);
|
||||
}
|
||||
} finally {
|
||||
_isResolvingPendingBatch = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Calculate distance between two points in meters
|
||||
double _calculateDistanceInMeters(
|
||||
double lat1,
|
||||
@@ -181,15 +128,6 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
}
|
||||
}
|
||||
|
||||
String _formatRelativeTime(BuildContext context, DateTime when) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final diff = DateTime.now().difference(when);
|
||||
if (diff.inMinutes < 1) return l10n.justNow;
|
||||
if (diff.inMinutes < 60) return l10n.minutesAgo(diff.inMinutes);
|
||||
if (diff.inHours < 24) return l10n.hoursAgo(diff.inHours);
|
||||
return l10n.daysAgo(diff.inDays);
|
||||
}
|
||||
|
||||
List<Contact> _filterContactsForSection(
|
||||
List<Contact> contacts,
|
||||
ContactSection section,
|
||||
@@ -593,7 +531,6 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
body: Consumer<ContactsProvider>(
|
||||
builder: (context, contactsProvider, child) {
|
||||
final messagesProvider = context.watch<MessagesProvider>();
|
||||
final connectionProvider = context.watch<ConnectionProvider>();
|
||||
final allChatContacts = _sortContacts(
|
||||
contactsProvider.chatContacts,
|
||||
ContactSection.teamMembers,
|
||||
@@ -673,17 +610,12 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
final showRepeatersSection = allRepeaters.isNotEmpty;
|
||||
final showRoomsSection = allRooms.isNotEmpty;
|
||||
final showChannelsSection = allChannels.isNotEmpty;
|
||||
final pendingAdverts = contactsProvider.pendingAdverts;
|
||||
|
||||
_schedulePendingAdvertResolution(pendingAdverts, connectionProvider);
|
||||
|
||||
// Check if there are any displayable contacts
|
||||
final hasDisplayableContacts =
|
||||
allChatContacts.isNotEmpty ||
|
||||
allRepeaters.isNotEmpty ||
|
||||
allRooms.isNotEmpty ||
|
||||
allChannels.isNotEmpty ||
|
||||
pendingAdverts.isNotEmpty;
|
||||
allChannels.isNotEmpty;
|
||||
|
||||
if (!hasDisplayableContacts) {
|
||||
return Center(
|
||||
@@ -838,27 +770,6 @@ class _ContactsTabState extends State<ContactsTab> {
|
||||
const Divider(height: 32),
|
||||
],
|
||||
|
||||
// Pending adverts are kept below resolved sections while we load details.
|
||||
if (pendingAdverts.isNotEmpty) ...[
|
||||
_SectionHeader(
|
||||
title: l10n.pending,
|
||||
count: pendingAdverts.length,
|
||||
icon: Icons.person_search,
|
||||
),
|
||||
...pendingAdverts.map(
|
||||
(advert) => _PendingAdvertTile(
|
||||
advert: advert,
|
||||
subtitle:
|
||||
'${l10n.publicKey}: ${advert.shortDisplayKey}\n${l10n.lastSeen}: ${_formatRelativeTime(context, advert.receivedAt)}',
|
||||
isResolving: _resolvingAdvertKeys.contains(
|
||||
advert.publicKeyHex,
|
||||
),
|
||||
onResolve: () => _handleResolveAdvert(advert),
|
||||
),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
],
|
||||
|
||||
// Channels (visible in both simple and advanced mode)
|
||||
if (showChannelsSection) ...[
|
||||
_SectionHeader(
|
||||
@@ -1263,46 +1174,6 @@ enum ContactSortMode { lastSeen, distance }
|
||||
|
||||
enum ContactSection { teamMembers, repeaters, rooms, channels }
|
||||
|
||||
class _PendingAdvertTile extends StatelessWidget {
|
||||
final PendingAdvert advert;
|
||||
final String subtitle;
|
||||
final bool isResolving;
|
||||
final VoidCallback onResolve;
|
||||
|
||||
const _PendingAdvertTile({
|
||||
required this.advert,
|
||||
required this.subtitle,
|
||||
required this.isResolving,
|
||||
required this.onResolve,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(child: Icon(Icons.campaign_outlined)),
|
||||
title: Text(
|
||||
advert.shortDisplayKey,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
subtitle: Text(subtitle),
|
||||
trailing: isResolving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.person_add_alt_1),
|
||||
tooltip: 'Resolve contact',
|
||||
onPressed: onResolve,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RenderedSavedGroup {
|
||||
final SavedContactGroup group;
|
||||
final List<Contact> contacts;
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../models/device_info.dart';
|
||||
import '../models/channel.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../providers/channels_provider.dart';
|
||||
import '../providers/connection_provider.dart';
|
||||
import '../providers/contacts_provider.dart';
|
||||
import '../services/validation_service.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
|
||||
@@ -14,6 +20,10 @@ class DeviceConfigScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
static const int _bulkDeleteBatchSize = 8;
|
||||
static const Duration _bulkDeleteInterItemDelay = Duration(milliseconds: 120);
|
||||
static const Duration _bulkDeleteBatchDelay = Duration(milliseconds: 700);
|
||||
static const Duration _bulkDeleteFinalSyncDelay = Duration(milliseconds: 900);
|
||||
static const List<_RadioPreset> _radioPresets = [
|
||||
_RadioPreset(
|
||||
id: 'australia',
|
||||
@@ -169,9 +179,12 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
|
||||
bool _telemetryEnabled = false;
|
||||
bool _repeatEnabled = false;
|
||||
bool _autoAddDiscoveredContactsEnabled = true;
|
||||
bool _showCustomRadioSettings = false;
|
||||
bool _isSavingPublicInfo = false;
|
||||
bool _isSavingRadioSettings = false;
|
||||
bool _isClearingContacts = false;
|
||||
bool _isClearingChannels = false;
|
||||
bool _publicInfoSaved = false;
|
||||
bool _radioSettingsSaved = false;
|
||||
String? _publicInfoError;
|
||||
@@ -252,6 +265,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
|
||||
// Initialize repeat mode from device info (firmware v9+)
|
||||
_repeatEnabled = deviceInfo.clientRepeat ?? false;
|
||||
_autoAddDiscoveredContactsEnabled =
|
||||
!(deviceInfo.manualAddContacts ?? false);
|
||||
|
||||
// Fetch allowed repeat frequencies on open if device supports repeat mode
|
||||
if (deviceInfo.clientRepeat != null &&
|
||||
@@ -377,7 +392,6 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
|
||||
Future<void> _savePublicInfo() async {
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final deviceInfo = connectionProvider.deviceInfo;
|
||||
final validator = ValidationService();
|
||||
|
||||
setState(() {
|
||||
@@ -387,6 +401,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
});
|
||||
|
||||
try {
|
||||
final manualAddContacts = _autoAddDiscoveredContactsEnabled ? 0 : 1;
|
||||
|
||||
// Save name
|
||||
if (_nameController.text.isNotEmpty) {
|
||||
await connectionProvider.setAdvertName(_nameController.text);
|
||||
@@ -425,7 +441,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
// Set telemetry modes to "Allow All" (mode 2 for both base and location)
|
||||
final telemetryModes = 0x0A; // binary: 00001010 (base=2, location=2)
|
||||
await connectionProvider.setOtherParams(
|
||||
manualAddContacts: deviceInfo.manualAddContacts == true ? 1 : 0,
|
||||
manualAddContacts: manualAddContacts,
|
||||
telemetryModes: telemetryModes,
|
||||
advertLocationPolicy: 1,
|
||||
);
|
||||
@@ -436,7 +452,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
// Set telemetry modes to "Deny" (mode 0)
|
||||
final telemetryModes = 0x00;
|
||||
await connectionProvider.setOtherParams(
|
||||
manualAddContacts: deviceInfo.manualAddContacts == true ? 1 : 0,
|
||||
manualAddContacts: manualAddContacts,
|
||||
telemetryModes: telemetryModes,
|
||||
advertLocationPolicy: 0,
|
||||
);
|
||||
@@ -687,6 +703,205 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _confirmClearAllContacts() async {
|
||||
final contacts = context
|
||||
.read<ContactsProvider>()
|
||||
.contacts
|
||||
.where((contact) => !contact.isChannel)
|
||||
.toList();
|
||||
if (contacts.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('No device contacts to clear.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Clear all contacts'),
|
||||
content: Text(
|
||||
'This will remove ${contacts.length} contact${contacts.length == 1 ? '' : 's'} from the connected device. Channels and radio settings will not be changed.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: Text(AppLocalizations.of(context)!.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
foregroundColor: Theme.of(context).colorScheme.onError,
|
||||
),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: const Text('Clear contacts'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed != true || !mounted) return;
|
||||
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
connectionProvider.clearError();
|
||||
|
||||
setState(() {
|
||||
_isClearingContacts = true;
|
||||
});
|
||||
|
||||
try {
|
||||
var processed = 0;
|
||||
for (final contact in List<Contact>.from(contacts)) {
|
||||
await contactsProvider.removeContact(
|
||||
contact.publicKeyHex,
|
||||
onRemoveFromDevice: connectionProvider.removeContact,
|
||||
);
|
||||
processed++;
|
||||
await Future.delayed(_bulkDeleteInterItemDelay);
|
||||
if (processed % _bulkDeleteBatchSize == 0) {
|
||||
await Future.delayed(_bulkDeleteBatchDelay);
|
||||
}
|
||||
}
|
||||
|
||||
// Flush the updated local contact set to storage immediately.
|
||||
await contactsProvider.persistNow();
|
||||
await Future.delayed(_bulkDeleteFinalSyncDelay);
|
||||
await connectionProvider.getContacts();
|
||||
if (connectionProvider.error != null) {
|
||||
throw Exception(connectionProvider.error!);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Cleared ${contacts.length} contact${contacts.length == 1 ? '' : 's'} from the device.',
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to clear contacts: $e'),
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isClearingContacts = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _confirmClearAllChannels() async {
|
||||
final channels = context
|
||||
.read<ChannelsProvider>()
|
||||
.channels
|
||||
.where((channel) => !channel.isPublicChannel && channel.name.isNotEmpty)
|
||||
.toList();
|
||||
if (channels.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('No custom channels to clear.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Clear all channels'),
|
||||
content: Text(
|
||||
'This will remove ${channels.length} custom channel${channels.length == 1 ? '' : 's'} from the connected device. Contacts and radio settings will not be changed.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(dialogContext).pop(false),
|
||||
child: Text(AppLocalizations.of(context)!.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
foregroundColor: Theme.of(context).colorScheme.onError,
|
||||
),
|
||||
onPressed: () => Navigator.of(dialogContext).pop(true),
|
||||
child: const Text('Clear channels'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed != true || !mounted) return;
|
||||
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final channelsProvider = context.read<ChannelsProvider>();
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
connectionProvider.clearError();
|
||||
|
||||
setState(() {
|
||||
_isClearingChannels = true;
|
||||
});
|
||||
|
||||
try {
|
||||
var processed = 0;
|
||||
for (final channel in List<Channel>.from(channels)) {
|
||||
await connectionProvider.deleteChannel(channel.index);
|
||||
processed++;
|
||||
await Future.delayed(_bulkDeleteInterItemDelay);
|
||||
if (processed % _bulkDeleteBatchSize == 0) {
|
||||
await Future.delayed(_bulkDeleteBatchDelay);
|
||||
}
|
||||
}
|
||||
|
||||
// Force local channel/contact cache cleanup before the device resync.
|
||||
for (final channel in channels) {
|
||||
channelsProvider.removeChannel(channel.index);
|
||||
final publicKeyBytes = Uint8List(32);
|
||||
publicKeyBytes[0] = 0xFF;
|
||||
publicKeyBytes[1] = channel.index;
|
||||
final publicKeyHex = publicKeyBytes
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join('');
|
||||
await contactsProvider.removeContact(publicKeyHex);
|
||||
}
|
||||
|
||||
await contactsProvider.persistNow();
|
||||
await Future.delayed(_bulkDeleteFinalSyncDelay);
|
||||
await connectionProvider.syncChannels();
|
||||
if (connectionProvider.error != null) {
|
||||
throw Exception(connectionProvider.error!);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
'Cleared ${channels.length} custom channel${channels.length == 1 ? '' : 's'} from the device.',
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Failed to clear channels: $e'),
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isClearingChannels = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final deviceInfo = context.watch<ConnectionProvider>().deviceInfo;
|
||||
@@ -788,6 +1003,28 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_SettingHighlightCard(
|
||||
icon: _autoAddDiscoveredContactsEnabled
|
||||
? Icons.person_add_alt_1
|
||||
: Icons.person_add_disabled,
|
||||
title: 'Auto-add discovered contacts',
|
||||
description:
|
||||
'Control whether the device automatically stores newly discovered contacts.',
|
||||
accentColor: _autoAddDiscoveredContactsEnabled
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
trailing: Switch(
|
||||
value: _autoAddDiscoveredContactsEnabled,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_autoAddDiscoveredContactsEnabled = value;
|
||||
_publicInfoSaved = false;
|
||||
_publicInfoError = null;
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
_SettingHighlightCard(
|
||||
icon: _telemetryEnabled
|
||||
? Icons.travel_explore
|
||||
@@ -1230,10 +1467,60 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _isClearingContacts || _isClearingChannels
|
||||
? null
|
||||
: _confirmClearAllContacts,
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: colorScheme.error,
|
||||
side: BorderSide(color: colorScheme.error),
|
||||
minimumSize: const Size.fromHeight(52),
|
||||
),
|
||||
icon: _isClearingContacts
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.people_alt_outlined),
|
||||
label: const Text('Clear all contacts'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _isClearingContacts || _isClearingChannels
|
||||
? null
|
||||
: _confirmClearAllChannels,
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: colorScheme.error,
|
||||
side: BorderSide(color: colorScheme.error),
|
||||
minimumSize: const Size.fromHeight(52),
|
||||
),
|
||||
icon: _isClearingChannels
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.forum_outlined),
|
||||
label: const Text('Clear all channels'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: _confirmFactoryReset,
|
||||
onPressed: _isClearingContacts || _isClearingChannels
|
||||
? null
|
||||
: _confirmFactoryReset,
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: colorScheme.error,
|
||||
foregroundColor: colorScheme.onError,
|
||||
|
||||
231
lib/screens/discovery_screen.dart
Normal file
231
lib/screens/discovery_screen.dart
Normal file
@@ -0,0 +1,231 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../models/contact.dart';
|
||||
import '../providers/connection_provider.dart';
|
||||
import '../providers/contacts_provider.dart';
|
||||
import '../services/mesh_map_nodes_service.dart';
|
||||
|
||||
class DiscoveryScreen extends StatefulWidget {
|
||||
const DiscoveryScreen({super.key});
|
||||
|
||||
@override
|
||||
State<DiscoveryScreen> createState() => _DiscoveryScreenState();
|
||||
}
|
||||
|
||||
class _DiscoveryScreenState extends State<DiscoveryScreen> {
|
||||
final Set<String> _resolvingAdvertKeys = <String>{};
|
||||
bool _isResolvingAll = false;
|
||||
late final Future<List<MeshMapNode>> _cachedNodesFuture;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cachedNodesFuture = MeshMapNodesService.loadCachedNodes(
|
||||
cacheTtl: MeshMapNodesService.traceCacheTtl,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resolveAdvert(PendingAdvert advert) async {
|
||||
final keyHex = advert.publicKeyHex;
|
||||
if (_resolvingAdvertKeys.contains(keyHex)) return;
|
||||
|
||||
setState(() {
|
||||
_resolvingAdvertKeys.add(keyHex);
|
||||
});
|
||||
|
||||
try {
|
||||
await context.read<ConnectionProvider>().getContact(advert.publicKey);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_resolvingAdvertKeys.remove(keyHex);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _resolveAll(List<PendingAdvert> adverts) async {
|
||||
if (_isResolvingAll || adverts.isEmpty) return;
|
||||
|
||||
setState(() {
|
||||
_isResolvingAll = true;
|
||||
});
|
||||
|
||||
try {
|
||||
for (final advert in adverts) {
|
||||
if (!mounted) break;
|
||||
await _resolveAdvert(advert);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isResolvingAll = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _formatRelativeTime(BuildContext context, DateTime when) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final diff = DateTime.now().difference(when);
|
||||
if (diff.inMinutes < 1) return l10n.justNow;
|
||||
if (diff.inMinutes < 60) return l10n.minutesAgo(diff.inMinutes);
|
||||
if (diff.inHours < 24) return l10n.hoursAgo(diff.inHours);
|
||||
return l10n.daysAgo(diff.inDays);
|
||||
}
|
||||
|
||||
String _displayNameForAdvert(
|
||||
PendingAdvert advert,
|
||||
ContactsProvider contactsProvider,
|
||||
List<MeshMapNode> cachedNodes,
|
||||
) {
|
||||
Contact? existingMatch;
|
||||
for (final contact in contactsProvider.contacts) {
|
||||
if (contact.publicKeyHex == advert.publicKeyHex) {
|
||||
existingMatch = contact;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (existingMatch != null && existingMatch.displayName.trim().isNotEmpty) {
|
||||
return existingMatch.displayName;
|
||||
}
|
||||
|
||||
MeshMapNode? cachedMatch;
|
||||
for (final node in cachedNodes) {
|
||||
if (node.publicKey == advert.publicKeyHex.toLowerCase()) {
|
||||
cachedMatch = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (cachedMatch != null && cachedMatch.name.trim().isNotEmpty) {
|
||||
return cachedMatch.name;
|
||||
}
|
||||
|
||||
return advert.shortDisplayKey;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Discovery')),
|
||||
body: FutureBuilder<List<MeshMapNode>>(
|
||||
future: _cachedNodesFuture,
|
||||
builder: (context, nodesSnapshot) =>
|
||||
Consumer2<ContactsProvider, ConnectionProvider>(
|
||||
builder: (context, contactsProvider, connectionProvider, child) {
|
||||
final pendingAdverts = contactsProvider.pendingAdverts;
|
||||
final isConnected = connectionProvider.deviceInfo.isConnected;
|
||||
final cachedNodes = nodesSnapshot.data ?? const <MeshMapNode>[];
|
||||
|
||||
if (pendingAdverts.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.person_search_outlined,
|
||||
size: 64,
|
||||
color: Theme.of(context).disabledColor,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No pending discoveries',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Unknown adverts will appear here until you choose to resolve them.',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Card(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.person_search),
|
||||
title: Text(
|
||||
'Pending discoveries (${pendingAdverts.length})',
|
||||
),
|
||||
subtitle: const Text(
|
||||
'Resolve entries manually so they do not auto-populate contacts.',
|
||||
),
|
||||
trailing: FilledButton.icon(
|
||||
onPressed: isConnected && !_isResolvingAll
|
||||
? () => _resolveAll(pendingAdverts)
|
||||
: null,
|
||||
icon: _isResolvingAll
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.download_for_offline_outlined),
|
||||
label: const Text('Resolve all'),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...pendingAdverts.map((advert) {
|
||||
final isResolving = _resolvingAdvertKeys.contains(
|
||||
advert.publicKeyHex,
|
||||
);
|
||||
final displayName = _displayNameForAdvert(
|
||||
advert,
|
||||
contactsProvider,
|
||||
cachedNodes,
|
||||
);
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
leading: const CircleAvatar(
|
||||
child: Icon(Icons.campaign_outlined),
|
||||
),
|
||||
title: Text(
|
||||
displayName,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${l10n.publicKey}: ${advert.shortDisplayKey}\n'
|
||||
'${l10n.lastSeen}: ${_formatRelativeTime(context, advert.receivedAt)}',
|
||||
),
|
||||
trailing: isResolving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
),
|
||||
)
|
||||
: IconButton(
|
||||
icon: const Icon(Icons.person_add_alt_1),
|
||||
tooltip: 'Resolve contact',
|
||||
onPressed: isConnected
|
||||
? () => _resolveAdvert(advert)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import '../providers/contacts_provider.dart';
|
||||
import '../theme/app_theme.dart';
|
||||
import 'messages_tab.dart';
|
||||
import 'contacts_tab.dart';
|
||||
import 'discovery_screen.dart';
|
||||
import 'sensors_tab.dart';
|
||||
import 'map_tab.dart';
|
||||
import 'repeaters_map_screen.dart';
|
||||
@@ -712,6 +713,39 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
),
|
||||
);
|
||||
|
||||
items.add(
|
||||
PopupMenuItem(
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.person_search),
|
||||
const SizedBox(width: 8),
|
||||
Consumer<ContactsProvider>(
|
||||
builder: (context, contactsProvider, child) {
|
||||
final pendingCount =
|
||||
contactsProvider.pendingAdverts.length;
|
||||
return Text(
|
||||
pendingCount > 0
|
||||
? 'Discovery ($pendingCount)'
|
||||
: 'Discovery',
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
final navigator = Navigator.of(context);
|
||||
Future.delayed(Duration.zero, () {
|
||||
if (!mounted) return;
|
||||
navigator.push(
|
||||
MaterialPageRoute(
|
||||
builder: (context) => const DiscoveryScreen(),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
items.add(
|
||||
PopupMenuItem(
|
||||
child: Row(
|
||||
|
||||
@@ -163,9 +163,13 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
|
||||
void _scrollToMessage(String messageId) {
|
||||
final messagesProvider = context.read<MessagesProvider>();
|
||||
final messages = _getFilteredMessages(messagesProvider);
|
||||
final messages = messagesProvider.buildDisplayMessages(
|
||||
_getFilteredMessages(messagesProvider),
|
||||
);
|
||||
|
||||
final messageIndex = messages.indexWhere((m) => m.id == messageId);
|
||||
final messageIndex = messages.indexWhere(
|
||||
(entry) => entry.message.id == messageId,
|
||||
);
|
||||
|
||||
if (messageIndex != -1 && _scrollController.hasClients) {
|
||||
// Calculate position - accounting for reverse list
|
||||
@@ -2019,7 +2023,9 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
return Consumer<MessagesProvider>(
|
||||
builder: (context, messagesProvider, child) {
|
||||
_syncChannelAutoReadTimer(messagesProvider);
|
||||
final messages = _getFilteredMessages(messagesProvider);
|
||||
final messages = messagesProvider.buildDisplayMessages(
|
||||
_getFilteredMessages(messagesProvider),
|
||||
);
|
||||
final bottomInset = MediaQuery.of(context).viewPadding.bottom;
|
||||
final composerBottomPadding = bottomInset > 0 ? 2.0 : 10.0;
|
||||
|
||||
|
||||
@@ -777,13 +777,7 @@ class _DecodedRouteSection extends StatelessWidget {
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
final originalSender = resolvedPath.isEmpty ? null : resolvedPath.first;
|
||||
|
||||
return _RouteSection(
|
||||
route: decodedRoute,
|
||||
path: resolvedPath,
|
||||
originalSender: originalSender,
|
||||
);
|
||||
return _RouteSection(route: decodedRoute, path: resolvedPath);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -827,13 +821,8 @@ class _DecodedRouteSection extends StatelessWidget {
|
||||
class _RouteSection extends StatelessWidget {
|
||||
final DecodedLogRxRoute route;
|
||||
final List<ResolvedNodeHash> path;
|
||||
final ResolvedNodeHash? originalSender;
|
||||
|
||||
const _RouteSection({
|
||||
required this.route,
|
||||
required this.path,
|
||||
required this.originalSender,
|
||||
});
|
||||
const _RouteSection({required this.route, required this.path});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -879,12 +868,6 @@ class _RouteSection extends StatelessWidget {
|
||||
value:
|
||||
'${route.hashSize} byte${route.hashSize == 1 ? '' : 's'}',
|
||||
),
|
||||
if (originalSender != null)
|
||||
_FactCard(
|
||||
icon: Icons.person_pin_circle,
|
||||
label: 'Original sender',
|
||||
value: _nodeLabel(originalSender!),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
@@ -1130,19 +1130,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
_buildSectionHeader('Messaging'),
|
||||
_buildSettingsCard([
|
||||
Consumer<AppProvider>(
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: const Icon(Icons.person_add_alt_1),
|
||||
title: const Text('Auto-add discovered contacts'),
|
||||
subtitle: const Text(
|
||||
'Automatically fetch and add new contacts when they are discovered',
|
||||
),
|
||||
value: appProvider.autoAddDiscoveredContacts,
|
||||
onChanged: (value) async {
|
||||
await appProvider.toggleAutoAddDiscoveredContacts(value);
|
||||
},
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.alt_route),
|
||||
title: const Text('Route path byte size'),
|
||||
|
||||
Reference in New Issue
Block a user