import 'dart:async'; import 'dart:developer'; import 'dart:io'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter_app_badge/flutter_app_badge.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../api/marianumcloud/talk/share_files_to_chat.dart'; import '../background/widget_background_task.dart'; import '../notification/notification_service.dart'; import '../push/chat_thread_store.dart'; import '../push/nid_store.dart'; import '../push/push_keypair.dart'; import '../push/push_tap_router.dart'; import '../routing/app_routes.dart'; import '../share_intent/share_intent_listener.dart'; import '../utils/app_paths.dart'; import '../utils/downloads/download_manager.dart'; import '../utils/file_clipboard.dart'; import '../widget_data/widget_sync.dart'; /// Removes what an account leaves on the device outside its own storage (see /// `AccountStorage` for that). Every step is isolated: one failing step used /// to skip all later ones and leave the previous account's data behind. abstract final class SessionWipe { static Future? _running; /// Completes once a running wipe finished. A login awaits it, otherwise the /// wipe could clear what the next account just stored (widget job, caches). static Future get done => _running ?? Future.value(); /// State that must be gone before the next frame (a login screen or another /// account can be reached right away): pending navigation and in-memory /// singletons. static void clearImmediate() { _step('share intents', ShareIntentListener.instance.clearAll); _step('share folder cache', resetTalkShareFolderCache); _step('pending navigation', () { AppRoutes.pendingChatToken.value = null; PushTapRouter.pendingTarget.value = null; }); _step('file clipboard', FileClipboard.instance.clear); _step('downloads', DownloadManager.instance.clearAll); } /// Runs whenever the active account stops being active (sign-out or /// switch). The tray and its bookkeeping belong to that account — a tap or /// inline reply there would otherwise act as the next one. A new keypair /// and FCM token make pushes still addressed to the previous registration /// undecryptable and undeliverable (an offline sign-out or switch could not /// unregister it). static Future accountLeft() async { await _stepAsync('download files', () async { final dir = Directory('${(await getTemporaryDirectory()).path}/downloads'); if (dir.existsSync()) await dir.delete(recursive: true); }); await _stepAsync( 'notification tray', NotificationService().flutterLocalNotificationsPlugin.cancelAll, ); await _stepAsync('app badge', () => FlutterAppBadge.count(0)); await _stepAsync('push nid store', NidStore().clear); await _stepAsync('push thread store', ChatThreadStore().clearAll); await _stepAsync('push keypair', const PushKeypair().clear); // Bounded: the next account waits for this, also without a network. await _stepAsync( 'fcm token', () => FirebaseMessaging.instance.deleteToken().timeout( const Duration(seconds: 5), ), ); } /// Wipes what outlives accounts, once the last one signed out. static Future deviceLeft() { final wipe = _deviceLeft(); _running = wipe; return wipe.whenComplete(() { if (identical(_running, wipe)) _running = null; }); } static Future _deviceLeft() async { // SettingsCubit is deliberately left alone: its selector wraps // MaterialApp, and emitting a fresh state here tore down the freshly // mounted Login tree (blank screen until the next interaction). await _stepAsync('shared preferences', () async { await (await SharedPreferences.getInstance()).clear(); }); await _stepAsync('chat background', () async { final image = File(AppPaths.chatBackgroundImage); if (image.existsSync()) await image.delete(); }); // Stop the periodic widget refresh job so the background isolate doesn't // wake up every 30 minutes only to write `loggedIn=false`. Re-registers // on the next successful login. await _stepAsync('widget task', WidgetBackgroundTask.cancelAll); await _stepAsync('widget data', WidgetSync.clear); await _stepAsync('widget update', WidgetSync.triggerUpdate); } static void _step(String name, void Function() step) { try { step(); } catch (e, s) { log('Session wipe step "$name" failed: $e', stackTrace: s); } } static Future _stepAsync( String name, Future Function() step, ) async { try { await step(); } catch (e, s) { log('Session wipe step "$name" failed: $e', stackTrace: s); } } }