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 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 Function(Uri endpoint) _headersFor; StreamSubscription? _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 = { 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 _guard(Future call) async { try { await call; } catch (error) { debugPrint('Notification service: $error'); } } void dispose() { unawaited(_states?.cancel()); } }