import 'dart:async'; import 'package:flutter/foundation.dart'; import '../domain/attention_transitions.dart'; import 'notification_bridge.dart'; import 'notification_ledger.dart'; import 'notification_models.dart'; import 'notification_store.dart'; /// The live notification capability behind the `Needs you` surface. /// /// It never invents a permission: [permission] is the platform's own answer, /// read from the [NotificationBridge], and `granted` is only ever reported when /// the platform said so. Nothing asks for permission on its own — /// [requestPermission] is the one explicit call — and a denied answer is never /// re-asked. /// /// Only live attention transitions raise a notification: the caller publishes /// the transitions the attention model raised (never the initial seed), and one /// identity is posted at most once, including across a reconnect, because the /// ledger records the identity before the platform is asked to show it. A /// dismissed identity is recorded but never shown. /// /// The manager wires it: set [onOpenRun] to open a run, call [load] once, and /// call [publishTransitions] with the attention controller's transitions. That /// call is idempotent, so passing the whole accumulated list is safe. class NotificationController extends ChangeNotifier { NotificationController({required this.store, NotificationBridge? bridge}) : bridge = bridge ?? createNotificationBridge(); /// The most notifications one publish posts, so a burst cannot flood the tray. static const maxNotificationsPerBatch = 5; final NotificationStore store; final NotificationBridge bridge; /// The tap seam: the manager sets this to open a run. Nothing here navigates. void Function(int runId)? onOpenRun; NotificationLedger _ledger = const NotificationLedger(); NotificationPermissionState _permission = NotificationPermissionState.unsupported; bool _loaded = false; bool _disposed = false; int _posted = 0; /// The platform's own permission state for this page. NotificationPermissionState get permission => _permission; /// True once the persisted ledger and the platform facts have been read. bool get loaded => _loaded; /// Whether the operator has ever been asked for permission. bool get asked => _ledger.asked; /// The transition identities this client has already recorded. Set get notified => _ledger.notified; /// True only when the platform itself reported `granted`. bool get canNotify => _permission == NotificationPermissionState.granted; /// How many notifications this session has actually posted. int get postedCount => _posted; /// Reads the persisted ledger and the platform's real permission facts once. Future load() async { NotificationLedger ledger; try { ledger = decodeNotificationLedger(await store.read()); } catch (_) { ledger = const NotificationLedger(); } if (_disposed) return; _ledger = ledger; _permission = notificationStateOf(bridge.environment()); _loaded = true; notifyListeners(); } /// Re-reads the platform's facts without asking anything, for example after /// the browser's site settings changed and the page regained focus. void refreshPermission() { if (_disposed) return; final next = notificationStateOf(bridge.environment()); if (next == _permission) return; _permission = next; notifyListeners(); } /// The one explicit request, only ever called from an operator gesture. /// /// A supported, secure page that has not decided is asked, and every other /// state answers with the platform's own word instead of prompting again. The /// request is issued before any await, so it stays inside the gesture that /// triggered it. Future requestPermission() async { if (_disposed) return _permission; final environment = bridge.environment(); _permission = notificationStateOf(environment); if (_permission != NotificationPermissionState.notRequested) { notifyListeners(); return _permission; } // The operator was asked, whatever the answer; persisted without awaiting so // the platform request stays in this gesture's frame. _ledger = _ledger.withAsked(true); unawaited(_persist(_ledger)); notifyListeners(); String answer; try { answer = await bridge.requestPermission(); } catch (_) { answer = ''; } if (_disposed) return _permission; final word = answer.trim().toLowerCase(); _permission = notificationStateOf( NotificationEnvironment( supported: environment.supported, secureContext: environment.secureContext, permission: word == 'granted' || word == 'denied' ? word : environment.permission, ), ); notifyListeners(); return _permission; } /// Posts one notification per live transition, in order. /// /// The initial seed raises no transition, so it never reaches here. A /// transition the operator dismissed, one the ledger already recorded and one /// past [maxNotificationsPerBatch] post nothing; every identity examined is /// recorded first, so a later publish cannot repeat it. Returns how many /// notifications the platform accepted. int publishTransitions( Iterable transitions, { Set dismissed = const {}, }) { if (_disposed) return 0; var posted = 0; var recorded = false; for (final transition in transitions) { if (posted >= maxNotificationsPerBatch) break; final identity = notificationIdentity(transition); if (_ledger.hasNotified(identity)) continue; _ledger = _ledger.recording(identity); recorded = true; if (dismissed.contains(transition.key)) continue; if (!canNotify) continue; final open = onOpenRun; final message = NotificationMessage( runId: transition.runId, title: notificationAlertTitle(transition.kind), body: notificationAlertBody(transition.entry), tag: identity, ); var shown = false; try { shown = bridge.show( message, onTap: open == null ? null : () => open(transition.runId), ); } catch (_) { shown = false; } if (shown) { posted++; _posted++; } } if (recorded) unawaited(_persist(_ledger)); return posted; } /// Writes the ledger without ever throwing into the caller's frame. Future _persist(NotificationLedger ledger) async { if (_disposed) return; try { await store.write(encodeNotificationLedger(ledger)); } catch (_) { // The in-memory ledger still applies for this session. } } @override void dispose() { _disposed = true; super.dispose(); } }