Files
umbrix/lib/features/config_option/notifier/warp_option_notifier.dart

71 lines
2.3 KiB
Dart
Raw Normal View History

2024-02-18 12:35:11 +03:30
import 'package:freezed_annotation/freezed_annotation.dart';
2024-02-03 12:36:27 +03:30
import 'package:hiddify/core/preferences/preferences_provider.dart';
2024-02-18 12:35:11 +03:30
import 'package:hiddify/features/config_option/data/config_option_data_providers.dart';
import 'package:hiddify/features/config_option/model/config_option_failure.dart';
import 'package:hiddify/utils/utils.dart';
2024-02-03 12:36:27 +03:30
import 'package:riverpod_annotation/riverpod_annotation.dart';
2024-02-18 12:35:11 +03:30
import 'package:shared_preferences/shared_preferences.dart';
2024-02-03 12:36:27 +03:30
2024-02-18 12:35:11 +03:30
part 'warp_option_notifier.freezed.dart';
2024-02-03 12:36:27 +03:30
part 'warp_option_notifier.g.dart';
@Riverpod(keepAlive: true)
2024-02-18 12:35:11 +03:30
class WarpOptionNotifier extends _$WarpOptionNotifier with AppLogger {
2024-02-03 12:36:27 +03:30
@override
2024-02-18 12:35:11 +03:30
WarpOptions build() {
final consent = _prefs.getBool(warpConsentGiven) ?? false;
bool hasWarpConfig = false;
try {
final accountId = _prefs.getString("warp-account-id");
final accessToken = _prefs.getString("warp-access-token");
hasWarpConfig = accountId != null && accessToken != null;
} catch (e) {
loggy.warning(e);
}
return WarpOptions(
consentGiven: consent,
configGeneration: hasWarpConfig
2024-02-20 22:16:47 +03:30
? const AsyncValue.data("")
2024-02-18 12:35:11 +03:30
: AsyncError(const MissingWarpConfigFailure(), StackTrace.current),
);
2024-02-03 12:36:27 +03:30
}
2024-02-18 12:35:11 +03:30
SharedPreferences get _prefs =>
ref.read(sharedPreferencesProvider).requireValue;
2024-02-03 12:36:27 +03:30
Future<void> agree() async {
await ref
.read(sharedPreferencesProvider)
.requireValue
.setBool(warpConsentGiven, true);
2024-02-18 12:35:11 +03:30
state = state.copyWith(consentGiven: true);
await generateWarpConfig();
}
Future<void> generateWarpConfig() async {
if (state.configGeneration.isLoading) return;
state = state.copyWith(configGeneration: const AsyncLoading());
final result = await AsyncValue.guard(
() async => await ref
.read(configOptionRepositoryProvider)
.generateWarpConfig()
.getOrElse((l) {
loggy.warning("error generating warp config: $l", l);
throw l;
}).run(),
);
state = state.copyWith(configGeneration: result);
2024-02-03 12:36:27 +03:30
}
static const warpConsentGiven = "warp_consent_given";
}
2024-02-18 12:35:11 +03:30
@freezed
class WarpOptions with _$WarpOptions {
const factory WarpOptions({
required bool consentGiven,
2024-02-20 22:16:47 +03:30
required AsyncValue<String> configGeneration,
2024-02-18 12:35:11 +03:30
}) = _WarpOptions;
}