diff --git a/app/lib/notifications/background_check.dart b/app/lib/notifications/background_check.dart index 4a80977..536078b 100644 --- a/app/lib/notifications/background_check.dart +++ b/app/lib/notifications/background_check.dart @@ -5,7 +5,9 @@ import 'package:shared_preferences/shared_preferences.dart'; import 'package:workmanager/workmanager.dart'; import 'package:pala/api/client.dart'; import 'package:pala/app/state/app_state.dart'; +import 'package:pala/utils/alert_digest.dart'; import 'package:pala/utils/encryption.dart'; +import 'package:pala/utils/gemini_summarizer.dart'; import '../state/session_store.dart'; import 'notification_service.dart'; @@ -29,6 +31,9 @@ void callbackDispatcher() { /// substituted lessons. Kept separate from that file because it needs its /// own session loading (no CLI process context here) and Flutter-only /// notification/storage APIs. +/// +/// Every alert also goes to the chat channels set up in Settings (Slack, +/// Discord), as one message per run, like the daemon's digest. Future checkForUpdatesAndNotify() async { WidgetsFlutterBinding.ensureInitialized(); if (Platform.isAndroid || Platform.isIOS) { @@ -48,15 +53,31 @@ Future checkForUpdatesAndNotify() async { SessionStore.attach(client); final prefs = await SharedPreferences.getInstance(); + final alerts = []; + try { + await _runChecks(client, prefs, alerts); + } finally { + // Sent even when a later check failed, so alerts that were already shown + // on the phone are not lost for the chat channels. + final configDir = AppState.instance.configDir; + await sendAlertDigest(alerts, configuredAlertSinks(configDir), GeminiSummarizer.fromConfig(configDir)); + } +} + +/// Shows a phone notification and queues the same line for the chat digest. +/// [geminiText] is the line without names, the only form a Gemini summary +/// may see (see [RunAlert]). +Future _alert(List alerts, String message, {String? geminiText}) async { + alerts.add((text: message, gemini: geminiText ?? message)); + await NotificationService.instance.show('Pala (Kréta)', message); +} +Future _runChecks(KretaClient client, SharedPreferences prefs, List alerts) async { final grades = await client.getGrades(); if (grades != null) { final oldCount = prefs.getInt('pala_bg_grades_count') ?? 0; if (oldCount > 0 && grades.length > oldCount) { - await NotificationService.instance.show( - 'Pala (Kréta)', - 'Kaptál ${grades.length - oldCount} új jegyet!', - ); + await _alert(alerts, 'Kaptál ${grades.length - oldCount} új jegyet!'); } await prefs.setInt('pala_bg_grades_count', grades.length); } @@ -65,10 +86,7 @@ Future checkForUpdatesAndNotify() async { if (homework != null) { final oldCount = prefs.getInt('pala_bg_homework_count') ?? 0; if (oldCount > 0 && homework.length > oldCount) { - await NotificationService.instance.show( - 'Pala (Kréta)', - 'Kaptál ${homework.length - oldCount} új házi feladatot!', - ); + await _alert(alerts, 'Kaptál ${homework.length - oldCount} új házi feladatot!'); } await prefs.setInt('pala_bg_homework_count', homework.length); } @@ -78,21 +96,18 @@ Future checkForUpdatesAndNotify() async { final tomorrow = DateTime.now().add(const Duration(days: 1)); for (final exam in exams) { if (exam.date != null && _isSameDay(exam.date!, tomorrow)) { - await NotificationService.instance.show( - 'Pala (Kréta)', - 'Holnap dolgozat: ${exam.subject} (${exam.mode})', - ); + await _alert(alerts, 'Holnap dolgozat: ${exam.subject} (${exam.mode})'); break; } } } - await _checkScheduleChanges(client, prefs); + await _checkScheduleChanges(client, prefs, alerts); } bool _isSameDay(DateTime a, DateTime b) => a.year == b.year && a.month == b.month && a.day == b.day; -Future _checkScheduleChanges(KretaClient client, SharedPreferences prefs) async { +Future _checkScheduleChanges(KretaClient client, SharedPreferences prefs, List alerts) async { final today = DateTime.now(); final start = DateTime(today.year, today.month, today.day); final end = start.add(const Duration(days: 2)); @@ -109,14 +124,12 @@ Future _checkScheduleChanges(KretaClient client, SharedPreferences prefs) final dayLabel = _isSameDay(lesson.date ?? today, today) ? 'Ma' : 'Holnap'; if (lesson.isCancelled) { - await NotificationService.instance.show( - 'Pala (Kréta)', - '$dayLabel elmarad: ${lesson.subject} (${lesson.lessonNumber}. óra)', - ); + await _alert(alerts, '$dayLabel elmarad: ${lesson.subject} (${lesson.lessonNumber}. óra)'); } else { - await NotificationService.instance.show( - 'Pala (Kréta)', + await _alert( + alerts, '$dayLabel helyettesítés: ${lesson.subject} — ${lesson.substituteTeacher}', + geminiText: '$dayLabel helyettesítés: ${lesson.subject}', ); } notifiedIds.add(id); diff --git a/app/lib/notifications/chat_alerts_card.dart b/app/lib/notifications/chat_alerts_card.dart new file mode 100644 index 0000000..ca0cb78 --- /dev/null +++ b/app/lib/notifications/chat_alerts_card.dart @@ -0,0 +1,240 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/chat_webhooks.dart'; +import 'package:url_launcher/url_launcher.dart'; +import '../theme/pala_theme.dart'; + +/// Settings card that turns Slack and Discord alerts on: the user pastes a +/// webhook address, the card checks it and saves it where the background +/// check (Android) and `pala --daemon` (desktop) read it. +/// +/// The saved address is a secret, so it is never shown again; the card only +/// says whether one is set. +class ChatAlertsCard extends StatefulWidget { + final ChatWebhookStore store; + + /// Stands in for the real notifier in tests. + final AlertSink Function(ChatService service)? sinkFor; + + const ChatAlertsCard({super.key, required this.store, this.sinkFor}); + + @override + State createState() => _ChatAlertsCardState(); +} + +class _ChatAlertsCardState extends State { + static const _help = { + ChatService.slack: ( + steps: 'Az api.slack.com/apps oldalon: Create New App, Incoming Webhooks bekapcsolása, ' + 'Add New Webhook to Workspace, majd másold ki a címet.', + hint: 'https://hooks.slack.com/services/...', + url: 'https://api.slack.com/messaging/webhooks', + ), + ChatService.discord: ( + steps: 'A csatornán: Csatorna szerkesztése, Integrációk, Webhookok, Új webhook, ' + 'majd Webhook URL másolása.', + hint: 'https://discord.com/api/webhooks/...', + url: 'https://support.discord.com/hc/articles/228383668', + ), + }; + + final _controllers = {for (final s in ChatService.values) s: TextEditingController()}; + final _errors = {}; + ChatService? _testing; + + @override + void dispose() { + for (final c in _controllers.values) { + c.dispose(); + } + super.dispose(); + } + + void _snack(String text, {bool ok = true}) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(text), backgroundColor: ok ? PalaTheme.success : PalaTheme.danger), + ); + } + + void _save(ChatService service) { + final saved = widget.store.save(service, _controllers[service]!.text); + setState(() { + if (saved) { + _errors.remove(service); + _controllers[service]!.clear(); + } else { + _errors[service] = 'Ez nem ${service.label} webhook cím. Így kell kezdődnie: ${_help[service]!.hint}'; + } + }); + if (saved) _snack('${service.label} webhook elmentve.'); + } + + void _remove(ChatService service) { + widget.store.remove(service); + setState(() => _errors.remove(service)); + _snack('${service.label} értesítések kikapcsolva.'); + } + + Future _sendTest(ChatService service) async { + setState(() => _testing = service); + final sink = widget.sinkFor?.call(service) ?? widget.store.sink(service); + final ok = await sink.send('Pala', 'Teszt üzenet: a ${service.label} értesítések be vannak állítva.'); + if (!mounted) return; + setState(() => _testing = null); + _snack( + ok + ? 'Teszt üzenet elküldve, nézd meg a csatornát.' + : 'Nem sikerült elküldeni. Ellenőrizd a netet, és hogy a webhook még létezik-e.', + ok: ok, + ); + } + + String get _whenItRuns { + if (Platform.isAndroid) { + return 'A háttérellenőrzés nagyjából 15 percenként fut, és az újdonságokat egy üzenetben küldi el.'; + } + if (Platform.isIOS) { + return 'iPhone-on a Pala nem fut a háttérben, ezért innen nem megy üzenet. ' + 'Az itt mentett cím csak ezen az eszközön él.'; + } + return 'Asztali gépen az üzeneteket a háttérellenőrzés (pala --daemon) küldi. Windowson a terminálos Pala ' + 'Beállítások menüjében kapcsolható be (Háttér-értesítések beállítása), Linuxon és macOS-en ütemezd cronnal.'; + } + + @override + Widget build(BuildContext context) { + final muted = TextStyle(color: PalaTheme.textMuted, fontSize: 12); + return Material( + color: PalaTheme.card, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide(color: PalaTheme.border), + ), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Slack és Discord értesítések', + style: TextStyle(color: PalaTheme.text, fontSize: 15, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 12), + Text( + 'Nem kötelező. Ha megadsz egy webhook címet, a Pala az új jegyeket, házi feladatokat, ' + 'számonkéréseket és óraváltozásokat a csatornádba is elküldi.', + style: muted, + ), + for (final service in ChatService.values) ...[ + const SizedBox(height: 16), + _buildService(service, muted), + ], + const SizedBox(height: 16), + Text(_whenItRuns, style: muted), + const SizedBox(height: 8), + Text( + 'Az üzenet szövege (tantárgy, jegy, helyettesítő tanár neve) a Slackhez vagy a Discordhoz kerül. ' + 'A webhook cím titok: aki ismeri, írhat a csatornádba.', + style: muted, + ), + ], + ), + ), + ); + } + + Widget _buildService(ChatService service, TextStyle muted) { + final help = _help[service]!; + final fromEnv = widget.store.isSetByEnvironment(service); + final saved = widget.store.hasSaved(service); + final active = fromEnv || saved; + final statusColor = active ? PalaTheme.success : PalaTheme.textMuted; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + service.label, + style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14, color: PalaTheme.text), + ), + const SizedBox(width: 10), + Icon(active ? Icons.check_circle : Icons.radio_button_unchecked, size: 14, color: statusColor), + const SizedBox(width: 4), + Text( + active ? 'Beállítva' : 'Nincs beállítva', + style: TextStyle(color: statusColor, fontSize: 12, fontWeight: FontWeight.w600), + ), + ], + ), + const SizedBox(height: 6), + if (fromEnv) + Text('A cím a ${service.envName} környezeti változóból jön, itt nem módosítható.', style: muted) + else ...[ + Text(help.steps, style: muted), + const SizedBox(height: 8), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextField( + key: ValueKey('webhook-${service.name}'), + controller: _controllers[service], + obscureText: true, + autocorrect: false, + enableSuggestions: false, + keyboardType: TextInputType.url, + onSubmitted: (_) => _save(service), + decoration: InputDecoration( + hintText: saved ? 'Új cím a cseréhez' : help.hint, + errorText: _errors[service], + errorMaxLines: 3, + ), + ), + ), + const SizedBox(width: 12), + ElevatedButton( + key: ValueKey('save-${service.name}'), + onPressed: () => _save(service), + child: const Text('Mentés'), + ), + ], + ), + ], + const SizedBox(height: 4), + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + if (active) + OutlinedButton.icon( + key: ValueKey('test-${service.name}'), + onPressed: _testing == null ? () => _sendTest(service) : null, + icon: const Icon(Icons.send_outlined, size: 16), + label: Text(_testing == service ? 'Küldés...' : 'Teszt üzenet', style: const TextStyle(fontSize: 12)), + ), + if (saved && !fromEnv) + OutlinedButton.icon( + key: ValueKey('remove-${service.name}'), + onPressed: () => _remove(service), + style: OutlinedButton.styleFrom( + foregroundColor: PalaTheme.danger, + side: BorderSide(color: PalaTheme.danger), + ), + icon: const Icon(Icons.delete_outline, size: 16), + label: const Text('Törlés', style: TextStyle(fontSize: 12)), + ), + TextButton.icon( + onPressed: () => launchUrl(Uri.parse(help.url), mode: LaunchMode.externalApplication), + icon: const Icon(Icons.open_in_new, size: 14), + label: const Text('Részletes útmutató', style: TextStyle(fontSize: 12)), + ), + ], + ), + ], + ); + } +} diff --git a/app/lib/views/settings_view.dart b/app/lib/views/settings_view.dart index b2bddf5..4b01ac2 100644 --- a/app/lib/views/settings_view.dart +++ b/app/lib/views/settings_view.dart @@ -3,10 +3,13 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; import 'package:path_provider/path_provider.dart'; +import 'package:pala/app/state/app_state.dart'; import 'package:pala/links.dart'; +import 'package:pala/utils/chat_webhooks.dart'; import 'package:pala/rules/wrapped_season.dart'; import 'package:pala/version.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../notifications/chat_alerts_card.dart'; import '../state/app_model.dart'; import '../theme/pala_theme.dart'; import '../features/wrapped/presentation/pala_wrapped_view.dart'; @@ -554,6 +557,10 @@ class _SettingsViewState extends State with SingleTickerProviderSt const SizedBox(height: 12), + ChatAlertsCard(store: ChatWebhookStore(AppState.instance.configDir)), + + const SizedBox(height: 12), + // System Integration Card _buildSectionCard( title: 'Komponensek & Rendszerintegráció', diff --git a/app/test/chat_alerts_card_test.dart b/app/test/chat_alerts_card_test.dart new file mode 100644 index 0000000..4df3646 --- /dev/null +++ b/app/test/chat_alerts_card_test.dart @@ -0,0 +1,129 @@ +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/chat_webhooks.dart'; +import 'package:pala_app/notifications/chat_alerts_card.dart'; + +const discordUrl = 'https://discord.com/api/webhooks/123456/abc-DEF_ghi'; + +class _FakeSink implements AlertSink { + final bool result; + final sent = []; + + _FakeSink(this.result); + + @override + bool get isEnabled => true; + + @override + String bold(String text) => text; + + @override + Future send(String title, String message) async { + sent.add(message); + return result; + } +} + +void main() { + late Directory dir; + late ChatWebhookStore store; + + setUp(() { + dir = Directory.systemTemp.createTempSync('pala_card'); + store = ChatWebhookStore(dir.path, environment: const {}); + }); + + tearDown(() => dir.deleteSync(recursive: true)); + + Future pump(WidgetTester tester, {ChatWebhookStore? withStore, _FakeSink? sink}) { + return tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: ChatAlertsCard(store: withStore ?? store, sinkFor: sink == null ? null : (_) => sink), + ), + ), + ), + ); + } + + testWidgets('starts with both services off and no test or remove button', (tester) async { + await pump(tester); + + expect(find.text('Nincs beállítva'), findsNWidgets(2)); + expect(find.text('Teszt üzenet'), findsNothing); + expect(find.text('Törlés'), findsNothing); + }); + + testWidgets('a wrong address shows an error and saves nothing', (tester) async { + await pump(tester); + + await tester.enterText(find.byKey(const ValueKey('webhook-discord')), 'https://example.com/hook'); + await tester.tap(find.byKey(const ValueKey('save-discord'))); + await tester.pump(); + + expect(find.textContaining('Ez nem Discord webhook cím'), findsOneWidget); + expect(store.hasSaved(ChatService.discord), isFalse); + }); + + testWidgets('a valid address is saved, cleared from the field and never shown again', (tester) async { + await pump(tester); + + await tester.enterText(find.byKey(const ValueKey('webhook-discord')), discordUrl); + await tester.tap(find.byKey(const ValueKey('save-discord'))); + await tester.pump(); + + expect(store.hasSaved(ChatService.discord), isTrue); + expect(find.text('Beállítva'), findsOneWidget); + expect(find.textContaining('abc-DEF_ghi'), findsNothing); + expect(find.byKey(const ValueKey('test-discord')), findsOneWidget); + }); + + testWidgets('the test button sends one message and reports the result', (tester) async { + store.save(ChatService.discord, discordUrl); + final sink = _FakeSink(true); + await pump(tester, sink: sink); + + await tester.tap(find.byKey(const ValueKey('test-discord'))); + await tester.pump(); + await tester.pump(); + + expect(sink.sent, hasLength(1)); + expect(find.textContaining('Teszt üzenet elküldve'), findsOneWidget); + }); + + testWidgets('a failed test message says so', (tester) async { + store.save(ChatService.discord, discordUrl); + await pump(tester, sink: _FakeSink(false)); + + await tester.tap(find.byKey(const ValueKey('test-discord'))); + await tester.pump(); + await tester.pump(); + + expect(find.textContaining('Nem sikerült elküldeni'), findsOneWidget); + }); + + testWidgets('remove turns the service off again', (tester) async { + store.save(ChatService.discord, discordUrl); + await pump(tester); + + await tester.tap(find.byKey(const ValueKey('remove-discord'))); + await tester.pump(); + + expect(store.hasSaved(ChatService.discord), isFalse); + expect(find.text('Nincs beállítva'), findsNWidgets(2)); + }); + + testWidgets('a webhook from the environment is shown as set and cannot be edited', (tester) async { + final fromEnv = ChatWebhookStore(dir.path, environment: const {'PALA_SLACK_WEBHOOK': 'x'}); + await pump(tester, withStore: fromEnv, sink: _FakeSink(true)); + + expect(find.byKey(const ValueKey('webhook-slack')), findsNothing); + expect(find.textContaining('PALA_SLACK_WEBHOOK'), findsOneWidget); + expect(find.byKey(const ValueKey('test-slack')), findsOneWidget); + expect(find.byKey(const ValueKey('remove-slack')), findsNothing); + }); +} diff --git a/docs/USER.md b/docs/USER.md index 7936c0a..00f5816 100644 --- a/docs/USER.md +++ b/docs/USER.md @@ -32,6 +32,7 @@ A főmenü "Beállítások" opciójában az alábbi funkciók érhetők el: - **Háttér-értesítések**: Windowson a Feladatütemezőbe kerül (`PalaDaemon`): a háttérben óránként és bejelentkezéskor ellenőrzi az új jegyeket, majd értesítést küld. Linuxon és macOS-en a `pala --daemon` parancsot magad ütemezheted (például cronnal), az értesítést a rendszer saját értesítési rendszere jeleníti meg. - **Slack-értesítések**: a `pala --daemon` minden értesítést egy Slack csatornába is elküld, ha megadsz egy Incoming Webhook címet. Tedd a `PALA_SLACK_WEBHOOK` környezeti változóba, vagy írd a `~/.config/pala/slack_webhook` fájlba (`chmod 600`). Csak `https://hooks.slack.com/services/...` címet fogad el. Értesít az új jegyekről (tantárggyal és értékkel), az új házi feladatokról, minden új számonkérésről egyszer, a holnapi számonkérésről egyszer, valamint az elmaradt és helyettesített órákról. Az első futás csak megjegyzi a meglévő dolgozatokat, nem küldi el őket. Egy futás összes értesítése egyetlen üzenetben érkezik. - **Discord-értesítések**: ugyanez Discordra is működik. Tedd a webhook címet a `PALA_DISCORD_WEBHOOK` környezeti változóba, vagy a `~/.config/pala/discord_webhook` fájlba (`chmod 600`). Csak `https://discord.com/api/webhooks//` alakú címet fogad el (a `discordapp.com`, `ptb.discord.com` és `canary.discord.com` is megfelel). A Slack és a Discord egyszerre is be lehet kapcsolva, így az átállás megszakítás nélkül megy. Az üzenet soha nem pingel senkit (`@everyone`, `@here` és említések nem működnek). A Discord 2000 karakteres korlátja miatt a hosszabb üzenet több részre oszlik, sortörésnél vágva. Ha a Discord lassításra kéri a küldést (429), egyszer vár, aztán egyszer újrapróbálja. +- **Beállítás az alkalmazásból**: a webhook címet nem kell kézzel fájlba írni. Az asztali és a mobil alkalmazásban a Fiók & Profil oldal Beállítások fülén a "Slack és Discord értesítések" kártyán beillesztheted a címet. Az alkalmazás ellenőrzi, elmenti (ugyanabba a fájlba, amit a `pala --daemon` olvas), és a "Teszt üzenet" gombbal ki is próbálhatod. Az elmentett címet többé nem mutatja meg, a "Törlés" gomb kikapcsolja az értesítést. Androidon a háttérellenőrzés (nagyjából 15 percenként) a telefonos értesítések mellett a csatornába is elküldi az újdonságokat, egy üzenetben. Asztali gépen továbbra is a `pala --daemon` küld, iPhone-on nincs háttérküldés. Ha a cím környezeti változóból jön, az alkalmazás csak jelzi, hogy be van állítva. - **Webhook titkosság**: a webhook cím és a token titok. A Pala hibakeresési naplóba (`PALA_DEBUG=1`) sem írja ki, sikertelen küldésnél is csak a hiba típusát naplózza. - **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó üzenetek végére rövid magyar összefoglaló kerül (Slacken és Discordon is). Új adat nélkül nincs üzenet és nincs API hívás. A modell a `PALA_GEMINI_MODEL` változóval állítható. A kérés csak a tantárgyakat, jegyeket, témákat, dátumokat, valamint a Moodle kurzusok és határidők nevét tartalmazza. A helyettesítő tanár neve és a Moodle értesítések szövege csak a chat üzenetbe kerül, a Geminihez nem. Az ingyenes szint tartalmát a Google felhasználhatja a termékei fejlesztéséhez. - **Moodle**: ha a `PALA_MOODLE_URL` be van állítva (például `https://moodle.iskolam.hu`), a futás az olvasatlan Moodle értesítéseket és a következő 14 nap határidejeit is ellenőrzi. Az első futás a `PALA_MOODLE_USER` és `PALA_MOODLE_PASSWORD` értékkel belép, és csak a tokent menti el. Csak jelszavas belépéssel működik (SSO nélkül), és a Moodle mobil szolgáltatásnak engedélyezettnek kell lennie. Hibás felhasználónév vagy jelszó esetén a Pala egyszer jelzi a hibát, utána nem próbálkozik újra, amíg a felhasználónevet vagy a jelszót meg nem változtatod. Ehhez a jelszó sózott hash-ét menti, magát a jelszót nem. Időtúllépés vagy szerverhiba nem zárolja a belépést. A meglévő értesítéseket és határidőket akkor jegyzi meg csendben, amikor a Moodle először sikeresen visszaadta a listát, ezért egy elmaradt első lekérés után sem érkezik egyszerre az összes olvasatlan elem. diff --git a/lib/utils/chat_webhooks.dart b/lib/utils/chat_webhooks.dart new file mode 100644 index 0000000..93a8622 --- /dev/null +++ b/lib/utils/chat_webhooks.dart @@ -0,0 +1,91 @@ +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/discord_notifier.dart'; +import 'package:pala/utils/owner_only.dart'; +import 'package:pala/utils/slack_notifier.dart'; + +/// A chat service that can receive Pala's alerts through a webhook. +enum ChatService { + slack('Slack', 'slack_webhook', 'PALA_SLACK_WEBHOOK'), + discord('Discord', 'discord_webhook', 'PALA_DISCORD_WEBHOOK'); + + const ChatService(this.label, this.fileName, this.envName); + + final String label; + + /// The file in the config directory that holds the webhook URL. + final String fileName; + + /// The environment variable that wins over the file. + final String envName; + + bool isValidWebhook(String? url) => switch (this) { + ChatService.slack => SlackNotifier.isValidWebhook(url), + ChatService.discord => DiscordNotifier.isValidWebhook(url), + }; +} + +/// Saves and removes the webhook files that [SlackNotifier.fromConfig] and +/// [DiscordNotifier.fromConfig] read, so a settings screen can turn chat +/// alerts on without the user editing files by hand. +/// +/// A webhook URL is a secret (anyone holding it can post to the channel), so +/// this class never returns a saved URL and never logs one. +class ChatWebhookStore { + final String configDir; + + /// Stands in for `Platform.environment` in tests. + final Map _environment; + + ChatWebhookStore(this.configDir, {Map? environment}) + : _environment = environment ?? Platform.environment; + + File _file(ChatService service) => File('$configDir/${service.fileName}'); + + /// True when the webhook comes from the environment variable. The file is + /// ignored then, so saving or removing it changes nothing. + bool isSetByEnvironment(ChatService service) => (_environment[service.envName]?.trim() ?? '').isNotEmpty; + + /// True when a valid webhook is saved in the config directory. + bool hasSaved(ChatService service) { + final file = _file(service); + if (!file.existsSync()) return false; + try { + return service.isValidWebhook(file.readAsStringSync().trim()); + } catch (_) { + return false; + } + } + + /// Saves [url] for [service]. Returns false and writes nothing when the + /// address is not one of the service's own webhook addresses. + bool save(ChatService service, String url) { + final value = url.trim(); + if (!service.isValidWebhook(value)) return false; + ensureOwnerOnlyDir(configDir); + final file = _file(service); + // Created empty and restricted first, so the secret is never readable by + // other accounts, not even for a moment. + file.writeAsStringSync(''); + if (Platform.isLinux || Platform.isMacOS) { + try { + Process.runSync('chmod', ['600', file.path]); + } catch (_) {} + } + file.writeAsStringSync(value); + return true; + } + + void remove(ChatService service) { + final file = _file(service); + if (file.existsSync()) file.deleteSync(); + } + + /// The notifier for [service], enabled only when a webhook is configured. + AlertSink sink(ChatService service, {http.Client? client}) => switch (service) { + ChatService.slack => SlackNotifier.fromConfig(configDir, client: client), + ChatService.discord => DiscordNotifier.fromConfig(configDir, client: client), + }; +} diff --git a/test/chat_webhooks_test.dart b/test/chat_webhooks_test.dart new file mode 100644 index 0000000..cacb08d --- /dev/null +++ b/test/chat_webhooks_test.dart @@ -0,0 +1,81 @@ +import 'dart:io'; + +import 'package:pala/utils/chat_webhooks.dart'; +import 'package:test/test.dart'; + +const slackUrl = 'https://hooks.slack.com/services/T000/B000/abcdef'; +const discordUrl = 'https://discord.com/api/webhooks/123456/abc-DEF_ghi'; + +void main() { + late Directory dir; + late ChatWebhookStore store; + + setUp(() { + dir = Directory.systemTemp.createTempSync('pala_webhooks'); + store = ChatWebhookStore(dir.path, environment: const {}); + }); + + tearDown(() => dir.deleteSync(recursive: true)); + + test('nothing is saved at first', () { + for (final service in ChatService.values) { + expect(store.hasSaved(service), isFalse); + expect(store.sink(service).isEnabled, isFalse); + } + }); + + test('a valid webhook is saved trimmed, into the file the notifier reads', () { + expect(store.save(ChatService.slack, ' $slackUrl\n'), isTrue); + expect(store.save(ChatService.discord, discordUrl), isTrue); + + expect(File('${dir.path}/slack_webhook').readAsStringSync(), slackUrl); + expect(File('${dir.path}/discord_webhook').readAsStringSync(), discordUrl); + for (final service in ChatService.values) { + expect(store.hasSaved(service), isTrue); + expect(store.sink(service).isEnabled, isTrue); + } + }); + + test('an address of another host is refused and leaves no file', () { + expect(store.save(ChatService.slack, discordUrl), isFalse); + expect(store.save(ChatService.discord, slackUrl), isFalse); + expect(store.save(ChatService.discord, 'https://example.com/api/webhooks/1/abc'), isFalse); + expect(store.save(ChatService.slack, ''), isFalse); + + expect(dir.listSync(), isEmpty); + }); + + test('a refused address keeps the webhook that was saved before', () { + store.save(ChatService.discord, discordUrl); + + expect(store.save(ChatService.discord, 'http://discord.com/api/webhooks/1/abc'), isFalse); + expect(File('${dir.path}/discord_webhook').readAsStringSync(), discordUrl); + }); + + test('a saved file with a tampered address does not count as saved', () { + File('${dir.path}/slack_webhook').writeAsStringSync('https://evil.example/services/x'); + + expect(store.hasSaved(ChatService.slack), isFalse); + }); + + test('remove deletes the file and is safe when there is none', () { + store.save(ChatService.slack, slackUrl); + + store.remove(ChatService.slack); + store.remove(ChatService.slack); + + expect(store.hasSaved(ChatService.slack), isFalse); + expect(File('${dir.path}/slack_webhook').existsSync(), isFalse); + }); + + test('the environment variable is reported, blank values are not', () { + final withEnv = ChatWebhookStore(dir.path, environment: const { + 'PALA_SLACK_WEBHOOK': slackUrl, + 'PALA_DISCORD_WEBHOOK': ' ', + }); + + expect(withEnv.isSetByEnvironment(ChatService.slack), isTrue); + expect(withEnv.isSetByEnvironment(ChatService.discord), isFalse); + expect(store.isSetByEnvironment(ChatService.slack), isFalse); + }); +}