Compare commits
12 Commits
5766eb6675
...
backup/ios
| Author | SHA1 | Date | |
|---|---|---|---|
| 6290c27a7e | |||
| a3a036440a | |||
| 062f1afe67 | |||
| 6d30767cb0 | |||
| 0e3c3c421f | |||
| b6d1b221b8 | |||
| e79c489de6 | |||
| c9a034c0f8 | |||
| 4dbe0b71e6 | |||
| eddfe52a51 | |||
| 1f2f7e9d4e | |||
| b28bebcce1 |
128
.woodpecker.yml
Normal file
@@ -0,0 +1,128 @@
|
||||
when:
|
||||
- event: [push, pull_request]
|
||||
- event: manual
|
||||
|
||||
steps:
|
||||
- name: submodules
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- git submodule update --init --recursive
|
||||
|
||||
- name: secrets
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
environment:
|
||||
UPLOAD_KEYSTORE_B64:
|
||||
from_secret: upload_keystore_b64
|
||||
KEYSTORE_PROPERTIES_B64:
|
||||
from_secret: keystore_properties_b64
|
||||
commands:
|
||||
- echo "$UPLOAD_KEYSTORE_B64" | base64 -d > secrets/upload-keystore.jks
|
||||
- echo "$KEYSTORE_PROPERTIES_B64" | base64 -d > secrets/keystore.properties
|
||||
|
||||
# Each step runs in a fresh container from the builder image -- only the
|
||||
# workspace volume is shared between them. Pointing PUB_CACHE at a
|
||||
# workspace-local dir (instead of the image's default /root/.pub-cache)
|
||||
# is what lets `flutter pub get`'s downloads survive into later steps.
|
||||
- name: dependencies
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter pub get
|
||||
|
||||
- name: codegen
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- dart run scripts/codegen.dart
|
||||
|
||||
- name: build-release
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch: main
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build appbundle --release
|
||||
|
||||
- name: build-debug
|
||||
image: git.firka.app/firka/firka-builder:latest
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
commands:
|
||||
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
|
||||
- cd firka
|
||||
- flutter build apk --debug --split-per-abi
|
||||
|
||||
- name: publish-release
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/bundle/release/app-release.aab
|
||||
file_name: app-release.aab
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-arm64-v8a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-arm64-v8a-debug.apk
|
||||
file_name: app-arm64-v8a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-armeabi-v7a
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-armeabi-v7a-debug.apk
|
||||
file_name: app-armeabi-v7a-debug.apk
|
||||
update: 'true'
|
||||
|
||||
- name: publish-debug-x86_64
|
||||
image: woodpeckercommunity/plugin-gitea-package:latest
|
||||
pull: true
|
||||
when:
|
||||
- branch:
|
||||
exclude: main
|
||||
settings:
|
||||
user:
|
||||
from_secret: gitea_username
|
||||
password:
|
||||
from_secret: gitea_token
|
||||
owner: firka
|
||||
package_name: firka
|
||||
package_version: ${CI_COMMIT_SHA}
|
||||
file_source: ./firka/build/app/outputs/flutter-apk/app-x86_64-debug.apk
|
||||
file_name: app-x86_64-debug.apk
|
||||
update: 'true'
|
||||
66
Jenkinsfile
vendored
@@ -1,66 +0,0 @@
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
FLUTTER_ROOT = "/opt/flutter"
|
||||
FLUTTER = "/opt/flutter/bin/flutter"
|
||||
DART = "/opt/flutter/bin/dart"
|
||||
ANDROID_SDK_ROOT = "/opt/android-sdk"
|
||||
ANDROID_HOME = "/opt/android-sdk"
|
||||
}
|
||||
stages {
|
||||
stage('Clone Submodules') {
|
||||
steps {
|
||||
sh 'git submodule update --init --recursive'
|
||||
}
|
||||
}
|
||||
stage('Dependencies') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
$FLUTTER pub get
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Setup') {
|
||||
steps {
|
||||
sh '''
|
||||
cp -r /opt/secrets ./
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Codegen') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
PATH="/opt/flutter/bin:$PATH" $DART run scripts/codegen.dart
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Build') {
|
||||
steps {
|
||||
sh '''
|
||||
cd firka
|
||||
echo "--- Checking secrets path ---"
|
||||
ls android/app/
|
||||
ls android/app/../../../ || echo "no parent"
|
||||
ls android/app/../../../secrets/ || echo "secrets not found at expected path"
|
||||
$FLUTTER config --android-sdk /opt/android-sdk
|
||||
$FLUTTER build apk --release
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Archive') {
|
||||
steps {
|
||||
archiveArtifacts(
|
||||
artifacts: 'firka/build/app/outputs/flutter-apk/app-debug.apk,firka/build/app/outputs/flutter-apk/app-release.apk',
|
||||
fingerprint: true
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
post {
|
||||
always {
|
||||
deleteDir()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -14,6 +17,7 @@ android {
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
isCoreLibraryDesugaringEnabled = true
|
||||
}
|
||||
buildFeatures {
|
||||
compose = true
|
||||
@@ -73,6 +77,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")
|
||||
|
||||
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
@@ -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:
|
||||
|
||||
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 1.3 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 4.5 KiB After Width: | Height: | Size: 957 B |
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 1.7 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 3.8 KiB |
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 8.1 KiB |
@@ -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
|
||||
}
|
||||
|
||||
|
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 13 KiB |
@@ -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_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"
|
||||
|
||||
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
@@ -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';
|
||||
@@ -201,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 {
|
||||
@@ -307,6 +315,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;
|
||||
|
||||
@@ -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<String, dynamic> _read() {
|
||||
try {
|
||||
final decoded = jsonDecode(Settings.lastSeen.value);
|
||||
|
||||
@@ -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,
|
||||
@@ -456,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,
|
||||
|
||||
@@ -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,14 @@ abstract class SettingsSchema {
|
||||
|
||||
@StringSetting(id: 1044, defaultValue: "[]")
|
||||
String get notifyMutedSubjects;
|
||||
|
||||
@EnumSetting(
|
||||
id: 1045,
|
||||
defaultValue: NotifyWakeupInterval.hourly,
|
||||
values: NotifyWakeupInterval.values,
|
||||
)
|
||||
NotifyWakeupInterval get notifyWakeupInterval;
|
||||
|
||||
@BoolSetting(id: 1046, defaultValue: false)
|
||||
bool get fcmDebugNotifyOnMessage;
|
||||
}
|
||||
|
||||
@@ -46,9 +46,11 @@ 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 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,
|
||||
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,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -96,4 +98,6 @@ 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);
|
||||
SilentlySettable<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
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',
|
||||
);
|
||||
}
|
||||
43
firka/lib/services/fcm_headless_bootstrap.dart
Normal file
@@ -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<void> 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<NavigatorState>(),
|
||||
);
|
||||
Settings = settings;
|
||||
initDone = true;
|
||||
}
|
||||
329
firka/lib/services/fcm_service.dart
Normal file
@@ -0,0 +1,329 @@
|
||||
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/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.
|
||||
@pragma('vm:entry-point')
|
||||
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
|
||||
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.
|
||||
/// 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;
|
||||
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.
|
||||
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;
|
||||
_lastTokenRefreshAt = DateTime.now();
|
||||
_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());
|
||||
}
|
||||
unawaited(_maybeShowDebugMessageNotification(message));
|
||||
});
|
||||
|
||||
_isInitialized = true;
|
||||
_logger.info('FcmService initialized');
|
||||
} catch (e, st) {
|
||||
_logger.severe('Failed to initialize FcmService: $e', e, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
67
firka/lib/services/local_notification_service.dart
Normal file
@@ -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<void> 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<void> 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(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
339
firka/lib/services/notification_diff_service.dart
Normal file
@@ -0,0 +1,339 @@
|
||||
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<void> 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<void> _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<void> _diffAndNotify<T extends GenericCacheModel>({
|
||||
required int accountKey,
|
||||
required String kind,
|
||||
required List<T> items,
|
||||
required String Function(List<T> newItems) title,
|
||||
required String Function(List<T> 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<T> _excludeMuted<T>(
|
||||
List<T> items,
|
||||
Set<String> mutedSubjects,
|
||||
String? Function(T) subjectOf,
|
||||
) {
|
||||
if (mutedSubjects.isEmpty) return items;
|
||||
return items.where((i) => !mutedSubjects.contains(subjectOf(i))).toList();
|
||||
}
|
||||
|
||||
static Set<String> _mutedSubjects() {
|
||||
try {
|
||||
final decoded = jsonDecode(Settings.notifyMutedSubjects.value);
|
||||
if (decoded is List) return decoded.whereType<String>().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')}';
|
||||
|
||||
/// 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
195
firka/lib/ui/phone/screens/settings/settings_fcm_status.dart
Normal 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),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
47
flake.nix
@@ -1,47 +0,0 @@
|
||||
{
|
||||
description = "Firka — development environment";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
android-nixpkgs = {
|
||||
url = "github:tadfisher/android-nixpkgs";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils, android-nixpkgs }:
|
||||
flake-utils.lib.eachSystem [ "aarch64-darwin" "x86_64-darwin" "x86_64-linux" ] (system:
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages.${system};
|
||||
androidSdk = android-nixpkgs.sdk.${system} (sdkPkgs: with sdkPkgs; [
|
||||
cmdline-tools-latest
|
||||
build-tools-34-0-0
|
||||
build-tools-35-0-0
|
||||
build-tools-36-1-0
|
||||
platform-tools
|
||||
platforms-android-34
|
||||
platforms-android-35
|
||||
platforms-android-36
|
||||
ndk-28-2-13676358
|
||||
cmake-3-22-1
|
||||
]);
|
||||
in
|
||||
{
|
||||
devShells.default = pkgs.mkShell {
|
||||
buildInputs = with pkgs; [
|
||||
flutter
|
||||
git
|
||||
jq
|
||||
jdk17
|
||||
androidSdk
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
export GRADLE_OPTS="-Dorg.gradle.project.android.aapt2FromMavenOverride=$ANDROID_HOME/build-tools/36.1.0/aapt2"
|
||||
flutter --version | head -1
|
||||
dart --version
|
||||
'';
|
||||
};
|
||||
});
|
||||
}
|
||||