<commit_before>import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import '../../../../core/database/data/models/server_model.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/helpers/failure_mapper_helper.dart';
import '../../../image_url/domain/usecases/get_image_url.dart';
import '../../../logging/domain/usecases/logging.dart';
import '../../../settings/domain/usecases/settings.dart';
import '../../../settings/presentation/bloc/settings_bloc.dart';
import '../../domain/entities/activity.dart';
import '../../domain/usecases/get_activity.dart';

part 'activity_event.dart';
part 'activity_state.dart';

enum ActivityLoadingState {
  initial,
  inProgress,
  success,
  failure,
}

Map<String, Map<String, dynamic>> _activityMap = {};
SettingsBloc _settingsBlocCache;

class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
  final GetActivity getActivity;
  final GetImageUrl getImageUrl;
  final Settings settings;
  final Logging logging;

  Timer _timer;

  ActivityBloc({
    @required GetActivity activity,
    @required GetImageUrl imageUrl,
    @required this.settings,
    @required this.logging,
  })  : assert(activity != null),
        getActivity = activity,
        getImageUrl = imageUrl,
        super(ActivityInitial(
          activityMap: _activityMap,
        ));

  @override
  Stream<ActivityState> mapEventToState(
    ActivityEvent event,
  ) async* {
    final currentState = state;
    final serverList = await settings.getAllServers();

    if (currentState is ActivityLoaded) {
      _activityMap = currentState.activityMap;
    }

    // If configured server is not in _activityMap then add it
    for (ServerModel server in serverList) {
      if (!_activityMap.containsKey(server.tautulliId)) {
        _activityMap[server.tautulliId] = {
          'plex_name': server.plexName,
          'loadingState': ActivityLoadingState.initial,
          'activityList': <ActivityItem>[],
          'failure': null,
          'bandwidth': {
            'lan': 0,
            'wan': 0,
          }
        };
      }
    }

    // Remove servers from _activityMap that are no longer configured
    List toRemove = [];
    for (String tautulliId in _activityMap.keys) {
      int item =
          serverList.indexWhere((server) => server.tautulliId == tautulliId);
      if (item == -1) {
        toRemove.add(tautulliId);
      }
    }
    _activityMap.removeWhere((key, value) => toRemove.contains(key));

    if (event is ActivityLoadAndRefresh) {
      _settingsBlocCache = event.settingsBloc;

      if (serverList.length > 0) {
        // Do not refresh servers that are still in the process of loading
        serverList.removeWhere((server) =>
            _activityMap[server.tautulliId]['loadingState'] ==
            ActivityLoadingState.inProgress);

        for (String key in _activityMap.keys.toList()) {
          _activityMap[key]['loadingState'] = ActivityLoadingState.inProgress;
        }
        yield ActivityLoaded(
          activityMap: _activityMap,
          loadedAt: DateTime.now(),
        );
        _loadServer(
          serverList: serverList,
          activityMap: _activityMap,
          settingsBloc: _settingsBlocCache,
        );
      } else {
        yield ActivityLoadFailure(
          failure: MissingServerFailure(),
          message:
              FailureMapperHelper.mapFailureToMessage(MissingServerFailure()),
          suggestion: FailureMapperHelper.mapFailureToSuggestion(
              MissingServerFailure()),
        );
      }
    }
    if (event is ActivityLoadServer) {
      yield* event.failureOrActivity.fold(
        (failure) async* {
          logging.error(
            'Activity: Failed to load activity for ${event.plexName}. ${FailureMapperHelper.mapFailureToMessage(failure)}',
          );

          _activityMap[event.tautulliId] = {
            'plex_name': event.plexName,
            'loadingState': ActivityLoadingState.failure,
            'activityList': <ActivityItem>[],
            'failure': failure,
          };

          yield ActivityLoaded(
            activityMap: _activityMap,
            loadedAt: DateTime.now(),
          );
        },
        (list) async* {
          List<ActivityItem> updatedList = [];
          int lanBandwidth = 0;
          int wanBandwidth = 0;

          for (ActivityItem activityItem in list) {
            //* Fetch and assign image URLs
            String posterImg;
            int posterRatingKey;
            String posterFallback;

            // Assign values for poster URL
            switch (activityItem.mediaType) {
              case ('movie'):
                posterImg = activityItem.thumb;
                posterRatingKey = activityItem.ratingKey;
                if (activityItem.live == 0) {
                  posterFallback = 'poster';
                } else {
                  posterFallback = 'poster-live';
                }
                break;
              case ('episode'):
                posterImg = activityItem.grandparentThumb;<commit_msg>Pass default bandwidth map on failure.<commit_after>import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:dartz/dartz.dart';
import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

import '../../../../core/database/data/models/server_model.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/helpers/failure_mapper_helper.dart';
import '../../../image_url/domain/usecases/get_image_url.dart';
import '../../../logging/domain/usecases/logging.dart';
import '../../../settings/domain/usecases/settings.dart';
import '../../../settings/presentation/bloc/settings_bloc.dart';
import '../../domain/entities/activity.dart';
import '../../domain/usecases/get_activity.dart';

part 'activity_event.dart';
part 'activity_state.dart';

enum ActivityLoadingState {
  initial,
  inProgress,
  success,
  failure,
}

Map<String, Map<String, dynamic>> _activityMap = {};
SettingsBloc _settingsBlocCache;

class ActivityBloc extends Bloc<ActivityEvent, ActivityState> {
  final GetActivity getActivity;
  final GetImageUrl getImageUrl;
  final Settings settings;
  final Logging logging;

  Timer _timer;

  ActivityBloc({
    @required GetActivity activity,
    @required GetImageUrl imageUrl,
    @required this.settings,
    @required this.logging,
  })  : assert(activity != null),
        getActivity = activity,
        getImageUrl = imageUrl,
        super(ActivityInitial(
          activityMap: _activityMap,
        ));

  @override
  Stream<ActivityState> mapEventToState(
    ActivityEvent event,
  ) async* {
    final currentState = state;
    final serverList = await settings.getAllServers();

    if (currentState is ActivityLoaded) {
      _activityMap = currentState.activityMap;
    }

    // If configured server is not in _activityMap then add it
    for (ServerModel server in serverList) {
      if (!_activityMap.containsKey(server.tautulliId)) {
        _activityMap[server.tautulliId] = {
          'plex_name': server.plexName,
          'loadingState': ActivityLoadingState.initial,
          'activityList': <ActivityItem>[],
          'failure': null,
          'bandwidth': {
            'lan': 0,
            'wan': 0,
          }
        };
      }
    }

    // Remove servers from _activityMap that are no longer configured
    List toRemove = [];
    for (String tautulliId in _activityMap.keys) {
      int item =
          serverList.indexWhere((server) => server.tautulliId == tautulliId);
      if (item == -1) {
        toRemove.add(tautulliId);
      }
    }
    _activityMap.removeWhere((key, value) => toRemove.contains(key));

    if (event is ActivityLoadAndRefresh) {
      _settingsBlocCache = event.settingsBloc;

      if (serverList.length > 0) {
        // Do not refresh servers that are still in the process of loading
        serverList.removeWhere((server) =>
            _activityMap[server.tautulliId]['loadingState'] ==
            ActivityLoadingState.inProgress);

        for (String key in _activityMap.keys.toList()) {
          _activityMap[key]['loadingState'] = ActivityLoadingState.inProgress;
        }
        yield ActivityLoaded(
          activityMap: _activityMap,
          loadedAt: DateTime.now(),
        );
        _loadServer(
          serverList: serverList,
          activityMap: _activityMap,
          settingsBloc: _settingsBlocCache,
        );
      } else {
        yield ActivityLoadFailure(
          failure: MissingServerFailure(),
          message:
              FailureMapperHelper.mapFailureToMessage(MissingServerFailure()),
          suggestion: FailureMapperHelper.mapFailureToSuggestion(
              MissingServerFailure()),
        );
      }
    }
    if (event is ActivityLoadServer) {
      yield* event.failureOrActivity.fold(
        (failure) async* {
          logging.error(
            'Activity: Failed to load activity for ${event.plexName}. ${FailureMapperHelper.mapFailureToMessage(failure)}',
          );

          _activityMap[event.tautulliId] = {
            'plex_name': event.plexName,
            'loadingState': ActivityLoadingState.failure,
            'activityList': <ActivityItem>[],
            'failure': failure,
            'bandwidth': {
              'lan': 0,
              'wan': 0,
            }
          };

          yield ActivityLoaded(
            activityMap: _activityMap,
            loadedAt: DateTime.now(),
          );
        },
        (list) async* {
          List<ActivityItem> updatedList = [];
          int lanBandwidth = 0;
          int wanBandwidth = 0;

          for (ActivityItem activityItem in list) {
            //* Fetch and assign image URLs
            String posterImg;
            int posterRatingKey;
            String posterFallback;

            // Assign values for poster URL
            switch (activityItem.mediaType) {
              case ('movie'):
                posterImg = activityItem.thumb;
                posterRatingKey = activityItem.ratingKey;
                if (activityItem.live == 0) {
                  posterFallback = 'poster';
                } else {
                  posterFallback = 'poster-live';
                }
                break;
              case ('episode'):
                posterImg = activityItem.grandparentThumb;
{'fraction_non_alphanumeric': 0.11508315809596635, 'fraction_numerical': 0.0015293442936341044, 'mean_word_length': 2.2154271665642287, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2139913', 'n_tokens_mistral': 2889, 'n_tokens_neox': 2840, 'n_words': 607}