From 1cf39ab87387c972dafe8ec218ff1c009e5e5540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Solti=20Csongor=20P=C3=A9ter?= Date: Mon, 9 Nov 2026 17:27:16 +0100 Subject: [PATCH 1/5] feat: send daemon alerts to Slack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pala --daemon collects the alerts of one run and posts them as a single Slack message through an Incoming Webhook (PALA_SLACK_WEBHOOK or ~/.config/pala/slack_webhook). Grade alerts list the new grades, exams are announced once when they appear and once the day before, and a failed Kréta login posts an error and exits non-zero. Co-Authored-By: Claude Opus 5.5 --- bin/pala.dart | 3 +- lib/app/cli_app.dart | 20 ++++++- lib/app/daemon/daemon_logic.dart | 95 ++++++++++++++++++++++++++++---- lib/utils/slack_notifier.dart | 85 ++++++++++++++++++++++++++++ test/slack_notifier_test.dart | 71 ++++++++++++++++++++++++ 5 files changed, 260 insertions(+), 14 deletions(-) create mode 100644 lib/utils/slack_notifier.dart create mode 100644 test/slack_notifier_test.dart diff --git a/bin/pala.dart b/bin/pala.dart index 689890b..efe8e59 100644 --- a/bin/pala.dart +++ b/bin/pala.dart @@ -133,7 +133,8 @@ void main(List arguments) async { if (argResults['daemon']) { await app.runDaemon(); - exit(0); + // A failed login sets exitCode, so a scheduled run shows up as failed. + exit(exitCode); } if (argResults['demo']) { diff --git a/lib/app/cli_app.dart b/lib/app/cli_app.dart index cc5fbf7..9ce2016 100644 --- a/lib/app/cli_app.dart +++ b/lib/app/cli_app.dart @@ -28,6 +28,7 @@ import 'package:pala/app/tui/screen_buffer.dart'; import 'package:pala/app/tui/tui_state.dart'; import 'package:pala/app/tui/tui_views.dart'; import 'package:pala/utils/logger.dart'; +import 'package:pala/utils/slack_notifier.dart'; import 'package:pala/utils/win32_console.dart'; import 'package:pala/version.dart'; import 'package:path/path.dart' as p; @@ -63,6 +64,11 @@ class PalaApp { } KretaClient? _client; + + /// Alert lines of the current daemon run. While it is non-null, Slack gets + /// one combined message at the end (with the optional Gemini summary) + /// instead of one message per alert. + List? _runAlerts; String? studentUid; File _getAuthFile() { @@ -144,9 +150,21 @@ class PalaApp { Future runDaemon() async { if (!await _tryAutoLogin()) { + // A scheduled run has no one watching it, so say on Slack that the + // login failed instead of failing silently. + await SlackNotifier.fromConfig(AppState.instance.configDir) + .send('Pala (hiba)', 'A Kréta bejelentkezés nem sikerült. Jelentkezz be újra a Palában.'); + exitCode = 1; return; } - await _checkNewItems(); + _runAlerts = []; + try { + await _checkNewItems(); + } finally { + final alerts = _runAlerts!; + _runAlerts = null; + await _flushAlertsToSlack(alerts); + } } void _showBanner() { diff --git a/lib/app/daemon/daemon_logic.dart b/lib/app/daemon/daemon_logic.dart index fa248ea..1a65c87 100644 --- a/lib/app/daemon/daemon_logic.dart +++ b/lib/app/daemon/daemon_logic.dart @@ -9,7 +9,15 @@ extension PalaAppDaemonLogic on PalaApp { if (grades != null) { if (grades.length > oldGradesCount && oldGradesCount > 0) { final newGradesCount = grades.length - oldGradesCount; - await _showToast('Pala (Kréta)', 'Kaptál $newGradesCount új jegyet!'); + // Kréta grades carry no stable id, so the newest ones by date stand + // in for "the new ones" when listing them. + final newest = [...grades] + ..sort((a, b) => (b.date ?? DateTime(0)).compareTo(a.date ?? DateTime(0))); + final details = newest + .take(newGradesCount) + .map((g) => '${g.subject}: ${g.displayValue}${g.theme != null && g.theme!.isNotEmpty ? ' (${g.theme})' : ''}') + .join('\n'); + await _showToast('Pala (Kréta)', 'Kaptál $newGradesCount új jegyet!\n$details'); } final currentData = state.getAuthData(); currentData['gradesCount'] = grades.length; @@ -30,21 +38,60 @@ extension PalaAppDaemonLogic on PalaApp { final exams = await _client!.getExams(); if (exams != null) { - final tomorrow = DateTime.now().add(Duration(days: 1)); - final tomorrowStr = '${tomorrow.year}-${tomorrow.month.toString().padLeft(2, '0')}-${tomorrow.day.toString().padLeft(2, '0')}'; - - for (var exam in exams) { - final examDateStr = exam.date?.toString().split(' ').first; - if (examDateStr == tomorrowStr) { - await _showToast('Pala (Kréta)', 'Holnap dolgozat: ${exam.subject} (${exam.mode})'); - break; - } - } + await _checkExams(exams); } await _checkScheduleChanges(); } + // The daemon runs on a timer (hourly by default), so every notification is + // remembered by exam id. Without that, a scheduled run would repeat the same + // "tomorrow" reminder every hour, which is noise on Slack. + // Two notices per exam: one when it first appears in Kréta, one the day before. + Future _checkExams(List exams) async { + final state = AppState.instance; + final authData = state.getAuthData(); + final firstRun = authData['notifiedExamIds'] == null; + final announced = ((authData['notifiedExamIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); + final reminded = ((authData['remindedExamIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); + + final today = DateTime.now(); + final startOfToday = DateTime(today.year, today.month, today.day); + final tomorrow = startOfToday.add(const Duration(days: 1)); + + final upcoming = exams.where((e) => e.date != null && !e.date!.isBefore(startOfToday)).toList() + ..sort((a, b) => a.date!.compareTo(b.date!)); + + for (final exam in upcoming) { + final id = exam.uid ?? '${exam.date}_${exam.subject}_${exam.mode}'; + final d = exam.date!; + final dateLabel = '${d.year}.${d.month.toString().padLeft(2, '0')}.${d.day.toString().padLeft(2, '0')}.'; + final theme = (exam.theme != null && exam.theme!.isNotEmpty) ? '\nTéma: ${exam.theme}' : ''; + + // On the very first run every existing exam would look new; record them + // silently instead of flooding the channel. + if (!announced.contains(id)) { + if (!firstRun) { + await _showToast('Pala (Kréta)', 'Új számonkérés: ${exam.subject} (${exam.mode}), $dateLabel$theme'); + } + announced.add(id); + } + + if (_isSameDay(d, tomorrow) && !reminded.contains(id)) { + await _showToast('Pala (Kréta)', 'Holnap ${exam.mode.toLowerCase()}: ${exam.subject}$theme'); + reminded.add(id); + } + } + + final currentIds = upcoming.map((e) => e.uid ?? '${e.date}_${e.subject}_${e.mode}').toSet(); + announced.retainWhere(currentIds.contains); + reminded.retainWhere(currentIds.contains); + + authData['notifiedExamIds'] = announced.toList(); + authData['remindedExamIds'] = reminded.toList(); + state.saveAuthData(authData); + } + bool _isSameDay(DateTime? a, DateTime b) { return a != null && a.year == b.year && a.month == b.month && a.day == b.day; } @@ -90,6 +137,16 @@ extension PalaAppDaemonLogic on PalaApp { // The text comes from Kréta (subject and teacher names), so it is passed as // data (environment variables or argv) and never spliced into script source. Future _showToast(String title, String message) async { + // Slack goes first: it is the channel that reaches the phone, and a + // missing desktop notifier (no notify-send on a server or in Termux) + // must not block it. + final collecting = _runAlerts; + if (collecting != null) { + collecting.add(message); + } else { + await SlackNotifier.fromConfig(AppState.instance.configDir).send(title, message); + } + if (Platform.isWindows) { const script = r''' [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null @@ -104,7 +161,10 @@ extension PalaAppDaemonLogic on PalaApp { await Process.run('powershell', ['-NoProfile', '-Command', script], environment: {'PALA_TOAST_TITLE': title, 'PALA_TOAST_MESSAGE': message}); } else if (Platform.isLinux) { - await Process.run('notify-send', [title, message]); + // Termux and headless servers have no notify-send. + try { + await Process.run('notify-send', [title, message]); + } on ProcessException catch (_) {} } else if (Platform.isMacOS) { await Process.run('osascript', [ '-e', 'on run argv', @@ -116,6 +176,17 @@ extension PalaAppDaemonLogic on PalaApp { } } + /// Sends the alerts of one run as a single Slack message. A run without + /// news posts nothing. + Future _flushAlertsToSlack(List alerts) async { + if (alerts.isEmpty) return; + final configDir = AppState.instance.configDir; + final slack = SlackNotifier.fromConfig(configDir); + if (!slack.isEnabled) return; + final body = StringBuffer(alerts.map((a) => '• $a').join('\n')); + await slack.send('Pala', body.toString()); + } + void _setupDaemon(bool enable) { if (enable) { installDaemon(); diff --git a/lib/utils/slack_notifier.dart b/lib/utils/slack_notifier.dart new file mode 100644 index 0000000..60fdfde --- /dev/null +++ b/lib/utils/slack_notifier.dart @@ -0,0 +1,85 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:pala/utils/logger.dart'; + +/// Posts daemon notifications to a Slack channel through an Incoming Webhook. +/// +/// The webhook URL is a secret (anyone holding it can post to the channel), so +/// it is read from the `PALA_SLACK_WEBHOOK` environment variable or from the +/// owner-only `slack_webhook` file in the config directory, never from argv. +class SlackNotifier { + final String? webhookUrl; + final http.Client _client; + + SlackNotifier(this.webhookUrl, {http.Client? client}) + : _client = client ?? http.Client(); + + /// Builds a notifier from the environment, falling back to + /// `/slack_webhook`. Returns a disabled notifier when neither is set. + factory SlackNotifier.fromConfig(String configDir, {http.Client? client}) { + final fromEnv = Platform.environment['PALA_SLACK_WEBHOOK']?.trim(); + if (fromEnv != null && fromEnv.isNotEmpty) { + return SlackNotifier(fromEnv, client: client); + } + final file = File('$configDir/slack_webhook'); + if (file.existsSync()) { + final value = file.readAsStringSync().trim(); + if (value.isNotEmpty) return SlackNotifier(value, client: client); + } + return SlackNotifier(null, client: client); + } + + bool get isEnabled => isValidWebhook(webhookUrl); + + /// Only Slack's own webhook host is accepted, so a typo or a tampered config + /// file cannot send Kréta data to an arbitrary server. + static bool isValidWebhook(String? url) { + if (url == null) return false; + final uri = Uri.tryParse(url); + return uri != null && + uri.scheme == 'https' && + uri.host == 'hooks.slack.com' && + uri.path.startsWith('/services/'); + } + + /// The Slack message body. Kréta text is sent as plain text inside the JSON + /// payload, with Slack's control characters escaped so a subject name cannot + /// trigger @channel pings or fake links. + static Map buildPayload(String title, String message) { + return { + 'text': '*${escape(title)}*\n${escape(message)}', + 'unfurl_links': false, + }; + } + + static String escape(String input) => input + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>'); + + /// Sends one message. Returns false when disabled or when Slack rejects it. + /// Errors are logged, never thrown, so a Slack outage does not stop the + /// desktop notification or the rest of the daemon run. + Future send(String title, String message) async { + if (!isEnabled) return false; + try { + final response = await _client + .post( + Uri.parse(webhookUrl!), + headers: {'Content-Type': 'application/json; charset=utf-8'}, + body: jsonEncode(buildPayload(title, message)), + ) + .timeout(const Duration(seconds: 15)); + if (response.statusCode != 200) { + PalaLogger.debug('Slack webhook HTTP ${response.statusCode}: ${response.body}'); + return false; + } + return true; + } catch (e) { + PalaLogger.debug('Slack webhook failed: $e'); + return false; + } + } +} diff --git a/test/slack_notifier_test.dart b/test/slack_notifier_test.dart new file mode 100644 index 0000000..7e447a0 --- /dev/null +++ b/test/slack_notifier_test.dart @@ -0,0 +1,71 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pala/utils/slack_notifier.dart'; +import 'package:test/test.dart'; + +void main() { + const hook = 'https://hooks.slack.com/services/T000/B000/XXXX'; + + group('isValidWebhook', () { + test('accepts a Slack incoming webhook', () { + expect(SlackNotifier.isValidWebhook(hook), isTrue); + }); + + test('rejects other hosts, plain http and empty values', () { + expect(SlackNotifier.isValidWebhook(null), isFalse); + expect(SlackNotifier.isValidWebhook(''), isFalse); + expect(SlackNotifier.isValidWebhook('http://hooks.slack.com/services/x'), isFalse); + expect(SlackNotifier.isValidWebhook('https://evil.example/services/x'), isFalse); + expect(SlackNotifier.isValidWebhook('https://hooks.slack.com.evil.example/services/x'), isFalse); + }); + }); + + test('payload escapes Slack control characters from Kréta text', () { + final payload = SlackNotifier.buildPayload('Pala', 'Matek & '); + expect(payload['text'], '*Pala*\nMatek <!channel> & <https://x|y>'); + }); + + test('send posts JSON to the webhook', () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response('ok', 200); + }); + final ok = await SlackNotifier(hook, client: client).send('Pala (Kréta)', 'Holnap dolgozat: Történelem'); + expect(ok, isTrue); + expect(captured.url.toString(), hook); + expect(jsonDecode(captured.body)['text'], contains('Történelem')); + }); + + test('send returns false and does not throw on Slack errors', () async { + final client = MockClient((_) async => http.Response('invalid_token', 403)); + expect(await SlackNotifier(hook, client: client).send('a', 'b'), isFalse); + + final failing = MockClient((_) async => throw const SocketException('offline')); + expect(await SlackNotifier(hook, client: failing).send('a', 'b'), isFalse); + }); + + test('disabled notifier sends nothing', () async { + var called = false; + final client = MockClient((_) async { + called = true; + return http.Response('ok', 200); + }); + expect(await SlackNotifier(null, client: client).send('a', 'b'), isFalse); + expect(called, isFalse); + }); + + test('fromConfig reads the owner-only file', () { + final dir = Directory.systemTemp.createTempSync('pala_slack'); + addTearDown(() => dir.deleteSync(recursive: true)); + File('${dir.path}/slack_webhook').writeAsStringSync('$hook\n'); + // The environment variable wins when set, so only check the file path + // when the test runner does not have one. + if ((Platform.environment['PALA_SLACK_WEBHOOK'] ?? '').isEmpty) { + expect(SlackNotifier.fromConfig(dir.path).webhookUrl, hook); + } + }); +} From 368a64bd645667341c626b11d25aefece7f53a0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Solti=20Csongor=20P=C3=A9ter?= Date: Mon, 9 Nov 2026 17:27:33 +0100 Subject: [PATCH 2/5] feat: check Moodle notifications and deadlines in the daemon When PALA_MOODLE_URL is set, pala --daemon logs in once through the Moodle mobile web service (password only in the POST body of login/token.php), keeps just the token in the auth data, and alerts on new unread notifications and on deadlines in the next 14 days. Co-Authored-By: Claude Opus 5.5 --- lib/api/moodle_client.dart | 175 +++++++++++++++++++++++++++++++ lib/app/cli_app.dart | 2 + lib/app/daemon/daemon_logic.dart | 72 +++++++++++++ 3 files changed, 249 insertions(+) create mode 100644 lib/api/moodle_client.dart diff --git a/lib/api/moodle_client.dart b/lib/api/moodle_client.dart new file mode 100644 index 0000000..54903b2 --- /dev/null +++ b/lib/api/moodle_client.dart @@ -0,0 +1,175 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:pala/utils/logger.dart'; + +/// One unread Moodle notification (grade posted, forum post, assignment +/// change, message). +class MoodleNotification { + final int id; + final String subject; + final DateTime? time; + + const MoodleNotification({required this.id, required this.subject, this.time}); +} + +/// One upcoming Moodle deadline or calendar event. +class MoodleEvent { + final int id; + final String name; + final String? course; + final DateTime? due; + + const MoodleEvent({required this.id, required this.name, this.course, this.due}); +} + +class MoodleLoginException implements Exception { + final String reason; + const MoodleLoginException(this.reason); + @override + String toString() => 'Moodle bejelentkezés sikertelen: $reason'; +} + +/// Read-only client for the Moodle mobile web service. +/// +/// Login uses `login/token.php` with the `moodle_mobile_app` service. The +/// password is only sent to that endpoint, once, and the returned token is +/// kept instead. The school site must keep the mobile service enabled and use +/// plain username and password login (no SSO), otherwise [login] throws. +class MoodleClient { + final Uri baseUri; + final http.Client _client; + String? token; + int? userId; + + MoodleClient(String baseUrl, {this.token, http.Client? client}) + : baseUri = Uri.parse(baseUrl), + _client = client ?? http.Client(); + + /// The base url must be https and have a host, so a typo cannot send the + /// password over plain http or to a path-less value. + static bool isValidBaseUrl(String? url) { + if (url == null) return false; + final uri = Uri.tryParse(url); + return uri != null && uri.scheme == 'https' && uri.host.isNotEmpty; + } + + Uri _endpoint(String path, [Map? query]) { + final basePath = baseUri.path.endsWith('/') ? baseUri.path : '${baseUri.path}/'; + return baseUri.replace(path: '$basePath$path', queryParameters: query); + } + + Future login(String username, String password) async { + // POST body, so the password never lands in a URL or in server logs. + final response = await _client + .post( + _endpoint('login/token.php'), + body: {'username': username, 'password': password, 'service': 'moodle_mobile_app'}, + ) + .timeout(const Duration(seconds: 20)); + if (response.statusCode != 200) { + throw MoodleLoginException('HTTP ${response.statusCode}'); + } + final data = jsonDecode(response.body); + if (data is Map && data['token'] is String) { + token = data['token'] as String; + return; + } + final reason = data is Map ? (data['error'] ?? data['errorcode'] ?? 'ismeretlen hiba') : 'ismeretlen válasz'; + throw MoodleLoginException(reason.toString()); + } + + Future _call(String function, Map params) async { + final response = await _client + .post( + _endpoint('webservice/rest/server.php'), + body: { + 'wstoken': token ?? '', + 'wsfunction': function, + 'moodlewsrestformat': 'json', + ...params, + }, + ) + .timeout(const Duration(seconds: 20)); + if (response.statusCode != 200) { + PalaLogger.debug('Moodle $function: HTTP ${response.statusCode}'); + return null; + } + final data = jsonDecode(response.body); + if (data is Map && data.containsKey('exception')) { + PalaLogger.debug('Moodle $function: ${data['errorcode']}'); + // An invalid token means the caller has to log in again. + if (data['errorcode'] == 'invalidtoken') throw const MoodleLoginException('lejárt token'); + return null; + } + return data; + } + + Future getUserId() async { + if (userId != null) return userId; + final data = await _call('core_webservice_get_site_info', {}); + if (data is Map && data['userid'] is int) { + userId = data['userid'] as int; + } + return userId; + } + + /// Unread notifications of the logged-in user, newest first. + Future?> getNotifications({int limit = 30}) async { + final uid = await getUserId(); + if (uid == null) return null; + final data = await _call('message_popup_get_popup_notifications', { + 'useridto': '$uid', + 'limit': '$limit', + 'offset': '0', + }); + return parseNotifications(data); + } + + static List? parseNotifications(dynamic data) { + if (data is! Map || data['notifications'] is! List) return null; + final result = []; + for (final n in data['notifications'] as List) { + if (n is! Map || n['id'] is! int) continue; + final read = n['read'] == true; + if (read) continue; + final created = n['timecreated']; + result.add(MoodleNotification( + id: n['id'] as int, + subject: (n['subject'] ?? n['shortenedsubject'] ?? '').toString(), + time: created is int ? DateTime.fromMillisecondsSinceEpoch(created * 1000) : null, + )); + } + return result; + } + + /// Deadlines and action events from now to [days] days ahead. + Future?> getUpcomingEvents({int days = 14, DateTime? now}) async { + final from = (now ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000; + final to = from + days * 86400; + final data = await _call('core_calendar_get_action_events_by_timesort', { + 'timesortfrom': '$from', + 'timesortto': '$to', + 'limitnum': '50', + }); + return parseEvents(data); + } + + static List? parseEvents(dynamic data) { + if (data is! Map || data['events'] is! List) return null; + final result = []; + for (final e in data['events'] as List) { + if (e is! Map || e['id'] is! int) continue; + final sort = e['timesort']; + final course = e['course']; + result.add(MoodleEvent( + id: e['id'] as int, + name: (e['name'] ?? '').toString(), + course: course is Map ? course['fullname']?.toString() : null, + due: sort is int ? DateTime.fromMillisecondsSinceEpoch(sort * 1000) : null, + )); + } + result.sort((a, b) => (a.due ?? DateTime(9999)).compareTo(b.due ?? DateTime(9999))); + return result; + } +} diff --git a/lib/app/cli_app.dart b/lib/app/cli_app.dart index 9ce2016..30d446d 100644 --- a/lib/app/cli_app.dart +++ b/lib/app/cli_app.dart @@ -9,6 +9,7 @@ import 'package:interact/interact.dart'; import 'package:pala/api/api.dart'; import 'package:pala/api/client.dart'; import 'package:pala/api/demo_client.dart'; +import 'package:pala/api/moodle_client.dart'; import 'package:pala/models/models.dart'; import 'package:pala/rules/absence_rules.dart'; import 'package:pala/rules/grade_rules.dart'; @@ -160,6 +161,7 @@ class PalaApp { _runAlerts = []; try { await _checkNewItems(); + await _checkMoodle(); } finally { final alerts = _runAlerts!; _runAlerts = null; diff --git a/lib/app/daemon/daemon_logic.dart b/lib/app/daemon/daemon_logic.dart index 1a65c87..8b516a3 100644 --- a/lib/app/daemon/daemon_logic.dart +++ b/lib/app/daemon/daemon_logic.dart @@ -187,6 +187,78 @@ extension PalaAppDaemonLogic on PalaApp { await slack.send('Pala', body.toString()); } + // Moodle is optional: it runs only when PALA_MOODLE_URL is set. The first run + // logs in with PALA_MOODLE_USER and PALA_MOODLE_PASSWORD and keeps only the + // token in the auth data, later runs reuse that token. + Future _checkMoodle() async { + final url = Platform.environment['PALA_MOODLE_URL']?.trim(); + if (url == null || url.isEmpty) return; + if (!MoodleClient.isValidBaseUrl(url)) { + await _showToast('Pala (Moodle)', 'A PALA_MOODLE_URL érvénytelen, https cím kell.'); + return; + } + + final state = AppState.instance; + var authData = state.getAuthData(); + final moodle = MoodleClient(url, token: authData['moodleToken']?.toString()); + + try { + if (moodle.token == null) { + final user = Platform.environment['PALA_MOODLE_USER']; + final password = Platform.environment['PALA_MOODLE_PASSWORD']; + if (user == null || password == null) return; + await moodle.login(user, password); + authData = state.getAuthData(); + authData['moodleToken'] = moodle.token; + state.saveAuthData(authData); + } + + final firstRun = authData['moodleNotifiedIds'] == null; + final seenNotifications = + ((authData['moodleNotifiedIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); + final seenEvents = + ((authData['moodleEventIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); + + final notifications = await moodle.getNotifications(); + if (notifications != null) { + for (final n in notifications) { + if (seenNotifications.add('${n.id}') && !firstRun) { + await _showToast('Pala (Moodle)', 'Moodle: ${n.subject}'); + } + } + seenNotifications.retainWhere(notifications.map((n) => '${n.id}').toSet().contains); + } + + final events = await moodle.getUpcomingEvents(); + if (events != null) { + for (final e in events) { + if (seenEvents.add('${e.id}') && !firstRun) { + final due = e.due; + final dueLabel = due == null + ? '' + : ', határidő: ${due.year}.${due.month.toString().padLeft(2, '0')}.${due.day.toString().padLeft(2, '0')}.'; + final course = e.course != null ? ' (${e.course})' : ''; + await _showToast('Pala (Moodle)', 'Új Moodle esemény: ${e.name}$course$dueLabel'); + } + } + seenEvents.retainWhere(events.map((e) => '${e.id}').toSet().contains); + } + + authData = state.getAuthData(); + authData['moodleNotifiedIds'] = seenNotifications.toList(); + authData['moodleEventIds'] = seenEvents.toList(); + state.saveAuthData(authData); + } on MoodleLoginException catch (e) { + // Drop a dead token so the next run logs in again. + authData = state.getAuthData(); + authData.remove('moodleToken'); + state.saveAuthData(authData); + await _showToast('Pala (Moodle)', '$e'); + } catch (e) { + PalaLogger.debug('Moodle ellenőrzés sikertelen: $e'); + } + } + void _setupDaemon(bool enable) { if (enable) { installDaemon(); From 65968ba783c75b944d267040d21c1d2a5f1a0cb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Solti=20Csongor=20P=C3=A9ter?= Date: Mon, 9 Nov 2026 17:27:48 +0100 Subject: [PATCH 3/5] feat: add a Gemini summary to the daemon's Slack message With PALA_GEMINI_API_KEY (or ~/.config/pala/gemini_key) set, a run that has new alerts appends a short Hungarian summary from Gemini. The key goes in the x-goog-api-key header, the model name is validated, and a run without alerts makes no API call. Co-Authored-By: Claude Opus 5.5 --- lib/app/cli_app.dart | 1 + lib/app/daemon/daemon_logic.dart | 9 +- lib/utils/gemini_summarizer.dart | 128 +++++++++++++++++++++++++++ test/gemini_moodle_test.dart | 147 +++++++++++++++++++++++++++++++ 4 files changed, 283 insertions(+), 2 deletions(-) create mode 100644 lib/utils/gemini_summarizer.dart create mode 100644 test/gemini_moodle_test.dart diff --git a/lib/app/cli_app.dart b/lib/app/cli_app.dart index 30d446d..60749f2 100644 --- a/lib/app/cli_app.dart +++ b/lib/app/cli_app.dart @@ -29,6 +29,7 @@ import 'package:pala/app/tui/screen_buffer.dart'; import 'package:pala/app/tui/tui_state.dart'; import 'package:pala/app/tui/tui_views.dart'; import 'package:pala/utils/logger.dart'; +import 'package:pala/utils/gemini_summarizer.dart'; import 'package:pala/utils/slack_notifier.dart'; import 'package:pala/utils/win32_console.dart'; import 'package:pala/version.dart'; diff --git a/lib/app/daemon/daemon_logic.dart b/lib/app/daemon/daemon_logic.dart index 8b516a3..2a8b8f4 100644 --- a/lib/app/daemon/daemon_logic.dart +++ b/lib/app/daemon/daemon_logic.dart @@ -176,14 +176,19 @@ extension PalaAppDaemonLogic on PalaApp { } } - /// Sends the alerts of one run as a single Slack message. A run without - /// news posts nothing. + /// Sends the alerts of one run as a single Slack message. The Gemini + /// summary is added only when there is at least one alert, so a run without + /// news posts nothing and costs no API call. Future _flushAlertsToSlack(List alerts) async { if (alerts.isEmpty) return; final configDir = AppState.instance.configDir; final slack = SlackNotifier.fromConfig(configDir); if (!slack.isEnabled) return; + final summary = await GeminiSummarizer.fromConfig(configDir).summarize(alerts); final body = StringBuffer(alerts.map((a) => '• $a').join('\n')); + if (summary != null) { + body.write('\n\nÖsszefoglaló: $summary'); + } await slack.send('Pala', body.toString()); } diff --git a/lib/utils/gemini_summarizer.dart b/lib/utils/gemini_summarizer.dart new file mode 100644 index 0000000..523aa80 --- /dev/null +++ b/lib/utils/gemini_summarizer.dart @@ -0,0 +1,128 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:pala/utils/logger.dart'; + +/// Turns the alerts of one daemon run into a short Hungarian summary with the +/// Gemini API. +/// +/// The API key is a secret, so it is read from `PALA_GEMINI_API_KEY` or from +/// the owner-only `gemini_key` file in the config directory, never from argv. +/// The summary is optional: when the key is missing or the call fails, +/// [summarize] returns null and the plain alerts still go out. +/// +/// Privacy: the prompt only holds the alert lines (subject names, grade +/// values, dates, Moodle course titles). No student name, class or school id +/// is added. Free-tier content may be used by Google to improve its products, +/// so keep the alert lines free of personal data. +class GeminiSummarizer { + static const defaultModel = 'gemini-2.5-flash'; + static const _host = 'generativelanguage.googleapis.com'; + static const _timeout = Duration(seconds: 20); + static const _maxInputChars = 4000; + + final String? apiKey; + final String model; + final http.Client _client; + + GeminiSummarizer(this.apiKey, {String? model, http.Client? client}) + : model = (model == null || model.isEmpty) ? defaultModel : model, + _client = client ?? http.Client(); + + factory GeminiSummarizer.fromConfig(String configDir, {http.Client? client}) { + final model = Platform.environment['PALA_GEMINI_MODEL']?.trim(); + final fromEnv = Platform.environment['PALA_GEMINI_API_KEY']?.trim(); + if (fromEnv != null && fromEnv.isNotEmpty) { + return GeminiSummarizer(fromEnv, model: model, client: client); + } + final file = File('$configDir/gemini_key'); + if (file.existsSync()) { + final value = file.readAsStringSync().trim(); + if (value.isNotEmpty) { + return GeminiSummarizer(value, model: model, client: client); + } + } + return GeminiSummarizer(null, model: model, client: client); + } + + bool get isEnabled => apiKey != null && apiKey!.isNotEmpty; + + /// The model name ends up in the URL path, so only the characters a model + /// id uses are allowed. + static bool isValidModel(String model) => + RegExp(r'^[a-zA-Z0-9._-]+$').hasMatch(model); + + static const instruction = + 'Te egy diákasszisztens vagy. Az alábbi sorok új iskolai értesítések ' + '(Kréta és Moodle). Írj magyarul 2-4 rövid mondatos összefoglalót. ' + 'Emeld ki a legsürgősebb határidőt vagy dolgozatot, és adj egy ' + 'konkrét teendőt. Ne találj ki adatot, csak a megadott sorokból ' + 'dolgozz. Ne használj emojit és formázást.'; + + static Map buildRequest(List alerts) { + var text = alerts.join('\n'); + if (text.length > _maxInputChars) { + text = text.substring(0, _maxInputChars); + } + return { + 'systemInstruction': { + 'parts': [ + {'text': instruction} + ] + }, + 'contents': [ + { + 'role': 'user', + 'parts': [ + {'text': text} + ] + } + ], + 'generationConfig': {'temperature': 0.3, 'maxOutputTokens': 300}, + }; + } + + /// Pulls the generated text out of a `generateContent` response. + static String? parseResponse(String body) { + try { + final data = jsonDecode(body); + final parts = data['candidates']?[0]?['content']?['parts']; + if (parts is! List) return null; + final text = parts + .map((p) => p is Map ? (p['text'] ?? '').toString() : '') + .join() + .trim(); + return text.isEmpty ? null : text; + } catch (_) { + return null; + } + } + + Future summarize(List alerts) async { + if (!isEnabled || alerts.isEmpty || !isValidModel(model)) return null; + final uri = Uri.https(_host, '/v1beta/models/$model:generateContent'); + try { + final response = await _client + .post( + uri, + headers: { + 'Content-Type': 'application/json', + 'x-goog-api-key': apiKey!, + }, + body: jsonEncode(buildRequest(alerts)), + ) + .timeout(_timeout); + if (response.statusCode != 200) { + PalaLogger.debug('Gemini: HTTP ${response.statusCode}'); + return null; + } + return parseResponse(response.body); + } catch (e) { + // The key travels in a header, never in the URL, so the error text is + // safe to log. + PalaLogger.debug('Gemini: $e'); + return null; + } + } +} diff --git a/test/gemini_moodle_test.dart b/test/gemini_moodle_test.dart new file mode 100644 index 0000000..31185ba --- /dev/null +++ b/test/gemini_moodle_test.dart @@ -0,0 +1,147 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pala/api/moodle_client.dart'; +import 'package:pala/utils/gemini_summarizer.dart'; +import 'package:test/test.dart'; + +void main() { + group('GeminiSummarizer', () { + test('is disabled without a key and makes no request', () async { + var called = false; + final client = MockClient((_) async { + called = true; + return http.Response('{}', 200); + }); + final summarizer = GeminiSummarizer(null, client: client); + expect(summarizer.isEnabled, isFalse); + expect(await summarizer.summarize(['Új jegy']), isNull); + expect(called, isFalse); + }); + + test('makes no request for an empty alert list', () async { + var called = false; + final client = MockClient((_) async { + called = true; + return http.Response('{}', 200); + }); + expect(await GeminiSummarizer('k', client: client).summarize([]), isNull); + expect(called, isFalse); + }); + + test('sends the key in a header, not in the URL, and parses the text', () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response( + jsonEncode({ + 'candidates': [ + { + 'content': { + 'parts': [ + {'text': 'Holnap dolgozat van. Tanulj matekot.'} + ] + } + } + ] + }), + 200, + ); + }); + final result = await GeminiSummarizer('secret-key', client: client).summarize(['Holnap dolgozat: Matek']); + expect(result, 'Holnap dolgozat van. Tanulj matekot.'); + expect(captured.url.host, 'generativelanguage.googleapis.com'); + expect(captured.url.toString(), isNot(contains('secret-key'))); + expect(captured.headers['x-goog-api-key'], 'secret-key'); + expect(captured.url.path, contains(GeminiSummarizer.defaultModel)); + }); + + test('returns null on HTTP errors and malformed bodies', () async { + final error = MockClient((_) async => http.Response('nope', 429)); + expect(await GeminiSummarizer('k', client: error).summarize(['x']), isNull); + expect(GeminiSummarizer.parseResponse('not json'), isNull); + expect(GeminiSummarizer.parseResponse('{"candidates":[]}'), isNull); + }); + + test('rejects a model name that could alter the URL path', () async { + var called = false; + final client = MockClient((_) async { + called = true; + return http.Response('{}', 200); + }); + final summarizer = GeminiSummarizer('k', model: '../evil', client: client); + expect(await summarizer.summarize(['x']), isNull); + expect(called, isFalse); + }); + + test('truncates very long input', () { + final request = GeminiSummarizer.buildRequest(List.filled(2000, 'sor')); + final text = request['contents'][0]['parts'][0]['text'] as String; + expect(text.length, lessThanOrEqualTo(4000)); + }); + }); + + group('MoodleClient', () { + test('only accepts https base urls', () { + expect(MoodleClient.isValidBaseUrl('https://moodle.iskolam.hu'), isTrue); + expect(MoodleClient.isValidBaseUrl('http://moodle.iskolam.hu'), isFalse); + expect(MoodleClient.isValidBaseUrl('moodle.iskolam.hu'), isFalse); + expect(MoodleClient.isValidBaseUrl(null), isFalse); + }); + + test('login posts the password in the body and keeps the token', () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response('{"token":"abc123"}', 200); + }); + final moodle = MoodleClient('https://moodle.iskolam.hu', client: client); + await moodle.login('diak', 'titok'); + expect(moodle.token, 'abc123'); + expect(captured.url.toString(), 'https://moodle.iskolam.hu/login/token.php'); + expect(captured.url.query, isEmpty); + expect(captured.body, contains('service=moodle_mobile_app')); + }); + + test('login throws with the server reason on a bad login', () async { + final client = MockClient((_) async => http.Response('{"error":"Invalid login","errorcode":"invalidlogin"}', 200)); + final moodle = MoodleClient('https://moodle.iskolam.hu', client: client); + expect(() => moodle.login('diak', 'rossz'), throwsA(isA())); + expect(moodle.token, isNull); + }); + + test('an invalid token raises MoodleLoginException so the caller logs in again', () async { + final client = MockClient((_) async => + http.Response('{"exception":"moodle_exception","errorcode":"invalidtoken"}', 200)); + final moodle = MoodleClient('https://moodle.iskolam.hu', token: 'old', client: client); + expect(() => moodle.getNotifications(), throwsA(isA())); + }); + + test('parseNotifications keeps only unread items', () { + final result = MoodleClient.parseNotifications({ + 'notifications': [ + {'id': 1, 'subject': 'Új jegy', 'read': false, 'timecreated': 1700000000}, + {'id': 2, 'subject': 'Régi', 'read': true}, + {'subject': 'Azonosító nélkül'}, + ] + }); + expect(result, isNotNull); + expect(result!.length, 1); + expect(result.first.id, 1); + expect(result.first.subject, 'Új jegy'); + }); + + test('parseEvents sorts by due time and reads the course name', () { + final result = MoodleClient.parseEvents({ + 'events': [ + {'id': 2, 'name': 'B', 'timesort': 1700100000, 'course': {'fullname': 'Matek'}}, + {'id': 1, 'name': 'A', 'timesort': 1700000000}, + ] + }); + expect(result!.map((e) => e.name).toList(), ['A', 'B']); + expect(result.last.course, 'Matek'); + expect(MoodleClient.parseEvents('x'), isNull); + }); + }); +} From 41f426ec2a6f57b10164480ccd8282aebbcf06b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Solti=20Csongor=20P=C3=A9ter?= Date: Mon, 9 Nov 2026 17:27:48 +0100 Subject: [PATCH 4/5] docs: describe Slack, Gemini and Moodle in the user guide Co-Authored-By: Claude Opus 5.5 --- docs/USER.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/USER.md b/docs/USER.md index 84da862..1bc1cfe 100644 --- a/docs/USER.md +++ b/docs/USER.md @@ -30,6 +30,10 @@ A főmenü "Beállítások" opciójában az alábbi funkciók érhetők el: - Git-alapú jegytörténet: Lokális Git tárolóba mentés (`Pala_Jegyek_Git`). - **Profilkezelés**: Váltás a mentett fiókok között. - **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 Slack üzenetben érkezik. +- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó Slack üzenet végére rövid magyar összefoglaló kerül. Ú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 jegyek, tantárgyak és dátumok szövegét tartalmazza, nevet 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. +- **Futtatás számítógép nélkül**: a `pala --daemon` egyetlen ellenőrzés után kilép, ezért ütemezett feladatból futtatható, például GitHub Actionsből. Sikertelen Kréta belépésnél Slack hibaüzenetet küld, és hibakóddal lép ki. ## 4. Komponensek, Rendszerintegráció & Eltávolítás A Pala teljes komponenskezelési támogatással rendelkezik a parancssorból és a grafikus beállításokból is: From 04c6b88f96a096b9d5deef9f826bcaaaac1420ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Solti=20Csongor=20P=C3=A9ter?= Date: Mon, 9 Nov 2026 17:30:33 +0100 Subject: [PATCH 5/5] fix: keep names out of the Gemini prompt and turn off Flash thinking The substitute-teacher name and Moodle notification subjects now go only to Slack; Gemini gets a version of those alerts without them. On gemini-2.5-flash models the request sets thinkingBudget 0, because thinking tokens count against maxOutputTokens and could leave the summary empty. Other models get no budget and no output cap. Co-Authored-By: Claude Opus 5.5 --- docs/USER.md | 2 +- lib/app/cli_app.dart | 5 +++-- lib/app/daemon/daemon_logic.dart | 21 ++++++++++++++------- lib/utils/gemini_summarizer.dart | 32 +++++++++++++++++++++++++------- test/gemini_moodle_test.dart | 29 +++++++++++++++++++++++++++++ 5 files changed, 72 insertions(+), 17 deletions(-) diff --git a/docs/USER.md b/docs/USER.md index 1bc1cfe..f324e5e 100644 --- a/docs/USER.md +++ b/docs/USER.md @@ -31,7 +31,7 @@ A főmenü "Beállítások" opciójában az alábbi funkciók érhetők el: - **Profilkezelés**: Váltás a mentett fiókok között. - **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 Slack üzenetben érkezik. -- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó Slack üzenet végére rövid magyar összefoglaló kerül. Ú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 jegyek, tantárgyak és dátumok szövegét tartalmazza, nevet nem. Az ingyenes szint tartalmát a Google felhasználhatja a termékei fejlesztéséhez. +- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó Slack üzenet végére rövid magyar összefoglaló kerül. Ú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 Slack ü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. - **Futtatás számítógép nélkül**: a `pala --daemon` egyetlen ellenőrzés után kilép, ezért ütemezett feladatból futtatható, például GitHub Actionsből. Sikertelen Kréta belépésnél Slack hibaüzenetet küld, és hibakóddal lép ki. diff --git a/lib/app/cli_app.dart b/lib/app/cli_app.dart index 60749f2..d47840d 100644 --- a/lib/app/cli_app.dart +++ b/lib/app/cli_app.dart @@ -69,8 +69,9 @@ class PalaApp { /// Alert lines of the current daemon run. While it is non-null, Slack gets /// one combined message at the end (with the optional Gemini summary) - /// instead of one message per alert. - List? _runAlerts; + /// instead of one message per alert. [gemini] is the same alert without + /// names or free text, the only form that goes to the Gemini prompt. + List<({String slack, String gemini})>? _runAlerts; String? studentUid; File _getAuthFile() { diff --git a/lib/app/daemon/daemon_logic.dart b/lib/app/daemon/daemon_logic.dart index 2a8b8f4..860e062 100644 --- a/lib/app/daemon/daemon_logic.dart +++ b/lib/app/daemon/daemon_logic.dart @@ -122,7 +122,8 @@ extension PalaAppDaemonLogic on PalaApp { if (lesson.isCancelled) { await _showToast('Pala (Kréta)', '$dayLabel elmarad: ${lesson.subject} (${lesson.lessonNumber}. óra)'); } else { - await _showToast('Pala (Kréta)', '$dayLabel helyettesítés: ${lesson.subject} — ${lesson.substituteTeacher}'); + await _showToast('Pala (Kréta)', '$dayLabel helyettesítés: ${lesson.subject} — ${lesson.substituteTeacher}', + geminiText: '$dayLabel helyettesítés: ${lesson.subject}'); } notifiedIds.add(id); } @@ -136,13 +137,18 @@ extension PalaAppDaemonLogic on PalaApp { // The text comes from Kréta (subject and teacher names), so it is passed as // data (environment variables or argv) and never spliced into script source. - Future _showToast(String title, String message) async { + // + // [geminiText] is what the Gemini summary sees instead of [message]. Pass it + // whenever the message holds a person's name or free text from a server + // (a teacher, a Moodle notification), so only subjects, grades, dates and + // course or deadline titles reach Gemini. + Future _showToast(String title, String message, {String? geminiText}) async { // Slack goes first: it is the channel that reaches the phone, and a // missing desktop notifier (no notify-send on a server or in Termux) // must not block it. final collecting = _runAlerts; if (collecting != null) { - collecting.add(message); + collecting.add((slack: message, gemini: geminiText ?? message)); } else { await SlackNotifier.fromConfig(AppState.instance.configDir).send(title, message); } @@ -179,13 +185,13 @@ extension PalaAppDaemonLogic on PalaApp { /// Sends the alerts of one run as a single Slack message. The Gemini /// summary is added only when there is at least one alert, so a run without /// news posts nothing and costs no API call. - Future _flushAlertsToSlack(List alerts) async { + Future _flushAlertsToSlack(List<({String slack, String gemini})> alerts) async { if (alerts.isEmpty) return; final configDir = AppState.instance.configDir; final slack = SlackNotifier.fromConfig(configDir); if (!slack.isEnabled) return; - final summary = await GeminiSummarizer.fromConfig(configDir).summarize(alerts); - final body = StringBuffer(alerts.map((a) => '• $a').join('\n')); + final summary = await GeminiSummarizer.fromConfig(configDir).summarize(alerts.map((a) => a.gemini).toList()); + final body = StringBuffer(alerts.map((a) => '• ${a.slack}').join('\n')); if (summary != null) { body.write('\n\nÖsszefoglaló: $summary'); } @@ -228,7 +234,8 @@ extension PalaAppDaemonLogic on PalaApp { if (notifications != null) { for (final n in notifications) { if (seenNotifications.add('${n.id}') && !firstRun) { - await _showToast('Pala (Moodle)', 'Moodle: ${n.subject}'); + // Notification subjects often name the sender or the poster. + await _showToast('Pala (Moodle)', 'Moodle: ${n.subject}', geminiText: 'Új Moodle értesítés'); } } seenNotifications.retainWhere(notifications.map((n) => '${n.id}').toSet().contains); diff --git a/lib/utils/gemini_summarizer.dart b/lib/utils/gemini_summarizer.dart index 523aa80..0676ed3 100644 --- a/lib/utils/gemini_summarizer.dart +++ b/lib/utils/gemini_summarizer.dart @@ -12,10 +12,12 @@ import 'package:pala/utils/logger.dart'; /// The summary is optional: when the key is missing or the call fails, /// [summarize] returns null and the plain alerts still go out. /// -/// Privacy: the prompt only holds the alert lines (subject names, grade -/// values, dates, Moodle course titles). No student name, class or school id -/// is added. Free-tier content may be used by Google to improve its products, -/// so keep the alert lines free of personal data. +/// Privacy: the prompt only holds the Gemini form of each alert line +/// (subject names, grade values, grade and exam topics, dates, Moodle course +/// and deadline titles). Teacher names and Moodle notification text stay in +/// the Slack message and are left out here, and no student name, class or +/// school id is added. Free-tier content may be used by Google to improve its +/// products, so a new alert that holds a name must pass a separate Gemini text. class GeminiSummarizer { static const defaultModel = 'gemini-2.5-flash'; static const _host = 'generativelanguage.googleapis.com'; @@ -60,7 +62,23 @@ class GeminiSummarizer { 'konkrét teendőt. Ne találj ki adatot, csak a megadott sorokból ' 'dolgozz. Ne használj emojit és formázást.'; - static Map buildRequest(List alerts) { + /// 2.5 Flash thinks by default, and the thinking tokens count against + /// maxOutputTokens, so a small cap can leave no room for the answer. A + /// short summary needs no thinking, so it is turned off there. Other models + /// may reject a zero budget, so they get neither setting and the + /// instruction keeps the answer short. + static Map _generationConfig(String model) { + if (model.startsWith('gemini-2.5-flash')) { + return { + 'temperature': 0.3, + 'maxOutputTokens': 300, + 'thinkingConfig': {'thinkingBudget': 0}, + }; + } + return {'temperature': 0.3}; + } + + static Map buildRequest(List alerts, {String model = defaultModel}) { var text = alerts.join('\n'); if (text.length > _maxInputChars) { text = text.substring(0, _maxInputChars); @@ -79,7 +97,7 @@ class GeminiSummarizer { ] } ], - 'generationConfig': {'temperature': 0.3, 'maxOutputTokens': 300}, + 'generationConfig': _generationConfig(model), }; } @@ -110,7 +128,7 @@ class GeminiSummarizer { 'Content-Type': 'application/json', 'x-goog-api-key': apiKey!, }, - body: jsonEncode(buildRequest(alerts)), + body: jsonEncode(buildRequest(alerts, model: model)), ) .timeout(_timeout); if (response.statusCode != 200) { diff --git a/test/gemini_moodle_test.dart b/test/gemini_moodle_test.dart index 31185ba..1c40d97 100644 --- a/test/gemini_moodle_test.dart +++ b/test/gemini_moodle_test.dart @@ -80,6 +80,35 @@ void main() { final text = request['contents'][0]['parts'][0]['text'] as String; expect(text.length, lessThanOrEqualTo(4000)); }); + + // 2.5 Flash thinks by default and the thinking tokens count against + // maxOutputTokens, which can leave no room for the answer. + test('turns thinking off for 2.5 Flash models', () { + for (final model in ['gemini-2.5-flash', 'gemini-2.5-flash-lite']) { + final config = GeminiSummarizer.buildRequest(['x'], model: model)['generationConfig'] as Map; + expect(config['thinkingConfig'], {'thinkingBudget': 0}, reason: model); + expect(config['maxOutputTokens'], 300, reason: model); + } + }); + + // Other models may reject a zero thinking budget, and their thinking + // would eat a small output cap, so neither is sent. + test('sends no thinking budget or output cap for other models', () { + final config = GeminiSummarizer.buildRequest(['x'], model: 'gemini-2.5-pro')['generationConfig'] as Map; + expect(config.containsKey('thinkingConfig'), isFalse); + expect(config.containsKey('maxOutputTokens'), isFalse); + }); + + test('the request body uses the configured model settings', () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response('{}', 200); + }); + await GeminiSummarizer('k', client: client).summarize(['x']); + final body = jsonDecode(captured.body) as Map; + expect(body['generationConfig']['thinkingConfig'], {'thinkingBudget': 0}); + }); }); group('MoodleClient', () {