Files
pipelines/app/lib/features/attention/notify/notification_controller.dart
T

251 lines
9.4 KiB
Dart

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 per entry into its run's qualifying state,
/// 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
/// after *every* authoritative read and pushed frame call [publishTransitions]
/// with the attention controller's accumulated transitions, its current rows
/// (through [notificationQualifyingKeys]) and its dismissed set. Publishing the
/// frame that leaves a state is what forgets the old identity, so the next gate
/// or retry is a new announcement. The 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 transition instance announced this session for each identity: a new
/// instance means the run entered the state again.
final Map<String, AttentionTransition> _announced = {};
/// The queued ledger writes, so an older snapshot cannot land after a newer one.
Future<void> _writes = Future<void>.value();
/// 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;
/// A copy of the transition identities this client has already announced.
/// Returned unmodifiable, so a caller cannot mutate the ledger behind
/// [publishTransitions]' back.
Set<String> get notified => Set<String>.unmodifiable(_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<void> load() async {
NotificationLedger ledger;
try {
ledger = decodeNotificationLedger(await store.read());
} catch (_) {
ledger = const NotificationLedger();
}
if (_disposed) return;
_ledger = ledger;
_announced.clear();
_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<NotificationPermissionState> 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.
///
/// [qualifying] is [notificationQualifyingKeys] for the *same* snapshot as
/// [transitions]: a transition whose run has left the state is stale and
/// neither posts nor records anything, then every recorded identity outside
/// [qualifying] is forgotten so the next gate can notify. Only the latest
/// entry per run+kind in a backlog is announced.
///
/// A caller that misses the leaving frame still gets the new transition: the
/// detector creates one instance per genuine transition, so an identity
/// announced earlier this session with a different instance is a new
/// occurrence; the same instance, and an identity loaded from the store before
/// this session, stay silent.
///
/// The initial seed raises no transition. A transition the operator dismissed,
/// one already recorded and one past [maxNotificationsPerBatch] post nothing.
/// Returns how many notifications the platform accepted.
int publishTransitions(
Iterable<AttentionTransition> transitions, {
required Set<String> qualifying,
Set<String> dismissed = const {},
}) {
if (_disposed) return 0;
var posted = 0;
var changed = false;
// A backlog may hold several entries for one run+kind; only the latest one
// describes the state that is current, so a coalesced burst notifies once.
final latest = <String, AttentionTransition>{};
for (final transition in transitions) {
latest[notificationIdentity(transition)] = transition;
}
for (final transition in latest.values) {
if (posted >= maxNotificationsPerBatch) break;
final identity = notificationIdentity(transition);
// Older than the snapshot: the run already left this state.
if (!qualifying.contains(identity)) continue;
final announced = _announced[identity];
if (identical(announced, transition)) continue;
if (announced == null && _ledger.hasNotified(identity)) {
// Restored from the store before this session: adopt the instance so a
// republish is recognized, but do not announce it again.
_announced[identity] = transition;
continue;
}
// A new instance for an identity announced this session is a later entry.
if (!_ledger.hasNotified(identity)) {
_ledger = _ledger.recording(identity);
changed = true;
}
_announced[identity] = transition;
if (dismissed.contains(identity)) 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++;
}
}
final pruned = _ledger.pruning(qualifying);
if (!identical(pruned, _ledger)) {
_ledger = pruned;
changed = true;
}
if (changed) unawaited(_persist(_ledger));
return posted;
}
/// Writes the ledger without ever throwing into the caller's frame, one write
/// at a time so their order matches the calls.
Future<void> _persist(NotificationLedger ledger) {
final encoded = encodeNotificationLedger(ledger);
final write = _writes.then((_) async {
if (_disposed) return;
try {
await store.write(encoded);
} catch (_) {
// The in-memory ledger still applies for this session.
}
});
_writes = write;
return write;
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}