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( _mapCreateNewRecoveryKeyToState, transformer: sequential(), ); on( _mapRecoveryKeyStatusRefreshToState, 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 (state is RecoveryKeyCreating) { return; } if (event.recoveryKeyStatus == null) { emit(RecoveryKeyError()); return; } emit(RecoveryKeyLoaded(keyStatus: event.recoveryKeyStatus)); } Future _mapCreateNewRecoveryKeyToState( final CreateNewRecoveryKey event, final Emitter emit, ) async { emit(RecoveryKeyCreating()); final GenericResult response = await getIt().api.generateRecoveryToken( event.expirationDate, event.numberOfUses, ); if (response.success) { emit(RecoveryKeyCreating(recoveryKey: response.data)); } else { emit(RecoveryKeyCreating(error: 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(); } }