Add contact import from QR code

Contacts could only be imported by pasting `meshcore://<hex advert>` from
the clipboard, so contact QR codes and links shared by the official app
(`meshcore://contact/add?name=...&public_key=...&type=...`) could not be
used at all.

Add a contact QR scanner screen, reachable from the contacts menu, that
scans with the camera or decodes a QR code from a photo in the gallery.
Both the official contact-card link and the existing hex advert form are
accepted; cards are applied with CMD_ADD_UPDATE_CONTACT and advert blobs
keep using CMD_IMPORT_CONTACT.

Fixes #529
This commit is contained in:
Gianluca Boiano committed 2026-09-13 00:23:46 +02:00
1 parent 92e1d15d1c
commit d0583f2039
28 files changed
+1231 -16

No files matched your search

+5
View File
@@ -2402,6 +2402,11 @@
"contacts_floodAdvert": "Flood Advert",
"contacts_copyAdvertToClipboard": "Copy Advert to Clipboard",
"contacts_addContactFromClipboard": "Add Contact from Clipboard",
"contacts_scanQrCode": "Scan QR Code",
"contacts_scanQrInstructions": "Point the camera at a MeshCore contact QR code",
"contacts_qrFromGallery": "Scan QR from Gallery",
"contacts_noQrCodeFound": "No QR code found in the selected image.",
"contacts_qrGalleryFailed": "Could not open the gallery.",
"contacts_ShareContact": "Copy contact to Clipboard",
"contacts_ShareContactZeroHop": "Share contact by advert",
"contacts_zeroHopContactAdvertSent": "Sent contact by advert.",
+5
View File
@@ -1905,6 +1905,11 @@
"contacts_copyAdvertToClipboard": "Copia Annuncio negli Appunti",
"contacts_addContactFromClipboard": "Aggiungere contatto dalla clipboard",
"contacts_clipboardEmpty": "La clipboard è vuota.",
"contacts_scanQrCode": "Scansiona codice QR",
"contacts_scanQrInstructions": "Inquadra un codice QR di un contatto MeshCore",
"contacts_qrFromGallery": "Scansiona QR dalla galleria",
"contacts_noQrCodeFound": "Nessun codice QR trovato nell'immagine selezionata.",
"contacts_qrGalleryFailed": "Impossibile aprire la galleria.",
"contacts_ShareContact": "Copia contatto negli Appunti",
"contacts_contactImported": "Il contatto è stato importato.",
"contacts_contactImportFailed": "Contatto non importato con successo.",
+30
View File
@@ -7372,6 +7372,36 @@ abstract class AppLocalizations {
/// **'Add Contact from Clipboard'**
String get contacts_addContactFromClipboard;
/// No description provided for @contacts_scanQrCode.
///
/// In en, this message translates to:
/// **'Scan QR Code'**
String get contacts_scanQrCode;
/// No description provided for @contacts_scanQrInstructions.
///
/// In en, this message translates to:
/// **'Point the camera at a MeshCore contact QR code'**
String get contacts_scanQrInstructions;
/// No description provided for @contacts_qrFromGallery.
///
/// In en, this message translates to:
/// **'Scan QR from Gallery'**
String get contacts_qrFromGallery;
/// No description provided for @contacts_noQrCodeFound.
///
/// In en, this message translates to:
/// **'No QR code found in the selected image.'**
String get contacts_noQrCodeFound;
/// No description provided for @contacts_qrGalleryFailed.
///
/// In en, this message translates to:
/// **'Could not open the gallery.'**
String get contacts_qrGalleryFailed;
/// No description provided for @contacts_ShareContact.
///
/// In en, this message translates to:
+17
View File
@@ -4253,6 +4253,23 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Добави контакт от клипборда';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Копирай контакт в клипборда';
+17
View File
@@ -4260,6 +4260,23 @@ class AppLocalizationsDe extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Kontakt aus Zwischenablage hinzufügen';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Kontakt in die Zwischenablage kopieren';
+17
View File
@@ -4188,6 +4188,23 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Add Contact from Clipboard';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Copy contact to Clipboard';
+17
View File
@@ -4252,6 +4252,23 @@ class AppLocalizationsEs extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Agregar contacto desde el portapapeles';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Copiar contacto al portapapeles';
+17
View File
@@ -4269,6 +4269,23 @@ class AppLocalizationsFr extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Ajouter un contact depuis le presse-papiers';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact =>
'Copier le contact dans le presse-papiers';
+17
View File
@@ -4250,6 +4250,23 @@ class AppLocalizationsHu extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Névjegy hozzáadása a vágólapról';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Névjegy másolása a vágólapra';
+17
View File
@@ -4260,6 +4260,23 @@ class AppLocalizationsIt extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Aggiungere contatto dalla clipboard';
@override
String get contacts_scanQrCode => 'Scansiona codice QR';
@override
String get contacts_scanQrInstructions =>
'Inquadra un codice QR di un contatto MeshCore';
@override
String get contacts_qrFromGallery => 'Scansiona QR dalla galleria';
@override
String get contacts_noQrCodeFound =>
'Nessun codice QR trovato nell\'immagine selezionata.';
@override
String get contacts_qrGalleryFailed => 'Impossibile aprire la galleria.';
@override
String get contacts_ShareContact => 'Copia contatto negli Appunti';
+17
View File
@@ -4042,6 +4042,23 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'クリップボードから連絡先を追加する';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => '連絡先をクリップボードにコピー';
+17
View File
@@ -4052,6 +4052,23 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => '복사본에서 연락처 추가';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => '연락처를 복사';
+17
View File
@@ -4238,6 +4238,23 @@ class AppLocalizationsNl extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Contact uit klembord toevoegen';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Contact naar Klembord kopiëren';
+17
View File
@@ -4270,6 +4270,23 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Dodaj kontakt z schowka';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Kopiuj kontakt do schowka';
+17
View File
@@ -4254,6 +4254,23 @@ class AppLocalizationsPt extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Adicionar Contato da Área de Transferência';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact =>
'Copiar contato para Área de Transferência';
+17
View File
@@ -4264,6 +4264,23 @@ class AppLocalizationsRu extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Добавить контакт из буфера обмена';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Копировать контакт в буфер обмена';
+17
View File
@@ -4235,6 +4235,23 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Pridať kontakt z schránky';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Kopírovať kontakt do schránky';
+17
View File
@@ -4231,6 +4231,23 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Dodaj stik iz odložišča';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Kopiraj stik v Odložišče';
+17
View File
@@ -4207,6 +4207,23 @@ class AppLocalizationsSv extends AppLocalizations {
String get contacts_addContactFromClipboard =>
'Lägg till kontakt från urklipp';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Kopiera kontakt till Urklipp';
+17
View File
@@ -4257,6 +4257,23 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => 'Додати контакт з буфера';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => 'Копіювати контакт у буфер обміну';
+17
View File
@@ -3966,6 +3966,23 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get contacts_addContactFromClipboard => '从剪贴板添加联系人';
@override
String get contacts_scanQrCode => 'Scan QR Code';
@override
String get contacts_scanQrInstructions =>
'Point the camera at a MeshCore contact QR code';
@override
String get contacts_qrFromGallery => 'Scan QR from Gallery';
@override
String get contacts_noQrCodeFound =>
'No QR code found in the selected image.';
@override
String get contacts_qrGalleryFailed => 'Could not open the gallery.';
@override
String get contacts_ShareContact => '复制联系人信息到剪贴板';
+277
View File
@@ -0,0 +1,277 @@
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mobile_scanner/mobile_scanner.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../theme/mesh_theme.dart';
import '../utils/contact_qr.dart';
import '../utils/contact_qr_frame.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../widgets/qr_scanner_widget.dart';
/// Screen for scanning MeshCore contact QR codes, either with the camera
/// or by picking a photo containing a QR code from the gallery.
class ContactQrScannerScreen extends StatefulWidget {
const ContactQrScannerScreen({super.key});
@override
State<ContactQrScannerScreen> createState() => _ContactQrScannerScreenState();
}
class _ContactQrScannerScreenState extends State<ContactQrScannerScreen> {
bool _isProcessing = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: AdaptiveAppBarTitle(context.l10n.contacts_scanQrCode),
centerTitle: true,
actions: [
IconButton(
tooltip: context.l10n.contacts_qrFromGallery,
icon: const Icon(Icons.photo_library),
onPressed: _isProcessing ? null : _pickFromGallery,
),
],
),
body: _isProcessing
? Container(
color: Theme.of(context).colorScheme.surface,
child: const Center(child: CircularProgressIndicator()),
)
: QrScannerWidget(
onScanned: (data) => _handleScannedData(data),
validator: (data) => parseContactQr(data) != null,
onValidationFailed: (_) => _showInvalidQrError(),
instructions: context.l10n.contacts_scanQrInstructions,
overlay: _buildThemedOverlay(context),
),
);
}
Widget _buildThemedOverlay(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: [
// Dark semi-transparent background with cutout
ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.black.withValues(alpha: 0.5),
BlendMode.srcOut,
),
child: Stack(
fit: StackFit.expand,
children: [
Container(
decoration: const BoxDecoration(
color: Colors.black,
backgroundBlendMode: BlendMode.dstOut,
),
),
Center(
child: Container(
height: 250,
width: 250,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(16),
),
),
),
],
),
),
// Corner brackets on top
const ScannerCornerOverlay(
scanWindowSize: 250,
borderColor: MeshPalette.blue,
borderWidth: 2,
cornerLength: 24,
),
// Instructions pill below the scan window
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 250 + 24),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 10,
),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.72),
borderRadius: BorderRadius.circular(MeshRadii.pill),
),
child: Text(
context.l10n.contacts_scanQrInstructions,
style: const TextStyle(color: MeshPalette.ink2, fontSize: 13),
textAlign: TextAlign.center,
),
),
],
),
),
],
);
}
Future<void> _pickFromGallery() async {
if (_isProcessing) return;
// Claim the flag before awaiting the picker, otherwise a camera detection
// can start a second import while the gallery sheet is open.
setState(() {
_isProcessing = true;
});
final XFile? image;
try {
image = await ImagePicker().pickImage(source: ImageSource.gallery);
} catch (e) {
if (mounted) {
setState(() {
_isProcessing = false;
});
_showGalleryError();
}
return;
}
if (!mounted) return;
if (image == null) {
setState(() {
_isProcessing = false;
});
return;
}
String? rawValue;
bool decodedAnyBarcode = false;
final controller = MobileScannerController();
try {
final capture = await controller.analyzeImage(image.path);
for (final barcode in capture?.barcodes ?? const []) {
final value = barcode.rawValue;
if (value == null || value.isEmpty) continue;
decodedAnyBarcode = true;
if (parseContactQr(value) != null) {
rawValue = value;
break;
}
}
} on UnsupportedError {
rawValue = null;
} catch (e) {
rawValue = null;
} finally {
controller.dispose();
}
if (!mounted) return;
if (rawValue == null) {
setState(() {
_isProcessing = false;
});
if (decodedAnyBarcode) {
_showInvalidQrError();
} else {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_noQrCodeFound),
backgroundColor: MeshPalette.warn,
duration: const Duration(seconds: 2),
);
}
return;
}
setState(() {
_isProcessing = false;
});
await _handleScannedData(rawValue);
}
Future<void> _handleScannedData(String data) async {
if (_isProcessing) return;
setState(() {
_isProcessing = true;
});
final scanned = parseContactQr(data);
if (scanned == null) {
if (mounted) {
setState(() {
_isProcessing = false;
});
_showInvalidQrError();
}
return;
}
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
final publicKey = scanned.publicKey;
// Saved contacts first (their flags matter), then discovery-only records,
// which still carry a known name worth preserving.
final existing = publicKey == null
? null
: connector.allContactsUnfiltered
.where(
(contact) => contact.publicKeyHex == pubKeyToHex(publicKey),
)
.firstOrNull;
final frame = buildContactQrFrame(
scanned,
existing: existing,
pathHashByteWidth: connector.pathHashByteWidth,
);
try {
await connector.sendFrame(frame, waitForGenericAck: true);
await connector.refreshContacts();
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_contactImported),
);
Navigator.pop(context);
} catch (e) {
if (mounted) {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_contactImportFailed),
);
}
} finally {
if (mounted) {
setState(() {
_isProcessing = false;
});
}
}
}
void _showInvalidQrError() {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_invalidAdvertFormat),
backgroundColor: MeshPalette.warn,
duration: const Duration(seconds: 2),
);
}
void _showGalleryError() {
showDismissibleSnackBar(
context,
content: Text(context.l10n.contacts_qrGalleryFailed),
backgroundColor: MeshPalette.warn,
duration: const Duration(seconds: 2),
);
}
}
+29
View File
@@ -34,6 +34,7 @@ import '../widgets/unread_badge.dart';
import '../helpers/snack_bar_builder.dart';
import 'channels_screen.dart';
import 'chat_screen.dart';
import 'contact_qr_scanner_screen.dart';
import 'discovery_screen.dart';
import 'map_screen.dart';
import 'repeater_hub_screen.dart';
@@ -376,6 +377,21 @@ class _ContactsScreenState extends State<ContactsScreen>
),
onTap: () => _contactImport(),
),
PopupMenuItem(
child: Row(
children: [
const Icon(Icons.qr_code_scanner),
const SizedBox(width: 8),
Text(context.l10n.contacts_scanQrCode),
],
),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ContactQrScannerScreen(),
),
),
),
const PopupMenuDivider(),
PopupMenuItem(
child: Row(
@@ -488,6 +504,19 @@ class _ContactsScreenState extends State<ContactsScreen>
_contactImport();
},
),
ListTile(
leading: const Icon(Icons.qr_code_scanner),
title: Text(context.l10n.contacts_scanQrCode),
onTap: () {
Navigator.pop(sheetContext);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ContactQrScannerScreen(),
),
);
},
),
ListTile(
leading: const Icon(Icons.person_add_rounded),
title: Text(context.l10n.discoveredContacts_Title),
+101
View File
@@ -0,0 +1,101 @@
import 'dart:typed_data';
/// Parsed result of a MeshCore contact QR / link.
class ScannedContact {
/// Raw advert packet bytes (legacy `meshcore://<hex>` form), else null.
final Uint8List? advertPacket;
/// 32-byte public key (contact-card form), else null.
final Uint8List? publicKey;
/// Contact name from the card form; empty string when unknown.
final String name;
/// Advert type: 1 Companion, 2 Repeater, 3 Room Server, 4 Sensor.
final int type;
const ScannedContact({
this.advertPacket,
this.publicKey,
this.name = '',
this.type = 1,
});
bool get isAdvertPacket => advertPacket != null;
}
/// Matches the advert packet minimum enforced by `buildImportContactFrame`.
const int _minAdvertPacketBytes = 98;
/// `buildImportContactFrame` prepends one command byte to a `maxFrameSize`
/// (172 byte) frame, so anything longer cannot be sent.
const int _maxAdvertPacketBytes = 171;
const int _contactCardKeyBytes = 32;
const String _legacyPrefix = 'meshcore://';
/// Returns null when [data] is not a recognizable MeshCore contact QR/link.
ScannedContact? parseContactQr(String data) {
final trimmed = data.trim();
if (trimmed.isEmpty) return null;
final uri = Uri.tryParse(trimmed);
if (uri == null || uri.scheme != 'meshcore') return null;
final normalizedPath = '${uri.host}${uri.path}'.toLowerCase().replaceAll(
RegExp(r'^/+|/+$'),
'',
);
if (normalizedPath == 'contact/add') {
return _parseContactCard(uri);
}
if (!trimmed.toLowerCase().startsWith(_legacyPrefix)) return null;
final hexString = trimmed.substring(_legacyPrefix.length);
final bytes = _tryHexDecode(hexString);
if (bytes == null ||
bytes.length < _minAdvertPacketBytes ||
bytes.length > _maxAdvertPacketBytes) {
return null;
}
return ScannedContact(advertPacket: bytes);
}
ScannedContact? _parseContactCard(Uri uri) {
final params = uri.queryParameters;
final publicKeyHex = params['public_key'];
if (publicKeyHex == null) return null;
final publicKey = _tryHexDecode(publicKeyHex);
if (publicKey == null || publicKey.length != _contactCardKeyBytes) {
return null;
}
final name = (params['name'] ?? '').trim();
int type = int.tryParse(params['type'] ?? '') ?? 1;
if (type < 1 || type > 4) type = 1;
return ScannedContact(publicKey: publicKey, name: name, type: type);
}
/// Local hex decoder: keeps this util pure-Dart. `hex2Uint8List` in
/// `connector/meshcore_protocol.dart` throws on invalid input and that file
/// pulls in `package:flutter/widgets.dart` and `package:crypto`, which this
/// util must not depend on.
Uint8List? _tryHexDecode(String hex) {
if (hex.isEmpty || hex.length.isOdd) return null;
final bytes = Uint8List(hex.length ~/ 2);
for (int i = 0; i < bytes.length; i++) {
final high = _hexDigit(hex.codeUnitAt(i * 2));
final low = _hexDigit(hex.codeUnitAt(i * 2 + 1));
if (high == null || low == null) return null;
bytes[i] = (high << 4) | low;
}
return bytes;
}
int? _hexDigit(int codeUnit) {
if (codeUnit >= 0x30 && codeUnit <= 0x39) return codeUnit - 0x30;
if (codeUnit >= 0x61 && codeUnit <= 0x66) return codeUnit - 0x61 + 10;
if (codeUnit >= 0x41 && codeUnit <= 0x46) return codeUnit - 0x41 + 10;
return null;
}
+74
View File
@@ -0,0 +1,74 @@
import 'dart:convert';
import 'dart:typed_data';
import '../connector/meshcore_protocol.dart';
import '../models/contact.dart';
import 'contact_qr.dart';
/// Builds the device frame that applies [scanned].
///
/// Advert blobs are replayed with `CMD_IMPORT_CONTACT`; contact cards are
/// written with `CMD_ADD_UPDATE_CONTACT`, preserving the flags, name and route
/// of [existing] when the QR omits them. A card carries no route, so a contact
/// the device does not know yet is written with the `0xFF` unknown-path
/// sentinel (`Contact.fromFrame` maps it to `hopCount == -1`) and its messages
/// flood until an advert supplies a path.
///
/// [pathHashByteWidth] is the connector's current path-hash mode, needed to
/// re-encode a preserved path the same way the rest of the app does.
Uint8List buildContactQrFrame(
ScannedContact scanned, {
Contact? existing,
int pathHashByteWidth = 1,
}) {
if (scanned.isAdvertPacket) {
return buildImportContactFrame(scanned.advertPacket!);
}
final route = _routeOf(existing, pathHashByteWidth);
return buildUpdateContactPathFrame(
scanned.publicKey!,
route.path,
route.pathLen,
type: scanned.type,
flags: existing?.flags ?? 0,
name: _fitName(
scanned.name.isEmpty ? (existing?.name ?? '') : scanned.name,
),
);
}
/// Rescanning a contact must not throw away a route the device already has:
/// writing an empty path with the unknown sentinel would force flooding until
/// another advert restores it. Reuse [existing]'s path when it is valid for the
/// current mode, encoded as `MeshCoreConnector._encodePathLenForCurrentMode`
/// does (hop count in bits 0-5, mode in bits 6-7).
({Uint8List path, int pathLen}) _routeOf(Contact? existing, int width) {
final unknown = (path: Uint8List(0), pathLen: 0xFF);
if (existing == null) return unknown;
final hops = existing.pathLength;
if (hops < 0 || hops > 0x3F) return unknown;
final hashWidth = width.clamp(1, 4).toInt();
final path = existing.path;
if (path.length > maxPathSize || path.length != hops * hashWidth) {
return unknown;
}
return (path: path, pathLen: hops | ((hashWidth - 1) << 6));
}
/// `writeCString` clips the encoded name to `maxNameSize - 1` bytes without
/// looking at character boundaries, which would leave a half-written rune in
/// the contact record. Drop whole characters instead.
String _fitName(String name) {
const limit = maxNameSize - 1;
if (utf8.encode(name).length <= limit) return name;
final buffer = StringBuffer();
var used = 0;
for (final rune in name.runes) {
final char = String.fromCharCode(rune);
final charBytes = utf8.encode(char).length;
if (used + charBytes > limit) break;
buffer.write(char);
used += charBytes;
}
return buffer.toString();
}
+152
View File
@@ -0,0 +1,152 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/contact.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
import 'package:meshcore_open/utils/contact_qr_frame.dart';
void main() {
final publicKey = Uint8List.fromList(List<int>.filled(32, 0xAB));
Contact contactWith({required String name, required int flags}) {
return Contact(
publicKey: publicKey,
name: name,
type: advTypeChat,
flags: flags,
pathLength: 2,
path: Uint8List.fromList([1, 2]),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
}
group('buildContactQrFrame advert packet', () {
test('replays the advert with CMD_IMPORT_CONTACT', () {
final advert = Uint8List.fromList(List<int>.filled(98, 7));
final frame = buildContactQrFrame(
ScannedContact(advertPacket: advert),
existing: contactWith(name: 'Old', flags: 0x03),
);
expect(frame[0], cmdImportContact);
expect(frame.sublist(1), advert);
});
});
group('buildContactQrFrame contact card', () {
test('writes an add/update frame with the unknown-path sentinel', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice', type: 2),
);
expect(frame[0], cmdAddUpdateContact);
expect(frame.sublist(1, 33), publicKey);
expect(frame[33], 2);
expect(frame[34], 0);
expect(frame[35], 0xFF, reason: 'path is unknown, not zero-hop');
final nameStart = 36 + maxPathSize;
final name = String.fromCharCodes(
frame
.sublist(nameStart, nameStart + maxNameSize)
.takeWhile((b) => b != 0),
);
expect(name, 'Alice');
});
test('preserves the flags of an existing contact', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice'),
existing: contactWith(name: 'Alice', flags: 0x05),
);
expect(frame[34], 0x05);
});
test('falls back to the existing name when the card has none', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey),
existing: contactWith(name: 'Existing', flags: 0),
);
final nameStart = 36 + maxPathSize;
final name = String.fromCharCodes(
frame
.sublist(nameStart, nameStart + maxNameSize)
.takeWhile((b) => b != 0),
);
expect(name, 'Existing');
});
test('drops whole characters when the name exceeds 31 bytes', () {
// 16 three-byte characters = 48 encoded bytes; only 10 fit in 31.
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: '☂' * 16),
);
final nameStart = 36 + maxPathSize;
final bytes = frame
.sublist(nameStart, nameStart + maxNameSize)
.takeWhile((b) => b != 0)
.toList();
expect(bytes.length, 30);
expect(utf8.decode(bytes), '☂' * 10);
});
});
group('buildContactQrFrame route preservation', () {
Contact contactWithPath(int pathLength, List<int> path) {
return Contact(
publicKey: publicKey,
name: 'Alice',
type: advTypeChat,
pathLength: pathLength,
path: Uint8List.fromList(path),
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
);
}
test('keeps the route of a contact the device already knows', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice'),
existing: contactWithPath(2, [0x11, 0x22]),
);
expect(frame[35], 0x02, reason: 'two hops, 1-byte hash mode');
expect(frame.sublist(36, 38), [0x11, 0x22]);
});
test('encodes the hash mode in bits 6-7 for wider path hashes', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice'),
existing: contactWithPath(2, [0x11, 0x22, 0x33, 0x44]),
pathHashByteWidth: 2,
);
expect(frame[35], 0x42);
expect(frame.sublist(36, 40), [0x11, 0x22, 0x33, 0x44]);
});
test('uses the unknown sentinel for a flood-only contact', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice'),
existing: contactWithPath(-1, const []),
);
expect(frame[35], 0xFF);
expect(frame.sublist(36, 36 + maxPathSize).every((b) => b == 0), isTrue);
});
test('uses the unknown sentinel when the path does not fit the mode', () {
final frame = buildContactQrFrame(
ScannedContact(publicKey: publicKey, name: 'Alice'),
existing: contactWithPath(2, [0x11, 0x22]),
pathHashByteWidth: 2,
);
expect(frame[35], 0xFF);
});
});
}
+156
View File
@@ -0,0 +1,156 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/utils/contact_qr.dart';
void main() {
group('parseContactQr official contact card', () {
test('parses name with + and percent-encoding, key, explicit type', () {
final key = List.generate(
32,
(i) => i.toRadixString(16).padLeft(2, '0'),
).join();
final result = parseContactQr(
'meshcore://contact/add?name=Jane+D%C3%B6e&public_key=$key&type=2',
);
expect(result, isNotNull);
expect(result!.isAdvertPacket, isFalse);
expect(result.name, 'Jane Döe');
expect(result.publicKey!.length, 32);
expect(result.publicKey![0], 0x00);
expect(result.publicKey![31], 0x1f);
expect(result.type, 2);
});
test('missing type defaults to 1', () {
final key = 'ab' * 32;
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=$key',
);
expect(result, isNotNull);
expect(result!.type, 1);
});
test('garbage type falls back to 1', () {
final key = 'ab' * 32;
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=$key&type=nope',
);
expect(result, isNotNull);
expect(result!.type, 1);
});
test('uppercase hex public key is accepted', () {
final key = 'AB' * 32;
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=$key',
);
expect(result, isNotNull);
expect(result!.publicKey!.length, 32);
expect(result.publicKey![0], 0xAB);
});
test('63-char public key is rejected', () {
final key = '${'ab' * 31}a';
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=$key',
);
expect(result, isNull);
});
test('non-hex public key is rejected', () {
final key = ('zz' * 32);
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=$key',
);
expect(result, isNull);
});
test('signed public key digits are rejected', () {
final result = parseContactQr(
'meshcore://contact/add?name=Bob&public_key=${'+1' * 32}',
);
expect(result, isNull);
});
test('missing name defaults to empty string', () {
final key = 'ab' * 32;
final result = parseContactQr('meshcore://contact/add?public_key=$key');
expect(result, isNotNull);
expect(result!.name, '');
});
});
group('parseContactQr legacy advert packet', () {
test('legacy hex form yields advert packet bytes', () {
final hex = '0a' * 98;
final result = parseContactQr('meshcore://$hex');
expect(result, isNotNull);
expect(result!.isAdvertPacket, isTrue);
expect(result.advertPacket!.length, 98);
expect(result.advertPacket![0], 0x0a);
});
test('odd-length hex is rejected', () {
final result = parseContactQr('meshcore://abc');
expect(result, isNull);
});
test('non-hex payload is rejected', () {
final result = parseContactQr('meshcore://zz${'00' * 97}');
expect(result, isNull);
});
test('payload shorter than the 98 byte advert minimum is rejected', () {
final result = parseContactQr('meshcore://${'ab' * 97}');
expect(result, isNull);
});
test('payload longer than the 171 byte frame limit is rejected', () {
final result = parseContactQr('meshcore://${'ab' * 172}');
expect(result, isNull);
});
test('payload at the 171 byte frame limit is accepted', () {
final result = parseContactQr('meshcore://${'ab' * 171}');
expect(result, isNotNull);
expect(result!.advertPacket!.length, 171);
});
});
group('parseContactQr rejects unsupported input', () {
test('channel add link is not a contact', () {
final result = parseContactQr(
'meshcore://channel/add?name=Public&secret=abcd',
);
expect(result, isNull);
});
test('non-meshcore scheme is rejected', () {
final result = parseContactQr('https://example.com/contact/add');
expect(result, isNull);
});
test('empty string is rejected', () {
expect(parseContactQr(''), isNull);
});
test('whitespace-only string is rejected', () {
expect(parseContactQr(' \n\t '), isNull);
});
});
}
+96 -16
View File
@@ -3,33 +3,58 @@
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"de": [
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"es": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"fr": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"hu": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"it": [
@@ -42,75 +67,130 @@
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"ko": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"nl": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"pl": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"pt": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"ru": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"sk": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"sl": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"sv": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied"
"settings_publicKeyCopied",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"uk": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
],
"zh": [
"urlImage_enable",
"urlImage_possible",
"settings_publicKeyCopied",
"reaction_report"
"reaction_report",
"contacts_scanQrCode",
"contacts_scanQrInstructions",
"contacts_qrFromGallery",
"contacts_noQrCodeFound",
"contacts_qrGalleryFailed"
]
}