Skip to content

Commit

Permalink
new: add more warp modes, handle both ipv4 and ipv6 in wireguard, add…
Browse files Browse the repository at this point in the history
… customizable size and more
  • Loading branch information
hiddify-com committed Jul 17, 2024
1 parent 9c424ea commit 1cab9ef
Show file tree
Hide file tree
Showing 8 changed files with 101 additions and 48 deletions.
2 changes: 2 additions & 0 deletions assets/translations/strings_en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,8 @@
"warpCleanIp": "Clean IP",
"warpPort": "Port",
"warpNoise": "Noise Count",
"warpNoiseSize": "Noise Size",
"warpNoiseMode": "Noise Mode",
"warpNoiseDelay": "Noise Delay"
}
}
2 changes: 1 addition & 1 deletion dependencies.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
core.version=1.6.3
core.version=1.7.0
16 changes: 16 additions & 0 deletions lib/features/config_option/data/config_option_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -271,13 +271,23 @@ abstract class ConfigOptions {
mapFrom: (value) => OptionalRange.parse(value, allowEmpty: true),
mapTo: const OptionalRangeJsonConverter().toJson,
);
static final warpNoiseMode = PreferencesNotifier.create<String, String>(
"warp-noise-mode",
"m6",
);

static final warpNoiseDelay = PreferencesNotifier.create<OptionalRange, String>(
"warp-noise-delay",
const OptionalRange(min: 10, max: 30),
mapFrom: (value) => OptionalRange.parse(value, allowEmpty: true),
mapTo: const OptionalRangeJsonConverter().toJson,
);
static final warpNoiseSize = PreferencesNotifier.create<OptionalRange, String>(
"warp-noise-size",
const OptionalRange(min: 10, max: 30),
mapFrom: (value) => OptionalRange.parse(value, allowEmpty: true),
mapTo: const OptionalRangeJsonConverter().toJson,
);

static final warpWireguardConfig = PreferencesNotifier.create<String, String>(
"warp-wireguard-config",
Expand Down Expand Up @@ -361,6 +371,8 @@ abstract class ConfigOptions {
"warp.clean-ip": warpCleanIp,
"warp.clean-port": warpPort,
"warp.noise": warpNoise,
"warp.noise-size": warpNoiseSize,
"warp.noise-mode": warpNoiseMode,
"warp.noise-delay": warpNoiseDelay,
"warp.wireguard-config": warpWireguardConfig,
"warp2.license-key": warp2LicenseKey,
Expand Down Expand Up @@ -461,6 +473,8 @@ abstract class ConfigOptions {
cleanIp: ref.watch(warpCleanIp),
cleanPort: ref.watch(warpPort),
noise: ref.watch(warpNoise),
noiseMode: ref.watch(warpNoiseMode),
noiseSize: ref.watch(warpNoiseSize),
noiseDelay: ref.watch(warpNoiseDelay),
),
warp2: SingboxWarpOption(
Expand All @@ -473,6 +487,8 @@ abstract class ConfigOptions {
cleanIp: ref.watch(warpCleanIp),
cleanPort: ref.watch(warpPort),
noise: ref.watch(warpNoise),
noiseMode: ref.watch(warpNoiseMode),
noiseSize: ref.watch(warpNoiseSize),
noiseDelay: ref.watch(warpNoiseDelay),
),
// geoipPath: ref.watch(geoAssetPathResolverProvider).relativePath(
Expand Down
15 changes: 15 additions & 0 deletions lib/features/config_option/overview/warp_options_widgets.dart
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,21 @@ class WarpOptionsTiles extends HookConsumerWidget {
presentValue: (value) => value.present(t),
formatInputValue: (value) => value.format(),
),
ValuePreferenceWidget(
value: ref.watch(ConfigOptions.warpNoiseMode),
preferences: ref.watch(ConfigOptions.warpNoiseMode.notifier),
enabled: canChangeOptions,
title: t.config.warpNoiseMode,
),
ValuePreferenceWidget(
value: ref.watch(ConfigOptions.warpNoiseSize),
preferences: ref.watch(ConfigOptions.warpNoiseSize.notifier),
enabled: canChangeOptions,
title: t.config.warpNoiseSize,
inputToValue: (input) => OptionalRange.tryParse(input, allowEmpty: true),
presentValue: (value) => value.present(t),
formatInputValue: (value) => value.format(),
),
ValuePreferenceWidget(
value: ref.watch(ConfigOptions.warpNoiseDelay),
preferences: ref.watch(ConfigOptions.warpNoiseDelay.notifier),
Expand Down
60 changes: 14 additions & 46 deletions lib/features/profile/data/profile_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,7 @@ abstract interface class ProfileRepository {
TaskEither<ProfileFailure, Unit> deleteById(String id);
}

class ProfileRepositoryImpl
with ExceptionHandler, InfraLogger
implements ProfileRepository {
class ProfileRepositoryImpl with ExceptionHandler, InfraLogger implements ProfileRepository {
ProfileRepositoryImpl({
required this.profileDataSource,
required this.profilePathResolver,
Expand Down Expand Up @@ -105,10 +103,7 @@ class ProfileRepositoryImpl

@override
Stream<Either<ProfileFailure, ProfileEntity?>> watchActiveProfile() {
return profileDataSource
.watchActiveProfile()
.map((event) => event?.toEntity())
.handleExceptions(
return profileDataSource.watchActiveProfile().map((event) => event?.toEntity()).handleExceptions(
(error, stackTrace) {
loggy.error("error watching active profile", error, stackTrace);
return ProfileUnexpectedFailure(error, stackTrace);
Expand All @@ -118,21 +113,15 @@ class ProfileRepositoryImpl

@override
Stream<Either<ProfileFailure, bool>> watchHasAnyProfile() {
return profileDataSource
.watchProfilesCount()
.map((event) => event != 0)
.handleExceptions(ProfileUnexpectedFailure.new);
return profileDataSource.watchProfilesCount().map((event) => event != 0).handleExceptions(ProfileUnexpectedFailure.new);
}

@override
Stream<Either<ProfileFailure, List<ProfileEntity>>> watchAll({
ProfilesSort sort = ProfilesSort.lastUpdate,
SortMode sortMode = SortMode.ascending,
}) {
return profileDataSource
.watchAll(sort: sort, sortMode: sortMode)
.map((event) => event.map((e) => e.toEntity()).toList())
.handleExceptions(ProfileUnexpectedFailure.new);
return profileDataSource.watchAll(sort: sort, sortMode: sortMode).map((event) => event.map((e) => e.toEntity()).toList()).handleExceptions(ProfileUnexpectedFailure.new);
}

@override
Expand All @@ -143,14 +132,10 @@ class ProfileRepositoryImpl
}) {
return exceptionHandler(
() async {
final existingProfile = await profileDataSource
.getByUrl(url)
.then((value) => value?.toEntity());
final existingProfile = await profileDataSource.getByUrl(url).then((value) => value?.toEntity());
if (existingProfile case RemoteProfileEntity()) {
loggy.info("profile with same url already exists, updating");
final baseProfile = markAsActive
? existingProfile.copyWith(active: true)
: existingProfile;
final baseProfile = markAsActive ? existingProfile.copyWith(active: true) : existingProfile;
return updateSubscription(
baseProfile,
cancelToken: cancelToken,
Expand All @@ -163,9 +148,7 @@ class ProfileRepositoryImpl
(profile) => TaskEither(
() async {
await profileDataSource.insert(
profile
.copyWith(id: profileId, active: markAsActive)
.toEntry(),
profile.copyWith(id: profileId, active: markAsActive).toEntry(),
);
return right(unit);
},
Expand All @@ -188,10 +171,7 @@ class ProfileRepositoryImpl
) {
return exceptionHandler(
() {
return singbox
.validateConfigByPath(path, tempPath, debug)
.mapLeft(ProfileFailure.invalidConfig)
.run();
return singbox.validateConfigByPath(path, tempPath, debug).mapLeft(ProfileFailure.invalidConfig).run();
},
ProfileUnexpectedFailure.new,
);
Expand Down Expand Up @@ -273,9 +253,7 @@ class ProfileRepositoryImpl
final configFile = profilePathResolver.file(id);
// TODO pass options
return await $(
singbox
.generateFullConfigByPath(configFile.path)
.mapLeft(ProfileFailure.unexpected),
singbox.generateFullConfigByPath(configFile.path).mapLeft(ProfileFailure.unexpected),
);
},
).handleExceptions(ProfileFailure.unexpected);
Expand All @@ -296,18 +274,15 @@ class ProfileRepositoryImpl
.flatMap(
(remoteProfile) => TaskEither(
() async {
final profilePatch = remoteProfile
.subInfoPatch()
.copyWith(lastUpdate: Value(DateTime.now()));
final profilePatch = remoteProfile.subInfoPatch().copyWith(lastUpdate: Value(DateTime.now()));

await profileDataSource.edit(
baseProfile.id,
patchBaseProfile
? profilePatch.copyWith(
name: Value(baseProfile.name),
url: Value(baseProfile.url),
updateInterval:
Value(baseProfile.options?.updateInterval),
updateInterval: Value(baseProfile.options?.updateInterval),
)
: profilePatch,
);
Expand Down Expand Up @@ -393,8 +368,7 @@ class ProfileRepositoryImpl
tempFile.path,
cancelToken: cancelToken,
);
final headers =
await _populateHeaders(response.headers.map, tempFile.path);
final headers = await _populateHeaders(response.headers.map, tempFile.path);
return await validateConfig(file.path, tempFile.path, false)
.andThen(
() => TaskEither(() async {
Expand Down Expand Up @@ -444,15 +418,9 @@ class ProfileRepositoryImpl
if (line.startsWith("#") || line.startsWith("//")) {
final index = line.indexOf(':');
if (index == -1) continue;
final key = line
.substring(0, index)
.replaceFirst(RegExp("^#|//"), "")
.trim()
.toLowerCase();
final key = line.substring(0, index).replaceFirst(RegExp("^#|//"), "").trim().toLowerCase();
final value = line.substring(index + 1).trim();
if (!headers.keys.contains(key) &&
_subInfoHeaders.contains(key) &&
value.isNotEmpty) {
if (!headers.keys.contains(key) && _subInfoHeaders.contains(key) && value.isNotEmpty) {
headers[key] = [value];
}
}
Expand Down
50 changes: 50 additions & 0 deletions lib/features/profile/notifier/profile_notifier.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fpdart/fpdart.dart';
import 'package:hiddify/core/haptic/haptic_service.dart';
import 'package:hiddify/core/localization/translations.dart';
import 'package:hiddify/core/model/failures.dart';
import 'package:hiddify/core/notification/in_app_notification_controller.dart';
import 'package:hiddify/core/preferences/general_preferences.dart';
import 'package:hiddify/core/preferences/preferences_provider.dart';
import 'package:hiddify/features/common/adaptive_root_scaffold.dart';
import 'package:hiddify/features/config_option/notifier/warp_option_notifier.dart';
import 'package:hiddify/features/config_option/overview/warp_options_widgets.dart';
import 'package:hiddify/features/connection/notifier/connection_notifier.dart';
import 'package:hiddify/features/profile/data/profile_data_providers.dart';
import 'package:hiddify/features/profile/data/profile_repository.dart';
Expand Down Expand Up @@ -53,6 +60,7 @@ class AddProfile extends _$AddProfile with AppLogger {
Future<void> add(String rawInput) async {
if (state.isLoading) return;
state = const AsyncLoading();
// await check4Warp(rawInput);
state = await AsyncValue.guard(
() async {
final activeProfile = await ref.read(activeProfileProvider.future);
Expand Down Expand Up @@ -100,6 +108,48 @@ class AddProfile extends _$AddProfile with AppLogger {
},
);
}

Future<void> check4Warp(String rawInput) async {
for (final line in rawInput.split("\n")) {
if (line.toLowerCase().startsWith("warp://")) {
final _prefs = ref.read(sharedPreferencesProvider).requireValue;
final _warp = ref.read(warpOptionNotifierProvider.notifier);

final consent = false && (_prefs.getBool(WarpOptionNotifier.warpConsentGiven) ?? false);

final t = ref.read(translationsProvider);
final notification = ref.read(inAppNotificationControllerProvider);

if (!consent) {
final agreed = await showDialog<bool>(
context: RootScaffold.stateKey.currentContext!,
builder: (context) => const WarpLicenseAgreementModal(),
);

if (agreed ?? false) {
await _prefs.setBool(WarpOptionNotifier.warpConsentGiven, true);
final toast = notification.showInfoToast(t.profile.add.addingWarpMsg, duration: const Duration(milliseconds: 100));
toast?.pause();
await _warp.generateWarpConfig();
toast?.start();
} else {
return;
}
}

final accountId = _prefs.getString("warp2-account-id");
final accessToken = _prefs.getString("warp2-access-token");
final hasWarp2Config = accountId != null && accessToken != null;

if (!hasWarp2Config || true) {
final toast = notification.showInfoToast(t.profile.add.addingWarpMsg, duration: const Duration(milliseconds: 100));
toast?.pause();
await _warp.generateWarp2Config();
toast?.start();
}
}
}
}
}

@riverpod
Expand Down
2 changes: 2 additions & 0 deletions lib/singbox/model/singbox_config_option.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ class SingboxWarpOption with _$SingboxWarpOption {
required String cleanIp,
required int cleanPort,
@OptionalRangeJsonConverter() required OptionalRange noise,
@OptionalRangeJsonConverter() required OptionalRange noiseSize,
@OptionalRangeJsonConverter() required OptionalRange noiseDelay,
@OptionalRangeJsonConverter() required String noiseMode,
}) = _SingboxWarpOption;

factory SingboxWarpOption.fromJson(Map<String, dynamic> json) => _$SingboxWarpOptionFromJson(json);
Expand Down
2 changes: 1 addition & 1 deletion libcore

0 comments on commit 1cab9ef

Please sign in to comment.