4 Commits

Author SHA1 Message Date
d8ee1d8073 fix(android): resolve ProGuard configuration path in release builds
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-09-09 00:09:03 +02:00
280b5142a5 ci: add staging branch pipeline and dynamic versioning trick
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
2026-09-08 21:02:36 +02:00
31b9d86ed9 chore: update codegen, build configs
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-09-08 19:51:00 +02:00
ff297bf4b8 feat(notifications): add multi-backend notification delivery with FCM and AlarmManager fallback
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was canceled
- Add Google Play Services (GMS) availability check via MainActivity platform channel
- Add AlarmNotificationService using android_alarm_manager_plus for periodic background checks
- Add NotificationDeliveryService coordinator to resolve delivery method and sync backends
- Add NotificationDeliveryMethod setting (auto, fcm, alarm) with automatic fallback when GMS is unavailable
- Update en/hu localization strings for notification delivery method selection
- Add unit and integration tests for alarm scheduling, settings effects handoff, and e2e wakeup diffing
2026-09-08 18:53:05 +02:00
27 changed files with 841 additions and 104 deletions

3
.gitignore vendored
View File

@@ -100,9 +100,12 @@ firka/debug-info/
**/.env*
**/*.dart.js
**/*.info.json
**/*.g.dart
**/.codegen-cache.yaml
# tools.py logs
tool_logs/build/*.log
tool_logs/d8dx_fix/*.log
tool_logs/pub_fix/*.log
secrets/upload_certificate.pem
secrets (2)/upload_certificate.pem

View File

@@ -111,27 +111,40 @@ steps:
- name: build-release
image: git.firka.app/firka/firka-builder:latest
when:
- branch: main
- branch: [main, staging]
commands:
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
- cd firka
- flutter build appbundle --release
- '[ -f "$(git rev-parse --git-dir)/shallow" ] && git fetch --unshallow 2>/dev/null || true'
- SHA=$(git rev-parse --short HEAD)
- COMMIT_COUNT=$(git rev-list --count HEAD)
- 'BASE_VERSION=$(grep "^version:" pubspec.yaml | cut -d: -f2 | cut -d+ -f1 | tr -d " ")'
- BUILD_NAME="$BASE_VERSION-$SHA"
- VERSION_CODE=$((2000 + COMMIT_COUNT))
- flutter build appbundle --release --build-name="$BUILD_NAME" --build-number="$VERSION_CODE"
- name: build-debug
image: git.firka.app/firka/firka-builder:latest
when:
- branch:
exclude: main
exclude: [main, staging]
commands:
- export PUB_CACHE="$CI_WORKSPACE/.pub-cache"
- cd firka
- flutter build apk --debug --split-per-abi
- '[ -f "$(git rev-parse --git-dir)/shallow" ] && git fetch --unshallow 2>/dev/null || true'
- SHA=$(git rev-parse --short HEAD)
- COMMIT_COUNT=$(git rev-list --count HEAD)
- 'BASE_VERSION=$(grep "^version:" pubspec.yaml | cut -d: -f2 | cut -d+ -f1 | tr -d " ")'
- BUILD_NAME="$BASE_VERSION-$SHA"
- VERSION_CODE=$((2000 + COMMIT_COUNT))
- flutter build apk --debug --split-per-abi --build-name="$BUILD_NAME" --build-number="$VERSION_CODE"
- name: publish-release
image: woodpeckercommunity/plugin-gitea-package:latest
pull: true
when:
- branch: main
- branch: [main, staging]
settings:
user:
from_secret: gitea_username
@@ -149,7 +162,7 @@ steps:
pull: true
when:
- branch:
exclude: main
exclude: [main, staging]
settings:
user:
from_secret: gitea_username
@@ -167,7 +180,7 @@ steps:
pull: true
when:
- branch:
exclude: main
exclude: [main, staging]
settings:
user:
from_secret: gitea_username
@@ -185,7 +198,7 @@ steps:
pull: true
when:
- branch:
exclude: main
exclude: [main, staging]
settings:
user:
from_secret: gitea_username
@@ -197,3 +210,4 @@ steps:
file_source: ./firka/build/app/outputs/flutter-apk/app-x86_64-debug.apk
file_name: app-x86_64-debug.apk
update: 'true'

View File

@@ -12,7 +12,7 @@ plugins {
}
android {
namespace = "app.firka.naplo"
compileSdk = flutter.compileSdkVersion
compileSdk = 37
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
@@ -59,7 +59,7 @@ android {
if (config != null) {
signingConfig = config
}
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
proguardFiles("proguard-rules.pro")
}
}
}
@@ -77,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")
implementation("com.google.android.gms:play-services-base:18.5.0")
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}
// Ensure .env exists before Flutter bundles assets (copy from .env.example if missing)
@@ -93,6 +94,26 @@ tasks.register("ensureEnv") {
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
dependsOn("ensureEnv")
}
// Ensure default ProGuard files exist at the projectDir location expected by AGP/R8 when build directory is relocated
val defaultProguardDir = file("${project.projectDir}/build/intermediates/default_proguard_files/global")
defaultProguardDir.mkdirs()
val defaultProguardOptimize = File(defaultProguardDir, "proguard-android-optimize.txt-9.2.0")
if (!defaultProguardOptimize.exists()) {
defaultProguardOptimize.writeText("-allowaccessmodification\n")
}
tasks.register("ensureProguardFiles") {
doLast {
defaultProguardDir.mkdirs()
if (!defaultProguardOptimize.exists()) {
defaultProguardOptimize.writeText("-allowaccessmodification\n")
}
}
}
tasks.matching { it.name.startsWith("compile") || it.name.contains("minify", ignoreCase = true) || it.name.contains("r8", ignoreCase = true) }.configureEach {
dependsOn("ensureProguardFiles")
}
flutter {
source = "../.."
}

View File

@@ -1 +1,75 @@
-keep class app.firka.naplo.glance.** { *; }
# Firka custom keep rules
-keep class app.firka.naplo.glance.** { *; }
# Android optimize rules (-allowaccessmodification)
-allowaccessmodification
# Android common keep rules
-keepattributes AnnotationDefault,
EnclosingMethod,
InnerClasses,
RuntimeVisibleAnnotations,
RuntimeVisibleParameterAnnotations,
RuntimeVisibleTypeAnnotations,
Signature
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService
-keep public class com.google.android.vending.licensing.ILicensingService
-dontnote com.android.vending.licensing.ILicensingService
-dontnote com.google.vending.licensing.ILicensingService
-dontnote com.google.android.vending.licensing.ILicensingService
# Native methods
-keepclasseswithmembernames,includedescriptorclasses class * {
native <methods>;
}
# Keep setters in Views so that animations can still work.
-keepclassmembers public class * extends android.view.View {
void set*(***);
*** get*();
}
# We want to keep methods in Activity that could be used in the XML attribute onClick.
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
# For enumeration classes
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
public static final ** CREATOR;
}
# Preserve annotated Javascript interface methods.
-keepclassmembers class * {
@android.webkit.JavascriptInterface <methods>;
}
# The support libraries contains references to newer platform versions.
-dontnote android.support.**
-dontnote androidx.**
-dontwarn android.support.**
-dontwarn androidx.**
# Understand the @Keep support annotation.
-keep class android.support.annotation.Keep
-keep @android.support.annotation.Keep class * {*;}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <methods>;
}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <fields>;
}
-keepclasseswithmembers class * {
@android.support.annotation.Keep <init>(...);
}
-dontnote org.apache.http.**
-dontnote android.net.http.**
-dontnote java.lang.invoke.**

View File

@@ -3,6 +3,7 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

View File

@@ -10,6 +10,8 @@ import android.util.Log
import androidx.glance.appwidget.updateAll
import app.firka.naplo.glance.TimetableWidget
import app.firka.naplo.glance.TimetableWidgetReceiver
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
@@ -174,6 +176,15 @@ class MainActivity : FlutterActivity() {
}
}
}
"isGmsAvailable" -> {
try {
val availability = GoogleApiAvailability.getInstance()
val resultCode = availability.isGooglePlayServicesAvailable(context)
result.success(resultCode == ConnectionResult.SUCCESS)
} catch (e: Exception) {
result.success(false)
}
}
else -> {
result.notImplemented()
}

View File

@@ -13,25 +13,27 @@ rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
afterEvaluate {
if (plugins.hasPlugin("com.android.application")) {
extensions.configure<ApplicationExtension> {
compileSdk = 37
defaultConfig {
// buildToolsVersion can be set here if needed
if (project.name != "app") {
project.evaluationDependsOn(":app")
// android_alarm_manager_plus 5.1.1's own build.gradle.kts only applies
// org.jetbrains.kotlin.android when AGP < 9, then unconditionally
// configures KotlinAndroidProjectExtension - which doesn't exist here
// on AGP 9+ unless we apply the plugin ourselves first.
if (project.name == "android_alarm_manager_plus") {
pluginManager.apply("org.jetbrains.kotlin.android")
}
afterEvaluate {
if (plugins.hasPlugin("com.android.library")) {
extensions.configure<LibraryExtension> {
compileSdk = 37
}
}
}
if (plugins.hasPlugin("com.android.library")) {
extensions.configure<LibraryExtension> {
compileSdk = 37
}
}
}
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
tasks.register<Delete>("clean") {

View File

@@ -15,3 +15,6 @@ kotlin.incremental.useClasspathSnapshot=true
android.builtInKotlin=false
android.newDsl=false
# Prevent AGP 9.0+ build failures due to relocated build directory ProGuard path mismatches
android.proguard.failOnMissingFiles=false

View File

@@ -1,22 +1,10 @@
icons:
"flutter_launcher_icons.yaml": "c600507ca0df7cebd0f708124842512a14ed3d597b779176200d6ba25b1335b1"
"pubspec.yaml": "5d40f014d654e257bc58e8ebfb2468a5ed7f75d913a67fb89314b9fda1c257a6"
"flutter_launcher_icons.yaml": "993c1cd3a99db70747299601e556d19ec959b0a16fd9ff2dbf2386cb6f2a640d"
"pubspec.yaml": "198608775541fab3b6ff8cc21545e12a3413455f6ed87355cfdb576a97efab2d"
"assets/images/logos/colored_logo.webp": "4b4fa99d144fe6694aa4487ba1b26aeecafae41e3c877836cd7da28d61a77983"
"assets/images/logos/monochrome_logo.png": "188d2b0a64c70323b09bcee721663d6698fb557066f20ddaec97bba6869c1c6c"
"assets/images/logos/monochrome_logo.png": "c269a5e689622484d800a4fda5927591a0bf99d34790a4f146b93cf6edabd455"
"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_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"
"lib/data/models/homework_cache_model.dart": "45789970b27d5790cdc54c292ef2f5feaa5f4e293b8a8862fd676d5eb3e25d29"
"lib/data/models/generic_cache_model.dart": "62003ec1fd73a0fa6786d337acdef42b9a6eb9efaa78d17eaf4fe091504b8490"
"lib/data/models/timetable_cache_model.dart": "b972bf51e399f8d20d4f9ad660082d4cc4a9798df9ac9d6ec9ef6ac640205572"
splash:
"flutter_native_splash.yaml": "0fd4a85d6f950d97298e99916927649940ffcfdadfc136ceee126fed0dbaa9f2"
"flutter_native_splash.yaml": "f1bddb74798b1539c4e9213ca9ae305d625ebb0ac5bcbe079b523437e0abc2c4"
"assets/images/logos/splash.png": "88fbebc3d686cb9095bcce362029b69978b1b14270e465e91d962b1425db1152"

View File

@@ -1,6 +1,7 @@
flutter_launcher_icons:
generate: true
android: "launcher_icon"
ios: false
image_path: "assets/images/logos/colored_logo.webp"
adaptive_icon_monochrome: "assets/images/logos/monochrome_logo.png"
adaptive_icon_background: "assets/images/logos/colored_logo_without_mustache.png"

View File

@@ -17,4 +17,6 @@ flutter_native_splash:
icon_background_color: "#7ca120"
icon_background_color_dark: "#7ca120"
android: true
ios: false
web: false

View File

@@ -1,6 +1,6 @@
import "package:firka/app/app_state.dart";
import "package:firka/app/initialization.dart";
import "package:firka/services/fcm_service.dart";
import "package:firka/services/notification_delivery_service.dart";
import "package:firka_common/data/models/token_model.dart";
import "package:kreta_api/kreta_api.dart";
@@ -18,9 +18,8 @@ Future<void> completeLogin(
await initializeApp();
if (data.client != null) {
await FcmService.onUserLogin(
await NotificationDeliveryService.onUserLogin(
client: data.client!,
settingsStore: data.settings,
);
}
}

View File

@@ -8,7 +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/notification_delivery_service.dart';
import 'package:firka/data/widget.dart';
import 'package:firka/core/settings/settings_effects.dart';
import 'package:firka/core/settings/settings_repository.dart';
@@ -167,7 +167,7 @@ Future<void> _initData(AppInitialization init) async {
// 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!));
unawaited(NotificationDeliveryService.onUserLogin(client: init.client!));
// Immediately refresh widget state from cached Isar lessons so widget is up to date
unawaited(WidgetCacheHelper.updateWidgetCacheFromIsar());
@@ -248,11 +248,11 @@ Future<void> initializeApp() async {
registerSettingsEffects(initData.settings, initData);
try {
await FcmService.initialize().timeout(const Duration(seconds: 8));
await NotificationDeliveryService.initialize().timeout(const Duration(seconds: 8));
} on TimeoutException catch (e, st) {
logger.warning('FcmService init timed out: $e', e, st);
logger.warning('NotificationDeliveryService init timed out: $e', e, st);
} catch (e, st) {
logger.severe('Failed to initialize FcmService: $e', e, st);
logger.severe('Failed to initialize NotificationDeliveryService: $e', e, st);
}
await _initData(initData);

View File

@@ -293,6 +293,12 @@ SettingsUiGroup buildSettingsTree(AppLocalizations l10n) {
SettingsRegistry.notifyAll,
always,
),
SettingsUiHeaderSmall(l10n.s_notif_delivery_method_header, isPushNotificationsEnabled),
SettingsUiEnum(SettingsRegistry.notificationDeliveryMethod, [
l10n.s_notif_delivery_auto,
l10n.s_notif_delivery_fcm,
l10n.s_notif_delivery_alarm,
], isPushNotificationsEnabled),
SettingsUiHeaderSmall(l10n.s_notif_wakeup_interval_header, isPushNotificationsEnabled),
SettingsUiEnum(SettingsRegistry.notifyWakeupInterval, [
l10n.s_notif_wakeup_hourly,

View File

@@ -5,6 +5,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/notification_delivery_service.dart";
import "package:firka/services/watch_sync_helper.dart";
import "settings_repository.dart";
@@ -53,12 +54,16 @@ void registerSettingsEffects(
}
});
repo.onChange(SettingsRegistry.notifyAll, (enabled) async {
await FcmService.handleEnabledChange(enabled);
repo.onChange(SettingsRegistry.notifyAll, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
});
repo.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
});
repo.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
await FcmService.handleWakeupIntervalChange();
await NotificationDeliveryService.handleWakeupIntervalChange();
});
for (final setting in [

View File

@@ -24,6 +24,8 @@ enum TitleCapitalization { lower, normal, upper }
/// `wakeup-2hourly` sent by the `fcm-notifier` backend service.
enum NotifyWakeupInterval { hourly, twoHourly }
enum NotificationDeliveryMethod { auto, fcm, alarm }
abstract class SettingsSchema {
@DoubleSetting(id: 1001, defaultValue: 0, min: 0, max: 120)
double get bellDelay;
@@ -177,4 +179,11 @@ abstract class SettingsSchema {
@BoolSetting(id: 1046, defaultValue: false)
bool get fcmDebugNotifyOnMessage;
@EnumSetting(
id: 1047,
defaultValue: NotificationDeliveryMethod.auto,
values: NotificationDeliveryMethod.values,
)
NotificationDeliveryMethod get notificationDeliveryMethod;
}

View File

@@ -44,9 +44,10 @@ class SettingsRegistry {
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 notificationDeliveryMethod = EnumSetting(id: 1047, defaultValue: NotificationDeliveryMethod.auto, values: NotificationDeliveryMethod.values);
static const all = <Setting>[
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage,
bellDelay, rounding1, rounding2, rounding3, rounding4, classAvgOnGraph, leftHandedMode, language, appIcon, childProtection, betaWarning, ttToastLessonNo, ttToastTestsAndHw, ttToastBreaks, statsForNerds, developerOptsEnabled, themeBrightness, ttToastSubstitution, ttToastABTimetable, wearOsSupport, titleFont, titleWeight, titleCapitalization, selectedThemeId, selectedCoreThemeId, selectedGradeThemeId, mockBackendEnabled, mockBackendUrl, lastSeen, surpriseGrades, seasonalAppIcons, uwuMode, notifyAll, notifyGrades, notifyHomeworkTests, notifyAbsences, notifyLessons, notifyMessages, notifyMutedSubjects, notifyWakeupInterval, fcmDebugNotifyOnMessage, notificationDeliveryMethod,
];
}
@@ -92,4 +93,5 @@ extension SettingsAccessors on SettingsRepository {
SilentlySettable<String> get notifyMutedSubjects => SilentlySettable(this, SettingsRegistry.notifyMutedSubjects);
SilentlySettable<NotifyWakeupInterval> get notifyWakeupInterval => SilentlySettable(this, SettingsRegistry.notifyWakeupInterval);
SilentlySettable<bool> get fcmDebugNotifyOnMessage => SilentlySettable(this, SettingsRegistry.fcmDebugNotifyOnMessage);
SilentlySettable<NotificationDeliveryMethod> get notificationDeliveryMethod => SilentlySettable(this, SettingsRegistry.notificationDeliveryMethod);
}

View File

@@ -0,0 +1,86 @@
import 'dart:async';
import 'dart:io';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:flutter/widgets.dart';
import 'package:logging/logging.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/notification_diff_service.dart';
const int _alarmNotificationSyncId = 910001;
@pragma('vm:entry-point')
Future<void> alarmNotificationWakeupCallback() async {
WidgetsFlutterBinding.ensureInitialized();
await NotificationDiffService.checkAll();
}
class AlarmNotificationService {
static final Logger _logger = Logger('AlarmNotificationService');
static bool _isInitialized = false;
@visibleForTesting
static bool? isAndroidOverride;
static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
@visibleForTesting
static void resetForTesting() {
_isInitialized = false;
isAndroidOverride = null;
}
static bool get isInitialized => _isInitialized;
static Future<void> initialize() async {
if (_isInitialized || !_isAndroid) return;
try {
await AndroidAlarmManager.initialize();
_isInitialized = true;
_logger.info('AlarmNotificationService initialized');
} catch (e, st) {
_logger.severe('Failed to initialize AlarmNotificationService: $e', e, st);
}
}
static Duration _durationFor(NotifyWakeupInterval interval) {
switch (interval) {
case NotifyWakeupInterval.hourly:
return const Duration(hours: 1);
case NotifyWakeupInterval.twoHourly:
return const Duration(hours: 2);
}
}
static Future<void> schedule() async {
if (!_isAndroid) return;
try {
await initialize();
final interval = _durationFor(Settings.notifyWakeupInterval.value);
await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
await AndroidAlarmManager.periodic(
interval,
_alarmNotificationSyncId,
alarmNotificationWakeupCallback,
exact: false,
wakeup: true,
rescheduleOnReboot: true,
);
_logger.info('Scheduled periodic alarm every ${interval.inHours}h');
} catch (e, st) {
_logger.severe('Failed to schedule alarm: $e', e, st);
}
}
static Future<void> cancel() async {
if (!_isAndroid) return;
try {
await AndroidAlarmManager.cancel(_alarmNotificationSyncId);
_logger.info('Cancelled periodic alarm');
} catch (e, st) {
_logger.warning('Failed to cancel alarm: $e', e, st);
}
}
}

View File

@@ -151,11 +151,29 @@ class FcmService {
}
}
static Future<bool>? _pendingPermissionRequest;
static Future<bool> _requestPermission() async {
if (_pendingPermissionRequest != null) {
return await _pendingPermissionRequest!;
}
final status = await Permission.notification.status;
if (status.isGranted) return true;
final result = await Permission.notification.request();
return result.isGranted;
final future = () async {
try {
final result = await Permission.notification.request();
return result.isGranted;
} catch (e) {
_logger.warning('Failed to request notification permission: $e');
return false;
} finally {
_pendingPermissionRequest = null;
}
}();
_pendingPermissionRequest = future;
return await future;
}
static String? _currentStudentId(KretaClient? client) {

View File

@@ -0,0 +1,150 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:logging/logging.dart';
import 'package:firka/api/client/kreta_client.dart';
import 'package:firka_common/data/database.dart';
import 'package:firka_common/data/models/token_model.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka/services/fcm_service.dart';
class NotificationDeliveryService {
static final Logger _logger = Logger('NotificationDeliveryService');
static const MethodChannel _mainChannel = MethodChannel('firka.app/main');
static bool? _cachedGmsAvailable;
@visibleForTesting
static bool? gmsAvailabilityOverride;
@visibleForTesting
static bool? isAndroidOverride;
static bool get _isAndroid => isAndroidOverride ?? Platform.isAndroid;
@visibleForTesting
static void resetForTesting() {
_cachedGmsAvailable = null;
gmsAvailabilityOverride = null;
isAndroidOverride = null;
}
static Future<bool> isGmsAvailable({bool forceRefresh = false}) async {
if (gmsAvailabilityOverride != null) {
return gmsAvailabilityOverride!;
}
if (!_isAndroid) return false;
if (_cachedGmsAvailable != null && !forceRefresh) {
return _cachedGmsAvailable!;
}
try {
final available = await _mainChannel.invokeMethod<bool>('isGmsAvailable');
_cachedGmsAvailable = available ?? false;
return _cachedGmsAvailable!;
} catch (e) {
_logger.warning('Error checking GMS availability: $e');
_cachedGmsAvailable = false;
return false;
}
}
static Future<NotificationDeliveryMethod> getEffectiveMethod() async {
final configured = Settings.notificationDeliveryMethod.value;
if (configured != NotificationDeliveryMethod.auto) {
return configured;
}
final gms = await isGmsAvailable();
return gms ? NotificationDeliveryMethod.fcm : NotificationDeliveryMethod.alarm;
}
static Future<void> initialize() async {
if (!_isAndroid) return;
final gms = await isGmsAvailable();
_logger.info('Initializing NotificationDeliveryService (GMS available: $gms)');
await AlarmNotificationService.initialize();
if (gms) {
await FcmService.initialize();
}
await syncDeliveryBackend();
}
static Future<void> syncDeliveryBackend() async {
if (!_isAndroid) return;
try {
if (!Settings.notifyAll.value) {
_logger.info('Push notifications disabled, tearing down delivery backends');
await FcmService.handleEnabledChange(false);
await AlarmNotificationService.cancel();
return;
}
final effectiveMethod = await getEffectiveMethod();
_logger.info('Syncing delivery backend for effective method: $effectiveMethod');
switch (effectiveMethod) {
case NotificationDeliveryMethod.fcm:
await AlarmNotificationService.cancel();
await FcmService.handleEnabledChange(true);
break;
case NotificationDeliveryMethod.alarm:
await FcmService.handleEnabledChange(false);
await AlarmNotificationService.schedule();
break;
case NotificationDeliveryMethod.auto:
break;
}
} catch (e, st) {
_logger.warning('Failed to sync delivery backend: $e', e, st);
}
}
static Future<void> handleWakeupIntervalChange() async {
if (!Settings.notifyAll.value) return;
final effectiveMethod = await getEffectiveMethod();
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
await FcmService.handleWakeupIntervalChange();
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
await AlarmNotificationService.schedule();
}
}
static Future<void> onUserLogin({required KretaClient client}) async {
if (!_isAndroid) return;
try {
final effectiveMethod = await getEffectiveMethod();
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
await FcmService.onUserLogin(client: client);
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
await AlarmNotificationService.schedule();
}
} catch (e, st) {
_logger.warning('Failed to process onUserLogin: $e', e, st);
}
}
static Future<void> onUserLogout() async {
if (!_isAndroid) return;
final effectiveMethod = await getEffectiveMethod();
if (effectiveMethod == NotificationDeliveryMethod.fcm) {
await FcmService.onUserLogout();
} else if (effectiveMethod == NotificationDeliveryMethod.alarm) {
final tokenCount = await isarInit.tokenModels.count();
if (tokenCount == 0) {
await AlarmNotificationService.cancel();
}
}
}
}

View File

@@ -1,7 +1,7 @@
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/notification_delivery_service.dart";
import "package:firka/ui/shared/firka_icon.dart";
import "package:firka/ui/theme/style.dart";
import "package:firka/ui/phone/widgets/login_webview.dart";
@@ -137,15 +137,14 @@ class SettingsAccountPickerView extends StatelessWidget {
return;
}
await FcmService.onUserLogout();
await NotificationDeliveryService.onUserLogout();
await data.settings.setSelectedAccountKey(token.key);
await initializeApp();
if (data.client != null) {
await FcmService.onUserLogin(
await NotificationDeliveryService.onUserLogin(
client: data.client!,
settingsStore: data.settings,
);
}
@@ -157,7 +156,7 @@ class SettingsAccountPickerView extends StatelessWidget {
Future<void> _logout(BuildContext context) async {
try {
await FcmService.onUserLogout();
await NotificationDeliveryService.onUserLogout();
final active = data.client!.cache.token.key;

View File

@@ -20,6 +20,7 @@ dependencies:
firebase_core: ^4.1.1
firebase_messaging: ^16.0.2
flutter_local_notifications: ^18.0.1
android_alarm_manager_plus: ^5.1.1
dio: ^5.8.0+1
isar_community: 3.3.0
isar_community_flutter_libs: 3.3.0

View File

@@ -6,10 +6,12 @@ import 'package:path/path.dart' as p;
import 'package:yaml/yaml.dart' as yaml;
const _lockFileName = 'codegen-lock.yaml';
const _cacheFileName = '.codegen-cache.yaml';
void main() async {
final root = _projectRoot();
stdout.writeln(root);
_cleanIos(root);
var ran = false;
if (_iconsOutOfDate(root)) {
@@ -31,6 +33,7 @@ void main() async {
runInShell: true,
);
if (iconResult.exitCode == 0) {
_cleanIos(root);
_updateLockWithHashes(root, 'icons', _computeHashes(root, inputs));
ran = true;
}
@@ -53,19 +56,23 @@ void main() async {
'--template-arb-file',
'app_hu.arb',
], root);
_updateLockWithHashes(root, 'l10n', _computeHashes(root, inputs));
_updateCacheWithHashes(root, 'l10n', _computeHashes(root, inputs));
ran = true;
}
var common = p.join(p.dirname(root), "firka_common");
if (_isarOutOfDate(common) || _isarGeneratedFilesMissing(common)) {
final common = p.join(p.dirname(root), 'firka_common');
if (_isarOutOfDate(common)) {
final inputs = _isarInputs(common);
final hashes = _computeHashes(common, inputs);
stdout.writeln(
'Isar generated dart files out of date or missing, running build_runner...',
);
await _run('dart', ['run', 'build_runner', 'build'], common);
_updateLockWithHashes(common, 'isar', hashes);
await _run(
'dart',
['run', 'build_runner', 'build', '--delete-conflicting-outputs'],
common,
);
_updateCacheWithHashes(common, 'isar', hashes);
ran = true;
}
@@ -76,10 +83,13 @@ void main() async {
'Splash out of date, running flutter_native_splash:create...',
);
await _run('dart', ['run', 'flutter_native_splash:create'], root);
_cleanIos(root);
_updateLockWithHashes(root, 'splash', _computeHashes(root, inputs));
ran = true;
}
_cleanIos(root);
if (!ran) {
stdout.writeln('All generated files are up to date.');
}
@@ -91,9 +101,10 @@ String _projectRoot() {
}
String _lockPath(String root) => p.join(root, _lockFileName);
String _cachePath(String root) => p.join(root, _cacheFileName);
Map<String, Map<String, String>>? _readLock(String root) {
final file = File(_lockPath(root));
Map<String, Map<String, String>>? _readYamlFile(String filePath) {
final file = File(filePath);
if (!file.existsSync()) return null;
try {
final content = file.readAsStringSync();
@@ -116,9 +127,9 @@ Map<String, Map<String, String>>? _readLock(String root) {
}
}
void _writeLock(String root, Map<String, Map<String, String>> lock) {
void _writeYamlFile(String filePath, Map<String, Map<String, String>> data) {
final buf = StringBuffer();
for (final stepEntry in lock.entries) {
for (final stepEntry in data.entries) {
buf.writeln('${stepEntry.key}:');
for (final fileEntry in stepEntry.value.entries) {
buf.writeln(
@@ -126,9 +137,15 @@ void _writeLock(String root, Map<String, Map<String, String>> lock) {
);
}
}
File(_lockPath(root)).writeAsStringSync(buf.toString());
File(filePath).writeAsStringSync(buf.toString());
}
Map<String, Map<String, String>>? _readLock(String root) =>
_readYamlFile(_lockPath(root));
Map<String, Map<String, String>>? _readCache(String root) =>
_readYamlFile(_cachePath(root));
String _escapeYaml(String s) =>
s.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
@@ -148,10 +165,10 @@ bool _hashesMatch(
String root,
String stepName,
List<File> inputs,
Map<String, Map<String, String>>? lock,
Map<String, Map<String, String>>? lockOrCache,
) {
if (lock == null || !lock.containsKey(stepName)) return false;
final stepHashes = lock[stepName]!;
if (lockOrCache == null || !lockOrCache.containsKey(stepName)) return false;
final stepHashes = lockOrCache[stepName]!;
for (final f in inputs) {
final rel = _relativePath(root, f);
final stored = stepHashes[rel];
@@ -172,22 +189,24 @@ void _updateLockWithHashes(
) {
final lock = _readLock(root) ?? <String, Map<String, String>>{};
lock[stepName] = Map.from(hashes);
_writeLock(root, lock);
_writeYamlFile(_lockPath(root), lock);
}
DateTime? _modified(File file) {
if (!file.existsSync()) return null;
return file.lastModifiedSync();
void _updateCacheWithHashes(
String root,
String stepName,
Map<String, String> hashes,
) {
final cache = _readCache(root) ?? <String, Map<String, String>>{};
cache[stepName] = Map.from(hashes);
_writeYamlFile(_cachePath(root), cache);
}
bool _anyNewerThan(Iterable<File> inputs, File output) {
final outTime = _modified(output);
if (outTime == null) return true;
for (final f in inputs) {
final t = _modified(f);
if (t != null && t.isAfter(outTime)) return true;
void _cleanIos(String root) {
final iosDir = Directory(p.join(root, 'ios'));
if (iosDir.existsSync()) {
iosDir.deleteSync(recursive: true);
}
return false;
}
List<File> _iconsInputs(String root) {
@@ -217,7 +236,7 @@ bool _iconsOutOfDate(String root) {
'android/app/src/main/res/mipmap-anydpi-v26/launcher_icon.xml',
),
);
if (!_anyNewerThan(inputs, output)) return false;
if (!output.existsSync()) return true;
return !_hashesMatch(root, 'icons', inputs, _readLock(root));
}
@@ -233,11 +252,28 @@ List<File> _l10nInputs(String root) {
return [l10nYml, ...arbs].where((f) => f.existsSync()).cast<File>().toList();
}
bool _l10nGeneratedFilesMissing(String root) {
final l10nDir = p.join(root, 'lib/l10n');
final mainOutput = File(p.join(l10nDir, 'app_localizations.dart'));
if (!mainOutput.existsSync()) return true;
final dir = Directory(l10nDir);
if (!dir.existsSync()) return true;
for (final file in dir.listSync().whereType<File>()) {
if (file.path.endsWith('.arb')) {
final base = p.basenameWithoutExtension(file.path);
final genFile = File(
p.join(l10nDir, '${base.replaceFirst("app_", "app_localizations_")}.dart'),
);
if (!genFile.existsSync()) return true;
}
}
return false;
}
bool _l10nOutOfDate(String root) {
final inputs = _l10nInputs(root);
final output = File(p.join(root, 'lib/l10n/app_localizations.dart'));
if (!_anyNewerThan(inputs, output)) return false;
return !_hashesMatch(root, 'l10n', inputs, _readLock(root));
if (_l10nGeneratedFilesMissing(root)) return true;
return !_hashesMatch(root, 'l10n', inputs, _readCache(root));
}
List<File> _isarInputs(String root) {
@@ -253,20 +289,6 @@ List<File> _isarInputs(String root) {
return list;
}
bool _isarOutOfDate(String root) {
final inputs = _isarInputs(root);
if (inputs.isEmpty) return false;
final modelsDir = p.join(root, 'lib/data/models');
for (final dartFile in inputs) {
final baseName = p.basenameWithoutExtension(dartFile.path);
final gFile = File(p.join(modelsDir, '$baseName.g.dart'));
if (_anyNewerThan([dartFile], gFile)) {
return !_hashesMatch(root, 'isar', inputs, _readLock(root));
}
}
return false;
}
bool _isarGeneratedFilesMissing(String root) {
final inputs = _isarInputs(root);
if (inputs.isEmpty) return false;
@@ -279,6 +301,13 @@ bool _isarGeneratedFilesMissing(String root) {
return false;
}
bool _isarOutOfDate(String root) {
final inputs = _isarInputs(root);
if (inputs.isEmpty) return false;
if (_isarGeneratedFilesMissing(root)) return true;
return !_hashesMatch(root, 'isar', inputs, _readCache(root));
}
List<File> _splashInputs(String root) {
final config = File(p.join(root, 'flutter_native_splash.yaml'));
final splashImage = File(p.join(root, 'assets/images/logos/splash.png'));
@@ -294,7 +323,11 @@ bool _splashOutOfDate(String root) {
final output = File(
p.join(root, 'android/app/src/main/res/drawable/launch_background.xml'),
);
if (!_anyNewerThan(inputs, output)) return false;
if (!output.existsSync()) return true;
final splash12 = File(
p.join(root, 'assets/images/logos/splash_android12.png'),
);
if (!splash12.existsSync()) return true;
return !_hashesMatch(root, 'splash', inputs, _readLock(root));
}

View File

@@ -6,6 +6,7 @@ import 'package:firka/app/app_state.dart';
import 'package:firka/app/initialization.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka/services/local_notification_service.dart';
import 'package:firka/services/notification_diff_service.dart';
import 'package:firka_common/data/database.dart';
@@ -312,6 +313,38 @@ void main() {
.where((n) => n.body.contains('Fizika') || n.body.contains('Newton'))
.toList();
expect(fizikaNotifs, isEmpty);
LocalNotificationService.postedNotifications.clear();
final alarmGradeUid = 'test-grade-alarm-${DateTime.now().millisecondsSinceEpoch}';
final alarmGradeTime = DateTime.now().toUtc().toIso8601String();
await _postItem(httpClient, '/admin/api/grades', {
'Uid': alarmGradeUid,
'RogzitesDatuma': alarmGradeTime,
'KeszitesDatuma': alarmGradeTime,
'Tantargy': {
'Uid': '14,TOR',
'Nev': 'Történelem',
'Kategoria': {'Uid': '1', 'Nev': 'Kötelező'},
'SortIndex': 14,
},
'Tema': 'Középkor',
'Tipus': {'Uid': '1', 'Nev': 'Szóbeli'},
'ErtekFajta': {'Uid': '1', 'Nev': 'Osztályzat'},
'ErtekeloTanarNeve': 'Hérodotosz',
'Jelleg': 'Ertekeles',
'SzamErtek': 5,
'SzovegesErtek': 'Jeles',
'SulySzazalekErteke': 100,
'OsztalyCsoport': {'Uid': '10,11.A'},
});
await alarmNotificationWakeupCallback();
final alarmNotif = LocalNotificationService.postedNotifications.firstWhere(
(n) => n.title.contains('jegy') && n.body.contains('Történelem'),
);
expect(alarmNotif.title, contains('jegy'));
expect(alarmNotif.body, contains('Történelem'));
});
});
});

View File

@@ -0,0 +1,102 @@
import 'dart:io';
import 'dart:ui';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka_common/data/database.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const alarmChannel = MethodChannel(
'dev.fluttercommunity.plus/android_alarm_manager',
JSONMethodCodec(),
);
late Directory tempDir;
late List<MethodCall> alarmCalls;
setUp(() async {
alarmCalls = [];
AlarmNotificationService.resetForTesting();
AlarmNotificationService.isAndroidOverride = true;
tempDir = Directory.systemTemp.createTempSync('alarm_test_');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(MethodCall methodCall) async => tempDir.path,
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
alarmChannel,
(MethodCall call) async {
alarmCalls.add(call);
return true;
},
);
AndroidAlarmManager.setTestOverrides(
getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
);
final isar = await initDB();
await isar.writeTxn(() async {
await isar.clear();
});
Settings = SettingsRepository(isar);
await Settings.loadAll();
});
tearDown(() async {
AlarmNotificationService.resetForTesting();
try {
tempDir.deleteSync(recursive: true);
} catch (_) {}
});
test('initialize invokes AlarmService.start', () async {
await AlarmNotificationService.initialize();
expect(AlarmNotificationService.isInitialized, isTrue);
expect(alarmCalls.any((call) => call.method == 'AlarmService.start'), isTrue);
});
test('schedule sets up hourly periodic alarm with sync ID 910001', () async {
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
await AlarmNotificationService.schedule();
final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
expect(periodicCalls, isNotEmpty);
final call = periodicCalls.last;
expect(call.arguments[0], 910001);
expect(call.arguments[3], isTrue); // wakeup
expect(call.arguments[5], const Duration(hours: 1).inMilliseconds);
expect(call.arguments[6], isTrue); // rescheduleOnReboot
});
test('schedule sets up two-hourly periodic alarm when configured', () async {
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
await AlarmNotificationService.schedule();
final periodicCalls = alarmCalls.where((call) => call.method == 'Alarm.periodic').toList();
expect(periodicCalls, isNotEmpty);
final call = periodicCalls.last;
expect(call.arguments[0], 910001);
expect(call.arguments[3], isTrue); // wakeup
expect(call.arguments[5], const Duration(hours: 2).inMilliseconds);
expect(call.arguments[6], isTrue); // rescheduleOnReboot
});
test('cancel invokes Alarm.cancel with sync ID 910001', () async {
await AlarmNotificationService.cancel();
final cancelCalls = alarmCalls.where((call) => call.method == 'Alarm.cancel').toList();
expect(cancelCalls, isNotEmpty);
expect(cancelCalls.last.arguments[0], 910001);
});
}

View File

@@ -0,0 +1,174 @@
import 'dart:io';
import 'dart:ui';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:firka/core/settings/settings_repository.dart';
import 'package:firka/core/settings/settings_schema.dart';
import 'package:firka/services/alarm_notification_service.dart';
import 'package:firka/services/notification_delivery_service.dart';
import 'package:firka_common/data/database.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const alarmChannel = MethodChannel(
'dev.fluttercommunity.plus/android_alarm_manager',
JSONMethodCodec(),
);
late Directory tempDir;
late List<MethodCall> alarmCalls;
setUp(() async {
alarmCalls = [];
NotificationDeliveryService.resetForTesting();
AlarmNotificationService.resetForTesting();
NotificationDeliveryService.isAndroidOverride = true;
AlarmNotificationService.isAndroidOverride = true;
tempDir = Directory.systemTemp.createTempSync('delivery_test_');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/path_provider'),
(MethodCall methodCall) async => tempDir.path,
);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
alarmChannel,
(MethodCall call) async {
alarmCalls.add(call);
return true;
},
);
AndroidAlarmManager.setTestOverrides(
getCallbackHandle: (_) => CallbackHandle.fromRawHandle(42),
);
final isar = await initDB();
await isar.writeTxn(() async {
await isar.clear();
});
Settings = SettingsRepository(isar);
await Settings.loadAll();
});
tearDown(() async {
NotificationDeliveryService.resetForTesting();
AlarmNotificationService.resetForTesting();
try {
tempDir.deleteSync(recursive: true);
} catch (_) {}
});
group('NotificationDeliveryService effective method resolution', () {
test('resolves explicit FCM setting', () async {
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
final effective = await NotificationDeliveryService.getEffectiveMethod();
expect(effective, NotificationDeliveryMethod.fcm);
});
test('resolves explicit Alarm setting', () async {
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
final effective = await NotificationDeliveryService.getEffectiveMethod();
expect(effective, NotificationDeliveryMethod.alarm);
});
test('auto resolves to FCM when GMS is available', () async {
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
NotificationDeliveryService.gmsAvailabilityOverride = true;
final effective = await NotificationDeliveryService.getEffectiveMethod();
expect(effective, NotificationDeliveryMethod.fcm);
});
test('auto resolves to Alarm when GMS is unavailable', () async {
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.auto);
NotificationDeliveryService.gmsAvailabilityOverride = false;
final effective = await NotificationDeliveryService.getEffectiveMethod();
expect(effective, NotificationDeliveryMethod.alarm);
});
});
group('NotificationDeliveryService backend coordination & settings effects', () {
test('syncDeliveryBackend cancels alarm when notifyAll is disabled', () async {
await Settings.notifyAll.set(false);
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
alarmCalls.clear();
await NotificationDeliveryService.syncDeliveryBackend();
final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
expect(cancelCalls, isNotEmpty);
expect(cancelCalls.last.arguments[0], 910001);
});
test('syncDeliveryBackend schedules alarm when method is alarm and notifyAll is true', () async {
await Settings.notifyAll.set(true);
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.hourly);
alarmCalls.clear();
await NotificationDeliveryService.syncDeliveryBackend();
final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
expect(periodicCalls, isNotEmpty);
expect(periodicCalls.last.arguments[0], 910001);
expect(periodicCalls.last.arguments[5], const Duration(hours: 1).inMilliseconds);
});
test('syncDeliveryBackend cancels alarm when switching from alarm to fcm', () async {
await Settings.notifyAll.set(true);
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
await NotificationDeliveryService.syncDeliveryBackend();
alarmCalls.clear();
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
await NotificationDeliveryService.syncDeliveryBackend();
final cancelCalls = alarmCalls.where((c) => c.method == 'Alarm.cancel').toList();
expect(cancelCalls, isNotEmpty);
expect(cancelCalls.last.arguments[0], 910001);
});
test('handleWakeupIntervalChange reschedules alarm with new duration', () async {
await Settings.notifyAll.set(true);
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
await Settings.notifyWakeupInterval.set(NotifyWakeupInterval.twoHourly);
alarmCalls.clear();
await NotificationDeliveryService.handleWakeupIntervalChange();
final periodicCalls = alarmCalls.where((c) => c.method == 'Alarm.periodic').toList();
expect(periodicCalls, isNotEmpty);
expect(periodicCalls.last.arguments[5], const Duration(hours: 2).inMilliseconds);
});
test('changing settings triggers registered settings effects', () async {
Settings.onChange(SettingsRegistry.notifyAll, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
});
Settings.onChange(SettingsRegistry.notificationDeliveryMethod, (_) async {
await NotificationDeliveryService.syncDeliveryBackend();
});
Settings.onChange(SettingsRegistry.notifyWakeupInterval, (_) async {
await NotificationDeliveryService.handleWakeupIntervalChange();
});
await Settings.notifyAll.set(true);
alarmCalls.clear();
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.alarm);
expect(alarmCalls.any((c) => c.method == 'Alarm.periodic'), isTrue);
alarmCalls.clear();
await Settings.notificationDeliveryMethod.set(NotificationDeliveryMethod.fcm);
expect(alarmCalls.any((c) => c.method == 'Alarm.cancel'), isTrue);
});
});
}