feat(notifications): add FCM debug status panel to developer settings

Adds an FcmStatus row + refresh-notification toggle to the Developer
settings subgroup: shows init state, token presence (last 6 chars),
notification permission (non-prompting), subscribed wakeup topic, and
last token-refresh time. Also registers on resumed sessions (app
reopened while already logged in), which previously only got FCM
registration via the explicit login/logout flow.
This commit is contained in:
2026-09-03 23:45:50 +02:00
parent 6d30767cb0
commit 062f1afe67
10 changed files with 387 additions and 3 deletions

View File

@@ -8,9 +8,9 @@ icons:
l10n:
"l10n.yml": "a57bc304cac4a2b0235593586f17f400a5165d67fc9aadeaa11893cfa36ee082"
"lib/l10n/app_pl.arb": "a8426455757e587c7635c3a62c650a4aae2a0cac1de1175e8ab7fb0d3b387537"
"lib/l10n/app_en.arb": "233a0d5f7a318437e89d1dfab69b84ac94d124c33bcafc23101c89a44e0e0247"
"lib/l10n/app_hu.arb": "73de4e8834ed8b85336ed8b562e6725128d770229c62910df4a982ba69140ad7"
"lib/l10n/app_de.arb": "c498950bbc917e35b1910451ad9fbd4e625db89151f07558e846a7c119a583af"
"lib/l10n/app_en.arb": "159405752b5e73eedbe546a59567550091926a37cf9cf6ce78dd58f1a0dd1d4b"
"lib/l10n/app_hu.arb": "c7fba2a8f91217433698d766e9451d8fad86ae71021adf714639fc3907a34891"
isar:
"lib/data/models/app_settings_model.dart": "5eb5af345f1347f104257f0999763650fe2673f9da1754bd12d3f756fe5c9723"
"lib/data/models/token_model.dart": "8c957cd07e473827d78fd8fd4fb6c1336b636a69c25c93618e1e7f94b7cf0683"

View File

@@ -202,6 +202,13 @@ Future<void> _initData(AppInitialization init) async {
logger.fine("Initializing kréta client as: ${token.username}");
init.client = KretaClient(token);
// A resumed session (app reopened with an already-logged-in account)
// never goes through login_finish.dart's onUserLogin call, so without
// this the FCM token would only ever get (re-)registered for a user who
// explicitly logs out and back in. Safe to call on every startup:
// onUserLogin() itself no-ops if notifyAll is off or permission is denied.
unawaited(FcmService.onUserLogin(client: init.client!));
// Don't block first paint on the network: render whatever is already
// cached, then stream in student/timetable/grades/etc. as they arrive.
unawaited(() async {

View File

@@ -510,6 +510,15 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsRegistry.statsForNerds,
always,
),
SettingsUiHeaderSmall(l10n.s_fcm_status_title, always),
SettingsUiFcmStatus(always),
SettingsUiBoolean(
null,
null,
l10n.s_fcm_notify_on_message,
SettingsRegistry.fcmDebugNotifyOnMessage,
always,
),
SettingsUiLogs(always),
],
isDeveloper,

View File

@@ -193,4 +193,7 @@ abstract class SettingsSchema {
values: NotifyWakeupInterval.values,
)
NotifyWakeupInterval get notifyWakeupInterval;
@BoolSetting(id: 1046, defaultValue: false)
bool get fcmDebugNotifyOnMessage;
}

View File

@@ -47,9 +47,10 @@ class SettingsRegistry {
static const notifyMessages = BoolSetting(id: 1043, defaultValue: true);
static const notifyMutedSubjects = StringSetting(id: 1044, defaultValue: "[]");
static const notifyWakeupInterval = EnumSetting(id: 1045, defaultValue: NotifyWakeupInterval.hourly, values: NotifyWakeupInterval.values);
static const fcmDebugNotifyOnMessage = BoolSetting(id: 1046, defaultValue: false);
static const all = <Setting>[
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, liveActivityEnabled, liveActivityPrivacyEverDeclined, morningNotificationEnabled, morningNotificationTime, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval,
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, liveActivityEnabled, liveActivityPrivacyEverDeclined, morningNotificationEnabled, morningNotificationTime, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage,
];
}
@@ -98,4 +99,5 @@ extension SettingsAccessors on SettingsRepository {
SilentlySettable<bool> get notifyMessages => SilentlySettable(this, SettingsRegistry.notifyMessages);
SilentlySettable<String> get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
SilentlySettable<NotifyWakeupInterval> get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
SilentlySettable<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
}

View File

@@ -157,6 +157,10 @@ class SettingsUiLogs extends SettingsUiNode {
const SettingsUiLogs(super.visible);
}
class SettingsUiFcmStatus extends SettingsUiNode {
const SettingsUiFcmStatus(super.visible);
}
class SettingsUiLicensePage extends SettingsUiNode {
const SettingsUiLicensePage(super.visible);
}

View File

@@ -12,11 +12,18 @@ import 'package:firka/app/app_state.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/firebase_options.dart';
import 'package:firka/services/fcm_headless_bootstrap.dart';
import 'package:firka/services/local_notification_service.dart';
import 'package:firka/services/notification_diff_service.dart';
const _wakeupDataType = 'wakeup';
const _hourlyTopic = 'wakeup-hourly';
const _twoHourlyTopic = 'wakeup-2hourly';
const _topicPrefix = '/topics/';
// Fixed id (outside the hash-derived range used by NotificationDiffService)
// so the debug "message received" notification always updates in place.
const _debugMessageNotificationId = 900001;
/// Must be a top-level function: FirebaseMessaging invokes it in its own
/// background isolate, where none of firka's normal app state is set up.
@@ -26,7 +33,13 @@ Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (message.data['type'] == _wakeupDataType) {
await NotificationDiffService.checkAll();
} else {
// checkAll() bootstraps Settings itself; other message types need it
// bootstrapped explicitly before FcmService can read the debug toggle.
await bootstrapHeadless();
}
await FcmService._maybeShowDebugMessageNotification(message);
}
/// Coordinates FCM push notification registration with firka's backend.
@@ -44,6 +57,27 @@ class FcmService {
static bool _isInitialized = false;
static String? _cachedToken;
static DateTime? _lastTokenRefreshAt;
/// Debug/status accessors for the developer settings screen.
static bool get isInitialized => _isInitialized;
static String? get cachedToken => _cachedToken;
static DateTime? get lastTokenRefreshAt => _lastTokenRefreshAt;
static String get subscribedTopic =>
_topicFor(Settings.notifyWakeupInterval.value);
/// Current notification permission status, without prompting for it.
/// Returns null if Firebase hasn't been initialized yet.
static Future<AuthorizationStatus?> permissionStatus() async {
if (!_isInitialized) return null;
try {
final settings = await FirebaseMessaging.instance.getNotificationSettings();
return settings.authorizationStatus;
} catch (e) {
_logger.warning('Error reading notification permission status: $e');
return null;
}
}
/// Sets up Firebase + the background handler and starts listening for
/// token refreshes. Safe to call once at app startup, before login.
@@ -68,6 +102,7 @@ class FcmService {
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
_cachedToken = token;
_lastTokenRefreshAt = DateTime.now();
_logger.info('FCM token refreshed');
unawaited(_registerIfLoggedIn());
});
@@ -79,6 +114,7 @@ class FcmService {
if (message.data['type'] == _wakeupDataType) {
unawaited(NotificationDiffService.checkAll());
}
unawaited(_maybeShowDebugMessageNotification(message));
});
_isInitialized = true;
@@ -88,6 +124,35 @@ class FcmService {
}
}
/// Best-effort label for which channel a message arrived on: the topic
/// name for topic-targeted messages (FCM sets `from` to
/// `/topics/<name>`), the `type` data field otherwise, or the raw
/// sender id as a last resort.
static String _channelLabel(RemoteMessage message) {
final from = message.from;
if (from != null && from.startsWith(_topicPrefix)) {
return from.substring(_topicPrefix.length);
}
final type = message.data['type'];
if (type != null) return type.toString();
return from ?? 'unknown';
}
static Future<void> _maybeShowDebugMessageNotification(
RemoteMessage message,
) async {
if (!Settings.fcmDebugNotifyOnMessage.value) return;
try {
await LocalNotificationService.show(
id: _debugMessageNotificationId,
title: 'FCM message received',
body: '${DateTime.now().toIso8601String()} - ${_channelLabel(message)}',
);
} catch (e, st) {
_logger.warning('Failed to show debug FCM message notification: $e', e, st);
}
}
static Future<bool> _requestPermission() async {
if (Platform.isIOS) {
final settings = await FirebaseMessaging.instance.requestPermission(

View File

@@ -242,4 +242,98 @@ class NotificationDiffService {
static String _fmtDateTime(DateTime d) =>
'${_fmtDate(d)} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
/// Sample content per category for [showTestNotification]. `titleSingle`
/// matches the wording `_checkAccount` uses for a lone new item on a
/// single-account device; `titleMulti` drops the possessive so it reads
/// naturally with a "(username)" suffix appended per account.
static const _testContent = {
LastSeenHelper.notifGrades: (
titleSingle: 'Új jegyed érkezett',
titleMulti: 'Új jegy érkezett',
body: 'Matematika: 5 (2026-01-02)',
),
LastSeenHelper.notifHomework: (
titleSingle: 'Új házi feladatod érkezett',
titleMulti: 'Új házi feladat érkezett',
body: 'Történelem: Olvasd el a 24. fejezetet (határidő: 2026-01-05)',
),
LastSeenHelper.notifTests: (
titleSingle: 'Új témazáród/dolgozatod érkezett',
titleMulti: 'Új témazáró/dolgozat érkezett',
body: 'Fizika: Mechanika témazáró (2026-01-09 10:00)',
),
LastSeenHelper.notifAbsences: (
titleSingle: 'Új hiányzásod/késésed érkezett',
titleMulti: 'Új hiányzás/késés érkezett',
body: 'Kémia: Igazolatlan hiányzás (2026-01-02 09:00)',
),
LastSeenHelper.notifLessons: (
titleSingle: 'Órarendváltozás történt',
titleMulti: 'Órarendváltozás történt',
body: 'Kémia (A-002, 2026-01-06 12:00)',
),
LastSeenHelper.notifLessonsCancelled: (
titleSingle: 'Elmaradt órád van',
titleMulti: 'Elmaradt óra',
body: 'Testnevelés - Nagy Béla (2026-01-06 12:00)',
),
LastSeenHelper.notifLessonsSubstituted: (
titleSingle: 'Helyettesítés van az órarendedben',
titleMulti: 'Helyettesítés',
body: 'Kémia: Nagy Béla -> Kovács Anna (2026-01-06 09:50)',
),
LastSeenHelper.notifMessages: (
titleSingle: 'Új üzeneted érkezett',
titleMulti: 'Új üzenet érkezett',
body: 'Nulladik óra átnevezése első órára - Müller Attila (2026-01-15 07:42)',
),
};
static const _simulatedUsernames = ['Gipsz Jakab', 'Kis Anna'];
/// Fires a local notification with placeholder content for [kind], for
/// eyeballing what each category looks like on-device without needing
/// real new data from the backend. Bypasses last-seen diffing entirely,
/// so it always shows regardless of what's already been seen.
///
/// With a single account logged in (the common case), shows one
/// notification with the personalized singular title. With more than one
/// account, fires one per account instead, with the impersonal title
/// suffixed by that account's username so they're distinguishable — this
/// mirrors what a real multi-account wakeup would look like, since
/// [checkAll] runs the diff separately per account. Pass
/// [simulateMultiAccount] to preview that layout without needing a second
/// account actually logged in on this device.
static Future<void> showTestNotification(
String kind, {
bool simulateMultiAccount = false,
}) async {
final content = _testContent[kind];
if (content == null) return;
await LocalNotificationService.init();
final usernames = simulateMultiAccount
? _simulatedUsernames
: (await isarInit.tokenModels.where().findAll())
.map((t) => t.username)
.toList();
if (usernames.length <= 1) {
await LocalNotificationService.show(
id: _notificationId(0, kind),
title: content.titleSingle,
body: content.body,
);
return;
}
for (var i = 0; i < usernames.length; i++) {
await LocalNotificationService.show(
id: _notificationId(i + 1, kind),
title: '${content.titleMulti} (${usernames[i]})',
body: content.body,
);
}
}
}

View File

@@ -0,0 +1,195 @@
import "package:firebase_messaging/firebase_messaging.dart";
import "package:flutter/material.dart";
import "package:majesticons_flutter/majesticons_flutter.dart";
import "package:firka/app/app_state.dart";
import "package:firka/core/last_seen_helper.dart";
import "package:firka/services/fcm_service.dart";
import "package:firka/services/notification_diff_service.dart";
import "package:firka/ui/phone/screens/settings/settings_metrics.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka_common/ui/components/firka_card.dart";
/// Read-only diagnostic panel for the developer settings screen: shows
/// whether FcmService has initialized, whether a token/permission is
/// present, which wakeup topic is currently subscribed, and when the token
/// last refreshed. Has its own refresh button since permission status is
/// read asynchronously and can change outside the app (system settings).
class SettingsFcmStatusView extends StatefulWidget {
final AppInitialization data;
const SettingsFcmStatusView({required this.data, super.key});
@override
State<SettingsFcmStatusView> createState() => _SettingsFcmStatusViewState();
}
class _SettingsFcmStatusViewState extends State<SettingsFcmStatusView> {
AuthorizationStatus? _permissionStatus;
bool _permissionLoaded = false;
@override
void initState() {
super.initState();
_loadPermissionStatus();
}
Future<void> _loadPermissionStatus() async {
final status = await FcmService.permissionStatus();
if (!mounted) return;
setState(() {
_permissionStatus = status;
_permissionLoaded = true;
});
}
String _permissionLabel() {
final l10n = widget.data.l10n;
if (!_permissionLoaded) return "…";
switch (_permissionStatus) {
case AuthorizationStatus.authorized:
case AuthorizationStatus.provisional:
return l10n.s_fcm_status_permission_granted;
case AuthorizationStatus.denied:
case AuthorizationStatus.deniedPermanently:
return l10n.s_fcm_status_permission_denied;
case AuthorizationStatus.notDetermined:
case null:
return l10n.s_fcm_status_permission_unknown;
}
}
List<(String kind, String label)> _testKinds() {
final l10n = widget.data.l10n;
return [
(LastSeenHelper.notifGrades, l10n.s_notif_grades),
(LastSeenHelper.notifHomework, l10n.s_notif_homework_tests),
(LastSeenHelper.notifTests, l10n.s_notif_homework_tests),
(LastSeenHelper.notifAbsences, l10n.s_notif_absences),
(LastSeenHelper.notifLessons, l10n.s_notif_lessons),
(LastSeenHelper.notifLessonsCancelled, l10n.s_notif_lessons_cancelled),
(LastSeenHelper.notifLessonsSubstituted, l10n.s_notif_lessons_substituted),
(LastSeenHelper.notifMessages, l10n.s_notif_messages),
];
}
Widget _testButton(String kind, String label, {bool simulateMultiAccount = false}) {
final scale = settingsScale(context);
return GestureDetector(
onTap: () => NotificationDiffService.showTestNotification(
kind,
simulateMultiAccount: simulateMultiAccount,
),
child: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.bellSolid,
color: appStyle.colors.accent,
),
const SizedBox(width: 8),
Text(
label,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
);
}
Widget _row(String label, String value) {
final scale = settingsScale(context);
return FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
Text(
label,
style: appStyle.fonts.B_16R.apply(color: appStyle.colors.textPrimary),
),
],
right: [
Text(
value,
style: appStyle.fonts.B_16R.apply(
color: appStyle.colors.textSecondary,
),
),
],
);
}
@override
Widget build(BuildContext context) {
final l10n = widget.data.l10n;
final scale = settingsScale(context);
final initialized = FcmService.isInitialized;
final token = FcmService.cachedToken;
final lastRefresh = FcmService.lastTokenRefreshAt;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_row(
l10n.s_fcm_status_title,
initialized
? l10n.s_fcm_status_initialized
: l10n.s_fcm_status_not_initialized,
),
_row(
token != null
? l10n.s_fcm_status_token_present
: l10n.s_fcm_status_token_missing,
token != null ? "...${token.substring(token.length - 6)}" : "-",
),
_row(l10n.s_fcm_status_permission_label, _permissionLabel()),
_row(l10n.s_fcm_status_topic_label, FcmService.subscribedTopic),
_row(
l10n.s_fcm_status_last_refresh_label,
lastRefresh?.toIso8601String() ?? l10n.s_fcm_status_last_refresh_never,
),
GestureDetector(
onTap: _loadPermissionStatus,
child: FirkaCard(
height: settingsItemHeight * scale,
rounding: settingsItemRounding * scale,
left: [
FirkaIconWidget(
FirkaIconType.majesticons,
Majesticon.reloadSolid,
color: appStyle.colors.accent,
),
const SizedBox(width: 8),
Text(
l10n.s_fcm_status_refresh_button,
style: appStyle.fonts.B_16SB.apply(
color: appStyle.colors.textPrimary,
),
),
],
),
),
const SizedBox(height: 12),
Text(
l10n.s_fcm_test_notifications_title,
style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary),
),
for (final (kind, label) in _testKinds()) _testButton(kind, label),
const SizedBox(height: 12),
Text(
l10n.s_fcm_test_notifications_multi_title,
style: appStyle.fonts.B_16SB.apply(color: appStyle.colors.textPrimary),
),
for (final (kind, label) in _testKinds())
_testButton(kind, label, simulateMultiAccount: true),
],
);
}
}

View File

@@ -24,6 +24,7 @@ import 'package:firka/core/state/firka_state.dart';
import 'settings_account_picker.dart';
import 'settings_app_icon_picker.dart';
import 'settings_bool_row.dart';
import 'settings_fcm_status.dart';
import 'settings_metrics.dart';
import 'settings_license_page.dart';
import 'settings_logs.dart';
@@ -459,6 +460,10 @@ class _SettingsScreenState extends FirkaState<SettingsScreen> {
widgets.add(SettingsLogsView(data: widget.data));
continue;
}
if (item is SettingsUiFcmStatus) {
widgets.add(SettingsFcmStatusView(data: widget.data));
continue;
}
}
return widgets;