import 'dart:async'; import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:selfprivacy/config/get_it_config.dart'; import 'package:selfprivacy/logic/api_maps/generic_result.dart'; import 'package:selfprivacy/logic/models/json/recovery_token_status.dart'; part 'recovery_key_event.dart'; part 'recovery_key_state.dart'; class RecoveryKeyBloc extends Bloc { RecoveryKeyBloc() : super(RecoveryKeyInitial()) { on( _mapRecoveryKeyStatusChangedToState, transformer: sequential(), ); on( _mapRecoveryKeyStatusRefreshToState, transformer: droppable(), ); final apiConnectionRepository = getIt(); _apiDataSubscription = apiConnectionRepository.dataStream.listen( (final ApiData apiData) { add( RecoveryKeyStatusChanged(apiData.recoveryKeyStatus.data), ); }, ); } StreamSubscription? _apiDataSubscription; Future _mapRecoveryKeyStatusChangedToState( final RecoveryKeyStatusChanged event, final Emitter emit, ) async { if (event.recoveryKeyStatus == null) { emit(RecoveryKeyError()); return; } emit(RecoveryKeyLoaded(keyStatus: event.recoveryKeyStatus)); } Future generateRecoveryKey({ final DateTime? expirationDate, final int? numberOfUses, }) async { final GenericResult response = await getIt() .api .generateRecoveryToken(expirationDate, numberOfUses); if (response.success) { getIt().apiData.recoveryKeyStatus.invalidate(); unawaited(getIt().reload(null)); return response.data; } else { throw GenerationError(response.message ?? 'Unknown error'); } } Future _mapRecoveryKeyStatusRefreshToState( final RecoveryKeyEvent event, final Emitter emit, ) async { emit(RecoveryKeyRefreshing(keyStatus: state._status)); getIt().apiData.recoveryKeyStatus.invalidate(); await getIt().reload(null); } @override void onChange(final Change change) { super.onChange(change); } @override Future close() { _apiDataSubscription?.cancel(); return super.close(); } } class GenerationError extends Error { GenerationError(this.message); final String message; }