Files
pipelines/app/lib/features/notification_service/notification_service_controller.dart
T
alan 826e420423 Deliver server notifications from the Android app itself
A native foreground service keeps an authenticated websocket to the
connected server (handed over by the app on every connect), subscribes with
a replay cursor, shows each notification with kind-based channels and
grouping, opens pipelines:// links on tap, and clears taps, dismissals and
cross-device clears. It starts at boot and app launch, backs off and follows
network changes. Settings gains the delivery switch, status, notification
and battery-exemption actions, and the server's optional ntfy_enabled
toggle.
2026-11-01 02:21:22 +00:00

85 lines
2.2 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import 'notification_service_bridge.dart';
/// Settings' view of background delivery: the switch, the live status and the
/// battery exemption, all read from the native service (never guessed).
class NotificationServiceController extends ChangeNotifier {
NotificationServiceController(
this.bridge, {
this.requestNotificationPermission,
}) {
_changes = bridge.changes.listen(_apply);
}
final NotificationServiceBridge bridge;
/// Asks Android 13+ for POST_NOTIFICATIONS (the app's existing request).
final Future<void> Function()? requestNotificationPermission;
late final StreamSubscription<NotificationServiceStatus> _changes;
NotificationServiceStatus? _status;
bool _busy = false;
String _error = '';
bool _disposed = false;
NotificationServiceStatus? get status => _status;
bool get busy => _busy;
String get error => _error;
Future<void> load() => _run(bridge.status);
/// Re-reads after returning from a system screen (permission, battery).
Future<void> refresh() => load();
Future<void> setEnabled(bool enabled) => _run(() async {
if (enabled && _status?.notificationsAllowed == false) {
await requestNotificationPermission?.call();
}
return bridge.setEnabled(enabled);
});
Future<void> allowNotifications() => _run(() async {
await requestNotificationPermission?.call();
return bridge.status();
});
Future<void> allowBackgroundDelivery() => _run(() async {
await bridge.requestBatteryExemption();
return bridge.status();
});
Future<void> _run(Future<NotificationServiceStatus> Function() action) async {
if (_busy) return;
_busy = true;
_error = '';
_notify();
try {
_status = await action();
} catch (error) {
_error = 'Background delivery is unavailable: $error';
} finally {
_busy = false;
_notify();
}
}
void _apply(NotificationServiceStatus status) {
_status = status;
_notify();
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
unawaited(_changes.cancel());
super.dispose();
}
}