Add connection info footer

This commit is contained in:
problematicconsumer
2024-02-09 12:02:52 +03:30
parent 37dc33667e
commit 7394f7c4c3
23 changed files with 520 additions and 65 deletions

View File

@@ -0,0 +1,38 @@
import 'package:flutter/widgets.dart';
class AnimatedVisibility extends StatelessWidget {
const AnimatedVisibility({
super.key,
required this.visible,
this.axis = Axis.horizontal,
this.padding = EdgeInsets.zero,
required this.child,
});
final bool visible;
final Axis axis;
final EdgeInsets padding;
final Widget child;
@override
Widget build(BuildContext context) {
final replacement = axis == Axis.vertical
? const SizedBox(width: double.infinity)
: const SizedBox.shrink();
return AnimatedSwitcher(
duration: const Duration(milliseconds: 200),
transitionBuilder: (child, animation) => SizeTransition(
sizeFactor: animation,
child: FadeTransition(opacity: animation, child: child),
),
child: visible
? AnimatedPadding(
padding: padding,
duration: const Duration(milliseconds: 200),
child: child,
)
: replacement,
);
}
}

View File

@@ -0,0 +1,39 @@
import 'package:flutter/material.dart';
class Skeleton extends StatelessWidget {
const Skeleton({
this.width,
this.height,
this.widthFactor,
this.heightFactor,
this.shape = BoxShape.rectangle,
this.alignment = AlignmentDirectional.center,
});
final double? width;
final double? height;
final double? widthFactor;
final double? heightFactor;
final BoxShape shape;
final AlignmentGeometry alignment;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return FractionallySizedBox(
widthFactor: widthFactor,
heightFactor: heightFactor,
alignment: alignment,
child: Container(
width: width,
height: height,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
shape: shape,
color: theme.hintColor.withOpacity(.16),
),
),
);
}
}

View File

@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:hiddify/core/app_info/app_info_provider.dart';
@@ -9,6 +11,7 @@ import 'package:hiddify/features/home/widget/connection_button.dart';
import 'package:hiddify/features/home/widget/empty_profiles_home_body.dart';
import 'package:hiddify/features/profile/notifier/active_profile_notifier.dart';
import 'package:hiddify/features/profile/widget/profile_tile.dart';
import 'package:hiddify/features/proxy/active/active_proxy_footer.dart';
import 'package:hiddify/utils/utils.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sliver_tools/sliver_tools.dart';
@@ -53,16 +56,14 @@ class HomePage extends HookConsumerWidget {
AsyncData(value: final profile?) => MultiSliver(
children: [
ProfileTile(profile: profile, isMain: true),
const SliverFillRemaining(
SliverFillRemaining(
hasScrollBody: false,
child: Padding(
padding: EdgeInsets.only(
left: 8,
right: 8,
top: 8,
bottom: 86,
),
child: ConnectionButton(),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Expanded(child: ConnectionButton()),
if (Platform.isAndroid) const ActiveProxyFooter(),
],
),
),
],

View File

@@ -0,0 +1,149 @@
import 'package:circle_flags/circle_flags.dart';
import 'package:dartx/dartx.dart';
import 'package:fluentui_system_icons/fluentui_system_icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:gap/gap.dart';
import 'package:hiddify/core/localization/translations.dart';
import 'package:hiddify/core/widget/animated_visibility.dart';
import 'package:hiddify/core/widget/skeleton_widget.dart';
import 'package:hiddify/features/proxy/active/active_proxy_notifier.dart';
import 'package:hiddify/features/stats/notifier/stats_notifier.dart';
import 'package:hiddify/utils/utils.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class ActiveProxyFooter extends HookConsumerWidget {
const ActiveProxyFooter({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final t = ref.watch(translationsProvider);
final asyncState = ref.watch(activeProxyNotifierProvider);
final stats = ref.watch(statsNotifierProvider).value;
return AnimatedVisibility(
axis: Axis.vertical,
visible: asyncState is AsyncData,
child: switch (asyncState) {
AsyncData(value: final info) => Padding(
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_InfoProp(
icon: FluentIcons.arrow_routing_24_regular,
text: info.proxy.selectedName.isNotNullOrBlank
? info.proxy.selectedName!
: info.proxy.name,
),
const Gap(8),
switch (info.ipInfo) {
AsyncData(value: final ip?) => _InfoProp.flag(
countryCode: ip.countryCode,
text: ip.ip,
),
AsyncError() => _InfoProp(
icon: FluentIcons.error_circle_20_regular,
text: t.general.unknown,
),
_ => _InfoProp.loading(
icon: FluentIcons.question_circle_24_regular,
),
},
],
),
),
Directionality(
textDirection: TextDirection.values[
(Directionality.of(context).index + 1) %
TextDirection.values.length],
child: Flexible(
child: Column(
children: [
_InfoProp(
icon: FluentIcons
.arrow_bidirectional_up_down_24_regular,
text: (stats?.downlinkTotal ?? 0).size(),
),
const Gap(8),
_InfoProp(
icon: FluentIcons.arrow_download_24_regular,
text: (stats?.downlink ?? 0).speed(),
),
],
),
),
),
],
),
),
_ => const SizedBox(),
},
);
}
}
class _InfoProp extends StatelessWidget {
_InfoProp({
required IconData icon,
required String text,
}) : icon = Icon(icon),
child = Text(
text,
overflow: TextOverflow.ellipsis,
),
isLoading = false;
_InfoProp.flag({
required String countryCode,
required String text,
}) : icon = Container(
width: 24,
height: 24,
padding: const EdgeInsets.all(2),
child: CircleFlag(countryCode),
),
child = Text(
text,
overflow: TextOverflow.ellipsis,
),
isLoading = false;
_InfoProp.loading({
required IconData icon,
}) : icon = Icon(icon),
child = const SizedBox(),
isLoading = true;
final Widget icon;
final Widget child;
final bool isLoading;
@override
Widget build(BuildContext context) {
return Row(
children: [
icon,
const Gap(8),
if (isLoading)
Flexible(
child: const Skeleton(height: 16, widthFactor: 1)
.animate(
onPlay: (controller) => controller.loop(),
)
.shimmer(
duration: 1000.ms,
angle: 45,
color: Theme.of(context).colorScheme.secondary,
),
)
else
Flexible(child: child),
],
);
}
}

View File

@@ -0,0 +1,75 @@
import 'package:dio/dio.dart';
import 'package:hiddify/features/connection/notifier/connection_notifier.dart';
import 'package:hiddify/features/proxy/data/proxy_data_providers.dart';
import 'package:hiddify/features/proxy/model/ip_info_entity.dart';
import 'package:hiddify/features/proxy/model/proxy_entity.dart';
import 'package:hiddify/features/proxy/model/proxy_failure.dart';
import 'package:hiddify/utils/riverpod_utils.dart';
import 'package:hiddify/utils/utils.dart';
import 'package:loggy/loggy.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'active_proxy_notifier.g.dart';
typedef ActiveProxyInfo = ({
ProxyItemEntity proxy,
AsyncValue<IpInfo?> ipInfo,
});
@riverpod
Stream<ProxyItemEntity?> activeProxyGroup(ActiveProxyGroupRef ref) async* {
final serviceRunning = await ref.watch(serviceRunningProvider.future);
if (!serviceRunning) {
throw const ServiceNotRunning();
}
yield* ref
.watch(proxyRepositoryProvider)
.watchActiveProxies()
.map((event) => event.getOrElse((l) => throw l))
.map((event) => event.firstOrNull?.items.firstOrNull);
}
@riverpod
Future<IpInfo?> proxyIpInfo(ProxyIpInfoRef ref) async {
final serviceRunning = await ref.watch(serviceRunningProvider.future);
if (!serviceRunning) {
return null;
}
final cancelToken = CancelToken();
ref.onDispose(() {
Loggy("ProxyIpInfo").debug("canceling");
cancelToken.cancel();
});
return ref
.watch(proxyRepositoryProvider)
.getCurrentIpInfo(cancelToken)
.getOrElse(
(err) {
Loggy("ProxyIpInfo").error("error getting proxy ip info", err);
throw err;
},
).run();
}
@riverpod
class ActiveProxyNotifier extends _$ActiveProxyNotifier with AppLogger {
@override
AsyncValue<ActiveProxyInfo> build() {
ref.disposeDelay(const Duration(seconds: 20));
final ipInfo = ref.watch(proxyIpInfoProvider);
final activeProxies = ref.watch(activeProxyGroupProvider);
return switch (activeProxies) {
AsyncData(value: final activeGroup?) =>
AsyncData((proxy: activeGroup, ipInfo: ipInfo)),
AsyncError(:final error, :final stackTrace) =>
AsyncError(error, stackTrace),
_ => const AsyncLoading(),
};
}
Future<void> refreshIpInfo() async {
if (state case AsyncData(:final value) when !value.ipInfo.isLoading) {
ref.invalidate(proxyIpInfoProvider);
}
}
}

View File

@@ -1,3 +1,4 @@
import 'package:dio/dio.dart';
import 'package:fpdart/fpdart.dart';
import 'package:hiddify/core/http_client/dio_http_client.dart';
import 'package:hiddify/core/utils/exception_handler.dart';
@@ -9,7 +10,8 @@ import 'package:hiddify/utils/custom_loggers.dart';
abstract interface class ProxyRepository {
Stream<Either<ProxyFailure, List<ProxyGroupEntity>>> watchProxies();
TaskEither<ProxyFailure, IpInfo> getCurrentIpInfo();
Stream<Either<ProxyFailure, List<ProxyGroupEntity>>> watchActiveProxies();
TaskEither<ProxyFailure, IpInfo> getCurrentIpInfo(CancelToken cancelToken);
TaskEither<ProxyFailure, Unit> selectProxy(
String groupTag,
String outboundTag,
@@ -31,7 +33,6 @@ class ProxyRepositoryImpl
@override
Stream<Either<ProxyFailure, List<ProxyGroupEntity>>> watchProxies() {
return singbox.watchOutbounds().map((event) {
print("outbounds: $event");
final groupWithSelected = {
for (final group in event) group.tag: group.selected,
};
@@ -63,6 +64,39 @@ class ProxyRepositoryImpl
);
}
@override
Stream<Either<ProxyFailure, List<ProxyGroupEntity>>> watchActiveProxies() {
return singbox.watchActiveOutbounds().map((event) {
final groupWithSelected = {
for (final group in event) group.tag: group.selected,
};
return event
.map(
(e) => ProxyGroupEntity(
tag: e.tag,
type: e.type,
selected: e.selected,
items: e.items
.map(
(e) => ProxyItemEntity(
tag: e.tag,
type: e.type,
urlTestDelay: e.urlTestDelay,
selectedTag: groupWithSelected[e.tag],
),
)
.toList(),
),
)
.toList();
}).handleExceptions(
(error, stackTrace) {
loggy.error("error watching active proxies", error, stackTrace);
return ProxyUnexpectedFailure(error, stackTrace);
},
);
}
@override
TaskEither<ProxyFailure, Unit> selectProxy(
String groupTag,
@@ -92,13 +126,16 @@ class ProxyRepositoryImpl
};
@override
TaskEither<ProxyFailure, IpInfo> getCurrentIpInfo() {
TaskEither<ProxyFailure, IpInfo> getCurrentIpInfo(CancelToken cancelToken) {
return TaskEither.tryCatch(
() async {
for (final source in _ipInfoSources.entries) {
try {
loggy.debug("getting current ip info using [${source.key}]");
final response = await client.get<Map<String, dynamic>>(source.key);
final response = await client.get<Map<String, dynamic>>(
source.key,
cancelToken: cancelToken,
);
if (response.statusCode == 200 && response.data != null) {
return source.value(response.data!);
}

View File

@@ -2,6 +2,7 @@ import 'package:hiddify/features/connection/notifier/connection_notifier.dart';
import 'package:hiddify/features/stats/data/stats_data_providers.dart';
import 'package:hiddify/features/stats/model/stats_entity.dart';
import 'package:hiddify/utils/custom_loggers.dart';
import 'package:hiddify/utils/riverpod_utils.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'stats_notifier.g.dart';
@@ -10,6 +11,7 @@ part 'stats_notifier.g.dart';
class StatsNotifier extends _$StatsNotifier with AppLogger {
@override
Stream<StatsEntity> build() async* {
ref.disposeDelay(const Duration(seconds: 10));
final serviceRunning = await ref.watch(serviceRunningProvider.future);
if (serviceRunning) {
yield* ref

View File

@@ -318,6 +318,12 @@ class FFISingboxService with InfraLogger implements SingboxService {
return _outboundsStream = outboundsStream;
}
@override
Stream<List<SingboxOutboundGroup>> watchActiveOutbounds() {
// TODO: implement watchActiveOutbounds
throw UnimplementedError();
}
@override
TaskEither<String, Unit> selectOutbound(String groupTag, String outboundTag) {
return TaskEither(

View File

@@ -182,6 +182,23 @@ class PlatformSingboxService with InfraLogger implements SingboxService {
);
}
@override
Stream<List<SingboxOutboundGroup>> watchActiveOutbounds() {
const channel = EventChannel("com.hiddify.app/active-groups");
loggy.debug("watching active outbounds");
return channel.receiveBroadcastStream().map(
(event) {
if (event case String _) {
return (jsonDecode(event) as List).map((e) {
return SingboxOutboundGroup.fromJson(e as Map<String, dynamic>);
}).toList();
}
loggy.error("[active group client] unexpected type, msg: $event");
throw "invalid type";
},
);
}
@override
Stream<SingboxStatus> watchStatus() => _status;

View File

@@ -56,6 +56,8 @@ abstract interface class SingboxService {
Stream<List<SingboxOutboundGroup>> watchOutbounds();
Stream<List<SingboxOutboundGroup>> watchActiveOutbounds();
TaskEither<String, Unit> selectOutbound(String groupTag, String outboundTag);
TaskEither<String, Unit> urlTest(String groupTag);