diff --git a/lib/services/node_banner_service.dart b/lib/services/node_banner_service.dart new file mode 100644 index 00000000..878758e3 --- /dev/null +++ b/lib/services/node_banner_service.dart @@ -0,0 +1,152 @@ +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 `;` with URL-encoded values. + /// 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 = {}; + for (final pair in record.split(';')) { + final eq = pair.indexOf('='); + if (eq <= 0) continue; + try { + fields[pair.substring(0, eq).trim().toLowerCase()] = + Uri.decodeComponent(pair.substring(eq + 1).trim()); + } on ArgumentError { + return null; + } + } + 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 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; + if (json['Status'] != 0) return null; + for (final answer in (json['Answer'] as List? ?? const [])) { + final record = answer as Map; + 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(); + } +} diff --git a/lib/widgets/get_node_banner.dart b/lib/widgets/get_node_banner.dart index 5060ae72..2c5e9763 100644 --- a/lib/widgets/get_node_banner.dart +++ b/lib/widgets/get_node_banner.dart @@ -2,25 +2,42 @@ import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import '../l10n/l10n.dart'; +import '../services/node_banner_service.dart'; import '../theme/mesh_theme.dart'; -/// Affiliate link for the SenseCAP MeshTracker X1. -const getNodeUrl = - 'https://www.seeedstudio.com/sensecap-meshtracker-x1-meshtastic-gps-tracker-p-6935.html' - '?sensecap_affiliate=JFWID0g&referring_service=link'; - /// Bottom banner on the connect screen pointing new users at a node to buy. -class GetNodeBanner extends StatelessWidget { - const GetNodeBanner({super.key}); +/// Its link (and optionally its text) comes from the `_banner` DNS TXT +/// record; it stays hidden until that loads, and when the lookup fails or the +/// record turns it off. +class GetNodeBanner extends StatefulWidget { + final Future Function()? loadConfig; - void _open() => - launchUrl(Uri.parse(getNodeUrl), mode: LaunchMode.externalApplication); + const GetNodeBanner({super.key, this.loadConfig}); + + @override + State createState() => _GetNodeBannerState(); +} + +class _GetNodeBannerState extends State { + NodeBannerConfig? _config; + + @override + void initState() { + super.initState(); + (widget.loadConfig ?? NodeBannerService().load)().then((config) { + if (mounted && config != null) setState(() => _config = config); + }); + } @override Widget build(BuildContext context) { + final config = _config; + if (config == null) return const SizedBox.shrink(); + final l10n = context.l10n; final scheme = Theme.of(context).colorScheme; final textTheme = Theme.of(context).textTheme; + void open() => launchUrl(config.url, mode: LaunchMode.externalApplication); return SafeArea( top: false, @@ -34,7 +51,7 @@ class GetNodeBanner extends StatelessWidget { ), clipBehavior: Clip.antiAlias, child: InkWell( - onTap: _open, + onTap: open, child: Padding( padding: const EdgeInsets.fromLTRB(14, 12, 14, 10), child: Column( @@ -51,7 +68,7 @@ class GetNodeBanner extends StatelessWidget { const SizedBox(width: 10), Expanded( child: Text( - l10n.scanner_getNodeTitle, + config.title ?? l10n.scanner_getNodeTitle, style: textTheme.titleMedium?.copyWith( color: scheme.onPrimaryContainer, fontWeight: FontWeight.w700, @@ -62,7 +79,7 @@ class GetNodeBanner extends StatelessWidget { ), const SizedBox(height: 6), Text( - l10n.scanner_getNodeBody, + config.body ?? l10n.scanner_getNodeBody, style: textTheme.bodyMedium?.copyWith( color: scheme.onPrimaryContainer, height: 1.35, @@ -72,9 +89,9 @@ class GetNodeBanner extends StatelessWidget { SizedBox( width: double.infinity, child: FilledButton.icon( - onPressed: _open, + onPressed: open, icon: const Icon(Icons.shopping_cart_outlined, size: 22), - label: Text(l10n.scanner_getNodeAction), + label: Text(config.action ?? l10n.scanner_getNodeAction), ), ), const SizedBox(height: 6), diff --git a/test/services/node_banner_service_test.dart b/test/services/node_banner_service_test.dart new file mode 100644 index 00000000..ed6e2bd3 --- /dev/null +++ b/test/services/node_banner_service_test.dart @@ -0,0 +1,95 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/services/node_banner_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _record = + 'v=1;on=1;url=https%3A%2F%2Fshop.example.com%2Fnode%3Fref%3Da%26b%3Dc;' + 'title=Need%20a%20node%3F'; + +String _doh(String data, {int status = 0, int ttl = 300}) => jsonEncode({ + 'Status': status, + 'Answer': [ + {'name': '_banner.meshcoreopen.org', 'type': 16, 'TTL': ttl, 'data': data}, + ], +}); + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + group('NodeBannerConfig.parse', () { + test('reads the link and decodes text overrides', () { + final config = NodeBannerConfig.parse(_record)!; + expect(config.url.toString(), 'https://shop.example.com/node?ref=a&b=c'); + expect(config.title, 'Need a node?'); + expect(config.body, isNull); + expect(config.action, isNull); + }); + + test('is off for on=0, unknown versions, and non-https links', () { + expect( + NodeBannerConfig.parse(_record.replaceAll('on=1', 'on=0')), + isNull, + ); + expect(NodeBannerConfig.parse(_record.replaceAll('v=1', 'v=2')), isNull); + expect(NodeBannerConfig.parse('v=1;on=1;url=http%3A%2F%2Fx.com'), isNull); + expect(NodeBannerConfig.parse('v=1;on=1'), isNull); + expect(NodeBannerConfig.parse('v=1;on=1;url=%E0%A4%A'), isNull); + }); + }); + + test('joins split TXT character-strings and unescapes them', () { + final answer = NodeBannerService.txtFromDohJson( + _doh(r'"v=1;on=1;url=https%3A%2F%2Fa.com" ";title=Say \"hi\""'), + )!; + expect(answer.text, 'v=1;on=1;url=https%3A%2F%2Fa.com;title=Say "hi"'); + expect(answer.ttl, 300); + }); + + test('no record or NXDOMAIN gives no answer', () { + expect(NodeBannerService.txtFromDohJson(jsonEncode({'Status': 3})), isNull); + expect(NodeBannerService.txtFromDohJson(jsonEncode({'Status': 0})), isNull); + }); + + test('load queries Cloudflare DoH and caches for the TTL', () async { + var calls = 0; + var now = DateTime(2026, 1, 1); + final client = MockClient((request) async { + calls++; + expect(request.url.host, 'cloudflare-dns.com'); + expect(request.url.queryParameters['name'], '_banner.meshcoreopen.org'); + expect(request.url.queryParameters['type'], 'TXT'); + expect(request.headers['accept'], 'application/dns-json'); + return http.Response(_doh('"$_record"'), 200); + }); + final service = NodeBannerService(client: client, now: () => now); + + expect((await service.load())?.title, 'Need a node?'); + expect((await service.load())?.title, 'Need a node?'); + expect(calls, 1); + + now = now.add(const Duration(minutes: 6)); + await service.load(); + expect(calls, 2); + }); + + test('load returns null when the lookup fails', () async { + final failing = NodeBannerService( + client: MockClient((_) async => throw http.ClientException('offline')), + ); + expect(await failing.load(), isNull); + + final serverError = NodeBannerService( + client: MockClient((_) async => http.Response('', 503)), + ); + expect(await serverError.load(), isNull); + }); +} diff --git a/test/widgets/get_node_banner_test.dart b/test/widgets/get_node_banner_test.dart index 5cb90bc9..6d573d0e 100644 --- a/test/widgets/get_node_banner_test.dart +++ b/test/widgets/get_node_banner_test.dart @@ -1,13 +1,18 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/services/node_banner_service.dart'; import 'package:meshcore_open/widgets/get_node_banner.dart'; +final _config = NodeBannerConfig(url: Uri.parse('https://example.com/node')); + void main() { Future pumpBanner( WidgetTester tester, { required Size size, required double textScale, + NodeBannerConfig? config, + bool hidden = false, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -21,7 +26,11 @@ void main() { size: size, textScaler: TextScaler.linear(textScale), ), - child: const Scaffold(bottomNavigationBar: GetNodeBanner()), + child: Scaffold( + bottomNavigationBar: GetNodeBanner( + loadConfig: () async => hidden ? null : config ?? _config, + ), + ), ), ), ); @@ -29,11 +38,11 @@ void main() { testWidgets('shows the pitch and affiliate link', (tester) async { await pumpBanner(tester, size: const Size(390, 844), textScale: 1); + await tester.pump(); expect(find.text('Need a new node?'), findsOneWidget); expect(find.text('Get one here'), findsOneWidget); expect(find.textContaining('Affiliate link'), findsOneWidget); - expect(getNodeUrl, contains('sensecap_affiliate=JFWID0g')); // Leaves most of the screen for the device list. expect( tester.getSize(find.byType(GetNodeBanner)).height, @@ -43,6 +52,38 @@ void main() { testWidgets('lays out on a narrow phone with large text', (tester) async { await pumpBanner(tester, size: const Size(320, 800), textScale: 1.5); + await tester.pump(); expect(tester.takeException(), isNull); }); + + testWidgets('uses text overrides from the record', (tester) async { + await pumpBanner( + tester, + size: const Size(390, 844), + textScale: 1, + config: NodeBannerConfig( + url: Uri.parse('https://example.com'), + title: 'Spring sale', + action: 'Shop now', + ), + ); + await tester.pump(); + + expect(find.text('Spring sale'), findsOneWidget); + expect(find.text('Shop now'), findsOneWidget); + expect(find.textContaining('Affiliate link'), findsOneWidget); + }); + + testWidgets('shows nothing when there is no config', (tester) async { + await pumpBanner( + tester, + size: const Size(390, 844), + textScale: 1, + hidden: true, + ); + await tester.pump(); + + expect(find.byType(InkWell), findsNothing); + expect(tester.getSize(find.byType(GetNodeBanner)).height, 0); + }); }