Files
pipelines/app/lib/features/notification_service/notification_service_handoff.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

75 lines
2.4 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../core/session/server_session.dart';
import '../../core/transport/pipelines_client.dart';
import 'notification_service_bridge.dart';
/// Shares the app's proven connection with the background service.
///
/// Whenever the shared client connects, the server it reached (its trusted
/// addresses and the web sign-in cookie the socket used) is handed to the
/// service, so the service authenticates exactly like the app. On creation it
/// starts the service if delivery is enabled and a server was handed over
/// before, which covers app launches after the service was stopped.
class NotificationServiceHandoff {
NotificationServiceHandoff({
required this.bridge,
required this.client,
required this.serverId,
@visibleForTesting Map<String, String> Function(Uri endpoint)? headersFor,
}) : _headersFor = headersFor ?? ServerSession.headersFor {
if (!bridge.supported) return;
unawaited(_guard(bridge.start()));
_states = client.states.listen(_onState);
if (client.state.kind == ConnectionKind.connected) _handOver();
}
final NotificationServiceBridge bridge;
final PipelinesClient client;
/// The logical server; falls back to the connected address when absent.
final String? serverId;
final Map<String, String> Function(Uri endpoint) _headersFor;
StreamSubscription<ConnectionState>? _states;
void _onState(ConnectionState state) {
if (state.kind == ConnectionKind.connected) _handOver();
}
void _handOver() {
final endpoint = client.endpoint;
if (endpoint == null) return;
final addresses = client.endpoints.isEmpty ? [endpoint] : client.endpoints;
// Connected address first: it is the one known to work right now.
final ordered = <String>{
endpoint.toString(),
for (final address in addresses) address.toString(),
}.toList();
final id = serverId;
unawaited(
_guard(
bridge.configure(
serverId: id == null || id.isEmpty ? ordered.first : id,
endpoints: ordered,
cookie: _headersFor(endpoint)['Cookie'] ?? '',
),
),
);
}
/// A missing or failing platform side must never break the app.
Future<void> _guard(Future<Object?> call) async {
try {
await call;
} catch (error) {
debugPrint('Notification service: $error');
}
}
void dispose() {
unawaited(_states?.cancel());
}
}