diff --git a/README.md b/README.md index c5175364..7a672274 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ The central courtyard for your self-hosted media stack. One Android app that fronts Sonarr, Radarr, Lidarr, Prowlarr, Bazarr, Seerr, Ombi, Tautulli, Tracearr, Jellyfin, Emby, Plex, Navidrome, qBittorrent, Deluge, Transmission, rTorrent, aria2, slskd, SABnzbd, NZBGet, Glances, -Speedtest Tracker, MySpeed, Beszel, dashdot, Gluetun, AdGuard Home, Cleanuparr -and Unraid - and routes every request through the right URL whether you're on +Speedtest Tracker, MySpeed, Beszel, dashdot, Gluetun, AdGuard Home, Technitium DNS, +Cleanuparr and Unraid - and routes every request through the right URL whether you're on the home Wi-Fi or out in the world. **[Website][site]** - screenshots and a tour, no install needed. @@ -88,6 +88,7 @@ each one covers: | dashdot | live CPU, memory, disk, and GPU usage with a system-info tab, dashboard widget | | Gluetun | VPN status, forwarded port, reconnect, dashboard widget | | AdGuard Home | protection switch and timed pause, statistics, top clients and domains, query log with block and unblock, blocklists, custom rules, blocked services and rewrites, persistent and runtime clients, DNS, cache, access and retention settings, dashboard widget | +| Technitium DNS | protection switch and timed pauses (30s, 1m, 10m, 1h, disable/enable), query rate and blocked sparklines, top clients and domains over configurable time ranges (1h, 24h, 7d, 30d), live paginated query logs with response type filter and one-tap domain blocking, blocked zones management, cache flushing, server metrics, dashboard widget (beta) | | Cleanuparr | system status, operational metrics, active strikes ledger & reset, audit events feed, background cleaner job triggers, dashboard widget (beta) | | Unraid | array and disk health, system with per-core load, Docker, VM control | diff --git a/STATUS.md b/STATUS.md index 3575200b..fcd389ac 100644 --- a/STATUS.md +++ b/STATUS.md @@ -38,7 +38,7 @@ Atrium is a **controller** app. Video playback was removed by design - **Dashboard widgets**, reorderable from Customize dashboard: Active downloads, Now streaming, Upcoming releases, Recently added, Recently downloaded, Requests (Seerr and Ombi), Glances, Dashdot, Speedtest - results, MySpeed, Gluetun VPN, AdGuard Home, Cleanuparr and Wake on LAN + results, MySpeed, Gluetun VPN, AdGuard Home, Technitium DNS, Cleanuparr and Wake on LAN - **Settings**: theme, biometric lock, profile import/export (SAF, live-verified), **Wake-on-LAN devices** (profile-stored, magic packets over pure Dart UDP), **custom HTTP headers** (global + per-instance, @@ -453,6 +453,24 @@ Atrium is a **controller** app. Video playback was removed by design - **Dashboard widget**: Integrated into `DashboardWidgetKind.downloads` for cross-service queue tracking. - Strictly dynamic Material 3 theming with `AtriumBottomNav` system insets support and `ExpressiveProgressIndicator`. +- **Technitium DNS** (beta; added 2026-11-22): network-wide DNS server and ad blocker (`service_technitium`). + Default port 5380, role: `ServiceRole.analytics`, API token authentication via Bearer token + (`Authorization: Bearer ` or `token=`). + - **Overview tab**: Protection status card with timed pauses (30 seconds, 1 minute, 10 minutes, + 1 hour, or until turned back on) and resume controls, queries & blocked metric tiles, + dual-series sparkline charts for total and blocked traffic, selectable time ranges (Last hour, + Last 24 hours, Last 7 days, Last 30 days), and top clients / top domains leaderboards. + - **Query Log tab**: Live paginated DNS queries log (`/api/logs/query`), response type filter chips + (All, Blocked, Allowed), instant domain search, query detail bottom sheet with record details, + client IP, protocol, and 1-tap Quick Block domain action. + - **Blocked Zones tab**: Blocked domain and zone rules management, add new blocked zone dialog, + zone deletion, and on-demand block list force update trigger (`/api/settings/forceUpdateBlockLists`). + - **Settings & Cache tab**: DNS server metrics (version, uptime, threads, memory), cache flushing + action (`/api/cache/flush`) with confirmation dialog, and blocking configuration overview. + - **Dashboard widget**: Compact `DashboardTechnitiumWidget` displaying protection state, + countdown timer when paused, queries count, blocked percentage share ring, and traffic sparkline chart. + - Full parity with AdGuard Home workflow and dynamic Material 3 theming. + - **iOS**: the target exists and CI builds it unsigned on macOS on every change, so it cannot rot unnoticed. Deep links already no-op off Android and dynamic colour falls back to Atrium's own seed, since iOS has no system diff --git a/app/assets/service_icons/technitium.png b/app/assets/service_icons/technitium.png new file mode 100644 index 00000000..87c6cedc Binary files /dev/null and b/app/assets/service_icons/technitium.png differ diff --git a/app/lib/src/connection_test/connection_tester.dart b/app/lib/src/connection_test/connection_tester.dart index c0ff04ff..799d799c 100644 --- a/app/lib/src/connection_test/connection_tester.dart +++ b/app/lib/src/connection_test/connection_tester.dart @@ -10,6 +10,7 @@ import 'package:service_plex/service_plex.dart'; import 'package:service_qbittorrent/service_qbittorrent.dart'; import 'package:service_rtorrent/service_rtorrent.dart'; import 'package:service_seerr/service_seerr.dart'; +import 'package:service_technitium/service_technitium.dart'; import 'connection_test_result.dart'; @@ -117,6 +118,8 @@ class ConnectionTester { return _testSeerr(forced); case ServiceKind.rtorrent: return _testRtorrent(forced); + case ServiceKind.technitium: + return _testTechnitium(forced); default: final HealthProbe probe = HealthProbe(dioFactory: _ref.read(dioFactoryProvider)); @@ -206,7 +209,8 @@ class ConnectionTester { // A forward-auth login portal answers 200 with a web page. The API // always answers with a JSON object, so anything else did not reach it. final String contentType = - response.headers.value(Headers.contentTypeHeader)?.toLowerCase() ?? ''; + response.headers.value(Headers.contentTypeHeader)?.toLowerCase() ?? + ''; if (contentType.contains('text/html') || response.data is! Map) { return connectionResultFromHealth(Health.warning); } @@ -344,6 +348,35 @@ class ConnectionTester { } } + Future _testTechnitium(Instance forced) async { + Dio? dio; + try { + dio = await _ref.read(dioFactoryProvider).create(forced); + final TechnitiumApi api = TechnitiumApi(dio); + await api.getSettings(); + return const ConnectionTestResult( + ConnectionOutcome.connected, + 'Connected', + ); + } on TechnitiumAuthException catch (e) { + return ConnectionTestResult( + ConnectionOutcome.authFailed, + e.message.isNotEmpty ? e.message : 'Invalid API key', + ); + } on Object catch (error) { + if (error is TechnitiumUnexpectedAnswer || + error is NetworkNotFoundException) { + return const ConnectionTestResult( + ConnectionOutcome.unreachable, + 'Reachable, but Technitium DNS did not answer at this address', + ); + } + return connectionResultFromError(error); + } finally { + dio?.close(force: true); + } + } + Future _verify(Future Function() action) async { try { await action(); diff --git a/app/lib/src/dashboard/dashboard_board.dart b/app/lib/src/dashboard/dashboard_board.dart index 11f59826..c8122a60 100644 --- a/app/lib/src/dashboard/dashboard_board.dart +++ b/app/lib/src/dashboard/dashboard_board.dart @@ -27,6 +27,7 @@ import 'package:service_gluetun/service_gluetun.dart'; import 'package:service_myspeed/service_myspeed.dart'; import 'package:service_aria2/service_aria2.dart'; import 'package:service_cleanuparr/service_cleanuparr.dart'; +import 'package:service_technitium/service_technitium.dart'; import 'package:service_slskd/service_slskd.dart'; import '../health_providers.dart'; @@ -35,6 +36,7 @@ import 'dashboard_layout.dart'; import 'dashboard_widget_kind.dart'; import 'widgets/adguard_home_widget.dart'; import 'widgets/cleanuparr_widget.dart'; +import 'widgets/technitium_widget.dart'; import 'widgets/dashdot_widget.dart'; import 'widgets/downloads_widget.dart'; import 'widgets/gluetun_status_widget.dart'; @@ -224,6 +226,10 @@ class DashboardBoard extends ConsumerWidget { return DashboardGotifyWidget( instances: _byKind(instances, ServiceKind.gotify), ); + case DashboardWidgetKind.technitium: + return DashboardTechnitiumWidget( + instances: _byKind(instances, ServiceKind.technitium), + ); case DashboardWidgetKind.wakeOnLan: return const DashboardWakeOnLanWidget(); } @@ -306,6 +312,11 @@ class DashboardBoard extends ConsumerWidget { case ServiceKind.slskd: ref.invalidate(slskdDownloadsProvider(i)); ref.invalidate(slskdUploadsProvider(i)); + case ServiceKind.technitium: + ref.invalidate(technitiumStatusProvider(i)); + ref.invalidate(technitiumStatsProvider(i)); + ref.invalidate(technitiumDashboardStatsProvider(i)); + ref.invalidate(technitiumSettingsProvider(i)); default: break; } @@ -380,16 +391,15 @@ class _EditBoard extends ConsumerWidget { ? 'Show widget' : 'Needs something that can fill it', icon: const Icon(Icons.add_circle_outline), - onPressed: - DashboardBoard._configured( + onPressed: DashboardBoard._configured( c.kind, instances, wolDeviceCount: wolCount, ) - ? () => ref - .read(dashboardLayoutProvider.notifier) - .setEnabled(c.kind, true) - : null, + ? () => ref + .read(dashboardLayoutProvider.notifier) + .setEnabled(c.kind, true) + : null, ), ), ), diff --git a/app/lib/src/dashboard/dashboard_widget_kind.dart b/app/lib/src/dashboard/dashboard_widget_kind.dart index 5e4675c9..60a22dd6 100644 --- a/app/lib/src/dashboard/dashboard_widget_kind.dart +++ b/app/lib/src/dashboard/dashboard_widget_kind.dart @@ -18,6 +18,7 @@ enum DashboardWidgetKind { wakeOnLan, cleanuparr, gotify, + technitium, } extension DashboardWidgetKindX on DashboardWidgetKind { @@ -37,6 +38,7 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.wakeOnLan => 'Wake on LAN', DashboardWidgetKind.cleanuparr => 'Cleanuparr', DashboardWidgetKind.gotify => 'Gotify', + DashboardWidgetKind.technitium => 'Technitium DNS', }; IconData get icon => switch (this) { @@ -55,6 +57,7 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.wakeOnLan => Icons.power_settings_new_rounded, DashboardWidgetKind.cleanuparr => Icons.cleaning_services_outlined, DashboardWidgetKind.gotify => Icons.notifications_active_outlined, + DashboardWidgetKind.technitium => Icons.dns_rounded, }; /// Service kinds whose presence makes this widget "configured". @@ -93,18 +96,14 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.serverInfo => const [ ServiceKind.glances ], - DashboardWidgetKind.dashdot => const [ - ServiceKind.dashdot - ], + DashboardWidgetKind.dashdot => const [ServiceKind.dashdot], DashboardWidgetKind.speedtestResults => const [ ServiceKind.speedtestTracker ], DashboardWidgetKind.gluetunStatus => const [ ServiceKind.gluetun ], - DashboardWidgetKind.myspeed => const [ - ServiceKind.myspeed - ], + DashboardWidgetKind.myspeed => const [ServiceKind.myspeed], DashboardWidgetKind.adguardHome => const [ ServiceKind.adguardHome ], @@ -112,6 +111,9 @@ extension DashboardWidgetKindX on DashboardWidgetKind { ServiceKind.cleanuparr ], DashboardWidgetKind.gotify => const [ServiceKind.gotify], + DashboardWidgetKind.technitium => const [ + ServiceKind.technitium, + ], // Wake-on-LAN answers to no service. Its targets are machines on the // network, kept on the profile beside the instances, so there is no // service whose presence could stand in for being set up. diff --git a/app/lib/src/dashboard/widgets/technitium_widget.dart b/app/lib/src/dashboard/widgets/technitium_widget.dart new file mode 100644 index 00000000..6225ef26 --- /dev/null +++ b/app/lib/src/dashboard/widgets/technitium_widget.dart @@ -0,0 +1,494 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_router/core_router.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:progress_indicator_m3e/progress_indicator_m3e.dart'; +import 'package:service_technitium/service_technitium.dart'; + +import '../dashboard_widget_card.dart'; +import '../dashboard_widget_kind.dart'; + +/// Dashboard widget for Technitium DNS Server. +class DashboardTechnitiumWidget extends StatelessWidget { + const DashboardTechnitiumWidget({ + required this.instances, + this.now = DateTime.now, + super.key, + }); + + final List instances; + final DateTime Function() now; + + @override + Widget build(BuildContext context) { + return DashboardWidgetCard( + kind: DashboardWidgetKind.technitium, + accent: Theme.of(context).colorScheme.primary, + onTap: + instances.length == 1 ? () => _open(context, instances.first) : null, + child: instances.isEmpty + ? const DashboardIdleRow( + text: 'No Technitium DNS instances configured', + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (int i = 0; i < instances.length; i++) ...[ + if (i > 0) const Divider(height: Insets.lg), + _TechnitiumBlock( + instance: instances[i], + showName: instances.length > 1, + onTap: instances.length > 1 + ? () => _open(context, instances[i]) + : null, + now: now, + ), + ], + ], + ), + ); + } + + void _open(BuildContext context, Instance instance) { + context.go(AtriumRoutes.servicePath(instance.kind.name, instance.id)); + } +} + +class _TechnitiumBlock extends ConsumerStatefulWidget { + const _TechnitiumBlock({ + required this.instance, + required this.showName, + required this.onTap, + required this.now, + }); + + final Instance instance; + final bool showName; + final VoidCallback? onTap; + final DateTime Function() now; + + @override + ConsumerState<_TechnitiumBlock> createState() => _TechnitiumBlockState(); +} + +class _TechnitiumBlockState extends ConsumerState<_TechnitiumBlock> { + bool _busy = false; + + Instance get _instance => widget.instance; + TechnitiumActions get _actions => + ref.read(technitiumActionsProvider(_instance)); + + Future _setProtection({required bool enabled, Duration? pause}) async { + if (_busy) return; + setState(() => _busy = true); + try { + await _actions.setProtection(enabled: enabled, pause: pause); + } on Object catch (error) { + if (mounted) { + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar( + SnackBar(content: Text(describeTechnitiumError(error))), + ); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final AsyncValue status = + ref.watch(technitiumStatusProvider(_instance)); + final TechnitiumStats? stats = + ref.watch(technitiumDashboardStatsProvider(_instance)).value; + + return InkWell( + borderRadius: BorderRadius.circular(12), + onTap: widget.onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: Insets.xs), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (widget.showName) + Padding( + padding: const EdgeInsets.only(bottom: Insets.sm), + child: Text( + _instance.name, + style: theme.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w700, + color: cs.onSurfaceVariant, + ), + ), + ), + status.when( + skipLoadingOnReload: true, + skipLoadingOnRefresh: true, + loading: () => const Center( + child: Padding( + padding: EdgeInsets.all(Insets.sm), + child: SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2.5), + ), + ), + ), + error: (Object _, StackTrace __) => + DashboardErrorRow(onRetry: _actions.refresh), + data: (TechnitiumStatus status) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _StateRow( + status: status, + busy: _busy, + onSet: _setProtection, + onPauseEnded: () => + ref.invalidate(technitiumStatusProvider(_instance)), + now: widget.now, + ), + const SizedBox(height: Insets.md), + _Summary(stats: stats), + if (stats != null && + stats.queriesSeries.length > 1) ...[ + const SizedBox(height: Insets.sm), + SizedBox( + height: 48, + child: TechnitiumSeriesChart( + series: stats.queriesSeries, + color: cs.primary, + over: stats.blockedSeries, + overColor: cs.error, + ), + ), + ], + const SizedBox(height: Insets.xs), + Text( + 'Last 24 hours', + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + ), + ); + } +} + +class _StateRow extends StatelessWidget { + const _StateRow({ + required this.status, + required this.busy, + required this.onSet, + required this.onPauseEnded, + required this.now, + }); + + final TechnitiumStatus status; + final bool busy; + final void Function({required bool enabled, Duration? pause}) onSet; + final VoidCallback onPauseEnded; + final DateTime Function() now; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final TechnitiumProtection state = status.protection; + final Color color = switch (state) { + TechnitiumProtection.on => cs.primary, + TechnitiumProtection.paused => cs.tertiary, + TechnitiumProtection.off => cs.error, + }; + final TextStyle? pillText = theme.textTheme.labelSmall?.copyWith( + color: color, + fontWeight: FontWeight.bold, + ); + final DateTime? pausedUntil = status.pausedUntil; + + final Widget pill = Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.sm, + vertical: Insets.xs, + ), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + switch (state) { + TechnitiumProtection.on => Icons.shield_rounded, + TechnitiumProtection.paused => Icons.pause_circle_outline_rounded, + TechnitiumProtection.off => Icons.shield_outlined, + }, + size: 14, + color: color, + ), + const SizedBox(width: Insets.xs), + Text( + switch (state) { + TechnitiumProtection.on => 'PROTECTED', + TechnitiumProtection.paused => 'PAUSED', + TechnitiumProtection.off => 'OFF', + }, + style: pillText, + ), + if (pausedUntil != null && + state == TechnitiumProtection.paused) ...[ + const SizedBox(width: Insets.xs), + TechnitiumCountdown( + until: pausedUntil, + onDone: onPauseEnded, + now: now, + style: pillText, + ), + ], + ], + ), + ); + + return Row( + children: [ + Expanded( + child: FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: pill, + ), + ), + const SizedBox(width: Insets.sm), + if (state == TechnitiumProtection.on) + _PauseButton(busy: busy, onSet: onSet) + else + FilledButton.tonalIcon( + style: FilledButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.xs, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + onPressed: busy ? null : () => onSet(enabled: true), + icon: const Icon(Icons.play_arrow_rounded, size: 16), + label: const Text('Resume'), + ), + ], + ); + } +} + +class _PauseButton extends StatelessWidget { + const _PauseButton({required this.busy, required this.onSet}); + + final bool busy; + final void Function({required bool enabled, Duration? pause}) onSet; + + Future _choose(BuildContext context) async { + final RenderBox button = context.findRenderObject()! as RenderBox; + final RenderBox overlay = Navigator.of(context, rootNavigator: true) + .overlay! + .context + .findRenderObject()! as RenderBox; + + final Duration? length = await showMenu( + context: context, + useRootNavigator: true, + position: RelativeRect.fromRect( + Rect.fromPoints( + button.localToGlobal( + button.size.bottomLeft(Offset.zero), + ancestor: overlay, + ), + button.localToGlobal( + button.size.bottomRight(Offset.zero), + ancestor: overlay, + ), + ), + Offset.zero & overlay.size, + ), + items: >[ + for (final TechnitiumPause pause in technitiumPauses) + PopupMenuItem( + value: pause.duration, + child: Text(pause.label), + ), + const PopupMenuDivider(), + const PopupMenuItem( + value: Duration.zero, + child: Text('Until turned back on'), + ), + ], + ); + + if (length == null) return; + onSet(enabled: false, pause: length == Duration.zero ? null : length); + } + + @override + Widget build(BuildContext context) { + return FilledButton.tonalIcon( + style: FilledButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.xs, + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + onPressed: busy ? null : () => _choose(context), + icon: const Icon(Icons.pause_rounded, size: 16), + label: const Text('Pause'), + ); + } +} + +class _Summary extends StatelessWidget { + const _Summary({required this.stats}); + + final TechnitiumStats? stats; + + @override + Widget build(BuildContext context) { + final ColorScheme cs = Theme.of(context).colorScheme; + final TechnitiumStats? stats = this.stats; + return Row( + children: [ + Expanded( + child: _Figure( + label: 'Queries', + value: stats == null + ? '-' + : formatTechnitiumCompact(stats.totalQueries), + color: cs.primary, + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: _Figure( + label: 'Blocked', + value: stats == null + ? '-' + : formatTechnitiumCompact(stats.blockedQueries), + color: cs.error, + ), + ), + const SizedBox(width: Insets.sm), + _ShareRing(percent: stats?.blockedPercent, color: cs.error), + ], + ); + } +} + +class _Figure extends StatelessWidget { + const _Figure({ + required this.label, + required this.value, + required this.color, + }); + + final String label; + final String value; + final Color color; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + value, + maxLines: 1, + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 6), + Text( + label, + style: theme.textTheme.labelMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ], + ); + } +} + +class _ShareRing extends StatelessWidget { + const _ShareRing({required this.percent, required this.color}); + + final double? percent; + final Color color; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final double? percent = this.percent; + return SizedBox( + width: 52, + height: 52, + child: Stack( + alignment: Alignment.center, + children: [ + TweenAnimationBuilder( + tween: Tween( + begin: 0, + end: ((percent ?? 0) / 100).clamp(0.0, 1.0), + ), + duration: const Duration(milliseconds: 600), + curve: Curves.easeOutCubic, + builder: (BuildContext context, double value, Widget? _) { + return CircularProgressIndicatorM3E( + value: value, + shape: ProgressM3EShape.flat, + activeColor: color, + trackColor: theme.colorScheme.surfaceContainerHighest, + ); + }, + ), + SizedBox( + width: 32, + height: 32, + child: FittedBox( + fit: BoxFit.scaleDown, + child: Text( + percent == null ? '-' : formatTechnitiumPercent(percent), + style: theme.textTheme.labelLarge?.copyWith( + fontWeight: FontWeight.w800, + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/src/screens/instance_form_screen.dart b/app/lib/src/screens/instance_form_screen.dart index 0d525850..a4dac288 100644 --- a/app/lib/src/screens/instance_form_screen.dart +++ b/app/lib/src/screens/instance_form_screen.dart @@ -299,7 +299,8 @@ class _InstanceFormScreenState extends ConsumerState { } bool get _warnAboutExternalHttp { - if (_kind != ServiceKind.speedtestTracker) { + if (_kind != ServiceKind.speedtestTracker && + _kind != ServiceKind.technitium) { return false; } final Uri? uri = Uri.tryParse(_externalUrl.text.trim()); @@ -493,7 +494,8 @@ class _InstanceFormScreenState extends ConsumerState { Flexible( child: Text( _kind.displayName, - style: theme.textTheme.titleLarge?.copyWith( + style: + theme.textTheme.titleLarge?.copyWith( fontWeight: FontWeight.bold, ), overflow: TextOverflow.ellipsis, @@ -716,11 +718,13 @@ class _InstanceFormScreenState extends ConsumerState { Container( padding: const EdgeInsets.all(Insets.sm), decoration: BoxDecoration( - color: _connectionOutcomeColor(context, entry.value.outcome) - .withValues(alpha: 0.1), + color: + _connectionOutcomeColor(context, entry.value.outcome) + .withValues(alpha: 0.1), borderRadius: BorderRadius.circular(Radii.sm), border: Border.all( - color: _connectionOutcomeColor(context, entry.value.outcome) + color: _connectionOutcomeColor( + context, entry.value.outcome) .withValues(alpha: 0.3), ), ), @@ -849,8 +853,7 @@ class _InstanceFormScreenState extends ConsumerState { border: const OutlineInputBorder(), labelText: local ? 'Email' : 'Username', ), - keyboardType: - local ? TextInputType.emailAddress : TextInputType.text, + keyboardType: local ? TextInputType.emailAddress : TextInputType.text, autocorrect: false, textInputAction: TextInputAction.next, onChanged: _clearConnectionTest, @@ -955,11 +958,13 @@ class _InstanceFormScreenState extends ConsumerState { decoration: InputDecoration( border: const OutlineInputBorder(), labelText: keyOptional ? 'API key (optional)' : 'API key', - helperText: keyOptional - ? (_kind == ServiceKind.slskd - ? 'Leave empty if authentication is disabled in slskd.' - : 'Leave empty if the control server has auth turned off.') - : null, + helperText: _kind == ServiceKind.technitium + ? 'Create an API token in Administration > API Tokens in the Technitium console.' + : keyOptional + ? (_kind == ServiceKind.slskd + ? 'Leave empty if authentication is disabled in slskd.' + : 'Leave empty if the control server has auth turned off.') + : null, ), autocorrect: false, onChanged: _clearConnectionTest, diff --git a/app/lib/src/screens/service_detail_screen.dart b/app/lib/src/screens/service_detail_screen.dart index 9ceb6129..00afbabe 100644 --- a/app/lib/src/screens/service_detail_screen.dart +++ b/app/lib/src/screens/service_detail_screen.dart @@ -36,6 +36,7 @@ import 'package:service_adguard_home/service_adguard_home.dart'; import 'package:service_aria2/service_aria2.dart'; import 'package:service_cleanuparr/service_cleanuparr.dart'; import 'package:service_slskd/service_slskd.dart'; +import 'package:service_technitium/service_technitium.dart'; import 'dashboard_screen.dart'; @@ -192,6 +193,15 @@ class _ServiceDetailScreenState extends ConsumerState { ), ); } + if (instance.kind == ServiceKind.technitium) { + return TechnitiumShell( + instance: instance, + drawer: ServicesDrawer( + instances: ref.watch(activeInstancesProvider), + profile: ref.watch(activeProfileProvider), + ), + ); + } return PopScope( canPop: false, onPopInvokedWithResult: (bool didPop, Object? result) { @@ -418,6 +428,7 @@ class _ServiceDetailScreenState extends ConsumerState { // Owns its own scaffold, handled above. ServiceKind.slskd => const SizedBox.shrink(), ServiceKind.gotify => GotifyHome(instance: instance), + ServiceKind.technitium => const SizedBox.shrink(), }; } } diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 0e0a119c..1624028e 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -66,6 +66,7 @@ dependencies: service_aria2: service_cleanuparr: service_slskd: + service_technitium: url_launcher: ^6.3.2 dev_dependencies: flutter_launcher_icons: ^0.14.3 diff --git a/app/test/technitium_brand_icon_test.dart b/app/test/technitium_brand_icon_test.dart new file mode 100644 index 00000000..5eb264ba --- /dev/null +++ b/app/test/technitium_brand_icon_test.dart @@ -0,0 +1,14 @@ +import 'package:core_models/core_models.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('the icon the picker asks for is bundled', () async { + final ByteData icon = await rootBundle + .load('assets/service_icons/${ServiceKind.technitium.name}.png'); + + expect(icon.lengthInBytes, greaterThan(0)); + }); +} diff --git a/app/test/technitium_widget_test.dart b/app/test/technitium_widget_test.dart new file mode 100644 index 00000000..8ef9cf48 --- /dev/null +++ b/app/test/technitium_widget_test.dart @@ -0,0 +1,165 @@ +import 'package:atrium/src/dashboard/widgets/technitium_widget.dart'; +import 'package:core_models/core_models.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_technitium/service_technitium.dart'; + +class _RecordingActions extends TechnitiumActions { + _RecordingActions(super.ref, super.instance); + + final List calls = []; + + @override + Future setProtection({required bool enabled, Duration? pause}) async { + calls.add('protection enabled=$enabled pause=${pause?.inSeconds}'); + } + + @override + Future refresh() async => calls.add('refresh'); +} + +void main() { + const Instance instance = Instance( + id: 'technitium-1', + name: 'DNS Main', + kind: ServiceKind.technitium, + localUrl: 'http://192.168.1.100:5380', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'secret-token'), + ); + + final DateTime readAt = DateTime(2026, 11, 22, 14, 0); + + TechnitiumStatus statusWith({ + bool enabled = true, + DateTime? pausedUntil, + }) { + return TechnitiumStatus( + version: '13.0.0', + isBlockingEnabled: enabled, + readAt: readAt, + pausedUntil: pausedUntil, + ); + } + + const TechnitiumStats testStats = TechnitiumStats( + totalQueries: 5000, + blockedQueries: 1000, + queriesSeries: [1000, 1500, 2500], + blockedSeries: [200, 300, 500], + ); + + testWidgets('shows idle text when no instances configured', + (WidgetTester tester) async { + await tester.pumpWidget( + const ProviderScope( + child: MaterialApp( + home: Scaffold( + body: DashboardTechnitiumWidget(instances: []), + ), + ), + ), + ); + + expect(find.text('No Technitium DNS instances configured'), findsOneWidget); + }); + + testWidgets('renders protected state, metrics and pause button', + (WidgetTester tester) async { + late _RecordingActions actions; + + await tester.pumpWidget( + ProviderScope( + overrides: [ + technitiumStatusProvider(instance).overrideWith( + (_) async => statusWith(enabled: true), + ), + technitiumDashboardStatsProvider(instance).overrideWith( + (_) async => testStats, + ), + technitiumActionsProvider(instance).overrideWith( + (Ref ref) => actions = _RecordingActions(ref, instance), + ), + ], + child: const MaterialApp( + home: Scaffold( + body: DashboardTechnitiumWidget( + instances: [instance], + ), + ), + ), + ), + ); + + await tester.pumpAndSettle(); + + expect(find.text('PROTECTED'), findsOneWidget); + expect(find.text('Queries'), findsOneWidget); + expect(find.text('5K'), findsOneWidget); + expect(find.text('Blocked'), findsOneWidget); + expect(find.text('1K'), findsOneWidget); + expect(find.text('20.0%'), findsOneWidget); + expect(find.text('Pause'), findsOneWidget); + + // Tap pause button to open pause menu + await tester.tap(find.text('Pause')); + await tester.pumpAndSettle(); + + expect(find.text('1 minute'), findsOneWidget); + expect(find.text('5 minutes'), findsOneWidget); + expect(find.text('10 minutes'), findsOneWidget); + expect(find.text('1 hour'), findsOneWidget); + expect(find.text('Until turned back on'), findsOneWidget); + + // Select 10 minutes + await tester.tap(find.text('10 minutes')); + await tester.pumpAndSettle(); + + expect(actions.calls, ['protection enabled=false pause=600']); + }); + + testWidgets('renders paused state and resume button', + (WidgetTester tester) async { + late _RecordingActions actions; + + final DateTime future = readAt.add(const Duration(minutes: 5)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + technitiumStatusProvider(instance).overrideWith( + (_) async => statusWith(enabled: true, pausedUntil: future), + ), + technitiumDashboardStatsProvider(instance).overrideWith( + (_) async => testStats, + ), + technitiumActionsProvider(instance).overrideWith( + (Ref ref) => actions = _RecordingActions(ref, instance), + ), + ], + child: MaterialApp( + home: Scaffold( + body: DashboardTechnitiumWidget( + instances: [instance], + now: () => readAt, + ), + ), + ), + ), + ); + + await tester.pumpAndSettle(); + + expect(find.text('PAUSED'), findsOneWidget); + expect(find.text('5:00'), findsOneWidget); + expect(find.text('Resume'), findsOneWidget); + + // Tap Resume + await tester.tap(find.text('Resume')); + await tester.pumpAndSettle(); + + expect(actions.calls, ['protection enabled=true pause=null']); + }); +} diff --git a/packages/core_models/lib/src/service_kind.dart b/packages/core_models/lib/src/service_kind.dart index 5ab1bbdf..dbbea14e 100644 --- a/packages/core_models/lib/src/service_kind.dart +++ b/packages/core_models/lib/src/service_kind.dart @@ -34,16 +34,15 @@ enum ServiceKind { aria2, cleanuparr, slskd, - gotify; + gotify, + technitium; /// All [ServiceKind] entries sorted alphabetically by their display name. - static List get sortedValues => - ServiceKind.values.toList() - ..sort( - (ServiceKind a, ServiceKind b) => a.displayName - .toLowerCase() - .compareTo(b.displayName.toLowerCase()), - ); + static List get sortedValues => ServiceKind.values.toList() + ..sort( + (ServiceKind a, ServiceKind b) => + a.displayName.toLowerCase().compareTo(b.displayName.toLowerCase()), + ); } /// Static metadata about a [ServiceKind] - display name, default port, the @@ -84,6 +83,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr => 'Cleanuparr', ServiceKind.slskd => 'slskd', ServiceKind.gotify => 'Gotify', + ServiceKind.technitium => 'Technitium DNS', }; /// One-line role description. @@ -119,6 +119,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr => 'Malware blocker & cleaner', ServiceKind.slskd => 'Soulseek client', ServiceKind.gotify => 'Notifications', + ServiceKind.technitium => 'Network-wide DNS & ad blocking', }; /// Whether this service's integration is still in beta. Surfaced as a @@ -130,7 +131,8 @@ extension ServiceKindX on ServiceKind { ServiceKind.aria2 || ServiceKind.cleanuparr || ServiceKind.slskd || - ServiceKind.gotify => + ServiceKind.gotify || + ServiceKind.technitium => true, _ => false, }; @@ -180,6 +182,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.slskd => 5030, // The port the official Docker image listens on. ServiceKind.gotify => 80, + ServiceKind.technitium => 5380, }; /// What auth flow the service uses by default. Some services (Jellyfin) can @@ -200,15 +203,14 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr || ServiceKind.ombi || // A client token; an application token can only post messages. - ServiceKind.gotify => + ServiceKind.gotify => AuthStyle.apiKey, + ServiceKind.technitium => AuthStyle.apiKey, // aria2's credential is its `--rpc-secret`, which is sent as the // first RPC parameter rather than as a header. It is optional - a // daemon with no secret answers anyone - so the form must not // demand one. - ServiceKind.aria2 || - ServiceKind.slskd => - AuthStyle.apiKey, + ServiceKind.aria2 || ServiceKind.slskd => AuthStyle.apiKey, // Transmission and rTorrent both use HTTP Basic, and for both it is // *optional* - rTorrent's XML-RPC has no auth of its own and is only // protected when someone puts a proxy in front - so the form must not @@ -266,6 +268,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.gluetun => ServiceRole.analytics, ServiceKind.myspeed => ServiceRole.analytics, ServiceKind.adguardHome => ServiceRole.analytics, + ServiceKind.technitium => ServiceRole.analytics, ServiceKind.cleanuparr || ServiceKind.gotify => ServiceRole.extra, }; diff --git a/packages/core_models/test/service_kind_test.dart b/packages/core_models/test/service_kind_test.dart index a4f1e0ec..3645b19d 100644 --- a/packages/core_models/test/service_kind_test.dart +++ b/packages/core_models/test/service_kind_test.dart @@ -40,6 +40,7 @@ void main() { 'cleanuparr', 'slskd', 'gotify', + 'technitium', ], ); }); @@ -180,6 +181,16 @@ void main() { expect(ServiceKind.slskd.acceptsTorrents, isFalse); }); + test('Technitium is registered as an apiKey analytics service', () { + expect(ServiceKind.technitium.displayName, 'Technitium DNS'); + expect(ServiceKind.technitium.tagline, 'Network-wide DNS & ad blocking'); + expect(ServiceKind.technitium.isBeta, isTrue); + expect(ServiceKind.technitium.defaultPort, 5380); + expect(ServiceKind.technitium.authStyle, AuthStyle.apiKey); + expect(ServiceKind.technitium.role, ServiceRole.analytics); + expect(ServiceKind.technitium.acceptsTorrents, isFalse); + }); + test('existing services retain their default ports', () { expect(ServiceKind.sonarr.defaultPort, 8989); expect(ServiceKind.glances.defaultPort, 61208); diff --git a/packages/core_networking/lib/src/auth_interceptor.dart b/packages/core_networking/lib/src/auth_interceptor.dart index 974f2c1d..7ca8b476 100644 --- a/packages/core_networking/lib/src/auth_interceptor.dart +++ b/packages/core_networking/lib/src/auth_interceptor.dart @@ -67,7 +67,9 @@ class AuthInterceptor extends Interceptor { switch (auth) { case InstanceAuthApiKey(:final String apiKey): switch (kind) { - case ServiceKind.speedtestTracker || ServiceKind.tracearr: + case ServiceKind.speedtestTracker || + ServiceKind.tracearr || + ServiceKind.technitium: options.headers['Authorization'] = 'Bearer $apiKey'; options.headers['Accept'] = 'application/json'; case ServiceKind.sabnzbd || ServiceKind.tautulli: diff --git a/packages/core_networking/lib/src/service_auth_headers.dart b/packages/core_networking/lib/src/service_auth_headers.dart index 04ab4a1b..d0a94931 100644 --- a/packages/core_networking/lib/src/service_auth_headers.dart +++ b/packages/core_networking/lib/src/service_auth_headers.dart @@ -15,7 +15,9 @@ Set serviceAuthHeaderNames(ServiceKind kind, InstanceAuth auth) { switch (auth) { case InstanceAuthApiKey(:final String apiKey): switch (kind) { - case ServiceKind.speedtestTracker || ServiceKind.tracearr: + case ServiceKind.speedtestTracker || + ServiceKind.tracearr || + ServiceKind.technitium: return const {'Authorization', 'Accept'}; case ServiceKind.sabnzbd || ServiceKind.tautulli: // Query parameter, not a header, so nothing collides. diff --git a/packages/core_networking/lib/src/service_health.dart b/packages/core_networking/lib/src/service_health.dart index 22f963e4..15eadaa3 100644 --- a/packages/core_networking/lib/src/service_health.dart +++ b/packages/core_networking/lib/src/service_health.dart @@ -146,6 +146,8 @@ enum _HealthMode { // `health` and `version` answer anyone; `current/user` refuses a wrong // token, and an application token too, which cannot read messages. return (path: 'current/user', mode: _HealthMode.authed); + case ServiceKind.technitium: + return (path: 'api/status', mode: _HealthMode.publicEndpoint); } } @@ -186,10 +188,7 @@ String? _probeBody(Instance instance) => switch (instance.kind) { String _aria2ProbeBody(Instance instance) { final String secret = switch (instance.auth) { InstanceAuthApiKey(:final String apiKey) => apiKey, - InstanceAuthUserPass() || - InstanceAuthPlex() || - InstanceAuthCookie() => - '', + InstanceAuthUserPass() || InstanceAuthPlex() || InstanceAuthCookie() => '', }; return jsonEncode({ 'jsonrpc': '2.0', @@ -245,8 +244,7 @@ class HealthProbe { ? {anonymousRequestExtra: true} : null, receiveTimeout: const Duration(seconds: 8), - contentType: - body == null ? null : _probeContentType(instance.kind), + contentType: body == null ? null : _probeContentType(instance.kind), responseType: body == null ? null : ResponseType.plain, ); final String probePath = _probePath(instance, cfg.path); @@ -371,7 +369,13 @@ Health interpretServiceHealthResponse( // attention. return Health.warning; case _HealthMode.publicEndpoint: - return (status >= 200 && status < 300) ? Health.ok : Health.error; + if (status >= 200 && status < 300) { + if (kind == ServiceKind.technitium && !_technitiumSaysOk(data)) { + return Health.warning; + } + return Health.ok; + } + return Health.error; case _HealthMode.reachable: return Health.ok; case _HealthMode.anonymous: @@ -441,3 +445,21 @@ bool _subsonicSaysOk(Object? data) { final Object? envelope = data['subsonic-response']; return envelope is Map && envelope['status'] == 'ok'; } + +/// Whether a Technitium DNS /api/status response succeeded. +/// +/// Returns true if status code was 2xx and body carries `{"status":"ok"}`. +bool _technitiumSaysOk(Object? data) { + Object? body = data; + if (body is String) { + try { + body = jsonDecode(body); + } on FormatException { + return false; + } + } + if (body is! Map) { + return false; + } + return body['status'] == 'ok'; +} diff --git a/packages/core_networking/test/service_auth_headers_test.dart b/packages/core_networking/test/service_auth_headers_test.dart index f4db3e56..6a980f9d 100644 --- a/packages/core_networking/test/service_auth_headers_test.dart +++ b/packages/core_networking/test/service_auth_headers_test.dart @@ -13,8 +13,7 @@ void main() { /// Runs a request through the interceptor and reports the headers it set. Set headersActuallySet(ServiceKind kind, InstanceAuth auth) { final RequestOptions options = RequestOptions(path: '/probe'); - final AuthInterceptor interceptor = - AuthInterceptor(kind: kind, auth: auth); + final AuthInterceptor interceptor = AuthInterceptor(kind: kind, auth: auth); interceptor.onRequest(options, RequestInterceptorHandler()); return options.headers.keys.toSet(); } @@ -45,7 +44,8 @@ void main() { } }); - test('MySpeed sets password and x-password headers only when key provided', () { + test('MySpeed sets password and x-password headers only when key provided', + () { expect( serviceAuthHeaderNames(ServiceKind.myspeed, apiKey), {'password', 'x-password'}, @@ -63,7 +63,7 @@ void main() { ); }); - test('the six kinds that spend Authorization on themselves are named', () { + test('the kinds that spend Authorization on themselves are named', () { // These are the ones where a user's own Authorization header never // reaches the wire, which is the whole reason the warning exists. final Set owners = { @@ -76,6 +76,7 @@ void main() { expect(owners, { ServiceKind.speedtestTracker, ServiceKind.tracearr, + ServiceKind.technitium, ServiceKind.nzbget, ServiceKind.transmission, ServiceKind.rtorrent, diff --git a/packages/core_networking/test/service_health_test.dart b/packages/core_networking/test/service_health_test.dart index 2ca210bb..fa3a9418 100644 --- a/packages/core_networking/test/service_health_test.dart +++ b/packages/core_networking/test/service_health_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { group('aria2 JSON-RPC health', _aria2Tests); group('AdGuard Home anonymous health', _adguardHomeTests); + group('Technitium DNS public health', _technitiumTests); group('proxy interception', _interceptionTests); group('Navidrome Subsonic health', _navidromeTests); group('Gluetun VPN health', _gluetunTests); @@ -109,7 +110,9 @@ void main() { interpretServiceHealthResponse( ServiceKind.myspeed, 401, - {'message': 'Please provide the correct password in the header'}, + { + 'message': 'Please provide the correct password in the header' + }, ), Health.warning, ); @@ -140,7 +143,9 @@ void _interceptionTests() { test('a 200 page is not a healthy service', () { expect( interpretServiceHealthResponse( - ServiceKind.sonarr, 200, '', + ServiceKind.sonarr, + 200, + '', contentType: html, ), Health.warning, @@ -150,7 +155,10 @@ void _interceptionTests() { test('it applies to the public-endpoint services too', () { expect( interpretServiceHealthResponse( - ServiceKind.jellyfin, 200, '', contentType: html, + ServiceKind.jellyfin, + 200, + '', + contentType: html, ), Health.warning, ); @@ -161,7 +169,10 @@ void _interceptionTests() { // accept a login portal. expect( interpretServiceHealthResponse( - ServiceKind.qbittorrent, 200, '', contentType: html, + ServiceKind.qbittorrent, + 200, + '', + contentType: html, ), Health.warning, ); @@ -170,7 +181,9 @@ void _interceptionTests() { test('a real json answer is still healthy', () { expect( interpretServiceHealthResponse( - ServiceKind.sonarr, 200, {'version': '4.0'}, + ServiceKind.sonarr, + 200, + {'version': '4.0'}, contentType: json, ), Health.ok, @@ -182,7 +195,9 @@ void _interceptionTests() { // 2xx is treated as an interception for exactly this reason. expect( interpretServiceHealthResponse( - ServiceKind.transmission, 409, '

409: Conflict

', + ServiceKind.transmission, + 409, + '

409: Conflict

', contentType: html, ), Health.ok, @@ -192,7 +207,10 @@ void _interceptionTests() { test('rtorrent answering 502 with a page is left alone', () { expect( interpretServiceHealthResponse( - ServiceKind.rtorrent, 502, '502', contentType: html, + ServiceKind.rtorrent, + 502, + '502', + contentType: html, ), Health.warning, ); @@ -203,7 +221,8 @@ void _interceptionTests() { // rather than sniffing the body. expect( interpretServiceHealthResponse( - ServiceKind.rtorrent, 200, + ServiceKind.rtorrent, + 200, '', contentType: 'text/xml', ), @@ -213,7 +232,8 @@ void _interceptionTests() { test('no content type at all changes nothing', () { expect( - interpretServiceHealthResponse(ServiceKind.sonarr, 200, {}), + interpretServiceHealthResponse( + ServiceKind.sonarr, 200, {}), Health.ok, ); }); @@ -495,3 +515,62 @@ void _adguardHomeTests() { expect(health(0), Health.error); }); } + +void _technitiumTests() { + Health health(int status, {Object? data, String? contentType}) => + interpretServiceHealthResponse( + ServiceKind.technitium, + status, + data, + contentType: contentType, + ); + + test('status 200 with ok status envelope is online', () { + expect( + health( + 200, + data: {'status': 'ok'}, + contentType: 'application/json', + ), + Health.ok, + ); + expect( + health( + 200, + data: '{"status":"ok"}', + contentType: 'application/json', + ), + Health.ok, + ); + }); + + test('status 200 with non-ok status or bad envelope is warning', () { + expect( + health(200, data: {'status': 'error'}), + Health.warning, + ); + expect( + health(200, data: {'hello': 'world'}), + Health.warning, + ); + expect( + health(200, data: 'not json at all'), + Health.warning, + ); + expect(health(200), Health.warning); + }); + + test('status 200 with HTML interception is warning', () { + expect( + health(200, data: 'Login', contentType: 'text/html'), + Health.warning, + ); + }); + + test('non-200 responses are error', () { + expect(health(401), Health.error); + expect(health(404), Health.error); + expect(health(500), Health.error); + expect(health(0), Health.error); + }); +} diff --git a/packages/core_ui/lib/src/service_visuals.dart b/packages/core_ui/lib/src/service_visuals.dart index 84f2990c..95643d6c 100644 --- a/packages/core_ui/lib/src/service_visuals.dart +++ b/packages/core_ui/lib/src/service_visuals.dart @@ -39,6 +39,7 @@ abstract final class ServiceVisuals { ServiceKind.cleanuparr => Icons.cleaning_services_outlined, ServiceKind.slskd => Icons.library_music_outlined, ServiceKind.gotify => Icons.notifications_active_outlined, + ServiceKind.technitium => Icons.dns_rounded, }; static Color accent(ServiceKind kind) => switch (kind) { @@ -73,6 +74,7 @@ abstract final class ServiceVisuals { ServiceKind.cleanuparr => const Color(0xFF7C3AED), ServiceKind.slskd => const Color(0xFF007ACC), ServiceKind.gotify => const Color(0xFF71CAEE), + ServiceKind.technitium => const Color(0xFF0078D7), }; /// Human label for a [ServiceRole] section header. diff --git a/pubspec.yaml b/pubspec.yaml index a5c7840a..31b0c96c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -56,3 +56,4 @@ workspace: - services/service_cleanuparr - services/service_slskd - services/service_gotify + - services/service_technitium diff --git a/services/service_technitium/lib/service_technitium.dart b/services/service_technitium/lib/service_technitium.dart new file mode 100644 index 00000000..539abffb --- /dev/null +++ b/services/service_technitium/lib/service_technitium.dart @@ -0,0 +1,25 @@ +library; + +export 'src/models/technitium_blocked_zone.dart'; +export 'src/models/technitium_query_log.dart'; +export 'src/models/technitium_settings.dart'; +export 'src/models/technitium_stats.dart'; +export 'src/models/technitium_status.dart'; +export 'src/models/technitium_top_stats.dart'; +export 'src/tabs/technitium_blocked_zones_tab.dart'; +export 'src/tabs/technitium_overview_tab.dart'; +export 'src/tabs/technitium_query_log_tab.dart'; +export 'src/tabs/technitium_settings_tab.dart'; +export 'src/technitium_api.dart'; +export 'src/technitium_errors.dart'; +export 'src/technitium_format.dart'; +export 'src/technitium_providers.dart'; +export 'src/technitium_session.dart'; +export 'src/technitium_shell.dart'; +export 'src/widgets/technitium_countdown.dart'; +export 'src/widgets/technitium_protection_card.dart'; +export 'src/widgets/technitium_query_detail_modal.dart'; +export 'src/widgets/technitium_query_log_row.dart'; +export 'src/widgets/technitium_series_chart.dart'; +export 'src/widgets/technitium_stat_tile.dart'; +export 'src/widgets/technitium_top_list.dart'; diff --git a/services/service_technitium/lib/src/models/technitium_blocked_zone.dart b/services/service_technitium/lib/src/models/technitium_blocked_zone.dart new file mode 100644 index 00000000..e80b2b6d --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_blocked_zone.dart @@ -0,0 +1,21 @@ +import 'technitium_json.dart'; + +/// A blocked zone / domain configured in Technitium. +class TechnitiumBlockedZone { + const TechnitiumBlockedZone({ + required this.domain, + this.disabled = false, + }); + + factory TechnitiumBlockedZone.fromJson(Map json) { + return TechnitiumBlockedZone( + domain: readString( + json['domain'] ?? json['zone'] ?? json['name'] ?? json['zoneName'], + ), + disabled: readBool(json['disabled']), + ); + } + + final String domain; + final bool disabled; +} diff --git a/services/service_technitium/lib/src/models/technitium_json.dart b/services/service_technitium/lib/src/models/technitium_json.dart new file mode 100644 index 00000000..2a09a87b --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_json.dart @@ -0,0 +1,36 @@ +/// Safe readers for Technitium JSON responses. +library; + +int readInt(Object? value) => value is num ? value.toInt() : 0; + +double readDouble(Object? value) => value is num ? value.toDouble() : 0.0; + +bool readBool(Object? value) => value == true || value == 'true'; + +String readString(Object? value) => + value is String ? value : (value?.toString() ?? ''); + +List readStrings(Object? value) => value is List + ? [ + for (final Object? item in value) + if (item != null) item.toString(), + ] + : const []; + +List readInts(Object? value) => value is List + ? [ + for (final Object? item in value) + if (item is num) item.toInt(), + ] + : const []; + +DateTime? parseTechnitiumDate(Object? value) { + if (value is String && value.isNotEmpty) { + try { + return DateTime.parse(value); + } on FormatException { + return null; + } + } + return null; +} diff --git a/services/service_technitium/lib/src/models/technitium_query_log.dart b/services/service_technitium/lib/src/models/technitium_query_log.dart new file mode 100644 index 00000000..66a59561 --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_query_log.dart @@ -0,0 +1,120 @@ +import 'technitium_json.dart'; + +/// Single DNS query log record from `/api/logs/query`. +class TechnitiumQueryEntry { + const TechnitiumQueryEntry({ + required this.qname, + required this.qtype, + required this.clientIp, + required this.responseType, + required this.rcode, + required this.protocol, + required this.roundTripTimeMs, + required this.answer, + this.timestamp, + this.clientName, + }); + + factory TechnitiumQueryEntry.fromJson(Map json) { + final String qname = readString( + json['qname'] ?? json['question'] ?? json['domain'] ?? json['query'], + ); + final String qtype = readString(json['qtype'] ?? json['type'] ?? 'A'); + final String client = readString( + json['clientIpAddress'] ?? json['clientIp'] ?? json['client'] ?? '', + ); + final String respType = readString( + json['responseType'] ?? json['status'] ?? 'Processed', + ); + final String rcode = readString(json['rcode'] ?? 'NoError'); + final String protocol = readString(json['protocol'] ?? 'UDP'); + final double rtt = readDouble(json['roundTripTime'] ?? json['rtt'] ?? 0); + final String answer = readString(json['answer'] ?? json['answers'] ?? ''); + final DateTime? ts = parseTechnitiumDate(json['timestamp'] ?? json['time']); + final String? cName = json['clientName'] is String && + (json['clientName'] as String).isNotEmpty + ? json['clientName'] as String + : (json['clientDomain'] is String + ? json['clientDomain'] as String + : null); + + return TechnitiumQueryEntry( + qname: qname, + qtype: qtype, + clientIp: client, + responseType: respType, + rcode: rcode, + protocol: protocol, + roundTripTimeMs: rtt, + answer: answer, + timestamp: ts, + clientName: cName, + ); + } + + final String qname; + final String qtype; + final String clientIp; + final String responseType; + final String rcode; + final String protocol; + final double roundTripTimeMs; + final String answer; + final DateTime? timestamp; + final String? clientName; + + bool get isBlocked => + responseType.toLowerCase().contains('block') || + responseType.toLowerCase().contains('drop'); +} + +/// Paginated query log page. +class TechnitiumQueryLogPage { + const TechnitiumQueryLogPage({ + required this.entries, + this.pageNumber = 1, + this.totalPages = 1, + this.totalEntries = 0, + }); + + factory TechnitiumQueryLogPage.fromJson(Map json) { + final Map response = + json['response'] is Map + ? json['response'] as Map + : json; + + final Object? rawEntries = + response['entries'] ?? response['logs'] ?? response['queries']; + final List list = []; + + if (rawEntries is List) { + for (final Object? item in rawEntries) { + if (item is Map) { + list.add(TechnitiumQueryEntry.fromJson(item)); + } else if (item is Map) { + list.add(TechnitiumQueryEntry.fromJson(item.cast())); + } + } + } else if (json['response'] is List) { + for (final Object? item in json['response'] as List) { + if (item is Map) { + list.add(TechnitiumQueryEntry.fromJson(item)); + } else if (item is Map) { + list.add(TechnitiumQueryEntry.fromJson(item.cast())); + } + } + } + + return TechnitiumQueryLogPage( + entries: list, + pageNumber: readInt(response['pageNumber'] ?? 1), + totalPages: readInt(response['totalPages'] ?? 1), + totalEntries: readInt(response['totalEntries'] ?? list.length), + ); + } + + final List entries; + final int pageNumber; + final int totalPages; + final int totalEntries; +} diff --git a/services/service_technitium/lib/src/models/technitium_settings.dart b/services/service_technitium/lib/src/models/technitium_settings.dart new file mode 100644 index 00000000..194bbbc4 --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_settings.dart @@ -0,0 +1,60 @@ +import 'technitium_json.dart'; + +/// Server settings from `/api/settings/get`. +class TechnitiumSettings { + const TechnitiumSettings({ + this.enableBlocking = true, + this.blockingType = 'NxDomain', + this.blockListUpdateIntervalHours = 24, + this.blockLists = const [], + this.dnsServerDomain = '', + this.temporaryDisableBlockingTill, + this.allowTxtBlockingReport = false, + }); + + factory TechnitiumSettings.fromJson(Map json) { + final Map response = + json['response'] is Map + ? json['response'] as Map + : json; + + final Object? rawBlockLists = + response['blockLists'] ?? response['blockListUrls']; + final List urls = []; + if (rawBlockLists is List) { + for (final Object? item in rawBlockLists) { + if (item is String) { + urls.add(item); + } else if (item is Map && item['url'] is String) { + urls.add(item['url'] as String); + } + } + } + + return TechnitiumSettings( + enableBlocking: response.containsKey('enableBlocking') + ? readBool(response['enableBlocking']) + : true, + blockingType: readString(response['blockingType'] ?? 'NxDomain'), + blockListUpdateIntervalHours: readInt( + response['blockListUpdateIntervalHours'] ?? 24, + ), + blockLists: urls, + dnsServerDomain: readString( + response['dnsServerDomain'] ?? response['serverDomain'] ?? '', + ), + temporaryDisableBlockingTill: parseTechnitiumDate( + response['temporaryDisableBlockingTill'], + ), + allowTxtBlockingReport: readBool(response['allowTxtBlockingReport']), + ); + } + + final bool enableBlocking; + final String blockingType; + final int blockListUpdateIntervalHours; + final List blockLists; + final String dnsServerDomain; + final DateTime? temporaryDisableBlockingTill; + final bool allowTxtBlockingReport; +} diff --git a/services/service_technitium/lib/src/models/technitium_stats.dart b/services/service_technitium/lib/src/models/technitium_stats.dart new file mode 100644 index 00000000..172ae2e1 --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_stats.dart @@ -0,0 +1,170 @@ +import 'technitium_json.dart'; + +/// An entry in a top-N list (top clients, top domains, top blocked). +class TechnitiumTopItem { + const TechnitiumTopItem({ + required this.name, + required this.hits, + this.domain, + }); + + factory TechnitiumTopItem.fromJson(Map json) { + return TechnitiumTopItem( + name: readString(json['name'] ?? json['client'] ?? json['domain']), + hits: readInt(json['hits'] ?? json['count'] ?? json['queries']), + domain: json['domain'] is String ? json['domain'] as String : null, + ); + } + + final String name; + final int hits; + final String? domain; +} + +/// Statistics returned by `/api/dashboard/stats/get`. +class TechnitiumStats { + const TechnitiumStats({ + this.totalQueries = 0, + this.blockedQueries = 0, + this.cachedQueries = 0, + this.clientsCount = 0, + this.forwardedQueries = 0, + this.authoritativeQueries = 0, + this.recursiveQueries = 0, + this.queriesSeries = const [], + this.blockedSeries = const [], + this.cachedSeries = const [], + this.chartLabels = const [], + this.topClients = const [], + this.topDomains = const [], + this.topBlockedDomains = const [], + }); + + factory TechnitiumStats.fromJson(Map json) { + final Map response = + json['response'] is Map + ? json['response'] as Map + : json; + + final Map stats = response['stats'] is Map + ? response['stats'] as Map + : response; + + final Map chartData = + response['mainChartData'] is Map + ? response['mainChartData'] as Map + : (response['chartData'] is Map + ? response['chartData'] as Map + : {}); + + final List clients = + parseTopList(response['topClients']); + final List domains = + parseTopList(response['topDomains']); + final List blocked = parseTopList( + response['topBlockedDomains'] ?? response['topBlocked'], + ); + + final int totalQ = readInt(stats['totalQueries'] ?? stats['queries']); + final int blockedQ = readInt( + stats['totalBlocked'] ?? stats['blockedQueries'] ?? stats['blocked'], + ); + final int cachedQ = readInt( + stats['totalCached'] ?? stats['cachedQueries'] ?? stats['cached'], + ); + final int clientsC = readInt( + stats['totalClients'] ?? stats['clientsCount'] ?? clients.length, + ); + + final List directQueries = readInts( + chartData['totalQueries'] ?? chartData['queries'], + ); + final List directBlocked = readInts( + chartData['blockedQueries'] ?? chartData['blocked'], + ); + final List directCached = readInts( + chartData['cachedQueries'] ?? chartData['cached'], + ); + + List seriesQueries = directQueries; + List seriesBlocked = directBlocked; + List seriesCached = directCached; + + final Object? rawDatasets = chartData['datasets']; + if (rawDatasets is List) { + for (final Object? ds in rawDatasets) { + if (ds is! Map) continue; + final String label = + readString(ds['label'] ?? ds['name']).toLowerCase(); + final List values = readInts(ds['data']); + if (values.isEmpty) continue; + if (label.contains('block') && seriesBlocked.isEmpty) { + seriesBlocked = values; + } else if (label.contains('cach') && seriesCached.isEmpty) { + seriesCached = values; + } else if ((label == 'total' || label.contains('quer')) && + seriesQueries.isEmpty) { + seriesQueries = values; + } + } + } + + return TechnitiumStats( + totalQueries: totalQ, + blockedQueries: blockedQ, + cachedQueries: cachedQ, + clientsCount: clientsC, + forwardedQueries: + readInt(stats['forwardedQueries'] ?? stats['forwarded']), + authoritativeQueries: readInt( + stats['totalAuthoritative'] ?? + stats['authoritativeQueries'] ?? + stats['authoritative'], + ), + recursiveQueries: readInt( + stats['totalRecursive'] ?? + stats['recursiveQueries'] ?? + stats['recursive'], + ), + queriesSeries: seriesQueries, + blockedSeries: seriesBlocked, + cachedSeries: seriesCached, + chartLabels: readStrings(chartData['labels']), + topClients: clients, + topDomains: domains, + topBlockedDomains: blocked, + ); + } + + final int totalQueries; + final int blockedQueries; + final int cachedQueries; + final int clientsCount; + final int forwardedQueries; + final int authoritativeQueries; + final int recursiveQueries; + final List queriesSeries; + final List blockedSeries; + final List cachedSeries; + final List chartLabels; + final List topClients; + final List topDomains; + final List topBlockedDomains; + + double get blockedPercent => + totalQueries == 0 ? 0.0 : (blockedQueries / totalQueries * 100); + + double get cachedPercent => + totalQueries == 0 ? 0.0 : (cachedQueries / totalQueries * 100); + + static List parseTopList(Object? list) { + if (list is! List) return const []; + return [ + for (final Object? item in list) + if (item is Map) + TechnitiumTopItem.fromJson(item) + else if (item is Map) + TechnitiumTopItem.fromJson(item.cast()), + ]; + } +} diff --git a/services/service_technitium/lib/src/models/technitium_status.dart b/services/service_technitium/lib/src/models/technitium_status.dart new file mode 100644 index 00000000..5a089a31 --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_status.dart @@ -0,0 +1,80 @@ +import 'technitium_json.dart'; + +/// Whether Technitium DNS blocking is filtering right now. +enum TechnitiumProtection { + on, + + /// Temporarily disabled for a duration, auto-resuming. + paused, + + /// Disabled until explicitly enabled. + off, +} + +/// What `/api/status` or status polling reports about the server. +class TechnitiumStatus { + const TechnitiumStatus({ + required this.version, + required this.isBlockingEnabled, + required this.readAt, + this.pausedUntil, + this.dnsServerDomain = '', + this.uptimeSeconds = 0, + this.serverIp = '', + }); + + factory TechnitiumStatus.fromJson( + Map json, { + required DateTime readAt, + bool isBlockingEnabled = true, + DateTime? pausedUntil, + }) { + final Map response = + json['response'] is Map + ? json['response'] as Map + : json; + + final Object? rawPaused = response['temporaryDisableBlockingTill']; + final DateTime? parsedPaused = + rawPaused != null ? parseTechnitiumDate(rawPaused) : pausedUntil; + + final bool blocking = response.containsKey('enableBlocking') + ? readBool(response['enableBlocking']) + : isBlockingEnabled; + + return TechnitiumStatus( + version: readString(response['version']), + dnsServerDomain: + readString(response['dnsServerDomain'] ?? response['serverDomain']), + isBlockingEnabled: blocking, + pausedUntil: parsedPaused, + readAt: readAt, + uptimeSeconds: readInt(response['uptime']), + serverIp: readString(response['serverIp'] ?? response['ip']), + ); + } + + final String version; + final String dnsServerDomain; + final bool isBlockingEnabled; + final DateTime? pausedUntil; + final DateTime readAt; + final int uptimeSeconds; + final String serverIp; + + TechnitiumProtection get protection { + if (pausedUntil != null && pausedUntil!.isAfter(readAt)) { + return TechnitiumProtection.paused; + } + if (!isBlockingEnabled) return TechnitiumProtection.off; + return TechnitiumProtection.on; + } + + Duration get pauseLeft { + if (protection == TechnitiumProtection.paused && pausedUntil != null) { + final Duration diff = pausedUntil!.difference(readAt); + return diff > Duration.zero ? diff : Duration.zero; + } + return Duration.zero; + } +} diff --git a/services/service_technitium/lib/src/models/technitium_top_stats.dart b/services/service_technitium/lib/src/models/technitium_top_stats.dart new file mode 100644 index 00000000..8d3a2ffa --- /dev/null +++ b/services/service_technitium/lib/src/models/technitium_top_stats.dart @@ -0,0 +1,30 @@ +import 'technitium_stats.dart'; + +/// Top statistics (top clients, top domains, and top blocked domains) +/// returned by `/api/dashboard/stats/get` or `/api/dashboard/stats`. +class TechnitiumTopStats { + const TechnitiumTopStats({ + this.topClients = const [], + this.topDomains = const [], + this.topBlockedDomains = const [], + }); + + factory TechnitiumTopStats.fromJson(Map json) { + final Map response = + json['response'] is Map + ? json['response'] as Map + : json; + + return TechnitiumTopStats( + topClients: TechnitiumStats.parseTopList(response['topClients']), + topDomains: TechnitiumStats.parseTopList(response['topDomains']), + topBlockedDomains: TechnitiumStats.parseTopList( + response['topBlockedDomains'] ?? response['topBlocked'], + ), + ); + } + + final List topClients; + final List topDomains; + final List topBlockedDomains; +} diff --git a/services/service_technitium/lib/src/tabs/technitium_blocked_zones_tab.dart b/services/service_technitium/lib/src/tabs/technitium_blocked_zones_tab.dart new file mode 100644 index 00000000..024e8707 --- /dev/null +++ b/services/service_technitium/lib/src/tabs/technitium_blocked_zones_tab.dart @@ -0,0 +1,308 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/technitium_blocked_zone.dart'; +import '../technitium_providers.dart'; + +/// Blocked zones management: listing, adding, removing, and triggering updates. +class TechnitiumBlockedZonesTab extends ConsumerStatefulWidget { + const TechnitiumBlockedZonesTab({ + required this.instance, + super.key, + }); + + final Instance instance; + + @override + ConsumerState createState() => + _TechnitiumBlockedZonesTabState(); +} + +class _TechnitiumBlockedZonesTabState + extends ConsumerState { + final TextEditingController _searchController = TextEditingController(); + bool _updating = false; + + Instance get _instance => widget.instance; + TechnitiumActions get _actions => + ref.read(technitiumActionsProvider(_instance)); + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + Future _addZone() async { + final TextEditingController controller = TextEditingController(); + final String? domain = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('Add Blocked Zone'), + content: TextField( + controller: controller, + autofocus: true, + decoration: const InputDecoration( + labelText: 'Domain name', + hintText: 'e.g. ads.example.com', + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () { + final String val = controller.text.trim(); + if (val.isNotEmpty) { + Navigator.of(ctx).pop(val); + } + }, + child: const Text('Add'), + ), + ], + ), + ); + + if (domain == null || domain.isEmpty) return; + try { + await _actions.addBlockedZone(domain); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Added $domain to Blocked Zones')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to add zone: $e')), + ); + } + } + } + + Future _deleteZone(String domain) async { + final bool? confirm = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('Delete Blocked Zone'), + content: Text('Remove $domain from blocked zones?'), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(ctx).colorScheme.error, + ), + onPressed: () => Navigator.of(ctx).pop(true), + child: const Text('Delete'), + ), + ], + ), + ); + + if (confirm != true) return; + try { + await _actions.deleteBlockedZone(domain); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Removed $domain')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to delete zone: $e')), + ); + } + } + } + + Future _forceUpdateBlockLists() async { + if (_updating) return; + setState(() => _updating = true); + try { + await _actions.forceUpdateBlockLists(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Block lists update triggered')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to update block lists: $e')), + ); + } + } finally { + if (mounted) setState(() => _updating = false); + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final AsyncValue> zonesAsync = + ref.watch(technitiumBlockedZonesProvider(_instance)); + + return Scaffold( + body: Column( + children: [ + // Header action strip + Padding( + padding: const EdgeInsets.all(Insets.md), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Filter blocked zones...', + prefixIcon: const Icon(Icons.search, size: 20), + suffixIcon: _searchController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () => + setState(_searchController.clear), + ) + : null, + filled: true, + fillColor: cs.surfaceContainerHigh, + contentPadding: + const EdgeInsets.symmetric(horizontal: Insets.md), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + ), + onChanged: (_) => setState(() {}), + ), + ), + const SizedBox(width: Insets.sm), + IconButton.filledTonal( + tooltip: 'Force update block lists', + onPressed: _updating ? null : _forceUpdateBlockLists, + icon: _updating + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync_rounded), + ), + ], + ), + ), + const Divider(height: 1), + + // Zone list + Expanded( + child: RefreshIndicator( + onRefresh: _actions.refreshBlockedZones, + child: zonesAsync.when( + data: (List zones) { + final String query = + _searchController.text.trim().toLowerCase(); + final List filtered = query.isEmpty + ? zones + : zones + .where( + (TechnitiumBlockedZone z) => + z.domain.toLowerCase().contains(query), + ) + .toList(); + + if (filtered.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.check_circle_outline, + size: 48, + color: cs.onSurfaceVariant, + ), + const SizedBox(height: Insets.sm), + Text( + query.isEmpty + ? 'No custom blocked zones' + : 'No matching zones', + style: theme.textTheme.bodyMedium?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ], + ), + ); + } + + return ListView.separated( + itemCount: filtered.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (BuildContext ctx, int index) { + final TechnitiumBlockedZone zone = filtered[index]; + return ListTile( + leading: CircleAvatar( + backgroundColor: cs.errorContainer, + child: Icon(Icons.block, size: 20, color: cs.error), + ), + title: Text( + zone.domain, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + trailing: IconButton( + icon: Icon(Icons.delete_outline, color: cs.error), + tooltip: 'Delete zone', + onPressed: () => _deleteZone(zone.domain), + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (Object e, _) => ListView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.all(Insets.lg), + children: [ + const SizedBox(height: Insets.xl), + Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'Failed to load blocked zones: $e', + textAlign: TextAlign.center, + ), + const SizedBox(height: Insets.md), + OutlinedButton.icon( + onPressed: () => ref.invalidate( + technitiumBlockedZonesProvider(_instance), + ), + icon: const Icon(Icons.refresh), + label: const Text('Retry'), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ], + ), + floatingActionButton: FloatingActionButton.extended( + heroTag: 'technitium-add-blocked-zone', + onPressed: _addZone, + icon: const Icon(Icons.add), + label: const Text('Add zone'), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/tabs/technitium_overview_tab.dart b/services/service_technitium/lib/src/tabs/technitium_overview_tab.dart new file mode 100644 index 00000000..59980d9c --- /dev/null +++ b/services/service_technitium/lib/src/tabs/technitium_overview_tab.dart @@ -0,0 +1,304 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/technitium_stats.dart'; +import '../models/technitium_status.dart'; +import '../technitium_format.dart'; +import '../technitium_providers.dart'; +import '../widgets/technitium_protection_card.dart'; +import '../widgets/technitium_series_chart.dart'; +import '../widgets/technitium_stat_tile.dart'; +import '../widgets/technitium_top_list.dart'; + +/// Overview tab displaying server protection, metrics, charts, and top lists. +class TechnitiumOverviewTab extends ConsumerStatefulWidget { + const TechnitiumOverviewTab({ + required this.instance, + this.now = DateTime.now, + super.key, + }); + + final Instance instance; + final DateTime Function() now; + + @override + ConsumerState createState() => + _TechnitiumOverviewTabState(); +} + +class _TechnitiumOverviewTabState extends ConsumerState { + bool _busy = false; + + Instance get _instance => widget.instance; + TechnitiumActions get _actions => + ref.read(technitiumActionsProvider(_instance)); + + Future _setProtection({required bool enabled, Duration? pause}) async { + if (_busy) return; + setState(() => _busy = true); + try { + await _actions.setProtection(enabled: enabled, pause: pause); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to update protection: $e')), + ); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + + final AsyncValue statusAsync = + ref.watch(technitiumStatusProvider(_instance)); + final AsyncValue statsAsync = + ref.watch(technitiumStatsProvider(_instance)); + final String activePeriod = + ref.watch(technitiumStatsPeriodProvider(_instance)); + + return RefreshIndicator( + onRefresh: _actions.refreshOverview, + child: ListView( + padding: const EdgeInsets.all(Insets.md), + children: [ + // 1. Protection Card + statusAsync.when( + data: (TechnitiumStatus status) => TechnitiumProtectionCard( + status: status, + busy: _busy, + onSet: _setProtection, + onPauseEnded: () => + ref.invalidate(technitiumStatusProvider(_instance)), + now: widget.now, + ), + loading: () => const Center( + child: Padding( + padding: EdgeInsets.all(Insets.lg), + child: CircularProgressIndicator(), + ), + ), + error: (Object e, _) => Material( + color: cs.errorContainer, + borderRadius: BorderRadius.circular(16), + child: Padding( + padding: const EdgeInsets.all(Insets.md), + child: Row( + children: [ + Icon(Icons.error_outline, color: cs.onErrorContainer), + const SizedBox(width: Insets.sm), + Expanded( + child: Text( + 'Failed to load status: $e', + style: TextStyle(color: cs.onErrorContainer), + ), + ), + IconButton( + icon: const Icon(Icons.refresh), + onPressed: () => + ref.invalidate(technitiumStatusProvider(_instance)), + ), + ], + ), + ), + ), + ), + const SizedBox(height: Insets.md), + + // 2. Time Range Selector + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Statistics', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + DropdownButton( + value: activePeriod, + underline: const SizedBox.shrink(), + items: const >[ + DropdownMenuItem( + value: 'LastHour', + child: Text('Last Hour'), + ), + DropdownMenuItem( + value: 'LastDay', + child: Text('Last 24 Hours'), + ), + DropdownMenuItem( + value: 'LastWeek', + child: Text('Last 7 Days'), + ), + DropdownMenuItem( + value: 'LastMonth', + child: Text('Last 30 Days'), + ), + ], + onChanged: (String? val) { + if (val != null) { + ref + .read(technitiumStatsPeriodProvider(_instance).notifier) + .state = val; + } + }, + ), + ], + ), + const SizedBox(height: Insets.xs), + + // 3. Stats Row + statsAsync.when( + data: (TechnitiumStats stats) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: TechnitiumStatTile( + label: 'Total Queries', + value: formatTechnitiumCompact(stats.totalQueries), + color: cs.primary, + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: TechnitiumStatTile( + label: 'Blocked', + value: formatTechnitiumCompact(stats.blockedQueries), + subValue: formatTechnitiumPercent(stats.blockedPercent), + color: cs.error, + ), + ), + ], + ), + const SizedBox(height: Insets.sm), + Row( + children: [ + Expanded( + child: TechnitiumStatTile( + label: 'Cached', + value: formatTechnitiumCompact(stats.cachedQueries), + subValue: formatTechnitiumPercent(stats.cachedPercent), + color: cs.tertiary, + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: TechnitiumStatTile( + label: 'Clients', + value: '${stats.clientsCount}', + color: cs.secondary, + ), + ), + ], + ), + const SizedBox(height: Insets.md), + + // 4. Query Rate Chart + if (stats.queriesSeries.length > 1) ...[ + Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(Insets.md), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Query Rate Over Time', + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Row( + children: [ + _legendDot(cs.primary, 'Total'), + const SizedBox(width: Insets.sm), + _legendDot(cs.error, 'Blocked'), + ], + ), + ], + ), + const SizedBox(height: Insets.md), + SizedBox( + height: 120, + child: TechnitiumSeriesChart( + series: stats.queriesSeries, + color: cs.primary, + over: stats.blockedSeries, + overColor: cs.error, + ), + ), + ], + ), + ), + ), + const SizedBox(height: Insets.md), + ], + + // 5. Top Lists + TechnitiumTopListCard( + title: 'Top Clients', + items: stats.topClients, + icon: Icons.devices_outlined, + accent: cs.secondary, + ), + const SizedBox(height: Insets.md), + TechnitiumTopListCard( + title: 'Top Domains', + items: stats.topDomains, + icon: Icons.language_outlined, + accent: cs.primary, + ), + const SizedBox(height: Insets.md), + TechnitiumTopListCard( + title: 'Top Blocked Domains', + items: stats.topBlockedDomains, + icon: Icons.block_outlined, + accent: cs.error, + ), + ], + ), + loading: () => const Center( + child: Padding( + padding: EdgeInsets.all(Insets.lg), + child: CircularProgressIndicator(), + ), + ), + error: (Object e, _) => Text('Error loading stats: $e'), + ), + ], + ), + ); + } + + Widget _legendDot(Color color, String label) { + return Row( + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 4), + Text( + label, + style: Theme.of(context).textTheme.labelSmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ); + } +} diff --git a/services/service_technitium/lib/src/tabs/technitium_query_log_tab.dart b/services/service_technitium/lib/src/tabs/technitium_query_log_tab.dart new file mode 100644 index 00000000..1a3a913a --- /dev/null +++ b/services/service_technitium/lib/src/tabs/technitium_query_log_tab.dart @@ -0,0 +1,288 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/technitium_query_log.dart'; +import '../technitium_providers.dart'; +import '../widgets/technitium_query_detail_modal.dart'; +import '../widgets/technitium_query_log_row.dart'; + +/// Paginated query log viewer with filters and one-tap blocking. +class TechnitiumQueryLogTab extends ConsumerStatefulWidget { + const TechnitiumQueryLogTab({ + required this.instance, + super.key, + }); + + final Instance instance; + + @override + ConsumerState createState() => + _TechnitiumQueryLogTabState(); +} + +class _TechnitiumQueryLogTabState extends ConsumerState { + late final TextEditingController _searchController; + + Instance get _instance => widget.instance; + TechnitiumActions get _actions => + ref.read(technitiumActionsProvider(_instance)); + + @override + void initState() { + super.initState(); + _searchController = TextEditingController( + text: ref.read(technitiumQueryLogSearchProvider(_instance)), + ); + } + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + Future _blockDomain(String domain) async { + try { + await _actions.addBlockedZone(domain); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Added $domain to Blocked Zones')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to block domain: $e')), + ); + } + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + + final String selectedFilter = + ref.watch(technitiumQueryLogFilterProvider(_instance)); + final int currentPage = + ref.watch(technitiumQueryLogPageProvider(_instance)); + final AsyncValue logPageAsync = + ref.watch(technitiumQueryLogProvider(_instance)); + + final List filterOptions = [ + 'All', + 'Blocked', + 'Cached', + 'Recursive', + 'Authoritative', + ]; + + return Column( + children: [ + // Search & Filter header + Padding( + padding: const EdgeInsets.fromLTRB( + Insets.md, + Insets.md, + Insets.md, + Insets.xs, + ), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search domain or client...', + prefixIcon: const Icon(Icons.search, size: 20), + suffixIcon: _searchController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () { + _searchController.clear(); + ref + .read( + technitiumQueryLogSearchProvider(_instance) + .notifier, + ) + .state = ''; + ref + .read( + technitiumQueryLogPageProvider(_instance) + .notifier, + ) + .state = 1; + }, + ) + : null, + filled: true, + fillColor: cs.surfaceContainerHigh, + contentPadding: const EdgeInsets.symmetric(horizontal: Insets.md), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + ), + onSubmitted: (String val) { + ref + .read(technitiumQueryLogSearchProvider(_instance).notifier) + .state = val.trim(); + ref + .read(technitiumQueryLogPageProvider(_instance).notifier) + .state = 1; + }, + ), + ), + + // Filter chips + SingleChildScrollView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.xs, + ), + child: Row( + children: [ + for (final String option in filterOptions) ...[ + Padding( + padding: const EdgeInsets.only(right: Insets.xs), + child: FilterChip( + label: Text(option), + selected: + selectedFilter.toLowerCase() == option.toLowerCase(), + onSelected: (bool selected) { + ref + .read( + technitiumQueryLogFilterProvider(_instance) + .notifier, + ) + .state = selected ? option : 'All'; + ref + .read( + technitiumQueryLogPageProvider(_instance).notifier, + ) + .state = 1; + }, + ), + ), + ], + ], + ), + ), + + const Divider(height: 1), + + // Query log list + Expanded( + child: RefreshIndicator( + onRefresh: _actions.refreshQueryLog, + child: logPageAsync.when( + data: (TechnitiumQueryLogPage page) { + if (page.entries.isEmpty) { + return ListView( + physics: const AlwaysScrollableScrollPhysics(), + children: [ + const SizedBox(height: Insets.xl * 2), + Center( + child: Text( + 'No queries found', + style: theme.textTheme.bodyMedium?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ), + ], + ); + } + return ListView.separated( + itemCount: page.entries.length, + separatorBuilder: (_, __) => const Divider(height: 1), + itemBuilder: (BuildContext ctx, int index) { + final TechnitiumQueryEntry entry = page.entries[index]; + return TechnitiumQueryLogRow( + entry: entry, + onTap: () => TechnitiumQueryDetailModal.show( + context, + entry: entry, + onBlockDomain: _blockDomain, + ), + ); + }, + ); + }, + loading: () => const Center(child: CircularProgressIndicator()), + error: (Object e, _) => Center( + child: Padding( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.error_outline, size: 36, color: cs.error), + const SizedBox(height: Insets.sm), + Text('Error loading logs: $e'), + const SizedBox(height: Insets.md), + FilledButton( + onPressed: () => ref + .invalidate(technitiumQueryLogProvider(_instance)), + child: const Text('Retry'), + ), + ], + ), + ), + ), + ), + ), + ), + + // Pagination row + logPageAsync.maybeWhen( + data: (TechnitiumQueryLogPage page) => Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.xs, + ), + color: cs.surfaceContainerHigh, + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Page $currentPage of ${page.totalPages.clamp(1, 9999)} (${page.totalEntries} queries)', + style: theme.textTheme.labelMedium?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + Row( + children: [ + IconButton( + icon: const Icon(Icons.chevron_left), + onPressed: currentPage > 1 + ? () => ref + .read( + technitiumQueryLogPageProvider(_instance) + .notifier, + ) + .state-- + : null, + ), + IconButton( + icon: const Icon(Icons.chevron_right), + onPressed: currentPage < page.totalPages + ? () => ref + .read( + technitiumQueryLogPageProvider(_instance) + .notifier, + ) + .state++ + : null, + ), + ], + ), + ], + ), + ), + orElse: () => const SizedBox.shrink(), + ), + ], + ); + } +} diff --git a/services/service_technitium/lib/src/tabs/technitium_settings_tab.dart b/services/service_technitium/lib/src/tabs/technitium_settings_tab.dart new file mode 100644 index 00000000..b459cc96 --- /dev/null +++ b/services/service_technitium/lib/src/tabs/technitium_settings_tab.dart @@ -0,0 +1,326 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../models/technitium_settings.dart'; +import '../models/technitium_status.dart'; +import '../technitium_providers.dart'; + +/// Settings and DNS cache operations tab. +class TechnitiumSettingsTab extends ConsumerStatefulWidget { + const TechnitiumSettingsTab({ + required this.instance, + super.key, + }); + + final Instance instance; + + @override + ConsumerState createState() => + _TechnitiumSettingsTabState(); +} + +class _TechnitiumSettingsTabState extends ConsumerState { + bool _flushing = false; + bool _updatingLists = false; + + Instance get _instance => widget.instance; + TechnitiumActions get _actions => + ref.read(technitiumActionsProvider(_instance)); + + Future _flushCache() async { + if (_flushing) return; + final bool? confirmed = await showDialog( + context: context, + builder: (BuildContext ctx) => AlertDialog( + title: const Text('Flush DNS cache?'), + content: const Text( + 'This will clear all cached DNS records from the server.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of(ctx).pop(true), + child: const Text('Flush'), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + setState(() => _flushing = true); + try { + await _actions.flushDnsCache(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('DNS cache flushed successfully')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to flush cache: $e')), + ); + } + } finally { + if (mounted) setState(() => _flushing = false); + } + } + + Future _toggleBlocking(bool enable) async { + try { + await _actions.setProtection(enabled: enable); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(enable ? 'Blocking enabled' : 'Blocking disabled'), + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to set blocking: $e')), + ); + } + } + } + + Future _forceUpdateBlockLists() async { + if (_updatingLists) return; + setState(() => _updatingLists = true); + try { + await _actions.forceUpdateBlockLists(); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Block lists update triggered')), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to update block lists: $e')), + ); + } + } finally { + if (mounted) setState(() => _updatingLists = false); + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + + final AsyncValue settingsAsync = + ref.watch(technitiumSettingsProvider(_instance)); + final AsyncValue statusAsync = + ref.watch(technitiumStatusProvider(_instance)); + + return RefreshIndicator( + onRefresh: _actions.refreshSettings, + child: ListView( + padding: const EdgeInsets.all(Insets.md), + children: [ + // 1. DNS Cache Section + Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.cached_rounded, color: cs.primary), + const SizedBox(width: Insets.sm), + Text( + 'DNS Cache', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: Insets.xs), + Text( + 'Clear cached DNS records immediately from the resolver.', + style: theme.textTheme.bodySmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + const SizedBox(height: Insets.md), + SizedBox( + width: double.infinity, + child: FilledButton.tonalIcon( + onPressed: _flushing ? null : _flushCache, + icon: _flushing + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.delete_sweep_rounded), + label: const Text('Flush DNS cache'), + ), + ), + ], + ), + ), + ), + const SizedBox(height: Insets.md), + + // 2. Blocking Configuration Section + settingsAsync.when( + data: (TechnitiumSettings settings) => Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.shield_outlined, color: cs.primary), + const SizedBox(width: Insets.sm), + Text( + 'Blocking Configuration', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: Insets.md), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Enable Blocking'), + subtitle: const Text( + 'Block network-wide ads and tracking domains', + ), + value: settings.enableBlocking, + onChanged: _toggleBlocking, + ), + const Divider(), + _infoRow(theme, 'Blocking Type', settings.blockingType), + _infoRow( + theme, + 'Update Interval', + '${settings.blockListUpdateIntervalHours} hours', + ), + _infoRow( + theme, + 'Configured Block Lists', + '${settings.blockLists.length} lists', + ), + const SizedBox(height: Insets.md), + SizedBox( + width: double.infinity, + child: OutlinedButton.icon( + onPressed: + _updatingLists ? null : _forceUpdateBlockLists, + icon: _updatingLists + ? const SizedBox( + width: 18, + height: 18, + child: + CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.sync), + label: const Text('Force update block lists'), + ), + ), + ], + ), + ), + ), + loading: () => const Center( + child: Padding( + padding: EdgeInsets.all(Insets.lg), + child: CircularProgressIndicator(), + ), + ), + error: (Object e, _) => Text('Error loading settings: $e'), + ), + const SizedBox(height: Insets.md), + + // 3. Server Metrics & Info + statusAsync.when( + data: (TechnitiumStatus status) => Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.info_outline, color: cs.primary), + const SizedBox(width: Insets.sm), + Text( + 'Server Info', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: Insets.md), + if (status.version.isNotEmpty) + _infoRow(theme, 'Version', status.version), + if (status.dnsServerDomain.isNotEmpty) + _infoRow(theme, 'Server Domain', status.dnsServerDomain), + if (status.serverIp.isNotEmpty) + _infoRow(theme, 'Server IP', status.serverIp), + if (status.uptimeSeconds > 0) + _infoRow( + theme, + 'Uptime', + '${status.uptimeSeconds ~/ 3600} hours ${(status.uptimeSeconds % 3600) ~/ 60} mins', + ), + ], + ), + ), + ), + loading: () => const SizedBox.shrink(), + error: (_, __) => const SizedBox.shrink(), + ), + ], + ), + ); + } + + Widget _infoRow(ThemeData theme, String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: Insets.xs), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(width: Insets.md), + Flexible( + child: Text( + value, + textAlign: TextAlign.end, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ); + } +} diff --git a/services/service_technitium/lib/src/technitium_api.dart b/services/service_technitium/lib/src/technitium_api.dart new file mode 100644 index 00000000..bfdf6251 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_api.dart @@ -0,0 +1,417 @@ +import 'dart:convert'; + +import 'package:dio/dio.dart'; + +import 'models/technitium_blocked_zone.dart'; +import 'models/technitium_query_log.dart'; +import 'models/technitium_settings.dart'; +import 'models/technitium_stats.dart'; +import 'models/technitium_status.dart'; +import 'models/technitium_top_stats.dart'; +import 'technitium_errors.dart'; +import 'technitium_session.dart'; + +/// HTTP API client for Technitium DNS Server. +class TechnitiumApi { + TechnitiumApi(this._dio, [TechnitiumSession? session]) + : _session = session ?? TechnitiumSession(); + + final Dio _dio; + final TechnitiumSession _session; + String? _queryLoggerName; + String? _queryLoggerClassPath; + + TechnitiumSession get session => _session; + + /// Validates and extracts JSON map from a response. + Map _unwrapResponse(Response response) { + Object? data = response.data; + if (data is String) { + try { + data = jsonDecode(data); + } on FormatException { + throw const TechnitiumUnexpectedAnswer('Response is not valid JSON'); + } + } + if (data is! Map) { + throw const TechnitiumUnexpectedAnswer( + 'Response body is not a JSON object', + ); + } + final Map map = + data is Map ? data : data.cast(); + + final Object? status = map['status']; + if (status == 'invalid-token' || status == '2fa-required') { + _session.recordAuthRefusal(); + final String msg = (map['errorMessage'] ?? + (status == '2fa-required' + ? 'Two-factor authentication required' + : 'Invalid or expired API token')) + .toString(); + throw TechnitiumAuthException(msg); + } + if (status == 'error') { + final String msg = + (map['errorMessage'] ?? map['message'] ?? 'Technitium API error') + .toString(); + final String lower = msg.toLowerCase(); + if (lower.contains('token') || + lower.contains('auth') || + lower.contains('unauthorized') || + lower.contains('forbidden') || + lower.contains('invalid session')) { + _session.recordAuthRefusal(); + throw TechnitiumAuthException(msg); + } + throw TechnitiumRequestException(msg); + } + if (status != 'ok' && status != 'success') { + throw const TechnitiumUnexpectedAnswer('Response status was not ok'); + } + _session.resetAuthRefusal(); + return map; + } + + Future> _get( + String path, { + Map? query, + }) async { + try { + final Response resp = await _dio.get( + path, + queryParameters: query, + options: Options(validateStatus: (int? s) => s != null && s < 500), + ); + if (resp.statusCode == 401 || resp.statusCode == 403) { + _session.recordAuthRefusal(); + throw const TechnitiumAuthException(); + } + if (resp.statusCode == 404) { + throw const TechnitiumUnexpectedAnswer('Endpoint not found (404)'); + } + if (resp.statusCode != null && resp.statusCode! >= 400) { + throw TechnitiumRequestException('HTTP ${resp.statusCode}'); + } + return _unwrapResponse(resp); + } on DioException catch (e) { + if (e.response?.statusCode == 401 || e.response?.statusCode == 403) { + _session.recordAuthRefusal(); + throw const TechnitiumAuthException(); + } + rethrow; + } + } + + /// Checks server status and health via `/api/status`. + Future getStatus() async { + final DateTime readAt = DateTime.now(); + final Map json = await _get('api/status'); + // Also try to inspect settings if available, else return status from response + return TechnitiumStatus.fromJson(json, readAt: readAt); + } + + /// Retrieves dashboard stats for the given range ([type]: `LastHour`, `LastDay`, `LastWeek`, `LastMonth`). + Future getStats({String type = 'LastDay'}) async { + Map json; + try { + json = await _get( + 'api/dashboard/stats/get', + query: {'type': type, 'utc': true}, + ); + } on TechnitiumUnexpectedAnswer { + json = await _get( + 'api/dashboard/stats', + query: {'type': type, 'utc': true}, + ); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + json = await _get( + 'api/dashboard/stats', + query: {'type': type, 'utc': true}, + ); + } else { + rethrow; + } + } + return TechnitiumStats.fromJson(json); + } + + /// Retrieves top statistics (top clients, top domains, and top blocked domains). + Future getTopStats({String type = 'LastDay'}) async { + Map json; + try { + json = await _get( + 'api/dashboard/stats/get', + query: {'type': type, 'utc': true}, + ); + } on TechnitiumUnexpectedAnswer { + json = await _get( + 'api/dashboard/stats', + query: {'type': type, 'utc': true}, + ); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + json = await _get( + 'api/dashboard/stats', + query: {'type': type, 'utc': true}, + ); + } else { + rethrow; + } + } + return TechnitiumTopStats.fromJson(json); + } + + /// Retrieves server configuration and blocking settings via `/api/settings/get`. + Future getSettings() async { + final Map json = await _get('api/settings/get'); + return TechnitiumSettings.fromJson(json); + } + + /// Toggles ad-blocking on or off via `/api/settings/set`. + Future setBlocking({required bool enabled}) async { + await _get( + 'api/settings/set', + query: {'enableBlocking': enabled}, + ); + } + + /// Temporarily pauses blocking for integer [minutes]. + /// + /// Passing `minutes: 0` re-enables blocking immediately. + Future temporaryDisableBlocking({required num minutes}) async { + await _get( + 'api/settings/temporaryDisableBlocking', + query: {'minutes': minutes.toInt()}, + ); + } + + /// Forces an immediate update and download of all configured block lists. + Future forceUpdateBlockLists() async { + try { + await _get('api/settings/forceUpdateBlockLists'); + } on TechnitiumUnexpectedAnswer { + await _get('api/blockLists/forceUpdate'); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + await _get('api/blockLists/forceUpdate'); + } else { + rethrow; + } + } + } + + /// Flushes the DNS resolver cache via `/api/cache/flush`. + Future flushDnsCache() async { + await _get('api/cache/flush'); + } + + /// Lists manually configured blocked zones / domains. + /// + /// Uses `/api/blocked/export` for a flat domain list on Technitium v13+, + /// falling back to `/api/blocked/list` (supporting both object-with-`zones` + /// and flat-array shapes). + Future> listBlockedZones() async { + try { + final Response exportResp = await _dio.get( + 'api/blocked/export', + options: Options( + responseType: ResponseType.plain, + validateStatus: (int? s) => s != null && s < 500, + ), + ); + if (exportResp.statusCode == 401 || exportResp.statusCode == 403) { + _session.recordAuthRefusal(); + throw const TechnitiumAuthException(); + } + if (exportResp.statusCode == 200 && exportResp.data is String) { + final String text = (exportResp.data as String).trim(); + if (text.isEmpty) return const []; + if (text.startsWith('{')) { + final Object? decoded = jsonDecode(text); + if (decoded is Map && + decoded['status'] != null && + decoded['status'] != 'ok') { + _unwrapResponse(exportResp); + } + } else { + _session.resetAuthRefusal(); + return [ + for (final String line in text.split(RegExp(r'\r?\n'))) + if (line.trim().isNotEmpty && !line.trim().startsWith('#')) + TechnitiumBlockedZone(domain: line.trim()), + ]; + } + } + } on DioException catch (e) { + if (e.response?.statusCode == 401 || e.response?.statusCode == 403) { + _session.recordAuthRefusal(); + throw const TechnitiumAuthException(); + } + if (e.response?.statusCode != 404) rethrow; + } + + Map json; + try { + json = await _get('api/blocked/list'); + } on TechnitiumUnexpectedAnswer { + json = await _get('api/blockedZones/list'); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + json = await _get('api/blockedZones/list'); + } else { + rethrow; + } + } + + final Object? raw = + json['response'] ?? json['blockedZones'] ?? json['zones']; + final List result = []; + if (raw is List) { + for (final Object? item in raw) { + if (item is String) { + result.add(TechnitiumBlockedZone(domain: item)); + } else if (item is Map) { + result.add(TechnitiumBlockedZone.fromJson(item)); + } else if (item is Map) { + result.add( + TechnitiumBlockedZone.fromJson(item.cast()), + ); + } + } + } else if (raw is Map) { + final Object? zones = raw['zones'] ?? raw['records']; + if (zones is List) { + for (final Object? item in zones) { + if (item is String && item.isNotEmpty) { + result.add(TechnitiumBlockedZone(domain: item)); + } else if (item is Map) { + result.add( + TechnitiumBlockedZone.fromJson(item.cast()), + ); + } + } + } + } + return result; + } + + /// Adds a domain or zone to the block list. + Future addBlockedZone(String domain) async { + try { + await _get('api/blocked/add', query: {'domain': domain}); + } on TechnitiumUnexpectedAnswer { + await _get( + 'api/blockedZones/add', + query: {'domain': domain}, + ); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + await _get( + 'api/blockedZones/add', + query: {'domain': domain}, + ); + } else { + rethrow; + } + } + } + + /// Deletes a domain or zone from the block list. + Future deleteBlockedZone(String domain) async { + try { + await _get( + 'api/blocked/delete', + query: {'domain': domain}, + ); + } on TechnitiumUnexpectedAnswer { + await _get( + 'api/blockedZones/delete', + query: {'domain': domain}, + ); + } on DioException catch (e) { + if (e.response?.statusCode == 404) { + await _get( + 'api/blockedZones/delete', + query: {'domain': domain}, + ); + } else { + rethrow; + } + } + } + + Future _ensureQueryLoggerApp() async { + if (_queryLoggerName != null && _queryLoggerClassPath != null) return; + final Map json = await _get('api/apps/list'); + final Object? response = json['response']; + final Object? apps = response is Map ? response['apps'] : json['apps']; + if (apps is List) { + for (final Object? app in apps) { + if (app is! Map) continue; + final String appName = (app['name'] ?? '').toString(); + final Object? dnsApps = app['dnsApps']; + if (dnsApps is List) { + for (final Object? dnsApp in dnsApps) { + if (dnsApp is Map && dnsApp['isQueryLogger'] == true) { + _queryLoggerName = appName; + _queryLoggerClassPath = (dnsApp['classPath'] ?? '').toString(); + return; + } + } + } + } + } + throw const TechnitiumRequestException( + 'No DNS Query Logger app is installed on this Technitium server', + ); + } + + /// Queries DNS logs with optional pagination and filters. + Future getQueryLogs({ + int pageNumber = 1, + int entriesPerPage = 50, + String? filter, + String? domain, + }) async { + await _ensureQueryLoggerApp(); + final Map query = { + 'name': _queryLoggerName, + 'classPath': _queryLoggerClassPath, + 'pageNumber': pageNumber, + 'entriesPerPage': entriesPerPage, + 'descendingOrder': true, + }; + if (filter != null && filter.isNotEmpty && filter.toLowerCase() != 'all') { + query['filter'] = filter; + query['responseType'] = filter; + } + if (domain != null && domain.trim().isNotEmpty) { + final String trimmed = domain.trim(); + if (_isIpAddress(trimmed)) { + query['clientIpAddress'] = trimmed; + } else { + query['qname'] = trimmed; + } + } + + final Map json = + await _get('api/logs/query', query: query); + return TechnitiumQueryLogPage.fromJson(json); + } + + static bool _isIpAddress(String input) { + try { + Uri.parseIPv4Address(input); + return true; + } on FormatException { + try { + Uri.parseIPv6Address(input); + return true; + } on FormatException { + return false; + } + } + } +} diff --git a/services/service_technitium/lib/src/technitium_errors.dart b/services/service_technitium/lib/src/technitium_errors.dart new file mode 100644 index 00000000..c60c92f2 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_errors.dart @@ -0,0 +1,56 @@ +import 'package:dio/dio.dart'; + +/// Refused API authentication (e.g. invalid API token). +class TechnitiumAuthException implements Exception { + const TechnitiumAuthException([this.message = 'Invalid API key']); + final String message; + + @override + String toString() => 'TechnitiumAuthException: $message'; +} + +/// The endpoint answered, but not with Technitium's API structure. +class TechnitiumUnexpectedAnswer implements Exception { + const TechnitiumUnexpectedAnswer([ + this.message = 'Unexpected answer from server', + ]); + final String message; + + @override + String toString() => 'TechnitiumUnexpectedAnswer: $message'; +} + +/// A request to Technitium failed with a server-reported error message. +class TechnitiumRequestException implements Exception { + const TechnitiumRequestException(this.message); + final String message; + + @override + String toString() => 'TechnitiumRequestException: $message'; +} + +/// Converts any error caught while calling Technitium into a human string. +String describeTechnitiumError(Object error) { + if (error is TechnitiumAuthException) { + return error.message; + } + if (error is TechnitiumRequestException) { + return error.message; + } + if (error is TechnitiumUnexpectedAnswer) { + return error.message; + } + if (error is DioException) { + final int? code = error.response?.statusCode; + if (code == 401 || code == 403) { + return 'Invalid API key (HTTP $code)'; + } + if (code == 404) { + return 'Endpoint not found (HTTP 404)'; + } + if (error.message != null && error.message!.isNotEmpty) { + return error.message!; + } + } + return error.toString(); +} diff --git a/services/service_technitium/lib/src/technitium_format.dart b/services/service_technitium/lib/src/technitium_format.dart new file mode 100644 index 00000000..3d126476 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_format.dart @@ -0,0 +1,34 @@ +import 'package:intl/intl.dart'; + +final NumberFormat _compact = NumberFormat.compact(); +final NumberFormat _percent = NumberFormat('0.0'); + +/// Formats large numbers compactly: 1200 → "1.2K", 3500000 → "3.5M". +String formatTechnitiumCompact(num value) => _compact.format(value); + +/// Formats a percentage: 12.34 → "12.3%". +String formatTechnitiumPercent(double value) => '${_percent.format(value)}%'; + +/// Formats remaining duration on a countdown: 0:45, 12:34, 1:02:15. +String formatTechnitiumCountdown(Duration duration) { + if (duration <= Duration.zero) return '0:00'; + final int hours = duration.inHours; + final int minutes = duration.inMinutes.remainder(60); + final int seconds = duration.inSeconds.remainder(60); + + final String sec = seconds.toString().padLeft(2, '0'); + if (hours > 0) { + final String min = minutes.toString().padLeft(2, '0'); + return '$hours:$min:$sec'; + } + return '$minutes:$sec'; +} + +/// Human readable label for dashboard stats periods. +String technitiumPeriodLabel(String period) => switch (period) { + 'LastHour' => 'Last hour', + 'LastDay' => 'Last 24 hours', + 'LastWeek' => 'Last 7 days', + 'LastMonth' => 'Last 30 days', + _ => period, + }; diff --git a/services/service_technitium/lib/src/technitium_providers.dart b/services/service_technitium/lib/src/technitium_providers.dart new file mode 100644 index 00000000..3344b0f9 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_providers.dart @@ -0,0 +1,266 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; + +import 'models/technitium_blocked_zone.dart'; +import 'models/technitium_query_log.dart'; +import 'models/technitium_settings.dart'; +import 'models/technitium_stats.dart'; +import 'models/technitium_status.dart'; +import 'technitium_api.dart'; +import 'technitium_session.dart'; + +/// Preset timed pauses for protection. +class TechnitiumPause { + const TechnitiumPause(this.label, this.duration); + final String label; + final Duration duration; +} + +const List technitiumPauses = [ + TechnitiumPause('1 minute', Duration(minutes: 1)), + TechnitiumPause('5 minutes', Duration(minutes: 5)), + TechnitiumPause('10 minutes', Duration(minutes: 10)), + TechnitiumPause('1 hour', Duration(hours: 1)), +]; + +/// The session manager for a Technitium instance. +final technitiumSessionProvider = Provider.family( + (Ref ref, Instance instance) => TechnitiumSession(), +); + +/// The API client for an instance. +final technitiumApiProvider = FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final Dio dio = await ref.watch(instanceDioProvider(instance).future); + final TechnitiumSession session = + ref.watch(technitiumSessionProvider(instance)); + return TechnitiumApi(dio, session); +}); + +/// Current dashboard time window for statistics (e.g. `LastHour`, `LastDay`, `LastWeek`, `LastMonth`). +final technitiumStatsPeriodProvider = + StateProvider.family((Ref ref, Instance _) => 'LastDay'); + +/// Server status, combining `/api/status` with settings blocking status. +final technitiumStatusProvider = + FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + final DateTime readAt = DateTime.now(); + final TechnitiumStatus status = await api.getStatus(); + final TechnitiumSettings settings = await api.getSettings(); + return TechnitiumStatus( + version: status.version.isNotEmpty ? status.version : '13.0.0', + dnsServerDomain: settings.dnsServerDomain.isNotEmpty + ? settings.dnsServerDomain + : status.dnsServerDomain, + isBlockingEnabled: settings.enableBlocking, + pausedUntil: settings.temporaryDisableBlockingTill, + readAt: readAt, + uptimeSeconds: status.uptimeSeconds, + serverIp: status.serverIp, + ); +}); + +/// Fixed 24-hour statistics for the Atrium dashboard widget. +final technitiumDashboardStatsProvider = + FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + return api.getStats(type: 'LastDay'); +}); + +/// Server statistics for the active period. +final technitiumStatsProvider = + FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + final String period = ref.watch(technitiumStatsPeriodProvider(instance)); + return api.getStats(type: period); +}); + +/// Server settings (blocking settings, upstream forwarders, cache configs). +final technitiumSettingsProvider = + FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + return api.getSettings(); +}); + +/// Manually configured blocked zones. +final technitiumBlockedZonesProvider = + FutureProvider.family, Instance>(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + return api.listBlockedZones(); +}); + +/// Current response-type filter for the query log. +final technitiumQueryLogFilterProvider = + StateProvider.family((Ref ref, Instance _) => 'All'); + +/// Current search term for the query log. +final technitiumQueryLogSearchProvider = + StateProvider.family((Ref ref, Instance _) => ''); + +/// Current page number for query log pagination. +final technitiumQueryLogPageProvider = + StateProvider.family((Ref ref, Instance _) => 1); + +/// Query log page stream. +final technitiumQueryLogProvider = + FutureProvider.family(( + Ref ref, + Instance instance, +) async { + final TechnitiumApi api = + await ref.watch(technitiumApiProvider(instance).future); + final String filter = ref.watch(technitiumQueryLogFilterProvider(instance)); + final String search = ref.watch(technitiumQueryLogSearchProvider(instance)); + final int page = ref.watch(technitiumQueryLogPageProvider(instance)); + + return api.getQueryLogs( + pageNumber: page, + filter: filter, + domain: search.isNotEmpty ? search : null, + ); +}); + +/// Actions coordinator for mutations (pause, resume, flush, block domain). +class TechnitiumActions { + const TechnitiumActions(this._ref, this._instance); + + final Ref _ref; + final Instance _instance; + + Future _api() => + _ref.read(technitiumApiProvider(_instance).future); + + /// Pauses, disables, or resumes DNS ad blocking. + Future setProtection({required bool enabled, Duration? pause}) async { + final TechnitiumApi api = await _api(); + try { + if (pause != null && pause > Duration.zero) { + final int minutes = (pause.inSeconds / 60).ceil().clamp(1, 1440); + await api.temporaryDisableBlocking(minutes: minutes); + } else if (enabled) { + // Enabling blocking disposes any pending temporary-disable timer. + await api.setBlocking(enabled: true); + } else { + // Cancel any pending temporary-disable timer without creating a + // new resume callback, then disable indefinitely. + await api.setBlocking(enabled: true); + await api.setBlocking(enabled: false); + } + } finally { + _ref.invalidate(technitiumStatusProvider(_instance)); + _ref.invalidate(technitiumSettingsProvider(_instance)); + _ref.invalidate(technitiumStatsProvider(_instance)); + _ref.invalidate(technitiumDashboardStatsProvider(_instance)); + } + } + + /// Flushes DNS server cache. + Future flushDnsCache() async { + final TechnitiumApi api = await _api(); + await api.flushDnsCache(); + _ref.invalidate(technitiumStatsProvider(_instance)); + _ref.invalidate(technitiumStatusProvider(_instance)); + } + + /// Forces an update of block lists. + Future forceUpdateBlockLists() async { + final TechnitiumApi api = await _api(); + await api.forceUpdateBlockLists(); + _ref.invalidate(technitiumSettingsProvider(_instance)); + } + + /// Adds a domain to blocked zones. + Future addBlockedZone(String domain) async { + final TechnitiumApi api = await _api(); + await api.addBlockedZone(domain); + _ref.invalidate(technitiumBlockedZonesProvider(_instance)); + _ref.invalidate(technitiumSettingsProvider(_instance)); + } + + /// Removes a domain from blocked zones. + Future deleteBlockedZone(String domain) async { + final TechnitiumApi api = await _api(); + await api.deleteBlockedZone(domain); + _ref.invalidate(technitiumBlockedZonesProvider(_instance)); + _ref.invalidate(technitiumSettingsProvider(_instance)); + } + + /// Invalidates [provider] and waits for it to settle. + /// + /// Errors stay on the provider's [AsyncValue]; the refresh gesture still + /// completes so the indicator can dismiss. + Future _reload(FutureProvider provider) async { + _ref.invalidate(provider); + try { + await _ref.read(provider.future); + } on Object { + // Surfaced through the provider's error state. + } + } + + /// Refreshes all active instance providers. + Future refresh() async { + await Future.wait(>[ + _reload(technitiumStatusProvider(_instance)), + _reload(technitiumStatsProvider(_instance)), + _reload(technitiumDashboardStatsProvider(_instance)), + _reload(technitiumSettingsProvider(_instance)), + _reload(technitiumBlockedZonesProvider(_instance)), + _reload(technitiumQueryLogProvider(_instance)), + ]); + } + + /// Refreshes the providers used by the overview tab. + Future refreshOverview() async { + await Future.wait(>[ + _reload(technitiumStatusProvider(_instance)), + _reload(technitiumStatsProvider(_instance)), + ]); + } + + /// Refreshes the providers used by the settings tab. + Future refreshSettings() async { + await Future.wait(>[ + _reload(technitiumStatusProvider(_instance)), + _reload(technitiumSettingsProvider(_instance)), + ]); + } + + /// Refreshes the blocked-zones tab. + Future refreshBlockedZones() => + _reload(technitiumBlockedZonesProvider(_instance)); + + /// Refreshes the query-log tab. + Future refreshQueryLog() => + _reload(technitiumQueryLogProvider(_instance)); +} + +final technitiumActionsProvider = Provider.family( + TechnitiumActions.new, +); diff --git a/services/service_technitium/lib/src/technitium_session.dart b/services/service_technitium/lib/src/technitium_session.dart new file mode 100644 index 00000000..e6f11db0 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_session.dart @@ -0,0 +1,20 @@ +/// Session state for a Technitium instance. +class TechnitiumSession { + TechnitiumSession(); + + int _refusals = 0; + DateTime? _lastRefusedAt; + + int get refusals => _refusals; + DateTime? get lastRefusedAt => _lastRefusedAt; + + void recordAuthRefusal() { + _refusals++; + _lastRefusedAt = DateTime.now(); + } + + void resetAuthRefusal() { + _refusals = 0; + _lastRefusedAt = null; + } +} diff --git a/services/service_technitium/lib/src/technitium_shell.dart b/services/service_technitium/lib/src/technitium_shell.dart new file mode 100644 index 00000000..820f59f7 --- /dev/null +++ b/services/service_technitium/lib/src/technitium_shell.dart @@ -0,0 +1,144 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_router/core_router.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; +import 'package:go_router/go_router.dart'; + +import 'tabs/technitium_blocked_zones_tab.dart'; +import 'tabs/technitium_overview_tab.dart'; +import 'tabs/technitium_query_log_tab.dart'; +import 'tabs/technitium_settings_tab.dart'; + +/// Currently active tab for a Technitium shell session. +final technitiumTabProvider = + StateProvider.family((Ref ref, Instance _) => 0); + +/// Main shell scaffold for Technitium DNS Server. +class TechnitiumShell extends ConsumerStatefulWidget { + const TechnitiumShell({ + required this.instance, + this.drawer, + this.now = DateTime.now, + super.key, + }); + + final Instance instance; + final Widget? drawer; + final DateTime Function() now; + + @override + ConsumerState createState() => _TechnitiumShellState(); +} + +class _TechnitiumShellState extends ConsumerState { + static const int _overview = 0; + static const int _queryLog = 1; + static const int _blockedZones = 2; + static const int _settings = 3; + + final GlobalKey _scaffoldKey = GlobalKey(); + final Set _shown = {0}; + + Instance get _instance => widget.instance; + + void _show(int tab) => + ref.read(technitiumTabProvider(_instance).notifier).state = tab; + + @override + Widget build(BuildContext context) { + final int tab = ref.watch(technitiumTabProvider(_instance)); + _shown.add(tab); + + return PopScope( + canPop: false, + onPopInvokedWithResult: (bool didPop, Object? result) { + if (didPop) return; + final ScaffoldState? scaffold = _scaffoldKey.currentState; + if (scaffold?.isDrawerOpen ?? false) { + scaffold!.closeDrawer(); + return; + } + if (ref.read(technitiumTabProvider(_instance)) != _overview) { + _show(_overview); + return; + } + GoRouter.of(context).go(AtriumRoutes.dashboard); + }, + child: Scaffold( + key: _scaffoldKey, + drawerEdgeDragWidth: widget.drawer != null ? 32 : null, + drawer: widget.drawer, + appBar: AppBar( + leading: widget.drawer == null + ? null + : IconButton( + icon: const Icon(Icons.menu), + tooltip: 'Services', + onPressed: () => _scaffoldKey.currentState?.openDrawer(), + ), + title: Row( + children: [ + Flexible( + child: Text( + _instance.name, + overflow: TextOverflow.ellipsis, + ), + ), + if (_instance.kind.isBeta) ...[ + const SizedBox(width: Insets.sm), + const BetaBadge(), + ], + ], + ), + ), + body: IndexedStack( + index: tab, + children: [ + TechnitiumOverviewTab(instance: _instance, now: widget.now), + if (_shown.contains(_queryLog)) + TechnitiumQueryLogTab(instance: _instance) + else + const SizedBox.shrink(), + if (_shown.contains(_blockedZones)) + TechnitiumBlockedZonesTab(instance: _instance) + else + const SizedBox.shrink(), + if (_shown.contains(_settings)) + TechnitiumSettingsTab(instance: _instance) + else + const SizedBox.shrink(), + ], + ), + bottomNavigationBar: AtriumBottomNav( + visible: true, + selectedIndex: tab, + onDestinationSelected: _show, + destinations: const [ + NavigationDestination( + icon: Icon(Icons.dashboard_outlined), + selectedIcon: Icon(Icons.dashboard_rounded), + label: 'Overview', + ), + NavigationDestination( + icon: Icon(Icons.receipt_long_outlined), + selectedIcon: Icon(Icons.receipt_long_rounded), + label: 'Query log', + ), + NavigationDestination( + icon: Icon(Icons.block_outlined), + selectedIcon: Icon(Icons.block_rounded), + label: 'Blocked zones', + ), + NavigationDestination( + icon: Icon(Icons.settings_outlined), + selectedIcon: Icon(Icons.settings_rounded), + label: 'Settings', + ), + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_countdown.dart b/services/service_technitium/lib/src/widgets/technitium_countdown.dart new file mode 100644 index 00000000..bcf9bddc --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_countdown.dart @@ -0,0 +1,65 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../technitium_format.dart'; + +/// A ticking countdown until [until]. +class TechnitiumCountdown extends StatefulWidget { + const TechnitiumCountdown({ + required this.until, + this.onDone, + this.style, + this.now = DateTime.now, + super.key, + }); + + final DateTime until; + final VoidCallback? onDone; + final TextStyle? style; + final DateTime Function() now; + + @override + State createState() => _TechnitiumCountdownState(); +} + +class _TechnitiumCountdownState extends State { + Timer? _timer; + bool _done = false; + + Duration get _left => widget.until.difference(widget.now()); + + @override + void initState() { + super.initState(); + _timer = Timer.periodic(const Duration(seconds: 1), (_) => _tick()); + } + + @override + void didUpdateWidget(TechnitiumCountdown oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.until != widget.until) { + _done = false; + } + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + void _tick() { + if (!mounted) return; + setState(() {}); + if (!_done && _left <= Duration.zero) { + _done = true; + widget.onDone?.call(); + } + } + + @override + Widget build(BuildContext context) { + return Text(formatTechnitiumCountdown(_left), style: widget.style); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_protection_card.dart b/services/service_technitium/lib/src/widgets/technitium_protection_card.dart new file mode 100644 index 00000000..160286c7 --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_protection_card.dart @@ -0,0 +1,186 @@ +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; + +import '../models/technitium_status.dart'; +import '../technitium_providers.dart'; +import 'technitium_countdown.dart'; + +/// Card showing current blocking status, countdown, and timed pause options. +class TechnitiumProtectionCard extends StatelessWidget { + const TechnitiumProtectionCard({ + required this.status, + required this.busy, + required this.onSet, + required this.onPauseEnded, + this.now = DateTime.now, + super.key, + }); + + final TechnitiumStatus status; + final bool busy; + final void Function({required bool enabled, Duration? pause}) onSet; + final VoidCallback onPauseEnded; + final DateTime Function() now; + + Future _showPauseMenu(BuildContext context) async { + final RenderBox button = context.findRenderObject()! as RenderBox; + final RenderBox overlay = Navigator.of(context, rootNavigator: true) + .overlay! + .context + .findRenderObject()! as RenderBox; + + final Duration? choice = await showMenu( + context: context, + useRootNavigator: true, + position: RelativeRect.fromRect( + Rect.fromPoints( + button.localToGlobal( + button.size.bottomLeft(Offset.zero), + ancestor: overlay, + ), + button.localToGlobal( + button.size.bottomRight(Offset.zero), + ancestor: overlay, + ), + ), + Offset.zero & overlay.size, + ), + items: >[ + for (final TechnitiumPause pause in technitiumPauses) + PopupMenuItem( + value: pause.duration, + child: Text(pause.label), + ), + const PopupMenuDivider(), + const PopupMenuItem( + value: Duration.zero, + child: Text('Until turned back on'), + ), + ], + ); + + if (choice == null) return; + if (choice == Duration.zero) { + onSet(enabled: false); + } else { + onSet(enabled: false, pause: choice); + } + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final TechnitiumProtection state = status.protection; + + final Color color = switch (state) { + TechnitiumProtection.on => cs.primary, + TechnitiumProtection.paused => cs.tertiary, + TechnitiumProtection.off => cs.error, + }; + + final IconData icon = switch (state) { + TechnitiumProtection.on => Icons.shield_rounded, + TechnitiumProtection.paused => Icons.pause_circle_outline_rounded, + TechnitiumProtection.off => Icons.shield_outlined, + }; + + final String title = switch (state) { + TechnitiumProtection.on => 'Protection is on', + TechnitiumProtection.paused => 'Protection is paused', + TechnitiumProtection.off => 'Protection is off', + }; + + final DateTime? pausedUntil = status.pausedUntil; + + return Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(24), + child: Padding( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 48, + height: 48, + decoration: BoxDecoration( + color: color.withValues(alpha: 0.16), + borderRadius: BorderRadius.circular(16), + ), + child: Icon(icon, color: color, size: 28), + ), + const SizedBox(width: Insets.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + if (pausedUntil != null && + state == TechnitiumProtection.paused) + Row( + children: [ + Text( + 'Resumes in ', + style: theme.textTheme.bodySmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + TechnitiumCountdown( + until: pausedUntil, + onDone: onPauseEnded, + now: now, + style: theme.textTheme.bodySmall?.copyWith( + color: color, + fontWeight: FontWeight.bold, + ), + ), + ], + ) + else + Text( + state == TechnitiumProtection.on + ? 'Blocking ads & trackers' + : 'DNS blocking disabled', + style: theme.textTheme.bodySmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: Insets.md), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + if (state == TechnitiumProtection.on) + Builder( + builder: (BuildContext ctx) => FilledButton.tonalIcon( + onPressed: busy ? null : () => _showPauseMenu(ctx), + icon: const Icon(Icons.pause_rounded, size: 18), + label: const Text('Pause'), + ), + ) + else + FilledButton.icon( + onPressed: busy ? null : () => onSet(enabled: true), + icon: const Icon(Icons.play_arrow_rounded, size: 18), + label: const Text('Resume'), + ), + ], + ), + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_query_detail_modal.dart b/services/service_technitium/lib/src/widgets/technitium_query_detail_modal.dart new file mode 100644 index 00000000..940508a4 --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_query_detail_modal.dart @@ -0,0 +1,149 @@ +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; + +import '../models/technitium_query_log.dart'; + +/// Modal bottom sheet showing query details with a one-tap block action. +class TechnitiumQueryDetailModal extends StatelessWidget { + const TechnitiumQueryDetailModal({ + required this.entry, + required this.onBlockDomain, + super.key, + }); + + final TechnitiumQueryEntry entry; + final Future Function(String domain) onBlockDomain; + + static Future show( + BuildContext context, { + required TechnitiumQueryEntry entry, + required Future Function(String domain) onBlockDomain, + }) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(24)), + ), + builder: (BuildContext ctx) => TechnitiumQueryDetailModal( + entry: entry, + onBlockDomain: onBlockDomain, + ), + ); + } + + Widget _row(ThemeData theme, String label, String value) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: Insets.xs), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: 120, + child: Text( + label, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + Expanded( + child: Text( + value, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + + return SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(Insets.lg), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.sm, + vertical: Insets.xs, + ), + decoration: BoxDecoration( + color: cs.primaryContainer, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + entry.qtype, + style: theme.textTheme.titleSmall?.copyWith( + color: cs.onPrimaryContainer, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: Text( + entry.qname, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: Insets.md), + const Divider(), + const SizedBox(height: Insets.xs), + _row(theme, 'Client IP', entry.clientIp), + if (entry.clientName != null) + _row(theme, 'Client name', entry.clientName!), + _row(theme, 'Response type', entry.responseType), + _row(theme, 'RCODE', entry.rcode), + _row(theme, 'Protocol', entry.protocol), + if (entry.roundTripTimeMs > 0) + _row(theme, 'Round trip time', '${entry.roundTripTimeMs} ms'), + if (entry.answer.isNotEmpty) _row(theme, 'Answer', entry.answer), + const SizedBox(height: Insets.lg), + SizedBox( + width: double.infinity, + child: FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: entry.isBlocked ? cs.secondary : cs.error, + foregroundColor: + entry.isBlocked ? cs.onSecondary : cs.onError, + padding: const EdgeInsets.symmetric(vertical: Insets.md), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + ), + ), + onPressed: () async { + Navigator.of(context).pop(); + await onBlockDomain(entry.qname); + }, + icon: Icon( + entry.isBlocked ? Icons.check_circle_outline : Icons.block, + ), + label: Text( + entry.isBlocked ? 'Already Blocked (Re-add)' : 'Block domain', + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_query_log_row.dart b/services/service_technitium/lib/src/widgets/technitium_query_log_row.dart new file mode 100644 index 00000000..98e73572 --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_query_log_row.dart @@ -0,0 +1,134 @@ +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:intl/intl.dart'; + +import '../models/technitium_query_log.dart'; + +final DateFormat _timeFormat = DateFormat.Hms(); + +/// A single row in the Technitium query log list. +class TechnitiumQueryLogRow extends StatelessWidget { + const TechnitiumQueryLogRow({ + required this.entry, + required this.onTap, + super.key, + }); + + final TechnitiumQueryEntry entry; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + + final Color statusColor; + if (entry.isBlocked) { + statusColor = cs.error; + } else if (entry.responseType.toLowerCase().contains('cache')) { + statusColor = cs.primary; + } else { + statusColor = cs.secondary; + } + + final String timeStr = + entry.timestamp != null ? _timeFormat.format(entry.timestamp!) : ''; + + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.sm, + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.xs, + vertical: 2, + ), + decoration: BoxDecoration( + color: cs.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + entry.qtype, + style: theme.textTheme.labelSmall?.copyWith( + fontWeight: FontWeight.bold, + fontFamily: 'monospace', + ), + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + entry.qname, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 2), + Row( + children: [ + if (timeStr.isNotEmpty) ...[ + Text( + timeStr, + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + const SizedBox(width: Insets.xs), + Text( + '•', + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + const SizedBox(width: Insets.xs), + ], + Expanded( + child: Text( + entry.clientName ?? entry.clientIp, + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ], + ), + ), + const SizedBox(width: Insets.sm), + Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.sm, + vertical: 4, + ), + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(8), + ), + child: Text( + entry.responseType, + style: theme.textTheme.labelSmall?.copyWith( + color: statusColor, + fontWeight: FontWeight.bold, + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_series_chart.dart b/services/service_technitium/lib/src/widgets/technitium_series_chart.dart new file mode 100644 index 00000000..195e71ec --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_series_chart.dart @@ -0,0 +1,61 @@ +import 'dart:math' as math; + +import 'package:fl_chart/fl_chart.dart'; +import 'package:flutter/material.dart'; + +/// Renders a dual-line query trend chart over time. +class TechnitiumSeriesChart extends StatelessWidget { + const TechnitiumSeriesChart({ + required this.series, + required this.color, + this.over = const [], + this.overColor, + super.key, + }); + + final List series; + final Color color; + final List over; + final Color? overColor; + + @override + Widget build(BuildContext context) { + if (series.isEmpty) { + return const SizedBox.shrink(); + } + final int highest = [...series, ...over].fold(0, math.max); + return LineChart( + LineChartData( + minX: 0, + maxX: (series.length - 1).toDouble(), + minY: 0, + maxY: math.max(1, highest).toDouble(), + gridData: const FlGridData(show: false), + titlesData: const FlTitlesData(show: false), + borderData: FlBorderData(show: false), + lineTouchData: const LineTouchData(enabled: false), + lineBarsData: [ + _line(series, color), + if (over.isNotEmpty) _line(over, overColor ?? color), + ], + ), + ); + } + + LineChartBarData _line(List points, Color color) { + return LineChartBarData( + spots: [ + for (int i = 0; i < points.length; i++) + FlSpot(i.toDouble(), points[i].toDouble()), + ], + color: color, + isCurved: true, + preventCurveOverShooting: true, + dotData: const FlDotData(show: false), + belowBarData: BarAreaData( + show: true, + color: color.withValues(alpha: 0.12), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_stat_tile.dart b/services/service_technitium/lib/src/widgets/technitium_stat_tile.dart new file mode 100644 index 00000000..25171e20 --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_stat_tile.dart @@ -0,0 +1,82 @@ +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; + +/// Single stat display block. +class TechnitiumStatTile extends StatelessWidget { + const TechnitiumStatTile({ + required this.label, + required this.value, + this.color, + this.subValue, + super.key, + }); + + final String label; + final String value; + final Color? color; + final String? subValue; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final Color tint = color ?? cs.primary; + + return Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(16), + child: Padding( + padding: const EdgeInsets.all(Insets.md), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + width: 8, + height: 8, + decoration: BoxDecoration( + color: tint, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: Insets.xs), + Expanded( + child: Text( + label, + style: theme.textTheme.labelMedium?.copyWith( + color: cs.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: Insets.xs), + FittedBox( + fit: BoxFit.scaleDown, + alignment: Alignment.centerLeft, + child: Text( + value, + style: theme.textTheme.headlineSmall?.copyWith( + fontWeight: FontWeight.bold, + color: cs.onSurface, + ), + ), + ), + if (subValue != null) ...[ + const SizedBox(height: 2), + Text( + subValue!, + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ], + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/lib/src/widgets/technitium_top_list.dart b/services/service_technitium/lib/src/widgets/technitium_top_list.dart new file mode 100644 index 00000000..64ad2b03 --- /dev/null +++ b/services/service_technitium/lib/src/widgets/technitium_top_list.dart @@ -0,0 +1,128 @@ +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; + +import '../models/technitium_stats.dart'; +import '../technitium_format.dart'; + +/// Card showing ranked list of clients or domains. +class TechnitiumTopListCard extends StatelessWidget { + const TechnitiumTopListCard({ + required this.title, + required this.items, + required this.icon, + this.accent, + this.onTapItem, + super.key, + }); + + final String title; + final List items; + final IconData icon; + final Color? accent; + final void Function(TechnitiumTopItem item)? onTapItem; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final Color color = accent ?? cs.primary; + + return Material( + color: cs.surfaceContainerHigh, + borderRadius: BorderRadius.circular(20), + child: Padding( + padding: const EdgeInsets.all(Insets.md), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(icon, size: 20, color: color), + const SizedBox(width: Insets.sm), + Text( + title, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(height: Insets.sm), + if (items.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: Insets.md), + child: Center( + child: Text( + 'No data for selected period', + style: theme.textTheme.bodySmall?.copyWith( + color: cs.onSurfaceVariant, + ), + ), + ), + ) + else + for (int i = 0; i < items.length && i < 10; i++) ...[ + if (i > 0) const Divider(height: 1), + InkWell( + onTap: onTapItem != null ? () => onTapItem!(items[i]) : null, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: Insets.xs, + horizontal: Insets.xs, + ), + child: Row( + children: [ + SizedBox( + width: 24, + child: Text( + '${i + 1}', + style: theme.textTheme.labelSmall?.copyWith( + color: cs.onSurfaceVariant, + fontWeight: FontWeight.bold, + ), + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + items[i].name, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w600, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + if (items[i].domain != null) + Text( + items[i].domain!, + style: theme.textTheme.bodySmall?.copyWith( + color: cs.onSurfaceVariant, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + const SizedBox(width: Insets.sm), + Text( + formatTechnitiumCompact(items[i].hits), + style: theme.textTheme.labelMedium?.copyWith( + color: color, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + ], + ], + ), + ), + ); + } +} diff --git a/services/service_technitium/pubspec.yaml b/services/service_technitium/pubspec.yaml new file mode 100644 index 00000000..1fa2011c --- /dev/null +++ b/services/service_technitium/pubspec.yaml @@ -0,0 +1,28 @@ +name: service_technitium +description: Technitium DNS Server API client and UI screens for Atrium. +publish_to: none +resolution: workspace + +environment: + sdk: ^3.6.0 + flutter: ^3.27.0 + +dependencies: + core_models: + core_networking: + core_router: + core_ui: + dio: ^5.7.0 + fl_chart: ^1.2.0 + flutter: + sdk: flutter + flutter_riverpod: ^3.3.2 + go_router: ^17.3.0 + intl: ^0.20.2 + progress_indicator_m3e: + url_launcher: ^6.3.0 + +dev_dependencies: + flutter_lints: ^6.0.0 + flutter_test: + sdk: flutter diff --git a/services/service_technitium/test/support/technitium_test_instance.dart b/services/service_technitium/test/support/technitium_test_instance.dart new file mode 100644 index 00000000..1fc8aedb --- /dev/null +++ b/services/service_technitium/test/support/technitium_test_instance.dart @@ -0,0 +1,11 @@ +import 'package:core_models/core_models.dart'; + +const Instance technitiumTestInstance = Instance( + id: 'technitium-test', + name: 'Technitium Test', + kind: ServiceKind.technitium, + localUrl: 'http://127.0.0.1:5380', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'test-token-12345'), +); diff --git a/services/service_technitium/test/technitium_api_test.dart b/services/service_technitium/test/technitium_api_test.dart new file mode 100644 index 00000000..5238d803 --- /dev/null +++ b/services/service_technitium/test/technitium_api_test.dart @@ -0,0 +1,299 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_technitium/service_technitium.dart'; + +class _MockAdapter implements HttpClientAdapter { + _MockAdapter(this.handler); + final ResponseBody Function(RequestOptions options) handler; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + return handler(options); + } + + @override + void close({bool force = false}) {} +} + +ResponseBody _json(Object? data, [int status = 200]) { + return ResponseBody.fromString( + jsonEncode(data), + status, + headers: >{ + Headers.contentTypeHeader: ['application/json'], + }, + ); +} + +void main() { + group('TechnitiumApi', () { + test('getStatus returns TechnitiumStatus', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + expect(opt.path, 'api/status'); + return _json({ + 'status': 'ok', + 'response': { + 'version': '13.0.0', + 'uptime': 3600, + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final TechnitiumStatus status = await api.getStatus(); + expect(status.version, '13.0.0'); + expect(status.uptimeSeconds, 3600); + }); + + test('getStats fetches dashboard statistics', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + expect(opt.path, 'api/dashboard/stats/get'); + expect(opt.queryParameters['type'], 'LastDay'); + return _json({ + 'status': 'ok', + 'response': { + 'stats': { + 'totalQueries': 500, + 'blockedQueries': 50, + }, + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final TechnitiumStats stats = await api.getStats(); + expect(stats.totalQueries, 500); + expect(stats.blockedQueries, 50); + }); + + test('getSettings fetches configuration', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + expect(opt.path, 'api/settings/get'); + return _json({ + 'status': 'ok', + 'response': { + 'enableBlocking': true, + 'blockingType': 'NxDomain', + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final TechnitiumSettings settings = await api.getSettings(); + expect(settings.enableBlocking, isTrue); + expect(settings.blockingType, 'NxDomain'); + }); + + test('mutations call expected endpoints', () async { + final List calledPaths = []; + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + calledPaths.add(opt.path); + return _json({'status': 'ok'}); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + await api.setBlocking(enabled: true); + await api.temporaryDisableBlocking(minutes: 10); + await api.forceUpdateBlockLists(); + await api.flushDnsCache(); + await api.addBlockedZone('bad.com'); + await api.deleteBlockedZone('bad.com'); + + expect(calledPaths, [ + 'api/settings/set', + 'api/settings/temporaryDisableBlocking', + 'api/settings/forceUpdateBlockLists', + 'api/cache/flush', + 'api/blocked/add', + 'api/blocked/delete', + ]); + }); + + test('listBlockedZones parses api/blocked/export plain text', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + expect(opt.path, 'api/blocked/export'); + return ResponseBody.fromString( + 'ads.example.com\ntelemetry.example.com\n', + 200, + headers: >{ + Headers.contentTypeHeader: ['text/plain'], + }, + ); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final List zones = await api.listBlockedZones(); + expect(zones.length, 2); + expect(zones[0].domain, 'ads.example.com'); + expect(zones[1].domain, 'telemetry.example.com'); + }); + + test('listBlockedZones falls back to api/blocked/list object shape', + () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + if (opt.path == 'api/blocked/export') { + return ResponseBody.fromString('Not Found', 404); + } + expect(opt.path, 'api/blocked/list'); + return _json({ + 'status': 'ok', + 'response': { + 'domain': '', + 'zones': ['ads.example.com', 'tracker.example.com'], + 'records': [], + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final List zones = await api.listBlockedZones(); + expect(zones.length, 2); + expect(zones[0].domain, 'ads.example.com'); + expect(zones[1].domain, 'tracker.example.com'); + }); + + test('getQueryLogs discovers query logger app and passes parameters', + () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + if (opt.path == 'api/apps/list') { + return _json({ + 'status': 'ok', + 'response': { + 'apps': [ + { + 'name': 'Query Logs (Sqlite)', + 'dnsApps': [ + { + 'classPath': 'QueryLogsSqlite.App', + 'isQueryLogger': true, + }, + ], + }, + ], + }, + }); + } + expect(opt.path, 'api/logs/query'); + expect(opt.queryParameters['name'], 'Query Logs (Sqlite)'); + expect(opt.queryParameters['classPath'], 'QueryLogsSqlite.App'); + expect(opt.queryParameters['pageNumber'], 2); + expect(opt.queryParameters['filter'], 'Blocked'); + return _json({ + 'status': 'ok', + 'response': { + 'pageNumber': 2, + 'totalPages': 4, + 'totalEntries': 100, + 'entries': [], + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + final TechnitiumQueryLogPage page = await api.getQueryLogs( + pageNumber: 2, + filter: 'Blocked', + ); + expect(page.pageNumber, 2); + expect(page.totalPages, 4); + }); + + test('getQueryLogs sends clientIpAddress for IP search and omits qname', + () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + if (opt.path == 'api/apps/list') { + return _json({ + 'status': 'ok', + 'response': { + 'apps': [ + { + 'name': 'Query Logs (Sqlite)', + 'dnsApps': [ + { + 'classPath': 'QueryLogsSqlite.App', + 'isQueryLogger': true, + }, + ], + }, + ], + }, + }); + } + expect(opt.path, 'api/logs/query'); + expect(opt.queryParameters['clientIpAddress'], '192.168.1.5'); + expect(opt.queryParameters.containsKey('qname'), isFalse); + return _json({ + 'status': 'ok', + 'response': { + 'pageNumber': 1, + 'totalPages': 1, + 'totalEntries': 0, + 'entries': [], + }, + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + await api.getQueryLogs(domain: '192.168.1.5'); + }); + + test('throws TechnitiumAuthException on token failure', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + return _json({ + 'status': 'error', + 'errorMessage': 'Invalid token provided', + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + expect( + api.getStatus, + throwsA(isA()), + ); + }); + + test('throws TechnitiumAuthException on invalid-token status', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + return _json({ + 'status': 'invalid-token', + }); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + expect( + api.getSettings, + throwsA(isA()), + ); + }); + + test('throws TechnitiumAuthException on 401 HTTP status', () async { + final Dio dio = Dio() + ..httpClientAdapter = _MockAdapter((RequestOptions opt) { + return _json({'message': 'Unauthorized'}, 401); + }); + + final TechnitiumApi api = TechnitiumApi(dio); + expect( + api.getStatus, + throwsA(isA()), + ); + }); + }); +} diff --git a/services/service_technitium/test/technitium_models_test.dart b/services/service_technitium/test/technitium_models_test.dart new file mode 100644 index 00000000..4159ee96 --- /dev/null +++ b/services/service_technitium/test/technitium_models_test.dart @@ -0,0 +1,233 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_technitium/service_technitium.dart'; + +void main() { + group('TechnitiumStatus', () { + test('parses active protected status', () { + final DateTime now = DateTime(2026, 11, 22, 12); + final TechnitiumStatus status = TechnitiumStatus.fromJson( + { + 'status': 'ok', + 'response': { + 'version': '13.0.0', + 'dnsServerDomain': 'dns.local', + 'enableBlocking': true, + 'temporaryDisableBlockingTill': null, + 'uptime': 3600, + }, + }, + readAt: now, + ); + + expect(status.version, '13.0.0'); + expect(status.dnsServerDomain, 'dns.local'); + expect(status.isBlockingEnabled, isTrue); + expect(status.protection, TechnitiumProtection.on); + expect(status.pauseLeft, Duration.zero); + }); + + test('parses paused status with countdown', () { + final DateTime now = DateTime(2026, 11, 22, 12); + final DateTime future = now.add(const Duration(minutes: 5)); + final TechnitiumStatus status = TechnitiumStatus.fromJson( + { + 'status': 'ok', + 'response': { + 'version': '13.0.0', + 'enableBlocking': true, + 'temporaryDisableBlockingTill': future.toIso8601String(), + }, + }, + readAt: now, + ); + + expect(status.protection, TechnitiumProtection.paused); + expect(status.pauseLeft, const Duration(minutes: 5)); + }); + + test('parses disabled status', () { + final DateTime now = DateTime(2026, 11, 22, 12); + final TechnitiumStatus status = TechnitiumStatus.fromJson( + { + 'status': 'ok', + 'response': { + 'enableBlocking': false, + }, + }, + readAt: now, + ); + + expect(status.protection, TechnitiumProtection.off); + }); + + test('parses paused status even when enableBlocking is false', () { + final DateTime now = DateTime.utc(2026, 11, 22, 12); + final TechnitiumStatus status = TechnitiumStatus.fromJson( + { + 'status': 'ok', + 'response': { + 'enableBlocking': false, + 'temporaryDisableBlockingTill': '2026-11-22T12:10:00Z', + }, + }, + readAt: now, + ); + + expect(status.protection, TechnitiumProtection.paused); + expect(status.pauseLeft, const Duration(minutes: 10)); + }); + }); + + group('TechnitiumStats', () { + test('parses totals, charts, and top lists', () { + final TechnitiumStats stats = TechnitiumStats.fromJson({ + 'status': 'ok', + 'response': { + 'stats': { + 'totalQueries': 1000, + 'blockedQueries': 200, + 'cachedQueries': 300, + 'totalClients': 5, + }, + 'mainChartData': { + 'totalQueries': [100, 200, 700], + 'blockedQueries': [20, 40, 140], + 'labels': ['10:00', '11:00', '12:00'], + }, + 'topClients': [ + {'name': '192.168.1.10', 'hits': 500}, + ], + 'topDomains': [ + {'name': 'google.com', 'hits': 300}, + ], + 'topBlockedDomains': [ + {'name': 'ads.example.com', 'hits': 100}, + ], + }, + }); + + expect(stats.totalQueries, 1000); + expect(stats.blockedQueries, 200); + expect(stats.cachedQueries, 300); + expect(stats.clientsCount, 5); + expect(stats.blockedPercent, 20.0); + expect(stats.cachedPercent, 30.0); + expect(stats.queriesSeries, [100, 200, 700]); + expect(stats.blockedSeries, [20, 40, 140]); + expect(stats.topClients.first.name, '192.168.1.10'); + expect(stats.topClients.first.hits, 500); + expect(stats.topDomains.first.name, 'google.com'); + expect(stats.topBlockedDomains.first.name, 'ads.example.com'); + }); + + test( + 'parses totalAuthoritative, totalRecursive, and mainChartData.datasets', + () { + final TechnitiumStats stats = TechnitiumStats.fromJson({ + 'status': 'ok', + 'response': { + 'stats': { + 'totalQueries': 925, + 'totalBlocked': 49, + 'totalCached': 481, + 'totalAuthoritative': 47, + 'totalRecursive': 348, + 'totalClients': 6, + }, + 'mainChartData': { + 'labels': ['10:00', '10:01'], + 'datasets': [ + { + 'label': 'Total', + 'data': [400, 525] + }, + { + 'label': 'Blocked', + 'data': [20, 29] + }, + { + 'label': 'Cached', + 'data': [200, 281] + }, + ], + }, + }, + }); + + expect(stats.authoritativeQueries, 47); + expect(stats.recursiveQueries, 348); + expect(stats.queriesSeries, [400, 525]); + expect(stats.blockedSeries, [20, 29]); + expect(stats.cachedSeries, [200, 281]); + }); + }); + + group('TechnitiumQueryLog', () { + test('parses log page and entries', () { + final TechnitiumQueryLogPage page = + TechnitiumQueryLogPage.fromJson({ + 'status': 'ok', + 'response': { + 'pageNumber': 1, + 'totalPages': 3, + 'totalEntries': 150, + 'entries': [ + { + 'qname': 'tracker.com', + 'qtype': 'A', + 'clientIpAddress': '192.168.1.5', + 'responseType': 'Blocked', + 'rcode': 'NxDomain', + 'protocol': 'UDP', + 'roundTripTime': 1.2, + 'answer': '0.0.0.0', + }, + ], + }, + }); + + expect(page.pageNumber, 1); + expect(page.totalPages, 3); + expect(page.totalEntries, 150); + expect(page.entries.length, 1); + expect(page.entries.first.qname, 'tracker.com'); + expect(page.entries.first.isBlocked, isTrue); + }); + }); + + group('TechnitiumSettings & BlockedZones', () { + test('parses server settings', () { + final TechnitiumSettings settings = + TechnitiumSettings.fromJson({ + 'status': 'ok', + 'response': { + 'enableBlocking': true, + 'blockingType': 'NxDomain', + 'blockListUpdateIntervalHours': 12, + 'blockLists': [ + 'https://example.com/blocklist.txt', + ], + }, + }); + + expect(settings.enableBlocking, isTrue); + expect(settings.blockingType, 'NxDomain'); + expect(settings.blockListUpdateIntervalHours, 12); + expect( + settings.blockLists, + ['https://example.com/blocklist.txt'], + ); + }); + + test('parses blocked zones', () { + final TechnitiumBlockedZone zone = + TechnitiumBlockedZone.fromJson({ + 'domain': 'ads.example.com', + 'disabled': false, + }); + + expect(zone.domain, 'ads.example.com'); + expect(zone.disabled, isFalse); + }); + }); +} diff --git a/services/service_technitium/test/technitium_providers_test.dart b/services/service_technitium/test/technitium_providers_test.dart new file mode 100644 index 00000000..a48da700 --- /dev/null +++ b/services/service_technitium/test/technitium_providers_test.dart @@ -0,0 +1,190 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_technitium/service_technitium.dart'; + +import 'support/technitium_test_instance.dart'; + +class _FakeApi extends TechnitiumApi { + _FakeApi() : super(Dio()); + + bool setBlockingCalled = false; + final List setBlockingHistory = []; + num? tempDisableMinutes; + bool flushCacheCalled = false; + bool forceUpdateCalled = false; + String? addedDomain; + String? deletedDomain; + Completer? statusGate; + + @override + Future getStatus() async { + final Completer? gate = statusGate; + if (gate != null) await gate.future; + return TechnitiumStatus( + version: '13.0.0', + isBlockingEnabled: true, + readAt: DateTime.now(), + ); + } + + @override + Future getSettings() async { + return const TechnitiumSettings(); + } + + @override + Future getStats({String type = 'LastDay'}) async { + return const TechnitiumStats(totalQueries: 100, blockedQueries: 10); + } + + @override + Future> listBlockedZones() async { + return const [ + TechnitiumBlockedZone(domain: 'bad.com'), + ]; + } + + @override + Future setBlocking({required bool enabled}) async { + setBlockingCalled = true; + setBlockingHistory.add(enabled); + } + + @override + Future temporaryDisableBlocking({required num minutes}) async { + tempDisableMinutes = minutes; + } + + @override + Future flushDnsCache() async { + flushCacheCalled = true; + } + + @override + Future forceUpdateBlockLists() async { + forceUpdateCalled = true; + } + + @override + Future addBlockedZone(String domain) async { + addedDomain = domain; + } + + @override + Future deleteBlockedZone(String domain) async { + deletedDomain = domain; + } +} + +void main() { + group('Technitium Providers and Actions', () { + test('Actions trigger mutations and invalidate state', () async { + final _FakeApi fakeApi = _FakeApi(); + final ProviderContainer container = ProviderContainer( + overrides: [ + technitiumApiProvider(technitiumTestInstance) + .overrideWith((_) async => fakeApi), + ], + ); + addTearDown(container.dispose); + + final TechnitiumActions actions = + container.read(technitiumActionsProvider(technitiumTestInstance)); + + // Test pause + await actions.setProtection( + enabled: false, + pause: const Duration(minutes: 10), + ); + expect(fakeApi.tempDisableMinutes, 10.0); + + // Test disable (clears pending pause via enable=true before disable) + await actions.setProtection(enabled: false); + expect(fakeApi.setBlockingHistory, [true, false]); + + // Test resume (enable=true disposes pause timer directly) + fakeApi.setBlockingCalled = false; + fakeApi.setBlockingHistory.clear(); + await actions.setProtection(enabled: true); + expect(fakeApi.setBlockingHistory, [true]); + expect(fakeApi.setBlockingCalled, isTrue); + + // Test flush cache + await actions.flushDnsCache(); + expect(fakeApi.flushCacheCalled, isTrue); + + // Test force update block lists + await actions.forceUpdateBlockLists(); + expect(fakeApi.forceUpdateCalled, isTrue); + + // Test add and delete zone + await actions.addBlockedZone('ad.tracker.com'); + expect(fakeApi.addedDomain, 'ad.tracker.com'); + + await actions.deleteBlockedZone('ad.tracker.com'); + expect(fakeApi.deletedDomain, 'ad.tracker.com'); + }); + + test('refreshOverview waits for provider reloads', () async { + final _FakeApi fakeApi = _FakeApi()..statusGate = Completer(); + final ProviderContainer container = ProviderContainer( + overrides: [ + technitiumApiProvider(technitiumTestInstance) + .overrideWith((_) async => fakeApi), + ], + ); + addTearDown(container.dispose); + + final TechnitiumActions actions = + container.read(technitiumActionsProvider(technitiumTestInstance)); + + bool completed = false; + final Future refresh = + actions.refreshOverview().whenComplete(() => completed = true); + + await Future.delayed(Duration.zero); + expect(completed, isFalse); + + fakeApi.statusGate!.complete(); + await refresh; + expect(completed, isTrue); + }); + + test('Period and query log filters update cleanly', () { + final ProviderContainer container = ProviderContainer(); + addTearDown(container.dispose); + + expect( + container.read(technitiumStatsPeriodProvider(technitiumTestInstance)), + 'LastDay', + ); + + container + .read(technitiumStatsPeriodProvider(technitiumTestInstance).notifier) + .state = 'LastWeek'; + expect( + container.read(technitiumStatsPeriodProvider(technitiumTestInstance)), + 'LastWeek', + ); + + expect( + container + .read(technitiumQueryLogFilterProvider(technitiumTestInstance)), + 'All', + ); + container + .read( + technitiumQueryLogFilterProvider(technitiumTestInstance).notifier, + ) + .state = 'Blocked'; + expect( + container + .read(technitiumQueryLogFilterProvider(technitiumTestInstance)), + 'Blocked', + ); + }); + }); +} diff --git a/services/service_technitium/test/technitium_shell_test.dart b/services/service_technitium/test/technitium_shell_test.dart new file mode 100644 index 00000000..de650625 --- /dev/null +++ b/services/service_technitium/test/technitium_shell_test.dart @@ -0,0 +1,112 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_technitium/service_technitium.dart'; + +import 'support/technitium_test_instance.dart'; + +void main() { + testWidgets('TechnitiumShell renders tabs and switches destinations', + (WidgetTester tester) async { + final TechnitiumStatus status = TechnitiumStatus( + version: '13.0.0', + isBlockingEnabled: true, + readAt: DateTime.now(), + ); + const TechnitiumStats stats = TechnitiumStats( + totalQueries: 1250, + blockedQueries: 250, + cachedQueries: 400, + clientsCount: 3, + topClients: [ + TechnitiumTopItem(name: '192.168.1.100', hits: 500), + ], + topDomains: [ + TechnitiumTopItem(name: 'google.com', hits: 300), + ], + topBlockedDomains: [ + TechnitiumTopItem(name: 'ads.example.com', hits: 150), + ], + ); + const TechnitiumSettings settings = TechnitiumSettings(); + const TechnitiumQueryLogPage queryLogPage = TechnitiumQueryLogPage( + entries: [ + TechnitiumQueryEntry( + qname: 'ads.tracker.net', + qtype: 'A', + clientIp: '192.168.1.50', + responseType: 'Blocked', + rcode: 'NxDomain', + protocol: 'UDP', + roundTripTimeMs: 0.8, + answer: '0.0.0.0', + ), + ], + totalEntries: 1, + ); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + technitiumStatusProvider(technitiumTestInstance) + .overrideWith((_) async => status), + technitiumStatsProvider(technitiumTestInstance) + .overrideWith((_) async => stats), + technitiumSettingsProvider(technitiumTestInstance) + .overrideWith((_) async => settings), + technitiumBlockedZonesProvider(technitiumTestInstance).overrideWith( + (_) async => const [ + TechnitiumBlockedZone(domain: 'blocked.example.com'), + ], + ), + technitiumQueryLogProvider(technitiumTestInstance) + .overrideWith((_) async => queryLogPage), + ], + child: const MaterialApp( + home: TechnitiumShell(instance: technitiumTestInstance), + ), + ), + ); + + // Initial pump + await tester.pumpAndSettle(); + + // Verify Overview Tab rendered + expect(find.text('Technitium Test'), findsOneWidget); + expect(find.text('Protection is on'), findsOneWidget); + expect(find.text('Total Queries'), findsOneWidget); + expect(find.text('Top Clients'), findsOneWidget); + expect(find.text('192.168.1.100'), findsOneWidget); + expect(find.text('Top Blocked Domains'), findsOneWidget); + expect(find.text('ads.example.com'), findsOneWidget); + + // Switch to Query Log tab + await tester.tap(find.text('Query log')); + await tester.pumpAndSettle(); + expect(find.text('ads.tracker.net'), findsOneWidget); + expect(find.text('Blocked'), findsWidgets); + + // Tap query log row to open detail modal + await tester.tap(find.text('ads.tracker.net')); + await tester.pumpAndSettle(); + expect(find.text('192.168.1.50'), findsWidgets); + expect(find.text('Already Blocked (Re-add)'), findsOneWidget); + + // Close modal + await tester.tap(find.text('Already Blocked (Re-add)')); + await tester.pumpAndSettle(); + + // Switch to Blocked zones tab + await tester.tap(find.text('Blocked zones')); + await tester.pumpAndSettle(); + expect(find.text('blocked.example.com'), findsOneWidget); + expect(find.text('Add zone'), findsOneWidget); + + // Switch to Settings tab + await tester.tap(find.text('Settings')); + await tester.pumpAndSettle(); + expect(find.text('DNS Cache'), findsOneWidget); + expect(find.text('Flush DNS cache'), findsOneWidget); + expect(find.text('Enable Blocking'), findsOneWidget); + }); +} diff --git a/site/public/assets/service_icons/technitium.png b/site/public/assets/service_icons/technitium.png new file mode 100644 index 00000000..87c6cedc Binary files /dev/null and b/site/public/assets/service_icons/technitium.png differ diff --git a/site/src/components/integrations.html b/site/src/components/integrations.html index 86120832..1c3abf02 100644 --- a/site/src/components/integrations.html +++ b/site/src/components/integrations.html @@ -44,6 +44,7 @@
Downloads & Utilities
  • MySpeed: Status with a manual run, the day's results, history with averages, and a dashboard widget.
  • Gluetun: VPN status, forwarded port, one-tap reconnect, and a dashboard widget.
  • AdGuard Home: Protection switch with timed pauses, statistics, top clients and domains, the query log with block and unblock, blocklists, custom rules, blocked services and rewrites, per-client settings, the server's DNS, cache, access and log settings, and a dashboard widget.
  • +
  • Technitium DNS: Protection switch with timed pauses, traffic statistics, top clients and domains, live query log with one-tap domain blocking, blocked zones, cache flushing, and a dashboard widget.
  • Beszel: Systems list, live metrics, and a per-system detail screen.
  • dashdot: Live CPU, memory, disk, and GPU usage with a system-info tab.
  • Unraid: Array and disk health, per-core system load, Docker containers, and virtual machine control.
  • diff --git a/site/src/data/services.js b/site/src/data/services.js index 309f092c..30ce5860 100644 --- a/site/src/data/services.js +++ b/site/src/data/services.js @@ -30,6 +30,7 @@ export const servicesList = [ 'dashdot', 'gluetun', 'adguard-home', + 'technitium', 'unraid' ]; @@ -494,6 +495,20 @@ export const servicesData = { 'Client, DNS, Cache, Access & Retention Settings' ] }, + technitium: { + name: 'Technitium DNS', + category: 'Downloads & Utilities', + icon: asset('assets/service_icons/technitium.png'), + screenshots: [], + description: 'Network-wide DNS server and ad blocker. Pause protection with timed pauses, inspect live query logs, and manage blocked zones and cache settings.', + features: [ + 'Protection Switch with Timed Pauses', + 'Statistics with Top Clients & Domains', + 'Query Log with Instant Domain Blocking', + 'Blocked Zones & Block List Updates', + 'DNS Cache Flush & Server Diagnostics' + ] + }, unraid: { name: 'Unraid', category: 'Downloads & Utilities',