relatica/lib/riverpod_controllers/background_updater_services...

68 wiersze
1.9 KiB
Dart
Czysty Zwykły widok Historia

import 'dart:async';
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../globals.dart';
import '../models/auth/profile.dart';
import '../services/auth_service.dart';
import 'connection_manager_services.dart';
import 'persistent_info_services.dart';
import 'settings_services.dart';
part 'background_updater_services.g.dart';
const _connectionsRefreshInterval = Duration(hours: 12);
const _timerRefresh = Duration(minutes: 1);
final _logger = Logger('BackgroundUpdatersProvider');
// TODO should this stop and be deleted if a profile is switched?
// TODO Confirm this is being bootstrapped correctly and running consistently
@riverpod
class BackgroundUpdaters extends _$BackgroundUpdaters {
bool _executingUpdate = false;
@override
Timer build(Profile profile) {
_logger.info('Building BackgroundUpdater for $profile');
ref.onDispose(() => state.cancel());
return Timer.periodic(_timerRefresh, (_) async {
await executeUpdatesForProfile();
});
}
Future<void> executeUpdatesForProfile() async {
if (_executingUpdate) {
return;
}
final lowBandwidthMode = ref.watch(lowBandwidthModeSettingProvider);
if (lowBandwidthMode) {
return;
}
if (getIt<AccountsService>().currentProfile != profile) {
return;
}
final dt =
DateTime.now().difference(ref.watch(persistentInfoProvider(profile)));
_logger.finer('Time since last update for ${profile.id}: $dt');
if (dt >= _connectionsRefreshInterval) {
if (_executingUpdate) {
return;
}
_executingUpdate = true;
try {
await ref
.read(allContactsUpdaterProvider(profile).notifier)
.updateAllContacts(true);
} catch (e) {
_logger.severe('Exception thrwn while executing update: $e');
}
_executingUpdate = false;
}
}
}