diff --git a/firka/android/app/build.gradle.kts b/firka/android/app/build.gradle.kts index 3072581a..7878bf90 100644 --- a/firka/android/app/build.gradle.kts +++ b/firka/android/app/build.gradle.kts @@ -14,6 +14,7 @@ android { compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 + isCoreLibraryDesugaringEnabled = true } buildFeatures { compose = true @@ -73,6 +74,7 @@ configurations.all { dependencies { implementation("androidx.glance:glance-appwidget:1.1.1") implementation("com.google.android.gms:play-services-wearable:18.1.0") + coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4") } // Ensure .env exists before Flutter bundles assets (copy from .env.example if missing) val envFile = file("${project.projectDir}/../../.env") diff --git a/firka/lib/core/last_seen_helper.dart b/firka/lib/core/last_seen_helper.dart index ffc42ef8..a997fd7a 100644 --- a/firka/lib/core/last_seen_helper.dart +++ b/firka/lib/core/last_seen_helper.dart @@ -12,6 +12,19 @@ class LastSeenHelper { static const omissions = "omissions"; static const messages = "messages"; + /// Separate dedup namespace for the FCM wakeup notification pipeline + /// (`NotificationDiffService`), distinct from the kinds above: those track + /// what the user has manually *opened* in the UI (e.g. for the "surprise + /// grades" reveal), which a background push must not silently mark as seen. + static const notifGrades = "notif_grades"; + static const notifHomework = "notif_homework"; + static const notifTests = "notif_tests"; + static const notifAbsences = "notif_absences"; + static const notifLessons = "notif_lessons"; + static const notifLessonsCancelled = "notif_lessons_cancelled"; + static const notifLessonsSubstituted = "notif_lessons_substituted"; + static const notifMessages = "notif_messages"; + static Map _read() { try { final decoded = jsonDecode(Settings.lastSeen.value); diff --git a/firka/lib/services/fcm_headless_bootstrap.dart b/firka/lib/services/fcm_headless_bootstrap.dart new file mode 100644 index 00000000..6f7b2de4 --- /dev/null +++ b/firka/lib/services/fcm_headless_bootstrap.dart @@ -0,0 +1,43 @@ +import 'package:flutter/widgets.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:path_provider/path_provider.dart'; + +import 'package:firka/app/app_state.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/l10n/app_localizations_hu.dart'; +import 'package:firka_common/data/database.dart'; + +/// Minimal, isolate-local stand-in for `initializeApp()` (see +/// `lib/app/initialization.dart`), used only by the FCM background message +/// isolate. That isolate has none of the running app's in-memory state (it's +/// a fresh Dart isolate, possibly a fresh process) — but `KretaClient` reads +/// the global `initData` (for `userAgent`/`toastCubit`) unconditionally, so +/// something has to populate it before a background wakeup can fetch data. +/// +/// Deliberately skips everything UI/theming/watch-sync/live-activity +/// related: those either don't apply headlessly or actively assume a +/// running app (native platform channels registered on the main +/// FlutterEngine, iCloud sync, etc). Idempotent per isolate — a warm +/// background isolate handling multiple wakeups only bootstraps once. +Future bootstrapHeadless() async { + if (initDone) return; + + final isar = await initDB(); + final settings = SettingsRepository(isar); + await settings.loadAll(); + + initData = AppInitialization( + isar: isar, + appDir: await getApplicationDocumentsDirectory(), + // Real device info requires a MethodChannel handler that's only + // registered on the main FlutterEngine; a placeholder is fine here, + // it only affects the User-Agent header string. + devInfo: DeviceInfo('background', '0', '0'), + packageInfo: await PackageInfo.fromPlatform(), + settings: settings, + l10n: AppLocalizationsHu(), + navigatorKey: GlobalKey(), + ); + Settings = settings; + initDone = true; +} diff --git a/firka/lib/services/local_notification_service.dart b/firka/lib/services/local_notification_service.dart new file mode 100644 index 00000000..9e1c7abc --- /dev/null +++ b/firka/lib/services/local_notification_service.dart @@ -0,0 +1,67 @@ +import 'package:flutter_local_notifications/flutter_local_notifications.dart'; + +/// Thin wrapper around flutter_local_notifications for showing the +/// notifications posted by [NotificationDiffService] after a background FCM +/// wakeup. Usable from both the main isolate and the headless background +/// isolate (each needs its own [init] call — plugin state isn't shared +/// across isolates). +class LocalNotificationService { + static const _channelId = 'firka_updates'; + static const _channelName = 'Firka frissítések'; + static const _channelDescription = + 'Új jegyek, házi feladatok, hiányzások és üzenetek értesítései.'; + + static final FlutterLocalNotificationsPlugin _plugin = + FlutterLocalNotificationsPlugin(); + static bool _initialized = false; + + static Future init() async { + if (_initialized) return; + + const androidInit = AndroidInitializationSettings('ic_notification'); + const iosInit = DarwinInitializationSettings(); + await _plugin.initialize( + const InitializationSettings(android: androidInit, iOS: iosInit), + ); + + const channel = AndroidNotificationChannel( + _channelId, + _channelName, + description: _channelDescription, + importance: Importance.defaultImportance, + ); + await _plugin + .resolvePlatformSpecificImplementation< + AndroidFlutterLocalNotificationsPlugin + >() + ?.createNotificationChannel(channel); + + _initialized = true; + } + + /// Shows a single notification. [id] should be stable per logical + /// notification (e.g. derived from account key + category) so a repeat + /// wakeup that finds the same new items updates rather than duplicates it. + static Future show({ + required int id, + required String title, + required String body, + }) async { + await init(); + await _plugin.show( + id, + title, + body, + const NotificationDetails( + android: AndroidNotificationDetails( + _channelId, + _channelName, + channelDescription: _channelDescription, + importance: Importance.defaultImportance, + priority: Priority.defaultPriority, + ), + iOS: DarwinNotificationDetails(), + ), + ); + } +} diff --git a/firka/lib/services/notification_diff_service.dart b/firka/lib/services/notification_diff_service.dart new file mode 100644 index 00000000..c2fa458c --- /dev/null +++ b/firka/lib/services/notification_diff_service.dart @@ -0,0 +1,245 @@ +import 'dart:convert'; + +import 'package:isar_community/isar.dart'; + +import 'package:firka_common/data/database.dart'; +import 'package:firka_common/data/last_seen.dart'; +import 'package:firka_common/data/models/generic_cache_model.dart'; +import 'package:firka_common/data/models/lesson_cache_model.dart'; +import 'package:firka_common/data/models/token_model.dart'; +import 'package:logging/logging.dart'; + +import 'package:firka/api/client/kreta_client.dart'; +import 'package:firka/core/last_seen_helper.dart'; +import 'package:firka/core/settings/settings_repository.dart'; +import 'package:firka/core/settings/settings_schema.dart'; +import 'package:firka/services/fcm_headless_bootstrap.dart'; +import 'package:firka/services/local_notification_service.dart'; + +/// Runs on a silent FCM wakeup: for every locally logged-in account, fetches +/// grades/homework/tests/absences/lessons/messages, diffs each against what +/// was last seen by *this pipeline* (see LastSeenHelper's notif* kinds, +/// which are deliberately separate from the UI's "opened" tracking), and +/// shows a local notification per category with genuinely new items. +class NotificationDiffService { + static final Logger _logger = Logger('NotificationDiffService'); + + static Future checkAll() async { + await bootstrapHeadless(); + await LocalNotificationService.init(); + + if (!Settings.notifyAll.value) { + _logger.info('checkAll: push disabled, skipping'); + return; + } + + final tokens = await isarInit.tokenModels.where().findAll(); + for (final token in tokens) { + try { + final client = KretaClient(token); + await _checkAccount(client, token.key, token.username); + } catch (e, st) { + _logger.warning('checkAll: account ${token.username} failed: $e', e, st); + } + } + } + + static Future _checkAccount( + KretaClient client, + int accountKey, + String username, + ) async { + final mutedSubjects = _mutedSubjects(); + + if (Settings.notifyGrades.value) { + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifGrades, + items: _excludeMuted(await client.getGrades(), mutedSubjects, (g) => g.subject.value?.name), + title: (n) => n.length == 1 ? 'Új jegy érkezett' : '${n.length} új jegy érkezett', + body: (n) => n + .map((g) => '${g.subject.value?.name ?? "?"}: ${g.textValue} (${_fmtDate(g.writtenAt)})') + .take(5) + .join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifGrades), + ); + } + + if (Settings.notifyHomeworkTests.value) { + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifHomework, + items: _excludeMuted(await client.getHomework(), mutedSubjects, (h) => h.subject.value?.name), + title: (n) => n.length == 1 ? 'Új házi feladat' : '${n.length} új házi feladat', + body: (n) => n.map((h) => h.subject.value?.name ?? "?").take(5).join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifHomework), + ); + + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifTests, + items: await client.getTests(), + title: (n) => n.length == 1 ? 'Új témazáró/dolgozat' : '${n.length} új témazáró/dolgozat', + body: (n) => n.map((t) => t.topic ?? t.method).take(5).join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifTests), + ); + } + + if (Settings.notifyAbsences.value) { + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifAbsences, + items: await client.getOmissions(), + title: (n) => n.length == 1 ? 'Új hiányzás/késés' : '${n.length} új hiányzás/késés', + body: (n) => n.map((o) => o.state.name).take(5).join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifAbsences), + ); + } + + if (Settings.notifyLessons.value) { + final now = DateTime.now(); + final lessons = await client.getLessons(now, now.add(const Duration(days: 7))); + + final cancelled = lessons.where(_isCancelledLesson).toList(); + final substituted = lessons + .where((l) => !_isCancelledLesson(l) && l.substituteTeacher != null) + .toList(); + final otherChanges = lessons + .where((l) => !_isCancelledLesson(l) && l.substituteTeacher == null) + .toList(); + + // Split into three separately-diffed notifications instead of one lump + // "schedule changed" — cancellations and substitutions carry which + // teacher and (for cancellations) that Kréta doesn't give a free-text + // reason, only the state label, so that's the most that's shown. + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifLessonsCancelled, + items: cancelled, + title: (n) => n.length == 1 ? 'Elmaradt óra' : '${n.length} elmaradt óra', + body: (n) => n + .map( + (l) => + '${l.subject.value?.name ?? l.name} - ${l.teacher ?? "?"} ' + '(${_fmtDateTime(l.start)})', + ) + .take(5) + .join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifLessonsCancelled), + ); + + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifLessonsSubstituted, + items: substituted, + title: (n) => n.length == 1 ? 'Helyettesítés' : '${n.length} helyettesítés', + body: (n) => n + .map( + (l) => + '${l.subject.value?.name ?? l.name}: ${l.teacher ?? "?"} -> ' + '${l.substituteTeacher} (${_fmtDateTime(l.start)})', + ) + .take(5) + .join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifLessonsSubstituted), + ); + + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifLessons, + items: otherChanges, + title: (n) => n.length == 1 + ? 'Órarendváltozás' + : '${n.length} órarendváltozás', + body: (n) => n + .map((l) => '${l.subject.value?.name ?? l.name} (${l.roomName ?? "?"})') + .take(5) + .join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifLessons), + ); + } + + if (Settings.notifyMessages.value) { + final combined = [ + ...await client.getNoticeBoard(), + ...await client.getInfoBoard(), + ]; + await _diffAndNotify( + accountKey: accountKey, + kind: LastSeenHelper.notifMessages, + items: combined, + title: (n) => n.length == 1 ? 'Új üzenet' : '${n.length} új üzenet', + body: (n) => n.map((m) => m.title).take(5).join(', '), + notificationId: _notificationId(accountKey, LastSeenHelper.notifMessages), + ); + } + } + + /// Diffs [items] against the stored last-seen marker for (accountKey, + /// kind). On the very first run for an account+kind there's no baseline + /// yet, so it seeds one silently instead of notifying about the entire + /// historical backlog. + static Future _diffAndNotify({ + required int accountKey, + required String kind, + required List items, + required String Function(List newItems) title, + required String Function(List newItems) body, + required int notificationId, + }) async { + final seen = LastSeenHelper.get(accountKey, kind); + + if (seen != null) { + final newItems = LastSeen.newerThan(items, seen); + if (newItems.isNotEmpty) { + await LocalNotificationService.show( + id: notificationId, + title: title(newItems), + body: body(newItems), + ); + } + } + + final newest = LastSeen.newestOf(items); + if (newest != null) { + await LastSeenHelper.set(accountKey, kind, newest); + } + } + + /// Muted-subject filtering only applies where the model has a directly + /// resolvable subject link populated during fetch (grades, homework). + /// Tests/lessons/absences/messages don't carry a reliably-loaded subject + /// reference at this point, so they're never muted by subject. + static List _excludeMuted( + List items, + Set mutedSubjects, + String? Function(T) subjectOf, + ) { + if (mutedSubjects.isEmpty) return items; + return items.where((i) => !mutedSubjects.contains(subjectOf(i))).toList(); + } + + static Set _mutedSubjects() { + try { + final decoded = jsonDecode(Settings.notifyMutedSubjects.value); + if (decoded is List) return decoded.whereType().toSet(); + } catch (_) {} + return const {}; + } + + static int _notificationId(int accountKey, String kind) => + Object.hash(accountKey, kind) & 0x7fffffff; + + /// Matches the "isCancelled" convention already used across the app's + /// live-activity/widget code (state names aren't a stable enum, just a + /// Kréta-provided label; "elmarad" is the substring that consistently + /// shows up for cancelled lessons across localizations seen so far). + static bool _isCancelledLesson(LessonCacheModel l) => + l.state.toLowerCase().contains('elmarad'); + + static String _fmtDate(DateTime d) => + '${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}'; + + static String _fmtDateTime(DateTime d) => + '${_fmtDate(d)} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}'; +}