diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 8e2cb565..cb713d38 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -78,6 +78,7 @@ body: - Gluetun - AdGuard Home - Cleanuparr + - Gotify - Unraid - Something else validations: diff --git a/app/assets/service_icons/gotify.png b/app/assets/service_icons/gotify.png new file mode 100644 index 00000000..4b5855f2 Binary files /dev/null and b/app/assets/service_icons/gotify.png differ diff --git a/app/lib/src/dashboard/dashboard_board.dart b/app/lib/src/dashboard/dashboard_board.dart index 98e18c3a..11f59826 100644 --- a/app/lib/src/dashboard/dashboard_board.dart +++ b/app/lib/src/dashboard/dashboard_board.dart @@ -8,6 +8,7 @@ import 'package:service_adguard_home/service_adguard_home.dart'; import 'package:service_dashdot/service_dashdot.dart'; import 'package:service_emby/service_emby.dart' as emby; import 'package:service_glances/service_glances.dart'; +import 'package:service_gotify/service_gotify.dart'; import 'package:service_jellyfin/service_jellyfin.dart' as jf; import 'package:service_deluge/service_deluge.dart'; import 'package:service_nzbget/service_nzbget.dart'; @@ -37,6 +38,7 @@ import 'widgets/cleanuparr_widget.dart'; import 'widgets/dashdot_widget.dart'; import 'widgets/downloads_widget.dart'; import 'widgets/gluetun_status_widget.dart'; +import 'widgets/gotify_widget.dart'; import 'widgets/myspeed_widget.dart'; import 'widgets/recently_added_widget.dart'; import 'widgets/recently_downloaded_widget.dart'; @@ -218,6 +220,10 @@ class DashboardBoard extends ConsumerWidget { return DashboardCleanuparrWidget( instances: _byKind(instances, ServiceKind.cleanuparr), ); + case DashboardWidgetKind.gotify: + return DashboardGotifyWidget( + instances: _byKind(instances, ServiceKind.gotify), + ); case DashboardWidgetKind.wakeOnLan: return const DashboardWakeOnLanWidget(); } @@ -295,6 +301,8 @@ class DashboardBoard extends ConsumerWidget { ref.invalidate(cleanuparrStrikesProvider(i)); ref.invalidate(cleanuparrStrikesCountProvider(i)); ref.invalidate(cleanuparrJobsProvider(i)); + case ServiceKind.gotify: + ref.invalidate(gotifyMessagesProvider((instance: i, appId: null))); case ServiceKind.slskd: ref.invalidate(slskdDownloadsProvider(i)); ref.invalidate(slskdUploadsProvider(i)); diff --git a/app/lib/src/dashboard/dashboard_widget_kind.dart b/app/lib/src/dashboard/dashboard_widget_kind.dart index 4e4b0bfd..5e4675c9 100644 --- a/app/lib/src/dashboard/dashboard_widget_kind.dart +++ b/app/lib/src/dashboard/dashboard_widget_kind.dart @@ -17,6 +17,7 @@ enum DashboardWidgetKind { adguardHome, wakeOnLan, cleanuparr, + gotify, } extension DashboardWidgetKindX on DashboardWidgetKind { @@ -35,6 +36,7 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.adguardHome => 'AdGuard Home', DashboardWidgetKind.wakeOnLan => 'Wake on LAN', DashboardWidgetKind.cleanuparr => 'Cleanuparr', + DashboardWidgetKind.gotify => 'Gotify', }; IconData get icon => switch (this) { @@ -52,6 +54,7 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.adguardHome => Icons.gpp_good_outlined, DashboardWidgetKind.wakeOnLan => Icons.power_settings_new_rounded, DashboardWidgetKind.cleanuparr => Icons.cleaning_services_outlined, + DashboardWidgetKind.gotify => Icons.notifications_active_outlined, }; /// Service kinds whose presence makes this widget "configured". @@ -108,6 +111,7 @@ extension DashboardWidgetKindX on DashboardWidgetKind { DashboardWidgetKind.cleanuparr => const [ ServiceKind.cleanuparr ], + DashboardWidgetKind.gotify => const [ServiceKind.gotify], // 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/gotify_widget.dart b/app/lib/src/dashboard/widgets/gotify_widget.dart new file mode 100644 index 00000000..2d3c55d4 --- /dev/null +++ b/app/lib/src/dashboard/widgets/gotify_widget.dart @@ -0,0 +1,236 @@ +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:service_gotify/service_gotify.dart'; + +import '../dashboard_widget_card.dart'; +import '../dashboard_widget_kind.dart'; + +/// Compact dashboard widget for Gotify. +/// +/// Shows how many messages are on the server, how many of them are high +/// priority, and the newest message. +class DashboardGotifyWidget extends StatelessWidget { + const DashboardGotifyWidget({ + required this.instances, + super.key, + }); + + final List instances; + + @override + Widget build(BuildContext context) { + final Color accent = ServiceVisuals.accent(ServiceKind.gotify); + + return DashboardWidgetCard( + kind: DashboardWidgetKind.gotify, + accent: accent, + onTap: + instances.length == 1 ? () => _open(context, instances.first) : null, + child: instances.isEmpty + ? const DashboardIdleRow(text: 'No Gotify instances configured') + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (int index = 0; index < instances.length; index++) ...[ + if (index > 0) const Divider(height: Insets.lg), + _GotifyInstanceBlock( + instance: instances[index], + showName: instances.length > 1, + onTap: instances.length > 1 + ? () => _open(context, instances[index]) + : null, + ), + ], + ], + ), + ); + } + + void _open(BuildContext context, Instance instance) { + context.go( + AtriumRoutes.servicePath(instance.kind.name, instance.id), + ); + } +} + +class _GotifyInstanceBlock extends ConsumerWidget { + const _GotifyInstanceBlock({ + required this.instance, + required this.showName, + required this.onTap, + }); + + final Instance instance; + final bool showName; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final ColorScheme colorScheme = Theme.of(context).colorScheme; + final TextTheme textTheme = Theme.of(context).textTheme; + // Unfiltered: an application picked on the Gotify screen is not the card's. + final GotifyFeedKey key = (instance: instance, appId: null); + final AsyncValue feedAsync = + ref.watch(gotifyMessagesProvider(key)); + + final Widget content = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (showName) ...[ + Text( + instance.name, + style: textTheme.labelMedium?.copyWith( + fontWeight: FontWeight.bold, + color: colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: Insets.xs), + ], + feedAsync.when( + skipLoadingOnReload: true, + skipLoadingOnRefresh: true, + loading: () => const Padding( + padding: EdgeInsets.symmetric(vertical: Insets.sm), + child: SizedBox( + height: 20, + width: 20, + child: ExpressiveProgressIndicator(strokeWidth: 2), + ), + ), + error: (err, _) => DashboardErrorRow( + onRetry: () => ref.invalidate(gotifyMessagesProvider(key)), + ), + data: (GotifyMessageFeed feed) => _GotifyContent(feed: feed), + ), + ], + ); + + if (onTap == null) return content; + + return InkWell( + onTap: onTap, + borderRadius: Radii.card, + child: content, + ); + } +} + +class _GotifyContent extends StatelessWidget { + const _GotifyContent({required this.feed}); + + final GotifyMessageFeed feed; + + @override + Widget build(BuildContext context) { + final ColorScheme colorScheme = Theme.of(context).colorScheme; + final TextTheme textTheme = Theme.of(context).textTheme; + final List messages = feed.messages; + + if (messages.isEmpty) { + return const DashboardIdleRow(text: 'No messages'); + } + + final GotifyMessage newest = messages.first; + final int highPriority = messages + .where((GotifyMessage m) => m.level == GotifyPriority.high) + .length; + final String title = newest.title?.trim().isNotEmpty == true + ? newest.title!.trim() + : newest.message; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: Insets.xs, + runSpacing: Insets.xs, + children: [ + _MiniStatPill( + icon: Icons.notifications_outlined, + label: feed.hasMore + ? '${messages.length}+ messages' + : '${messages.length} messages', + color: colorScheme.surfaceContainerHighest, + textColor: colorScheme.onSurfaceVariant, + ), + _MiniStatPill( + icon: Icons.priority_high_rounded, + label: feed.hasMore + ? '$highPriority+ high priority' + : '$highPriority high priority', + color: highPriority > 0 + ? colorScheme.errorContainer + : colorScheme.surfaceContainerHighest, + textColor: highPriority > 0 + ? colorScheme.onErrorContainer + : colorScheme.onSurfaceVariant, + ), + ], + ), + const SizedBox(height: Insets.sm), + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600), + ), + if (newest.date != null) + Text( + gotifyRelativeTime(newest.date!, DateTime.now()), + style: textTheme.bodySmall?.copyWith( + color: colorScheme.onSurfaceVariant, + ), + ), + ], + ); + } +} + +class _MiniStatPill extends StatelessWidget { + const _MiniStatPill({ + required this.icon, + required this.label, + required this.color, + required this.textColor, + }); + + final IconData icon; + final String label; + final Color color; + final Color textColor; + + @override + Widget build(BuildContext context) { + final TextTheme textTheme = Theme.of(context).textTheme; + + return Container( + padding: const EdgeInsets.symmetric( + horizontal: Insets.xs + 2, + vertical: Insets.xxs, + ), + decoration: BoxDecoration( + color: color, + borderRadius: Radii.chip, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 12, color: textColor), + const SizedBox(width: Insets.xxs + 1), + Text( + label, + style: textTheme.labelSmall?.copyWith( + color: textColor, + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ); + } +} diff --git a/app/lib/src/screens/instance_form_screen.dart b/app/lib/src/screens/instance_form_screen.dart index 456e0ca4..0d525850 100644 --- a/app/lib/src/screens/instance_form_screen.dart +++ b/app/lib/src/screens/instance_form_screen.dart @@ -666,7 +666,8 @@ class _InstanceFormScreenState extends ConsumerState { _kind == ServiceKind.dashdot || _kind == ServiceKind.gluetun || _kind == ServiceKind.qbittorrent || - _kind == ServiceKind.slskd) ...[ + _kind == ServiceKind.slskd || + _kind == ServiceKind.gotify) ...[ const SizedBox(height: Insets.md), TextFormField( controller: _pollingInterval, @@ -924,6 +925,26 @@ class _InstanceFormScreenState extends ConsumerState { ), ]; } + if (_kind == ServiceKind.gotify) { + return [ + TextFormField( + controller: _apiKey, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Client token', + helperText: 'Create one under Clients in Gotify. An app ' + 'token can only send messages, not read them.', + helperMaxLines: 2, + ), + obscureText: true, + autocorrect: false, + enableSuggestions: false, + onChanged: _clearConnectionTest, + validator: (String? v) => + (v == null || v.trim().isEmpty) ? 'Required' : null, + ), + ]; + } // Gluetun's control server and slskd can run without auth, through a role with // auth = "none" or SLSKD_NO_AUTH=true, and then there is no key to give. final bool keyOptional = diff --git a/app/lib/src/screens/service_detail_screen.dart b/app/lib/src/screens/service_detail_screen.dart index 7a969b96..9ceb6129 100644 --- a/app/lib/src/screens/service_detail_screen.dart +++ b/app/lib/src/screens/service_detail_screen.dart @@ -18,6 +18,7 @@ import 'package:service_qbittorrent/service_qbittorrent.dart'; import 'package:service_radarr/service_radarr.dart'; import 'package:service_sabnzbd/service_sabnzbd.dart'; import 'package:service_glances/service_glances.dart'; +import 'package:service_gotify/service_gotify.dart'; import 'package:service_beszel/service_beszel.dart'; import 'package:service_sonarr/service_sonarr.dart'; import 'package:service_speedtest_tracker/service_speedtest_tracker.dart'; @@ -416,6 +417,7 @@ class _ServiceDetailScreenState extends ConsumerState { ServiceKind.cleanuparr => const SizedBox.shrink(), // Owns its own scaffold, handled above. ServiceKind.slskd => const SizedBox.shrink(), + ServiceKind.gotify => GotifyHome(instance: instance), }; } } diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 058eeaea..53e61b76 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -48,6 +48,7 @@ dependencies: service_sabnzbd: service_sonarr: service_glances: + service_gotify: service_beszel: service_dashdot: service_speedtest_tracker: diff --git a/app/test/gotify_brand_icon_test.dart b/app/test/gotify_brand_icon_test.dart new file mode 100644 index 00000000..f071f6e0 --- /dev/null +++ b/app/test/gotify_brand_icon_test.dart @@ -0,0 +1,18 @@ +import 'package:core_models/core_models.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Gotify has its own icon in the service picker. +/// +/// The picker loads `assets/service_icons/.png` and falls back to a +/// generic icon when there is none. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('the icon the picker asks for is bundled', () async { + final ByteData icon = await rootBundle + .load('assets/service_icons/${ServiceKind.gotify.name}.png'); + + expect(icon.lengthInBytes, greaterThan(0)); + }); +} diff --git a/app/test/gotify_widget_test.dart b/app/test/gotify_widget_test.dart new file mode 100644 index 00000000..c52b663c --- /dev/null +++ b/app/test/gotify_widget_test.dart @@ -0,0 +1,112 @@ +import 'package:atrium/src/dashboard/widgets/gotify_widget.dart'; +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 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_gotify/service_gotify.dart'; + +const Instance _instance = Instance( + id: 'gotify-1', + name: 'Home Gotify', + kind: ServiceKind.gotify, + localUrl: 'http://gotify.local', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'client-token'), +); + +/// Serves a fixed feed instead of polling a server. +class _FixedFeed extends GotifyMessagesNotifier { + _FixedFeed(super.key, this.feed); + + final GotifyMessageFeed feed; + + @override + Future build() async => feed; +} + +Override _feed(int? appId, GotifyMessageFeed feed) { + final GotifyFeedKey key = (instance: _instance, appId: appId); + return gotifyMessagesProvider(key).overrideWith(() => _FixedFeed(key, feed)); +} + +const GotifyMessageFeed _everything = GotifyMessageFeed( + messages: [ + GotifyMessage(id: 3, appId: 2, title: 'Updated nginx', message: 'ok'), + GotifyMessage(id: 2, appId: 1, message: 'Disk full', priority: 8), + GotifyMessage(id: 1, appId: 1, message: 'Backup done'), + ], + nextSince: 1, +); + +const GotifyMessageFeed _backupsOnly = GotifyMessageFeed( + messages: [ + GotifyMessage(id: 2, appId: 1, message: 'Disk full', priority: 8), + ], +); + +Future _pump(WidgetTester tester, ProviderContainer container) async { + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const Scaffold( + body: DashboardGotifyWidget(instances: [_instance]), + ), + ), + ), + ); + await tester.pump(); + await tester.pump(); +} + +void main() { + testWidgets('shows the message counts and the newest message', + (WidgetTester tester) async { + final ProviderContainer container = ProviderContainer( + overrides: [_feed(null, _everything)], + ); + addTearDown(container.dispose); + await _pump(tester, container); + + expect(find.text('Gotify'), findsOneWidget); + // Only part of the server's messages is loaded. + expect(find.text('3+ messages'), findsOneWidget); + expect(find.text('1+ high priority'), findsOneWidget); + expect(find.text('Updated nginx'), findsOneWidget); + }); + + testWidgets('ignores an application picked on the Gotify screen', + (WidgetTester tester) async { + final ProviderContainer container = ProviderContainer( + overrides: [ + _feed(null, _everything), + _feed(1, _backupsOnly), + ], + ); + addTearDown(container.dispose); + // The screen is still open with Backups picked. + container.listen(gotifySelectedAppProvider(_instance), (_, __) {}); + container.read(gotifySelectedAppProvider(_instance).notifier).state = 1; + + await _pump(tester, container); + + expect(find.text('3+ messages'), findsOneWidget); + expect(find.text('Updated nginx'), findsOneWidget); + expect(find.text('Disk full'), findsNothing); + }); + + testWidgets('says so when there are no messages', + (WidgetTester tester) async { + final ProviderContainer container = ProviderContainer( + overrides: [_feed(null, GotifyMessageFeed.empty)], + ); + addTearDown(container.dispose); + await _pump(tester, container); + + expect(find.text('No messages'), findsOneWidget); + }); +} diff --git a/packages/core_models/lib/src/service_kind.dart b/packages/core_models/lib/src/service_kind.dart index c91a41b9..5ab1bbdf 100644 --- a/packages/core_models/lib/src/service_kind.dart +++ b/packages/core_models/lib/src/service_kind.dart @@ -33,7 +33,8 @@ enum ServiceKind { adguardHome, aria2, cleanuparr, - slskd; + slskd, + gotify; /// All [ServiceKind] entries sorted alphabetically by their display name. static List get sortedValues => @@ -82,6 +83,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.aria2 => 'aria2', ServiceKind.cleanuparr => 'Cleanuparr', ServiceKind.slskd => 'slskd', + ServiceKind.gotify => 'Gotify', }; /// One-line role description. @@ -116,6 +118,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.aria2 => 'Download client', ServiceKind.cleanuparr => 'Malware blocker & cleaner', ServiceKind.slskd => 'Soulseek client', + ServiceKind.gotify => 'Notifications', }; /// Whether this service's integration is still in beta. Surfaced as a @@ -126,7 +129,8 @@ extension ServiceKindX on ServiceKind { ServiceKind.rtorrent || ServiceKind.aria2 || ServiceKind.cleanuparr || - ServiceKind.slskd => + ServiceKind.slskd || + ServiceKind.gotify => true, _ => false, }; @@ -174,6 +178,8 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr => 11011, // slskd default HTTP/API port. ServiceKind.slskd => 5030, + // The port the official Docker image listens on. + ServiceKind.gotify => 80, }; /// What auth flow the service uses by default. Some services (Jellyfin) can @@ -192,7 +198,9 @@ extension ServiceKindX on ServiceKind { ServiceKind.gluetun || ServiceKind.myspeed || ServiceKind.cleanuparr || - ServiceKind.ombi => + ServiceKind.ombi || + // A client token; an application token can only post messages. + ServiceKind.gotify => 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 @@ -258,7 +266,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.gluetun => ServiceRole.analytics, ServiceKind.myspeed => ServiceRole.analytics, ServiceKind.adguardHome => ServiceRole.analytics, - ServiceKind.cleanuparr => ServiceRole.extra, + ServiceKind.cleanuparr || ServiceKind.gotify => ServiceRole.extra, }; /// Whether this service can be handed a torrent - a magnet URI, a link to a diff --git a/packages/core_models/test/service_kind_test.dart b/packages/core_models/test/service_kind_test.dart index 41b3be0b..a4f1e0ec 100644 --- a/packages/core_models/test/service_kind_test.dart +++ b/packages/core_models/test/service_kind_test.dart @@ -39,10 +39,21 @@ void main() { 'aria2', 'cleanuparr', 'slskd', + 'gotify', ], ); }); + test('Gotify is registered as an apiKey extra service', () { + expect(ServiceKind.gotify.displayName, 'Gotify'); + expect(ServiceKind.gotify.tagline, 'Notifications'); + expect(ServiceKind.gotify.isBeta, isTrue); + expect(ServiceKind.gotify.defaultPort, 80); + expect(ServiceKind.gotify.authStyle, AuthStyle.apiKey); + expect(ServiceKind.gotify.role, ServiceRole.extra); + expect(ServiceKind.gotify.acceptsTorrents, isFalse); + }); + test('Ombi is registered as an apiKey request service', () { expect(ServiceKind.ombi.displayName, 'Ombi'); expect(ServiceKind.ombi.tagline, 'Requests'); diff --git a/packages/core_networking/lib/src/auth_interceptor.dart b/packages/core_networking/lib/src/auth_interceptor.dart index 5239d39e..974f2c1d 100644 --- a/packages/core_networking/lib/src/auth_interceptor.dart +++ b/packages/core_networking/lib/src/auth_interceptor.dart @@ -39,6 +39,7 @@ const String anonymousRequestExtra = 'atrium.anonymous'; /// | Navidrome | `?u=` + `?t=` salted MD5 + `?s=` query params | /// | Ombi | `ApiKey` header | /// | aria2 | `token:` as the first RPC parameter | +/// | Gotify | `X-Gotify-Key` header (client token) | /// /// `Jellyfin/Emby` and `qBittorrent` both use the user/password auth flow: /// the session token / cookie is acquired out of band and stored in the @@ -100,6 +101,8 @@ class AuthInterceptor extends Interceptor { if (apiKey.isNotEmpty) { options.headers['X-Api-Key'] = apiKey; } + case ServiceKind.gotify: + options.headers['X-Gotify-Key'] = apiKey; case _: options.headers['X-Api-Key'] = apiKey; } diff --git a/packages/core_networking/lib/src/service_auth_headers.dart b/packages/core_networking/lib/src/service_auth_headers.dart index e072d083..04ab4a1b 100644 --- a/packages/core_networking/lib/src/service_auth_headers.dart +++ b/packages/core_networking/lib/src/service_auth_headers.dart @@ -33,6 +33,8 @@ Set serviceAuthHeaderNames(ServiceKind kind, InstanceAuth auth) { return const {}; case ServiceKind.slskd: return apiKey.isEmpty ? const {} : const {'X-Api-Key'}; + case ServiceKind.gotify: + return const {'X-Gotify-Key'}; case _: return const {'X-Api-Key'}; } diff --git a/packages/core_networking/lib/src/service_health.dart b/packages/core_networking/lib/src/service_health.dart index f1d7a5db..22f963e4 100644 --- a/packages/core_networking/lib/src/service_health.dart +++ b/packages/core_networking/lib/src/service_health.dart @@ -142,6 +142,10 @@ enum _HealthMode { return (path: 'jsonrpc', mode: _HealthMode.authed); case ServiceKind.slskd: return (path: 'api/v0/application', mode: _HealthMode.authed); + case ServiceKind.gotify: + // `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); } } diff --git a/packages/core_networking/test/auth_interceptor_test.dart b/packages/core_networking/test/auth_interceptor_test.dart index fd254f61..8dcdc83c 100644 --- a/packages/core_networking/test/auth_interceptor_test.dart +++ b/packages/core_networking/test/auth_interceptor_test.dart @@ -116,6 +116,27 @@ void main() { expect(request.headers.containsKey('Authorization'), isFalse); }); + test('Gotify client token is sent only as X-Gotify-Key', () async { + const String token = 'placeholder-gotify-client-token'; + final _RecordingAdapter adapter = _RecordingAdapter(); + final Dio dio = Dio(BaseOptions(baseUrl: 'https://gotify.example.test/')) + ..httpClientAdapter = adapter + ..interceptors.add( + const AuthInterceptor( + kind: ServiceKind.gotify, + auth: InstanceAuth.apiKey(apiKey: token), + ), + ); + + await dio.get('message'); + + final RequestOptions request = adapter.request!; + expect(request.headers['X-Gotify-Key'], token); + expect(request.headers.containsKey('X-Api-Key'), isFalse); + expect(request.headers.containsKey('Authorization'), isFalse); + expect(request.uri.toString(), isNot(contains(token))); + }); + test('aria2 sends no auth header at all', () async { // The daemon reads its `--rpc-secret` from the first parameter of every // RPC call, not from a header. A header would hand the secret to every diff --git a/packages/core_ui/lib/src/service_visuals.dart b/packages/core_ui/lib/src/service_visuals.dart index 257791c9..84f2990c 100644 --- a/packages/core_ui/lib/src/service_visuals.dart +++ b/packages/core_ui/lib/src/service_visuals.dart @@ -38,6 +38,7 @@ abstract final class ServiceVisuals { ServiceKind.aria2 => Icons.download_for_offline_outlined, ServiceKind.cleanuparr => Icons.cleaning_services_outlined, ServiceKind.slskd => Icons.library_music_outlined, + ServiceKind.gotify => Icons.notifications_active_outlined, }; static Color accent(ServiceKind kind) => switch (kind) { @@ -71,6 +72,7 @@ abstract final class ServiceVisuals { ServiceKind.aria2 => const Color(0xFF2F6FA8), ServiceKind.cleanuparr => const Color(0xFF7C3AED), ServiceKind.slskd => const Color(0xFF007ACC), + ServiceKind.gotify => const Color(0xFF71CAEE), }; /// Human label for a [ServiceRole] section header. diff --git a/pubspec.yaml b/pubspec.yaml index d5ab2586..a5c7840a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -55,3 +55,4 @@ workspace: - services/service_aria2 - services/service_cleanuparr - services/service_slskd + - services/service_gotify diff --git a/services/service_gotify/lib/service_gotify.dart b/services/service_gotify/lib/service_gotify.dart new file mode 100644 index 00000000..ada0f1f4 --- /dev/null +++ b/services/service_gotify/lib/service_gotify.dart @@ -0,0 +1,5 @@ +export 'src/gotify_api.dart'; +export 'src/gotify_format.dart'; +export 'src/gotify_home.dart'; +export 'src/gotify_providers.dart'; +export 'src/models/gotify_models.dart'; diff --git a/services/service_gotify/lib/src/gotify_api.dart b/services/service_gotify/lib/src/gotify_api.dart new file mode 100644 index 00000000..70ccbfcf --- /dev/null +++ b/services/service_gotify/lib/src/gotify_api.dart @@ -0,0 +1,73 @@ +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; + +import 'models/gotify_models.dart'; + +/// Client for Gotify's REST API, authenticated with a client token +/// (`X-Gotify-Key`, attached by [AuthInterceptor]). +/// +/// An application token can only post messages; every call here needs a +/// client token. +class GotifyApi { + const GotifyApi(this._dio); + + final Dio _dio; + + /// The most messages Gotify returns in one page. + static const int maxPageSize = 200; + + Future _send(Future Function() call) async { + try { + return await call(); + } on DioException catch (e) { + throw NetworkException.fromDio(e); + } + } + + /// `GET application`. + Future> getApplications() => _send(() async { + final Response response = + await _dio.get('application'); + final Object? data = response.data; + if (data is! List) throw const GotifyUnexpectedAnswer(); + return [ + for (final Object? item in data) + if (item is Map) + GotifyApplication.fromJson(item.cast()), + ]; + }); + + /// `GET message`, or `GET application/{appId}/message` for one + /// application. Newest first; [since] returns only messages older than + /// that id. + Future getMessages({ + int? appId, + int limit = 50, + int? since, + }) => + _send(() async { + final Response response = await _dio.get( + appId == null ? 'message' : 'application/$appId/message', + queryParameters: { + 'limit': limit.clamp(1, maxPageSize), + 'since': ?since, + }, + ); + return GotifyMessagePage.fromResponse(response.data); + }); + + /// `DELETE message/{id}`. + Future deleteMessage(int id) => _send(() async { + await _dio.delete('message/$id'); + }); + + /// `DELETE message`: every message of every application. + Future deleteAllMessages() => _send(() async { + await _dio.delete('message'); + }); + + /// `DELETE application/{appId}/message`. + Future deleteApplicationMessages(int appId) => _send(() async { + await _dio.delete('application/$appId/message'); + }); +} diff --git a/services/service_gotify/lib/src/gotify_format.dart b/services/service_gotify/lib/src/gotify_format.dart new file mode 100644 index 00000000..77ffabf9 --- /dev/null +++ b/services/service_gotify/lib/src/gotify_format.dart @@ -0,0 +1,10 @@ +import 'package:intl/intl.dart'; + +/// "just now", "5m ago", "3h ago", then a date such as "Nov 8, 14:05". +String gotifyRelativeTime(DateTime time, DateTime now) { + final Duration age = now.difference(time); + if (age.inMinutes < 1) return 'just now'; + if (age.inHours < 1) return '${age.inMinutes}m ago'; + if (age.inDays < 1) return '${age.inHours}h ago'; + return DateFormat.MMMd().add_Hm().format(time); +} diff --git a/services/service_gotify/lib/src/gotify_home.dart b/services/service_gotify/lib/src/gotify_home.dart new file mode 100644 index 00000000..2909e0d6 --- /dev/null +++ b/services/service_gotify/lib/src/gotify_home.dart @@ -0,0 +1,341 @@ +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'gotify_format.dart'; +import 'gotify_providers.dart'; +import 'models/gotify_models.dart'; + +/// Gotify's messages, filterable by application, with swipe to delete and +/// clearing. Rendered inside the app's generic service scaffold. +class GotifyHome extends ConsumerStatefulWidget { + const GotifyHome({required this.instance, super.key}); + + final Instance instance; + + @override + ConsumerState createState() => _GotifyHomeState(); +} + +class _GotifyHomeState extends ConsumerState { + bool _loadingOlder = false; + + Instance get _instance => widget.instance; + + /// The feed for the application currently picked on this screen. + GotifyFeedKey get _feedKey => ( + instance: _instance, + appId: ref.read(gotifySelectedAppProvider(_instance)), + ); + + Future _refresh() async { + ref.invalidate(gotifyApplicationsProvider(_instance)); + final GotifyFeedKey key = _feedKey; + ref.invalidate(gotifyMessagesProvider(key)); + try { + await ref.read(gotifyMessagesProvider(key).future); + } on Object { + // Shown by the list's error view. + } + } + + void _showError(Object error) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(_describe(error)), + backgroundColor: Theme.of(context).colorScheme.error, + ), + ); + } + + Future _delete(GotifyMessage message) async { + try { + await ref.read(gotifyMessagesProvider(_feedKey).notifier).delete( + message.id, + ); + } on Object catch (e) { + _showError(e); + } + } + + Future _loadOlder() async { + setState(() => _loadingOlder = true); + try { + await ref.read(gotifyMessagesProvider(_feedKey).notifier).loadOlder(); + } on Object catch (e) { + _showError(e); + } finally { + if (mounted) setState(() => _loadingOlder = false); + } + } + + Future _clear(String scope) async { + final bool? confirmed = await showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: const Text('Delete messages?'), + content: Text('Every message from $scope is deleted from the server. ' + 'This cannot be undone.'), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of(context).pop(true), + child: const Text('Delete'), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + try { + await ref.read(gotifyMessagesProvider(_feedKey).notifier).clear(); + } on Object catch (e) { + _showError(e); + } + } + + @override + Widget build(BuildContext context) { + final List apps = + ref.watch(gotifyApplicationsProvider(_instance)).value ?? + const []; + final Map appsById = { + for (final GotifyApplication a in apps) a.id: a, + }; + final int? selected = ref.watch(gotifySelectedAppProvider(_instance)); + final AsyncValue feed = ref.watch( + gotifyMessagesProvider((instance: _instance, appId: selected)), + ); + final bool hasMessages = feed.value?.messages.isNotEmpty ?? false; + + return Column( + children: [ + SizedBox( + height: 56, + child: Row( + children: [ + Expanded( + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric( + horizontal: Insets.lg, + vertical: Insets.sm, + ), + children: [ + _AppChip( + label: 'All', + selected: selected == null, + onSelected: () => ref + .read(gotifySelectedAppProvider(_instance).notifier) + .state = null, + ), + for (final GotifyApplication app in apps) + _AppChip( + label: app.name, + selected: selected == app.id, + onSelected: () => ref + .read( + gotifySelectedAppProvider(_instance).notifier, + ) + .state = app.id, + ), + ], + ), + ), + IconButton( + tooltip: 'Delete all shown', + icon: const Icon(Icons.delete_sweep_outlined), + onPressed: hasMessages + ? () => _clear( + selected == null + ? 'every application' + : appsById[selected]?.name ?? 'this application', + ) + : null, + ), + const SizedBox(width: Insets.xs), + ], + ), + ), + Expanded( + child: AsyncValueView( + value: feed, + onRetry: _refresh, + data: (GotifyMessageFeed data) => EasyRefresh( + onRefresh: _refresh, + child: data.messages.isEmpty + ? ListView( + children: const [ + SizedBox(height: 120), + EmptyView( + icon: Icons.notifications_none_outlined, + title: 'No messages', + message: 'New notifications show up here.', + ), + ], + ) + : ListView.builder( + padding: const EdgeInsets.fromLTRB( + Insets.lg, + 0, + Insets.lg, + Insets.xl, + ), + itemCount: data.messages.length + (data.hasMore ? 1 : 0), + itemBuilder: (BuildContext context, int index) { + if (index == data.messages.length) { + return Padding( + padding: const EdgeInsets.only(top: Insets.sm), + child: Center( + child: _loadingOlder + ? const ExpressiveProgressIndicator() + : TextButton.icon( + onPressed: _loadOlder, + icon: const Icon(Icons.expand_more), + label: const Text('Load older'), + ), + ), + ); + } + final GotifyMessage message = data.messages[index]; + return Dismissible( + key: ValueKey(message.id), + direction: DismissDirection.endToStart, + background: const _DeleteBackground(), + onDismissed: (_) => _delete(message), + child: GotifyMessageCard( + message: message, + appName: appsById[message.appId]?.name, + ), + ); + }, + ), + ), + ), + ), + ], + ); + } +} + +class _AppChip extends StatelessWidget { + const _AppChip({ + required this.label, + required this.selected, + required this.onSelected, + }); + + final String label; + final bool selected; + final VoidCallback onSelected; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.only(right: Insets.sm), + child: ChoiceChip( + label: Text(label), + selected: selected, + onSelected: (_) => onSelected(), + ), + ); +} + +class _DeleteBackground extends StatelessWidget { + const _DeleteBackground(); + + @override + Widget build(BuildContext context) { + final ColorScheme scheme = Theme.of(context).colorScheme; + return Container( + margin: const EdgeInsets.symmetric(vertical: Insets.xs), + decoration: BoxDecoration( + color: scheme.errorContainer, + borderRadius: Radii.card, + ), + alignment: Alignment.centerRight, + padding: const EdgeInsets.symmetric(horizontal: Insets.lg), + child: Icon(Icons.delete_outline, color: scheme.onErrorContainer), + ); + } +} + +/// One message: application, title, age, priority and the full text. +class GotifyMessageCard extends StatelessWidget { + const GotifyMessageCard({required this.message, this.appName, super.key}); + + final GotifyMessage message; + final String? appName; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + final ColorScheme scheme = theme.colorScheme; + final Color accent = switch (message.level) { + GotifyPriority.high => scheme.error, + GotifyPriority.normal => scheme.primary, + GotifyPriority.low => scheme.outline, + }; + final String source = appName ?? 'Application ${message.appId}'; + final DateTime? date = message.date; + return Card( + margin: const EdgeInsets.symmetric(vertical: Insets.xs), + child: Padding( + padding: const EdgeInsets.all(Insets.md), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 14, + backgroundColor: accent.withValues(alpha: 0.15), + child: Text( + source.characters.first.toUpperCase(), + style: theme.textTheme.labelLarge?.copyWith(color: accent), + ), + ), + const SizedBox(width: Insets.sm), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + message.title ?? source, + style: theme.textTheme.titleSmall, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + Text( + [ + if (message.title != null) source, + if (date != null) + gotifyRelativeTime(date, DateTime.now()), + ].join(' ยท '), + style: theme.textTheme.bodySmall + ?.copyWith(color: scheme.outline), + ), + ], + ), + ), + if (message.level == GotifyPriority.high) + Icon(Icons.priority_high_rounded, size: 18, color: accent), + ], + ), + if (message.message.isNotEmpty) ...[ + const SizedBox(height: Insets.sm), + SelectableText(message.message, style: theme.textTheme.bodyMedium), + ], + ], + ), + ), + ); + } +} + +String _describe(Object error) => + error is NetworkException ? error.message : error.toString(); diff --git a/services/service_gotify/lib/src/gotify_providers.dart b/services/service_gotify/lib/src/gotify_providers.dart new file mode 100644 index 00000000..5e4ea184 --- /dev/null +++ b/services/service_gotify/lib/src/gotify_providers.dart @@ -0,0 +1,190 @@ +import 'dart:async'; + +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/legacy.dart'; + +import 'gotify_api.dart'; +import 'models/gotify_models.dart'; + +final gotifyApiProvider = + FutureProvider.autoDispose.family( + (Ref ref, Instance instance) async { + final Dio dio = await ref.watch(instanceDioProvider(instance).future); + return GotifyApi(dio); + }, + retry: (int _, Object _) => null, +); + +final gotifyApplicationsProvider = + FutureProvider.autoDispose.family, Instance>( + (Ref ref, Instance instance) async { + final GotifyApi api = await ref.watch(gotifyApiProvider(instance).future); + return api.getApplications(); + }, + retry: (int _, Object _) => null, +); + +/// The application the screen's message list is filtered to, or null for all. +final gotifySelectedAppProvider = + StateProvider.autoDispose.family((Ref ref, Instance _) { + return null; +}); + +/// Which messages a feed holds: every application's when [appId] is null, +/// otherwise that one application's. +/// +/// Part of the key rather than read from [gotifySelectedAppProvider], so the +/// dashboard's unfiltered feed never picks up a filter chosen on the screen. +typedef GotifyFeedKey = ({Instance instance, int? appId}); + +/// The message list, kept across polls and "load older". +/// +/// Not a polled FutureProvider: rebuilding on every tick would throw away the +/// older pages the user has loaded. A timer fetches the newest page instead +/// and merges it; see [GotifyMessageFeed.mergeNewest]. +class GotifyMessagesNotifier extends AsyncNotifier { + GotifyMessagesNotifier(this.key); + + final GotifyFeedKey key; + + Instance get instance => key.instance; + + static const int pageSize = 50; + + /// Failed polls in a row cap out at skipping 31 ticks between tries. + static const int _maxBackoffShift = 5; + + bool _syncing = false; + int _failures = 0; + int _ticksToSkip = 0; + + /// Counts deletes and clears, before and after each reaches the server. A + /// poll that overlapped one fetched the list as it was, so its page would + /// put deleted messages back; it is dropped and the next tick fetches again. + int _edits = 0; + + /// Deletes and clears still waiting on the server. No poll starts while + /// one is: the server may still hold what was deleted, and the counter + /// above does not move until the request is done. + int _pendingEdits = 0; + + @override + Future build() async { + final Timer timer = Timer.periodic( + Duration(seconds: instance.pollingIntervalSeconds.clamp(1, 3600)), + (_) => _tick(), + ); + ref.onDispose(timer.cancel); + + final GotifyApi api = await ref.watch(gotifyApiProvider(instance).future); + return GotifyMessageFeed.fromPage( + await api.getMessages(appId: key.appId), + ); + } + + void _tick() { + if (_ticksToSkip > 0) { + _ticksToSkip--; + return; + } + final AppLifecycleState? lifecycle = + SchedulerBinding.instance.lifecycleState; + if (lifecycle == null || lifecycle == AppLifecycleState.resumed) { + unawaited(sync()); + } + } + + /// Folds the newest page into what is on screen. A failure leaves the list + /// as it is and backs off: a wrong token or a server that is down is tried + /// again after 1, 3, 7, ... skipped ticks rather than on every one. + Future sync() async { + if (_syncing || _pendingEdits > 0 || state.value == null) return; + _syncing = true; + final int edits = _edits; + try { + final GotifyApi api = await ref.read(gotifyApiProvider(instance).future); + final GotifyMessagePage page = + await api.getMessages(appId: key.appId); + _failures = 0; + _ticksToSkip = 0; + if (!ref.mounted || edits != _edits) return; + final GotifyMessageFeed? current = state.value; + if (current == null) return; + state = AsyncData( + current.mergeNewest(page, pageSize), + ); + } on Object { + if (_failures < _maxBackoffShift) _failures++; + _ticksToSkip = (1 << _failures) - 1; + } finally { + _syncing = false; + } + } + + /// Fetches the next, older page. + Future loadOlder() async { + final GotifyMessageFeed? current = state.value; + if (current == null || !current.hasMore) return; + final GotifyApi api = await ref.read(gotifyApiProvider(instance).future); + final GotifyMessagePage page = await api.getMessages( + appId: key.appId, + since: current.nextSince, + ); + if (!ref.mounted) return; + state = AsyncData( + (state.value ?? current).appendOlder(page), + ); + } + + /// Removes the message at once (a dismissed tile must leave the tree), then + /// asks the server. A refusal reloads the list and rethrows. + Future delete(int id) async { + _edits++; + _pendingEdits++; + final GotifyMessageFeed? current = state.value; + if (current != null) { + state = AsyncData(current.without(id)); + } + try { + final GotifyApi api = await ref.read(gotifyApiProvider(instance).future); + await api.deleteMessage(id); + } on Object { + if (ref.mounted) ref.invalidateSelf(); + rethrow; + } finally { + _edits++; + _pendingEdits--; + } + } + + /// Deletes every message, or every message of this feed's application. + Future clear() async { + _edits++; + _pendingEdits++; + final int? appId = key.appId; + try { + final GotifyApi api = await ref.read(gotifyApiProvider(instance).future); + if (appId == null) { + await api.deleteAllMessages(); + } else { + await api.deleteApplicationMessages(appId); + } + } finally { + _edits++; + _pendingEdits--; + } + if (ref.mounted) { + state = const AsyncData(GotifyMessageFeed.empty); + } + } +} + +final gotifyMessagesProvider = AsyncNotifierProvider.autoDispose + .family( + GotifyMessagesNotifier.new, + retry: (int _, Object _) => null, +); diff --git a/services/service_gotify/lib/src/models/gotify_models.dart b/services/service_gotify/lib/src/models/gotify_models.dart new file mode 100644 index 00000000..c35b428e --- /dev/null +++ b/services/service_gotify/lib/src/models/gotify_models.dart @@ -0,0 +1,189 @@ +/// Something answered, but not with Gotify's JSON: another server, a +/// reverse proxy's sign-in page, or a wrong base path. +class GotifyUnexpectedAnswer implements Exception { + const GotifyUnexpectedAnswer(); + + String get message => + 'Something other than Gotify answered at this address. Check the URL ' + 'and any reverse proxy in front of it.'; + + @override + String toString() => message; +} + +int? _int(Object? value) => switch (value) { + final int v => v, + final num v => v.toInt(), + final String v => int.tryParse(v), + _ => null, + }; + +String? _text(Object? value) { + if (value is! String) return null; + final String trimmed = value.trim(); + return trimmed.isEmpty ? null : trimmed; +} + +DateTime? _date(Object? value) => + value is String ? DateTime.tryParse(value)?.toLocal() : null; + +/// An application registered on the server: the sender of messages. +class GotifyApplication { + const GotifyApplication({ + required this.id, + required this.name, + this.description, + this.defaultPriority = 0, + this.internal = false, + this.lastUsed, + }); + + factory GotifyApplication.fromJson(Map json) => + GotifyApplication( + id: _int(json['id']) ?? 0, + name: _text(json['name']) ?? 'Application', + description: _text(json['description']), + defaultPriority: _int(json['defaultPriority']) ?? 0, + internal: json['internal'] == true, + lastUsed: _date(json['lastUsed']), + ); + + final int id; + final String name; + final String? description; + final int defaultPriority; + + /// Created by a Gotify plugin rather than by a user. + final bool internal; + final DateTime? lastUsed; +} + +/// How Gotify's own clients group the 0-10 priority scale. +enum GotifyPriority { low, normal, high } + +class GotifyMessage { + const GotifyMessage({ + required this.id, + required this.appId, + required this.message, + this.title, + this.priority = 0, + this.date, + }); + + factory GotifyMessage.fromJson(Map json) => GotifyMessage( + id: _int(json['id']) ?? 0, + appId: _int(json['appid']) ?? 0, + message: json['message'] is String ? json['message'] as String : '', + title: _text(json['title']), + priority: _int(json['priority']) ?? 0, + date: _date(json['date']), + ); + + final int id; + final int appId; + final String message; + final String? title; + final int priority; + final DateTime? date; + + GotifyPriority get level => priority >= 8 + ? GotifyPriority.high + : priority >= 4 + ? GotifyPriority.normal + : GotifyPriority.low; +} + +/// One page of `GET message` or `GET application/{id}/message`. +class GotifyMessagePage { + const GotifyMessagePage({required this.messages, this.nextSince}); + + /// Reads `{messages: [...], paging: {since, next, ...}}`. Gotify only sets + /// `paging.next` while older messages remain, and `paging.since` is the + /// value to pass as `since` to fetch them. + factory GotifyMessagePage.fromResponse(Object? data) { + if (data is! Map) throw const GotifyUnexpectedAnswer(); + final Object? list = data['messages']; + if (list is! List) throw const GotifyUnexpectedAnswer(); + final Object? paging = data['paging']; + final int? since = paging is Map && paging['next'] != null + ? _int(paging['since']) + : null; + return GotifyMessagePage( + messages: [ + for (final Object? item in list) + if (item is Map) GotifyMessage.fromJson(item.cast()), + ], + nextSince: since != null && since > 0 ? since : null, + ); + } + + final List messages; + + /// The `since` for the next, older page, or null when there is none. + final int? nextSince; +} + +/// The messages on screen: possibly several pages, newest first. +class GotifyMessageFeed { + const GotifyMessageFeed({required this.messages, this.nextSince}); + + factory GotifyMessageFeed.fromPage(GotifyMessagePage page) => + GotifyMessageFeed(messages: page.messages, nextSince: page.nextSince); + + static const GotifyMessageFeed empty = + GotifyMessageFeed(messages: []); + + final List messages; + final int? nextSince; + + bool get hasMore => nextSince != null; + + /// Folds a freshly fetched newest page of [pageSize] into this feed. + /// + /// With no more than one page loaded, or when the server has nothing older + /// than the fresh page, the fresh page simply replaces the feed. With older + /// pages loaded, the fresh page is authoritative for its own range: loaded + /// messages in that range it no longer has were deleted elsewhere and are + /// dropped, while the older tail the user scrolled to is kept. If the whole + /// fresh page is newer than anything loaded, messages may be missing in + /// between, so the feed starts over from the fresh page. + GotifyMessageFeed mergeNewest(GotifyMessagePage newest, int pageSize) { + if (messages.length <= pageSize || + newest.messages.isEmpty || + newest.nextSince == null) { + return GotifyMessageFeed.fromPage(newest); + } + final int floor = newest.messages.last.id; + if (floor > messages.first.id) return GotifyMessageFeed.fromPage(newest); + final List tail = [ + for (final GotifyMessage m in messages) + if (m.id < floor) m, + ]; + return GotifyMessageFeed( + messages: [...newest.messages, ...tail], + nextSince: tail.isEmpty ? newest.nextSince : nextSince, + ); + } + + /// Appends an older [page], skipping any message already shown. + GotifyMessageFeed appendOlder(GotifyMessagePage page) { + final Set seen = {for (final GotifyMessage m in messages) m.id}; + return GotifyMessageFeed( + messages: [ + ...messages, + for (final GotifyMessage m in page.messages) + if (!seen.contains(m.id)) m, + ], + nextSince: page.nextSince, + ); + } + + GotifyMessageFeed without(int id) => GotifyMessageFeed( + messages: [ + for (final GotifyMessage m in messages) + if (m.id != id) m, + ], + nextSince: nextSince, + ); +} diff --git a/services/service_gotify/pubspec.yaml b/services/service_gotify/pubspec.yaml new file mode 100644 index 00000000..2cd2b246 --- /dev/null +++ b/services/service_gotify/pubspec.yaml @@ -0,0 +1,23 @@ +name: service_gotify +description: Gotify notification server API client and UI screens for Atrium. +publish_to: none +resolution: workspace + +environment: + sdk: ^3.8.0 + flutter: ^3.27.0 + +dependencies: + core_models: + core_networking: + core_ui: + dio: ^5.7.0 + flutter: + sdk: flutter + flutter_riverpod: ^3.3.2 + intl: ^0.20.2 + +dev_dependencies: + flutter_lints: ^6.0.0 + flutter_test: + sdk: flutter diff --git a/services/service_gotify/test/gotify_api_test.dart b/services/service_gotify/test/gotify_api_test.dart new file mode 100644 index 00000000..0ebf7f47 --- /dev/null +++ b/services/service_gotify/test/gotify_api_test.dart @@ -0,0 +1,176 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_networking/core_networking.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_gotify/service_gotify.dart'; + +void main() { + late _Adapter adapter; + late GotifyApi api; + + void serve(Object? body, {int status = 200, String? contentType}) { + adapter = _Adapter( + (RequestOptions _) => ResponseBody.fromString( + body is String ? body : jsonEncode(body), + status, + headers: >{ + Headers.contentTypeHeader: [ + contentType ?? Headers.jsonContentType, + ], + }, + ), + ); + api = GotifyApi( + Dio(BaseOptions(baseUrl: 'http://gotify.test/')) + ..httpClientAdapter = adapter, + ); + } + + final Map page = { + 'messages': >[ + { + 'id': 25, + 'appid': 5, + 'message': 'Backup finished', + 'title': 'Backup', + 'priority': 8, + 'date': '2026-11-08T10:00:00Z', + }, + { + 'id': 24, + 'appid': 6, + 'message': 'Disk 80% full', + 'title': '', + 'priority': 2, + 'date': '2026-11-08T09:00:00Z', + }, + ], + 'paging': { + 'size': 2, + 'since': 24, + 'limit': 2, + 'next': 'http://gotify.test/message?limit=2&since=24', + }, + }; + + test('reads a page of messages and where the next one starts', () async { + serve(page); + final GotifyMessagePage result = await api.getMessages(limit: 2); + + expect(adapter.requests.single.path, 'message'); + expect(adapter.requests.single.queryParameters, { + 'limit': 2, + }); + expect(result.messages.map((GotifyMessage m) => m.id), [25, 24]); + expect(result.messages.first.title, 'Backup'); + expect(result.messages.first.level, GotifyPriority.high); + expect(result.messages.last.title, isNull); + expect(result.messages.last.level, GotifyPriority.low); + expect( + result.messages.first.date!.isAtSameMomentAs(DateTime.utc(2026, 11, 8, 10)), + isTrue, + ); + expect(result.nextSince, 24); + }); + + test('the last page has no next', () async { + serve({ + 'messages': [], + 'paging': {'size': 0, 'since': 0, 'limit': 50}, + }); + expect((await api.getMessages()).nextSince, isNull); + }); + + test('one application and an older page use their own path and since', + () async { + serve(page); + await api.getMessages(appId: 5, since: 24, limit: 999); + + final RequestOptions request = adapter.requests.single; + expect(request.path, 'application/5/message'); + expect(request.queryParameters, { + 'limit': GotifyApi.maxPageSize, + 'since': 24, + }); + }); + + test('applications are listed', () async { + serve(>[ + { + 'id': 5, + 'token': 'AWx-secret', + 'name': 'Backups', + 'description': 'Nightly', + 'internal': false, + 'defaultPriority': 4, + }, + ]); + final List apps = await api.getApplications(); + + expect(adapter.requests.single.path, 'application'); + expect(apps.single.name, 'Backups'); + expect(apps.single.defaultPriority, 4); + }); + + test('deletes go to the right routes', () async { + serve(null); + await api.deleteMessage(25); + await api.deleteApplicationMessages(5); + await api.deleteAllMessages(); + + expect( + adapter.requests.map((RequestOptions r) => '${r.method} ${r.path}'), + [ + 'DELETE message/25', + 'DELETE application/5/message', + 'DELETE message', + ], + ); + }); + + test('a login page instead of the API is reported as such', () async { + serve('Sign in', contentType: 'text/html'); + await expectLater( + api.getMessages(), + throwsA(isA()), + ); + }); + + test('a refused token becomes an auth error with Gotify\'s reason', + () async { + serve( + { + 'error': 'Unauthorized', + 'errorCode': 401, + 'errorDescription': 'you need to provide a valid access token', + }, + status: 401, + ); + await expectLater( + api.getApplications(), + throwsA(isA()), + ); + }); +} + +class _Adapter implements HttpClientAdapter { + _Adapter(this.handler); + + final ResponseBody Function(RequestOptions) handler; + final List requests = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + return handler(options); + } + + @override + void close({bool force = false}) {} +} diff --git a/services/service_gotify/test/gotify_delete_race_test.dart b/services/service_gotify/test/gotify_delete_race_test.dart new file mode 100644 index 00000000..d106c8fa --- /dev/null +++ b/services/service_gotify/test/gotify_delete_race_test.dart @@ -0,0 +1,145 @@ +import 'dart:async'; + +import 'package:core_models/core_models.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_gotify/service_gotify.dart'; + +const Instance _instance = Instance( + id: 'gotify-1', + name: 'Home Gotify', + kind: ServiceKind.gotify, + localUrl: 'http://gotify.local', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'client-token'), +); + +GotifyMessage _m(int id) => GotifyMessage(id: id, appId: 1, message: '$id'); + +/// A server holding messages 3, 2 and 1. Every fetch after the first waits +/// for [release], so a poll can be caught in flight, and deletes wait for +/// [holdDeletes] when it is set, so a delete can be caught in flight too. +class _HeldApi extends GotifyApi { + _HeldApi() : super(Dio()); + + int fetches = 0; + final Completer release = Completer(); + final List deleted = []; + Completer? holdDeletes; + + @override + Future getMessages({ + int? appId, + int limit = 50, + int? since, + }) async { + if (fetches++ > 0) await release.future; + return GotifyMessagePage(messages: [_m(3), _m(2), _m(1)]); + } + + @override + Future deleteMessage(int id) async { + await holdDeletes?.future; + deleted.add(id); + } + + @override + Future deleteAllMessages() async => holdDeletes?.future; +} + +List _ids(GotifyMessageFeed? feed) => + feed!.messages.map((GotifyMessage m) => m.id).toList(); + +void main() { + const GotifyFeedKey key = (instance: _instance, appId: null); + + late _HeldApi api; + late ProviderContainer container; + + setUp(() async { + api = _HeldApi(); + container = ProviderContainer( + overrides: [ + gotifyApiProvider(_instance).overrideWith((Ref ref) async => api), + ], + ); + container.listen(gotifyMessagesProvider(key), (_, _) {}); + await container.read(gotifyMessagesProvider(key).future); + }); + + tearDown(() => container.dispose()); + + test('a poll that began before a delete does not bring the message back', + () async { + final GotifyMessagesNotifier feed = + container.read(gotifyMessagesProvider(key).notifier); + + final Future poll = feed.sync(); + await feed.delete(2); + api.release.complete(); + await poll; + + expect(api.deleted, [2]); + expect(_ids(container.read(gotifyMessagesProvider(key)).value), [3, 1]); + }); + + test('a poll that began before clearing does not refill the list', () async { + final GotifyMessagesNotifier feed = + container.read(gotifyMessagesProvider(key).notifier); + + final Future poll = feed.sync(); + await feed.clear(); + api.release.complete(); + await poll; + + expect(_ids(container.read(gotifyMessagesProvider(key)).value), isEmpty); + }); + + test('a poll that runs while a delete is in flight does not land', + () async { + final GotifyMessagesNotifier feed = + container.read(gotifyMessagesProvider(key).notifier); + api.release.complete(); + api.holdDeletes = Completer(); + + final Future deleting = feed.delete(2); + await feed.sync(); + api.holdDeletes!.complete(); + await deleting; + + expect(_ids(container.read(gotifyMessagesProvider(key)).value), [3, 1]); + }); + + test('a poll that runs while a clear is in flight does not land', () async { + final GotifyMessagesNotifier feed = + container.read(gotifyMessagesProvider(key).notifier); + api.release.complete(); + api.holdDeletes = Completer(); + + final Future clearing = feed.clear(); + final int fetchesBefore = api.fetches; + await feed.sync(); + expect(api.fetches, fetchesBefore); + api.holdDeletes!.complete(); + await clearing; + + expect(_ids(container.read(gotifyMessagesProvider(key)).value), isEmpty); + }); + + test('a poll with no delete during it still lands', () async { + final GotifyMessagesNotifier feed = + container.read(gotifyMessagesProvider(key).notifier); + await feed.delete(2); + + final Future poll = feed.sync(); + api.release.complete(); + await poll; + + // The fake server never forgets 2, so a poll that started after the + // delete shows it again: the guard only discards polls that overlap. + expect(_ids(container.read(gotifyMessagesProvider(key)).value), + [3, 2, 1]); + }); +} diff --git a/services/service_gotify/test/gotify_feed_test.dart b/services/service_gotify/test/gotify_feed_test.dart new file mode 100644 index 00000000..345c4cc0 --- /dev/null +++ b/services/service_gotify/test/gotify_feed_test.dart @@ -0,0 +1,123 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_gotify/service_gotify.dart'; + +GotifyMessage _m(int id) => GotifyMessage(id: id, appId: 1, message: '$id'); + +List _ids(GotifyMessageFeed feed) => + feed.messages.map((GotifyMessage m) => m.id).toList(); + +void main() { + group('mergeNewest', () { + test('with one page loaded, the fresh page replaces it', () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(5), _m(4), _m(3)], + nextSince: 3, + ); + final GotifyMessageFeed merged = feed.mergeNewest( + GotifyMessagePage(messages: [_m(6), _m(5), _m(3)]), + 3, + ); + // 4 was deleted elsewhere and is gone; there is no next page any more. + expect(_ids(merged), [6, 5, 3]); + expect(merged.hasMore, isFalse); + }); + + test('with older pages loaded, only newer messages are prepended', () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(5), _m(4), _m(3), _m(2)], + nextSince: 2, + ); + final GotifyMessageFeed merged = feed.mergeNewest( + GotifyMessagePage( + messages: [_m(6), _m(5)], + nextSince: 5, + ), + 2, + ); + expect(_ids(merged), [6, 5, 4, 3, 2]); + expect(merged.nextSince, 2); + }); + + test('with older pages loaded, deletions in the fresh range are dropped', + () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(6), _m(5), _m(4), _m(3), _m(2)], + nextSince: 2, + ); + final GotifyMessageFeed merged = feed.mergeNewest( + // 6 and 4 were deleted elsewhere; the older tail is kept. + GotifyMessagePage( + messages: [_m(7), _m(5), _m(3)], + nextSince: 3, + ), + 3, + ); + expect(_ids(merged), [7, 5, 3, 2]); + expect(merged.nextSince, 2); + }); + + test('when the fresh page covers everything loaded, its paging is used', + () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(6), _m(5), _m(4)], + nextSince: 4, + ); + final GotifyMessageFeed merged = feed.mergeNewest( + GotifyMessagePage( + messages: [_m(6), _m(4)], + nextSince: 4, + ), + 2, + ); + expect(_ids(merged), [6, 4]); + expect(merged.nextSince, 4); + }); + + test('a whole fresh page with more behind it starts over', () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(3), _m(2), _m(1)], + ); + final GotifyMessageFeed merged = feed.mergeNewest( + GotifyMessagePage( + messages: [_m(9), _m(8)], + nextSince: 8, + ), + 2, + ); + expect(_ids(merged), [9, 8]); + expect(merged.nextSince, 8); + }); + }); + + test('appendOlder skips messages already shown', () { + final GotifyMessageFeed feed = GotifyMessageFeed( + messages: [_m(5), _m(4)], + nextSince: 4, + ); + final GotifyMessageFeed next = feed.appendOlder( + GotifyMessagePage(messages: [_m(4), _m(3)]), + ); + expect(_ids(next), [5, 4, 3]); + expect(next.hasMore, isFalse); + }); + + test('without drops one message', () { + final GotifyMessageFeed feed = + GotifyMessageFeed(messages: [_m(2), _m(1)]); + expect(_ids(feed.without(2)), [1]); + }); + + test('relative time', () { + final DateTime now = DateTime(2026, 11, 8, 12); + expect(gotifyRelativeTime(now, now), 'just now'); + expect( + gotifyRelativeTime(now.subtract(const Duration(minutes: 5)), now), + '5m ago', + ); + expect( + gotifyRelativeTime(now.subtract(const Duration(hours: 3)), now), + '3h ago', + ); + expect(gotifyRelativeTime(DateTime(2026, 11, 1, 14, 5), now), 'Nov 1 14:05'); + }); +} diff --git a/services/service_gotify/test/gotify_home_test.dart b/services/service_gotify/test/gotify_home_test.dart new file mode 100644 index 00000000..aa92831d --- /dev/null +++ b/services/service_gotify/test/gotify_home_test.dart @@ -0,0 +1,117 @@ +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 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:service_gotify/service_gotify.dart'; + +const Instance _instance = Instance( + id: 'gotify-1', + name: 'Home Gotify', + kind: ServiceKind.gotify, + localUrl: 'http://gotify.local', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'client-token'), +); + +const List _apps = [ + GotifyApplication(id: 1, name: 'Backups'), + GotifyApplication(id: 2, name: 'Watchtower'), +]; + +/// Serves a fixed feed instead of polling a server. +class _FixedFeed extends GotifyMessagesNotifier { + _FixedFeed(super.key, this.feed); + + final GotifyMessageFeed feed; + + @override + Future build() async => feed; +} + +Override _feed(int? appId, GotifyMessageFeed feed) { + final GotifyFeedKey key = (instance: _instance, appId: appId); + return gotifyMessagesProvider(key).overrideWith(() => _FixedFeed(key, feed)); +} + +Future _pump(WidgetTester tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + gotifyApplicationsProvider(_instance).overrideWith((Ref ref) async => _apps), + _feed( + null, + const GotifyMessageFeed( + messages: [ + GotifyMessage( + id: 3, + appId: 2, + title: 'Updated nginx', + message: 'nginx:1.27 is running', + ), + GotifyMessage( + id: 2, + appId: 1, + title: 'Backup failed', + message: 'Disk full', + priority: 8, + ), + ], + nextSince: 2, + ), + ), + _feed( + 1, + const GotifyMessageFeed( + messages: [ + GotifyMessage( + id: 2, + appId: 1, + title: 'Backup failed', + message: 'Disk full', + priority: 8, + ), + ], + ), + ), + ], + child: MaterialApp( + theme: AtriumTheme.light(null), + home: const Scaffold(body: GotifyHome(instance: _instance)), + ), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('lists every application\'s messages with their sender', + (WidgetTester tester) async { + await _pump(tester); + + expect(find.widgetWithText(ChoiceChip, 'All'), findsOneWidget); + expect(find.widgetWithText(ChoiceChip, 'Backups'), findsOneWidget); + expect(find.text('Updated nginx'), findsOneWidget); + expect(find.text('Backup failed'), findsOneWidget); + // Once on its chip, once under its message. + expect(find.text('Watchtower'), findsNWidgets(2)); + expect(find.text('Backups'), findsNWidgets(2)); + expect(find.byIcon(Icons.priority_high_rounded), findsOneWidget); + // More is on the server. + expect(find.text('Load older'), findsOneWidget); + }); + + testWidgets('picking an application shows only its messages', + (WidgetTester tester) async { + await _pump(tester); + + await tester.tap(find.widgetWithText(ChoiceChip, 'Backups')); + await tester.pumpAndSettle(); + + expect(find.text('Backup failed'), findsOneWidget); + expect(find.text('Updated nginx'), findsNothing); + expect(find.text('Load older'), findsNothing); + }); +}