import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../application/clipboard_failures.dart'; import '../domain/chat_account_usage.dart'; import '../domain/chat_usage_warning.dart'; const chatQuotaMarksPreferenceKey = 'pipelines.chatQuotaMarks.v1'; /// The app session's quota warning state, shared by every open chat since a /// harness account's quota is account-wide: which windows the operator /// dismissed (and at which level and reset), and which levels were already /// announced with a SnackBar. Both are kept in shared preferences, so a reload /// neither brings a dismissed warning back nor repeats an announcement. class ChatUsageWarnings extends ChangeNotifier { ChatUsageWarnings({ this.preferences, bool Function(String message)? announce, this.clock = DateTime.now, }) : _announce = announce ?? showAppMessage; /// The instance chats use unless a test hands them their own. static final ChatUsageWarnings shared = ChatUsageWarnings( preferences: SharedPreferences.getInstance, ); /// Where the marks are kept across reloads; null keeps them in memory. final Future Function()? preferences; final bool Function(String message) _announce; /// The time stored marks are pruned against. final DateTime Function() clock; final Map _dismissed = {}; final Map _announced = {}; Future? _loaded; /// Dismissals by [chatQuotaKey]. Map get dismissed => Map.unmodifiable(_dismissed); /// Reads the stored marks once; marks recorded meanwhile win. Future load() => _loaded ??= _read(); Future _read() async { final preferences = this.preferences; if (preferences == null) return; final String? raw; try { raw = (await preferences()).getString(chatQuotaMarksPreferenceKey); } on Object catch (error) { // Without storage the marks still hold for this app session. debugPrint('Quota warnings: could not read preferences: $error'); return; } if (raw == null) return; try { final decoded = jsonDecode(raw); if (decoded is! Map) return; var changed = false; for (final (name, into) in [ ('dismissed', _dismissed), ('announced', _announced), ]) { final marks = decoded[name]; if (marks is! Map) continue; for (final MapEntry(:key, :value) in marks.entries) { if (value is! List || value.length != 2) continue; final [level, resetsAt] = value; if (level is! int || resetsAt is! int) continue; into.putIfAbsent('$key', () { changed = true; return ChatQuotaMark(level: level, resetsAt: resetsAt); }); } } if (changed) notifyListeners(); } on FormatException { // A corrupt entry is replaced by the next save. } } /// Announces each window of [usage] that reached a warning level not yet /// announced or dismissed since its last reset, once per app (and across /// reloads). Future report(ChatAccountUsage usage, {DateTime? now}) async { await load(); final crossed = chatQuotaNewlyCrossed( usage, now ?? clock(), _announced, _dismissed, ); if (crossed.isEmpty) return; for (final window in crossed) { _announced[chatQuotaKey(usage.harness, window)] = chatQuotaMarkOf(window); } _announce(chatQuotaAnnouncement(usage.harness, crossed)); await _save(); } /// Hides [warning] until one of its windows reaches the next level or /// resets. void dismiss(ChatUsageWarning warning) { for (final window in warning.windows) { _dismissed[chatQuotaKey(warning.harness, window)] = chatQuotaMarkOf( window, ); } notifyListeners(); unawaited(_save()); } Future _save() async { final preferences = this.preferences; if (preferences == null) return; final now = clock().millisecondsSinceEpoch; // A mark for a window that has reset since can never cover it again. Map> live(Map marks) => { for (final MapEntry(:key, :value) in marks.entries) if (value.resetsAt <= 0 || value.resetsAt > now) key: [value.level, value.resetsAt], }; final value = jsonEncode({ 'dismissed': live(_dismissed), 'announced': live(_announced), }); try { await (await preferences()).setString(chatQuotaMarksPreferenceKey, value); } on Object catch (error) { debugPrint('Quota warnings: could not save preferences: $error'); } } }