forked from firka/firka
feat(notifications): add Firebase Cloud Messaging push support
Firebase project config, topic subscriptions synced to login state and per-category settings, a client for the Go FCM backend, and a settings UI to toggle push and its wakeup interval.
This commit is contained in:
@@ -2,6 +2,9 @@ import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services")
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
|
||||
29
firka/android/app/google-services.json
Normal file
29
firka/android/app/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
29
firka/android/app/src/debug/google-services.json
Normal file
29
firka/android/app/src/debug/google-services.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "219357380322",
|
||||
"project_id": "firka-4633b",
|
||||
"storage_bucket": "firka-4633b.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:219357380322:android:5b776732799faa5c08a8bb",
|
||||
"android_client_info": {
|
||||
"package_name": "app.firka.naplo.debug"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -684,6 +684,13 @@
|
||||
<meta-data
|
||||
android:name="com.google.android.wearable.standalone"
|
||||
android:value="true" />
|
||||
|
||||
<!-- Small status-bar icon for FCM notification-payload messages that
|
||||
Android displays automatically (data-only wakeups instead go
|
||||
through LocalNotificationService, which sets its own icon). -->
|
||||
<meta-data
|
||||
android:name="com.google.firebase.messaging.default_notification_icon"
|
||||
android:resource="@drawable/ic_notification" />
|
||||
</application>
|
||||
|
||||
<!-- Required to query activities that can process text, see:
|
||||
|
||||
@@ -19,6 +19,9 @@ pluginManagement {
|
||||
plugins {
|
||||
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
|
||||
id("com.android.application") version "9.2.0" apply false
|
||||
// START: FlutterFire Configuration
|
||||
id("com.google.gms.google-services") version("4.4.4") apply false
|
||||
// END: FlutterFire Configuration
|
||||
id("org.jetbrains.kotlin.android") version "2.3.10" apply false
|
||||
id("org.jetbrains.kotlin.plugin.compose") version "2.3.10" apply false
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
icons:
|
||||
"flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1"
|
||||
"pubspec.yaml": "dbb15aa3301f9f021134e6705847dfbc5149df751d698ba79e3b01da03e12353"
|
||||
"pubspec.yaml": "5d40f014d654e257bc58e8ebfb2468a5ed7f75d913a67fb89314b9fda1c257a6"
|
||||
"assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983"
|
||||
"assets/images/logos/monochrome_logo.png": "188d2b0a64c70323b09bcee721663d6698fb557066f20ddaec97bba6869c1c6c"
|
||||
"assets/images/logos/colored_logo_without_mustache.png": "d11cff9f38985885873bfdd2d84e61f8fab03803eada94d4caac1545ef3685f3"
|
||||
"assets/images/logos/colored_logo_only_mustache.png": "bad6220c11bdfb1dfe04e5173bd2ebedd3999689d4b3a68fc63dc520c96dd33b"
|
||||
l10n:
|
||||
"l10n.yml": "a57bc304cac4a2b0235593586f17f400a5165d67fc9aadeaa11893cfa36ee082"
|
||||
"lib/l10n/app_de.arb": "acaa77af7b19d9ea479bd876245d76b3079d05ce05f51db7a8300ea17dd68907"
|
||||
"lib/l10n/app_hu.arb": "63bfe9901b9fc233940de5bd1e9a714e4cbe91638861d0f2591df22e3bd8e91f"
|
||||
"lib/l10n/app_en.arb": "828c1536f650fb5240d511d32b2f89f8dca84576dfadc3626edb79fcd39887c9"
|
||||
"lib/l10n/app_pl.arb": "a8426455757e587c7635c3a62c650a4aae2a0cac1de1175e8ab7fb0d3b387537"
|
||||
"lib/l10n/app_en.arb": "233a0d5f7a318437e89d1dfab69b84ac94d124c33bcafc23101c89a44e0e0247"
|
||||
"lib/l10n/app_hu.arb": "73de4e8834ed8b85336ed8b562e6725128d770229c62910df4a982ba69140ad7"
|
||||
"lib/l10n/app_de.arb": "c498950bbc917e35b1910451ad9fbd4e625db89151f07558e846a7c119a583af"
|
||||
isar:
|
||||
"lib/data/models/app_settings_model.dart": "5eb5af345f1347f104257f0999763650fe2673f9da1754bd12d3f756fe5c9723"
|
||||
"lib/data/models/token_model.dart": "8c957cd07e473827d78fd8fd4fb6c1336b636a69c25c93618e1e7f94b7cf0683"
|
||||
|
||||
1
firka/firebase.json
Normal file
1
firka/firebase.json
Normal file
@@ -0,0 +1 @@
|
||||
{"flutter":{"platforms":{"android":{"default":{"projectId":"firka-4633b","appId":"1:219357380322:android:5b776732799faa5c08a8bb","fileOutput":"android/app/google-services.json"}},"dart":{"lib/firebase_options.dart":{"projectId":"firka-4633b","configurations":{"android":"1:219357380322:android:5b776732799faa5c08a8bb"}}}}}}
|
||||
138
firka/lib/api/client/notification_backend_client.dart
Normal file
138
firka/lib/api/client/notification_backend_client.dart
Normal file
@@ -0,0 +1,138 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
|
||||
/// Client for registering FCM push tokens with firka's backend, mirroring
|
||||
/// LiveActivityBackendClient's conventions (same backend, same auth scheme).
|
||||
/// Requires the backend to expose the `/notifications/*` routes below.
|
||||
class NotificationBackendClient {
|
||||
static final Logger _logger = Logger('NotificationBackendClient');
|
||||
|
||||
final Dio _dio;
|
||||
|
||||
NotificationBackendClient({Dio? dio}) : _dio = dio ?? Dio() {
|
||||
if (!dotenv.isInitialized) {
|
||||
throw StateError(
|
||||
'NotificationBackendClient created before dotenv finished loading',
|
||||
);
|
||||
}
|
||||
|
||||
final baseUrl = dotenv.env['BACKEND_BASE_URL'];
|
||||
final apiKey = dotenv.env['BACKEND_API_KEY'] ?? '';
|
||||
|
||||
_dio.options.baseUrl = baseUrl!;
|
||||
_dio.options.connectTimeout = const Duration(seconds: 10);
|
||||
_dio.options.receiveTimeout = const Duration(seconds: 10);
|
||||
_dio.options.headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'x-api-key': apiKey,
|
||||
};
|
||||
|
||||
_logger.info('Notification backend configured successfully!');
|
||||
}
|
||||
|
||||
/// Register (or refresh) an FCM token for a student, with the current
|
||||
/// notification category preferences.
|
||||
Future<bool> registerToken({
|
||||
required String fcmToken,
|
||||
required String studentId,
|
||||
required bool notifyAll,
|
||||
required bool notifyGrades,
|
||||
required bool notifyHomeworkTests,
|
||||
required bool notifyAbsences,
|
||||
required bool notifyLessons,
|
||||
required bool notifyMessages,
|
||||
String? language,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.post(
|
||||
'/notifications/fcm-token',
|
||||
data: {
|
||||
'fcmToken': fcmToken,
|
||||
'studentId': studentId,
|
||||
'notifyAll': notifyAll,
|
||||
'notifyGrades': notifyGrades,
|
||||
'notifyHomeworkTests': notifyHomeworkTests,
|
||||
'notifyAbsences': notifyAbsences,
|
||||
'notifyLessons': notifyLessons,
|
||||
'notifyMessages': notifyMessages,
|
||||
'language': ?language,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200 || response.statusCode == 201) {
|
||||
_logger.info('FCM token registered successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning('Failed to register FCM token: ${response.statusCode}');
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error registering FCM token: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Update notification category preferences for an already-registered token.
|
||||
Future<bool> updatePreferences({
|
||||
required String fcmToken,
|
||||
required bool notifyAll,
|
||||
required bool notifyGrades,
|
||||
required bool notifyHomeworkTests,
|
||||
required bool notifyAbsences,
|
||||
required bool notifyLessons,
|
||||
required bool notifyMessages,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.put(
|
||||
'/notifications/preferences',
|
||||
data: {
|
||||
'fcmToken': fcmToken,
|
||||
'notifyAll': notifyAll,
|
||||
'notifyGrades': notifyGrades,
|
||||
'notifyHomeworkTests': notifyHomeworkTests,
|
||||
'notifyAbsences': notifyAbsences,
|
||||
'notifyLessons': notifyLessons,
|
||||
'notifyMessages': notifyMessages,
|
||||
},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
_logger.info('Notification preferences updated successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning(
|
||||
'Failed to update notification preferences: ${response.statusCode}',
|
||||
);
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error updating notification preferences: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Unregister an FCM token (called on logout or when push is disabled).
|
||||
Future<bool> unregisterToken({required String fcmToken}) async {
|
||||
try {
|
||||
final response = await _dio.delete(
|
||||
'/notifications/fcm-token',
|
||||
data: {'fcmToken': fcmToken},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
_logger.info('FCM token unregistered successfully');
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.warning(
|
||||
'Failed to unregister FCM token: ${response.statusCode}',
|
||||
);
|
||||
return false;
|
||||
} catch (e) {
|
||||
_logger.severe('Error unregistering FCM token: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import "dart:io";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
import "package:firka_common/data/models/token_model.dart";
|
||||
import "package:kreta_api/kreta_api.dart";
|
||||
@@ -19,6 +20,13 @@ Future<void> completeLogin(
|
||||
await data.settings.setSelectedAccountKey(tokenModel.key);
|
||||
await initializeApp();
|
||||
|
||||
if (data.client != null) {
|
||||
await FcmService.onUserLogin(
|
||||
client: data.client!,
|
||||
settingsStore: data.settings,
|
||||
);
|
||||
}
|
||||
|
||||
if (Platform.isIOS) {
|
||||
final watchInstalled = await WatchSyncHelper.isWatchAppInstalled();
|
||||
if (watchInstalled) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import 'package:flutter/services.dart';
|
||||
import 'package:firka/app/app_state.dart';
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka_common/data/models/token_model.dart';
|
||||
import 'package:firka/services/fcm_service.dart';
|
||||
import 'package:firka/services/live_activity_service.dart';
|
||||
import 'package:firka/core/settings/settings_effects.dart';
|
||||
import 'package:firka/core/settings/settings_repository.dart';
|
||||
@@ -307,6 +308,14 @@ Future<void> initializeApp() async {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await FcmService.initialize().timeout(const Duration(seconds: 8));
|
||||
} on TimeoutException catch (e, st) {
|
||||
logger.warning('FcmService init timed out: $e', e, st);
|
||||
} catch (e, st) {
|
||||
logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
}
|
||||
|
||||
await _initData(initData);
|
||||
|
||||
initDone = true;
|
||||
|
||||
@@ -28,6 +28,8 @@ bool isMorningNotificationEnabled() =>
|
||||
bool isWearOsSupportEnabled() =>
|
||||
Platform.isAndroid && Settings.wearOsSupport.value;
|
||||
|
||||
bool isPushNotificationsEnabled() => Settings.notifyAll.value;
|
||||
|
||||
bool isDebug() => kDebugMode;
|
||||
|
||||
bool isDebugIOS() => kDebugMode && Platform.isIOS;
|
||||
@@ -298,10 +300,62 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.bellSolid,
|
||||
l10n.s_notifications,
|
||||
const [],
|
||||
always,
|
||||
[
|
||||
SettingsUiBackHeader(l10n.s_settings, always),
|
||||
SettingsUiHeader(l10n.s_notifications, always),
|
||||
SettingsUiPadding(23, always),
|
||||
SettingsUiBoolean(
|
||||
FirkaIconType.majesticons,
|
||||
Majesticon.bellSolid,
|
||||
l10n.s_notif_push_enabled,
|
||||
SettingsRegistry.notifyAll,
|
||||
always,
|
||||
),
|
||||
SettingsUiHeaderSmall(l10n.s_notif_wakeup_interval_header, isPushNotificationsEnabled),
|
||||
SettingsUiEnum(SettingsRegistry.notifyWakeupInterval, [
|
||||
l10n.s_notif_wakeup_hourly,
|
||||
l10n.s_notif_wakeup_two_hourly,
|
||||
], isPushNotificationsEnabled),
|
||||
SettingsUiHeaderSmall(l10n.s_notif_categories_header, isPushNotificationsEnabled),
|
||||
SettingsUiBoolean(
|
||||
null,
|
||||
null,
|
||||
l10n.s_notif_grades,
|
||||
SettingsRegistry.notifyGrades,
|
||||
isPushNotificationsEnabled,
|
||||
),
|
||||
SettingsUiBoolean(
|
||||
null,
|
||||
null,
|
||||
l10n.s_notif_homework_tests,
|
||||
SettingsRegistry.notifyHomeworkTests,
|
||||
isPushNotificationsEnabled,
|
||||
),
|
||||
SettingsUiBoolean(
|
||||
null,
|
||||
null,
|
||||
l10n.s_notif_absences,
|
||||
SettingsRegistry.notifyAbsences,
|
||||
isPushNotificationsEnabled,
|
||||
),
|
||||
SettingsUiBoolean(
|
||||
null,
|
||||
null,
|
||||
l10n.s_notif_lessons,
|
||||
SettingsRegistry.notifyLessons,
|
||||
isPushNotificationsEnabled,
|
||||
),
|
||||
SettingsUiBoolean(
|
||||
null,
|
||||
null,
|
||||
l10n.s_notif_messages,
|
||||
SettingsRegistry.notifyMessages,
|
||||
isPushNotificationsEnabled,
|
||||
),
|
||||
],
|
||||
isAndroid,
|
||||
null,
|
||||
l10n.s_todo,
|
||||
l10n.s_notifications_desc,
|
||||
),
|
||||
SettingsUiSubGroup(
|
||||
FirkaIconType.majesticons,
|
||||
|
||||
@@ -4,6 +4,7 @@ import "package:permission_handler/permission_handler.dart";
|
||||
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/live_activity_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
|
||||
@@ -62,6 +63,26 @@ void registerSettingsEffects(
|
||||
await LiveActivityService.syncGlobalSettingWithCurrentUser();
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyAll, (enabled) async {
|
||||
await FcmService.handleEnabledChange(enabled);
|
||||
});
|
||||
|
||||
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
|
||||
await FcmService.handleWakeupIntervalChange();
|
||||
});
|
||||
|
||||
for (final setting in [
|
||||
SettingsRegistry.notifyGrades,
|
||||
SettingsRegistry.notifyHomeworkTests,
|
||||
SettingsRegistry.notifyAbsences,
|
||||
SettingsRegistry.notifyLessons,
|
||||
SettingsRegistry.notifyMessages,
|
||||
]) {
|
||||
repo.onChange(setting, (_) async {
|
||||
await FcmService.updatePreferences();
|
||||
});
|
||||
}
|
||||
|
||||
// These two mirror LiveActivity widgets on iOS only, matching the original
|
||||
// postUpdate wiring that was only attached inside an `if (Platform.isIOS)` block.
|
||||
if (Platform.isIOS) {
|
||||
|
||||
@@ -19,6 +19,11 @@ enum TitleFont {
|
||||
|
||||
enum TitleCapitalization { lower, normal, upper }
|
||||
|
||||
/// How often the background wakeup push (that triggers a silent data refresh
|
||||
/// + local notification) should fire. Backed by FCM topics `wakeup-hourly`/
|
||||
/// `wakeup-2hourly` sent by the `fcm-notifier` backend service.
|
||||
enum NotifyWakeupInterval { hourly, twoHourly }
|
||||
|
||||
abstract class SettingsSchema {
|
||||
@DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120)
|
||||
double get bellDelay;
|
||||
@@ -181,4 +186,11 @@ abstract class SettingsSchema {
|
||||
|
||||
@StringSetting(id: 1044, defaultValue: "[]")
|
||||
String get notifyMutedSubjects;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1045,
|
||||
defaultValue: NotifyWakeupInterval.hourly,
|
||||
values: NotifyWakeupInterval.values,
|
||||
)
|
||||
NotifyWakeupInterval get notifyWakeupInterval;
|
||||
}
|
||||
|
||||
@@ -46,9 +46,10 @@ class SettingsRegistry {
|
||||
static const notifyLessons = BoolSetting(id: 1042, defaultValue: true);
|
||||
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 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,
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -96,4 +97,5 @@ extension SettingsAccessors on SettingsRepository {
|
||||
SilentlySettable<bool> get notifyLessons => SilentlySettable(this, SettingsRegistry.notifyLessons);
|
||||
SilentlySettable<bool> get notifyMessages => SilentlySettable(this, SettingsRegistry.notifyMessages);
|
||||
SilentlySettable<String> get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
|
||||
SilentlySettable<NotifyWakeupInterval> get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
|
||||
}
|
||||
|
||||
62
firka/lib/firebase_options.dart
Normal file
62
firka/lib/firebase_options.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
// File generated by FlutterFire CLI.
|
||||
// ignore_for_file: type=lint
|
||||
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
|
||||
import 'package:flutter/foundation.dart'
|
||||
show defaultTargetPlatform, kIsWeb, TargetPlatform;
|
||||
|
||||
/// Default [FirebaseOptions] for use with your Firebase apps.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'firebase_options.dart';
|
||||
/// // ...
|
||||
/// await Firebase.initializeApp(
|
||||
/// options: DefaultFirebaseOptions.currentPlatform,
|
||||
/// );
|
||||
/// ```
|
||||
class DefaultFirebaseOptions {
|
||||
static FirebaseOptions get currentPlatform {
|
||||
if (kIsWeb) {
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for web - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for ios - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.macOS:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for macos - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.windows:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for windows - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.linux:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for linux - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static const FirebaseOptions android = FirebaseOptions(
|
||||
apiKey: 'AIzaSyD-3VE9--eKRDGm1UW_P9JLaM2Hyd2Wfx4',
|
||||
appId: '1:219357380322:android:5b776732799faa5c08a8bb',
|
||||
messagingSenderId: '219357380322',
|
||||
projectId: 'firka-4633b',
|
||||
storageBucket: 'firka-4633b.firebasestorage.app',
|
||||
);
|
||||
}
|
||||
Submodule firka/lib/l10n updated: f4ae8bbd36...16d3b9bc4c
264
firka/lib/services/fcm_service.dart
Normal file
264
firka/lib/services/fcm_service.dart
Normal file
@@ -0,0 +1,264 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
import 'package:firka/api/client/kreta_client.dart';
|
||||
import 'package:firka/api/client/notification_backend_client.dart';
|
||||
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/notification_diff_service.dart';
|
||||
|
||||
const _wakeupDataType = 'wakeup';
|
||||
const _hourlyTopic = 'wakeup-hourly';
|
||||
const _twoHourlyTopic = 'wakeup-2hourly';
|
||||
|
||||
/// 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.
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
|
||||
if (message.data['type'] == _wakeupDataType) {
|
||||
await NotificationDiffService.checkAll();
|
||||
}
|
||||
}
|
||||
|
||||
/// Coordinates FCM push notification registration with firka's backend.
|
||||
/// Android-only for now: `flutterfire configure` has only been run for
|
||||
/// Android, so `DefaultFirebaseOptions.currentPlatform` throws on iOS. Once
|
||||
/// iOS is configured (re-run `flutterfire configure` with both platforms
|
||||
/// selected), drop the `Platform.isAndroid` guard in [initialize] to make
|
||||
/// this cross-platform like the rest of the service already assumes.
|
||||
/// Push is enabled by default; the master switch is SettingsRegistry.notifyAll,
|
||||
/// toggleable from the notifications settings page.
|
||||
class FcmService {
|
||||
static final Logger _logger = Logger('FcmService');
|
||||
static final NotificationBackendClient _backendClient =
|
||||
NotificationBackendClient();
|
||||
|
||||
static bool _isInitialized = false;
|
||||
static String? _cachedToken;
|
||||
|
||||
/// Sets up Firebase + the background handler and starts listening for
|
||||
/// token refreshes. Safe to call once at app startup, before login.
|
||||
static Future<void> initialize() async {
|
||||
if (_isInitialized) return;
|
||||
if (!Platform.isAndroid) return;
|
||||
|
||||
try {
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
|
||||
FirebaseMessaging.onBackgroundMessage(
|
||||
firebaseMessagingBackgroundHandler,
|
||||
);
|
||||
|
||||
await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
FirebaseMessaging.instance.onTokenRefresh.listen((token) {
|
||||
_cachedToken = token;
|
||||
_logger.info('FCM token refreshed');
|
||||
unawaited(_registerIfLoggedIn());
|
||||
});
|
||||
|
||||
// Data-only wakeups don't display anything on their own; if the app
|
||||
// happens to be foregrounded when one arrives, run the same
|
||||
// fetch+diff+notify pipeline as the background isolate does.
|
||||
FirebaseMessaging.onMessage.listen((message) {
|
||||
if (message.data['type'] == _wakeupDataType) {
|
||||
unawaited(NotificationDiffService.checkAll());
|
||||
}
|
||||
});
|
||||
|
||||
_isInitialized = true;
|
||||
_logger.info('FcmService initialized');
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> _requestPermission() async {
|
||||
if (Platform.isIOS) {
|
||||
final settings = await FirebaseMessaging.instance.requestPermission(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
return settings.authorizationStatus == AuthorizationStatus.authorized ||
|
||||
settings.authorizationStatus == AuthorizationStatus.provisional;
|
||||
}
|
||||
|
||||
final status = await Permission.notification.status;
|
||||
if (status.isGranted) return true;
|
||||
final result = await Permission.notification.request();
|
||||
return result.isGranted;
|
||||
}
|
||||
|
||||
static String? _currentStudentId(KretaClient? client) {
|
||||
try {
|
||||
final effectiveClient = client ?? (initDone ? initData.client : null);
|
||||
return effectiveClient?.cache.token.username;
|
||||
} catch (e) {
|
||||
_logger.warning('Error reading current studentId: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _registerIfLoggedIn() async {
|
||||
final studentId = _currentStudentId(null);
|
||||
if (studentId == null) return;
|
||||
await _register(studentId: studentId);
|
||||
}
|
||||
|
||||
static String _topicFor(NotifyWakeupInterval interval) =>
|
||||
interval == NotifyWakeupInterval.hourly ? _hourlyTopic : _twoHourlyTopic;
|
||||
|
||||
/// Subscribes to the wakeup topic matching the user's chosen interval and
|
||||
/// unsubscribes from the other one, so only one cadence of pushes arrives.
|
||||
static Future<void> _subscribeToWakeupTopic() async {
|
||||
final topic = _topicFor(Settings.notifyWakeupInterval.value);
|
||||
final other = topic == _hourlyTopic ? _twoHourlyTopic : _hourlyTopic;
|
||||
await FirebaseMessaging.instance.subscribeToTopic(topic);
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(other);
|
||||
}
|
||||
|
||||
static Future<void> _unsubscribeFromWakeupTopics() async {
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(_hourlyTopic);
|
||||
await FirebaseMessaging.instance.unsubscribeFromTopic(_twoHourlyTopic);
|
||||
}
|
||||
|
||||
/// Called from the notifyWakeupInterval settings effect when the user
|
||||
/// switches between hourly/2-hourly.
|
||||
static Future<void> handleWakeupIntervalChange() async {
|
||||
if (!_isInitialized || !Settings.notifyAll.value) return;
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
static Future<void> _register({required String studentId}) async {
|
||||
try {
|
||||
final token = _cachedToken ??= await FirebaseMessaging.instance.getToken();
|
||||
if (token == null) {
|
||||
_logger.warning('No FCM token available to register');
|
||||
return;
|
||||
}
|
||||
|
||||
await _backendClient.registerToken(
|
||||
fcmToken: token,
|
||||
studentId: studentId,
|
||||
notifyAll: Settings.notifyAll.value,
|
||||
notifyGrades: Settings.notifyGrades.value,
|
||||
notifyHomeworkTests: Settings.notifyHomeworkTests.value,
|
||||
notifyAbsences: Settings.notifyAbsences.value,
|
||||
notifyLessons: Settings.notifyLessons.value,
|
||||
notifyMessages: Settings.notifyMessages.value,
|
||||
);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to register FCM token: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// Called after a successful login (push is on by default, per
|
||||
/// SettingsRegistry.notifyAll's default value of true).
|
||||
static Future<void> onUserLogin({
|
||||
required KretaClient client,
|
||||
SettingsRepository? settingsStore,
|
||||
}) async {
|
||||
if (!_isInitialized) return;
|
||||
if (!Settings.notifyAll.value) {
|
||||
_logger.info('onUserLogin: push notifications disabled, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
final studentId = _currentStudentId(client);
|
||||
if (studentId == null) {
|
||||
_logger.warning('onUserLogin: no current user, skipping');
|
||||
return;
|
||||
}
|
||||
|
||||
final granted = await _requestPermission();
|
||||
if (!granted) {
|
||||
_logger.info('onUserLogin: notification permission not granted');
|
||||
return;
|
||||
}
|
||||
|
||||
await _register(studentId: studentId);
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
/// Called on logout: unregisters the current token from the backend.
|
||||
static Future<void> onUserLogout() async {
|
||||
await _unsubscribeFromWakeupTopics();
|
||||
|
||||
final token = _cachedToken;
|
||||
if (token == null) return;
|
||||
|
||||
try {
|
||||
await _backendClient.unregisterToken(fcmToken: token);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to unregister FCM token: $e', e, st);
|
||||
}
|
||||
_cachedToken = null;
|
||||
}
|
||||
|
||||
/// Called from the notifyAll settings effect when the master toggle changes.
|
||||
static Future<void> handleEnabledChange(bool enabled) async {
|
||||
if (!_isInitialized) return;
|
||||
|
||||
if (!enabled) {
|
||||
await _unsubscribeFromWakeupTopics();
|
||||
final token = _cachedToken;
|
||||
if (token != null) {
|
||||
try {
|
||||
await _backendClient.unregisterToken(fcmToken: token);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to unregister FCM token: $e', e, st);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final granted = await _requestPermission();
|
||||
if (!granted) {
|
||||
_logger.info('handleEnabledChange: notification permission not granted');
|
||||
return;
|
||||
}
|
||||
|
||||
final studentId = _currentStudentId(null);
|
||||
if (studentId == null) return;
|
||||
await _register(studentId: studentId);
|
||||
await _subscribeToWakeupTopic();
|
||||
}
|
||||
|
||||
/// Called when a category toggle (grades/homework/etc.) changes, to push
|
||||
/// the updated preferences to the backend for the already-registered token.
|
||||
static Future<void> updatePreferences() async {
|
||||
if (!_isInitialized || !Settings.notifyAll.value) return;
|
||||
final token = _cachedToken;
|
||||
if (token == null) return;
|
||||
|
||||
try {
|
||||
await _backendClient.updatePreferences(
|
||||
fcmToken: token,
|
||||
notifyAll: Settings.notifyAll.value,
|
||||
notifyGrades: Settings.notifyGrades.value,
|
||||
notifyHomeworkTests: Settings.notifyHomeworkTests.value,
|
||||
notifyAbsences: Settings.notifyAbsences.value,
|
||||
notifyLessons: Settings.notifyLessons.value,
|
||||
notifyMessages: Settings.notifyMessages.value,
|
||||
);
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to update FCM notification preferences: $e', e, st);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import "dart:io";
|
||||
import "package:dart_jsonwebtoken/dart_jsonwebtoken.dart";
|
||||
import "package:firka/app/app_state.dart";
|
||||
import "package:firka/app/initialization.dart";
|
||||
import "package:firka/services/fcm_service.dart";
|
||||
import "package:firka/services/live_activity_service.dart";
|
||||
import "package:firka/services/watch_sync_helper.dart";
|
||||
import "package:firka/ui/shared/firka_icon.dart";
|
||||
@@ -141,6 +142,7 @@ class SettingsAccountPickerView extends StatelessWidget {
|
||||
}
|
||||
|
||||
final previousAccountId = data.client!.cache.token.key;
|
||||
await FcmService.onUserLogout();
|
||||
if (Platform.isIOS) {
|
||||
await LiveActivityService.onUserLogout();
|
||||
try {
|
||||
@@ -162,6 +164,13 @@ class SettingsAccountPickerView extends StatelessWidget {
|
||||
await data.settings.setSelectedAccountKey(token.key);
|
||||
await initializeApp();
|
||||
|
||||
if (data.client != null) {
|
||||
await FcmService.onUserLogin(
|
||||
client: data.client!,
|
||||
settingsStore: data.settings,
|
||||
);
|
||||
}
|
||||
|
||||
if (Platform.isIOS) {
|
||||
var watchReachable = false;
|
||||
try {
|
||||
@@ -207,6 +216,7 @@ class SettingsAccountPickerView extends StatelessWidget {
|
||||
|
||||
Future<void> _logout(BuildContext context) async {
|
||||
try {
|
||||
await FcmService.onUserLogout();
|
||||
if (Platform.isIOS) {
|
||||
await LiveActivityService.onUserLogout();
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ dependencies:
|
||||
|
||||
cupertino_icons: ^1.0.8
|
||||
flutter_launcher_icons: ^0.14.3
|
||||
firebase_core: ^4.1.1
|
||||
firebase_messaging: ^16.0.2
|
||||
flutter_local_notifications: ^18.0.1
|
||||
dio: ^5.8.0+1
|
||||
isar_community: 3.3.0
|
||||
isar_community_flutter_libs: 3.3.0
|
||||
|
||||
Reference in New Issue
Block a user