Files
umbrix/lib/features/profiles/notifier/profiles_notifier.dart

82 lines
2.4 KiB
Dart
Raw Normal View History

2023-07-06 17:18:41 +03:30
import 'dart:async';
2023-07-24 19:45:58 +03:30
import 'package:fpdart/fpdart.dart';
2023-07-06 17:18:41 +03:30
import 'package:hiddify/data/data_providers.dart';
2023-07-26 16:42:31 +03:30
import 'package:hiddify/domain/enums.dart';
2023-07-06 17:18:41 +03:30
import 'package:hiddify/domain/profiles/profiles.dart';
2023-07-26 14:17:11 +03:30
import 'package:hiddify/features/common/active_profile/active_profile_notifier.dart';
2023-07-06 17:18:41 +03:30
import 'package:hiddify/utils/utils.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'profiles_notifier.g.dart';
2023-07-26 16:42:31 +03:30
@riverpod
class ProfilesSortNotifier extends _$ProfilesSortNotifier with AppLogger {
@override
({ProfilesSort by, SortMode mode}) build() {
return (by: ProfilesSort.lastUpdate, mode: SortMode.descending);
}
void changeSort(ProfilesSort sortBy) =>
state = (by: sortBy, mode: state.mode);
void toggleMode() => state = (
by: state.by,
mode: state.mode == SortMode.ascending
? SortMode.descending
: SortMode.ascending
);
}
2023-07-06 17:18:41 +03:30
@riverpod
class ProfilesNotifier extends _$ProfilesNotifier with AppLogger {
@override
Stream<List<Profile>> build() {
2023-07-26 16:42:31 +03:30
final sort = ref.watch(profilesSortNotifierProvider);
2023-07-06 17:18:41 +03:30
return _profilesRepo
2023-07-26 16:42:31 +03:30
.watchAll(sort: sort.by, mode: sort.mode)
2023-07-06 17:18:41 +03:30
.map((event) => event.getOrElse((l) => throw l));
}
ProfilesRepository get _profilesRepo => ref.read(profilesRepositoryProvider);
Future<void> selectActiveProfile(String id) async {
loggy.debug('changing active profile to: [$id]');
await _profilesRepo.setAsActive(id).mapLeft((f) {
loggy.warning('failed to set [$id] as active profile, $f');
throw f;
}).run();
}
2023-07-26 14:17:11 +03:30
Future<Unit> addProfile(String url) async {
final activeProfile = await ref.read(activeProfileProvider.future);
loggy.debug("adding profile, url: [$url]");
return ref
.read(profilesRepositoryProvider)
.addByUrl(url, markAsActive: activeProfile == null)
.getOrElse((l) {
loggy.warning("failed to add profile: $l");
throw l;
}).run();
}
2023-07-24 19:45:58 +03:30
Future<Unit?> updateProfile(Profile profile) async {
loggy.debug("updating profile");
return ref
.read(profilesRepositoryProvider)
.update(profile)
.getOrElse((l) => throw l)
.run();
}
2023-07-06 17:18:41 +03:30
Future<void> deleteProfile(Profile profile) async {
loggy.debug('deleting profile: ${profile.name}');
await _profilesRepo.delete(profile.id).mapLeft(
(f) {
loggy.warning('failed to delete profile, $f');
throw f;
},
).run();
}
}