123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- import 'dart:io';
- import 'package:flutter/widgets.dart';
- import 'package:get/get.dart';
- import 'package:naiyouwl/app/bean/proxie.dart';
- import 'package:naiyouwl/app/common/LogHelper.dart';
- import 'package:naiyouwl/app/common/SharedPreferencesUtil.dart';
- import 'package:naiyouwl/app/controller/controllers.dart';
- import 'package:naiyouwl/app/data/model/NodeMode.dart';
- import 'package:naiyouwl/app/network/api_service.dart';
- import 'package:naiyouwl/app/network/dio_client.dart';
- import 'package:naiyouwl/app/utils/shell.dart';
- import 'package:naiyouwl/app/utils/system_proxy.dart';
- import 'package:naiyouwl/app/utils/utils.dart';
- import 'package:proxy_manager/proxy_manager.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:tray_manager/tray_manager.dart';
- import 'package:window_manager/window_manager.dart';
- import 'package:path/path.dart' as path;
- import '../const/const.dart';
- class GlobalController extends GetxController {
- final proxyManager = ProxyManager();
- bool systemProxy = false;
- late BuildContext context;
- final List<String> modes = ['rule', 'global'];
- final List<String> routeModes = ['sys', 'tun'];
- var msgStatus = "未连接".obs;
- var routeModesSelect = "sys".obs;
- var modesSelect = "rule".obs;
- var nodeModes = <NodeMode>[].obs;
- var isLoading = false.obs;
- var errorMsg = ''.obs;
- var statusCode = 0.obs;
- var selectMageNode = false.obs;
- var systemProxySwitchIng = false.obs;
- var tunProxySwitchIng = false.obs;
- bool allowStatusUpdate = false;
- final selectedNode = Rx<NodeMode?>(null);
- // 策略组
- var proxieGroups = <ProxieProxiesItem>[].obs;
- // 代理集
- var proxieProviders = <ProxieProviderItem>[].obs;
- // 代理
- var proxieProxies = <ProxieProxiesItem>[].obs;
- // 所有节点
- var allProxies = <String, ProxieProxiesItem>{}.obs;
- final List<String> groupInternalTypes = ['DIRECT', 'REJECT', 'GLOBAL'];
- final List<String> groupTypes = [
- ProxieProxieType.selector,
- ProxieProxieType.urltest,
- ProxieProxieType.fallback,
- ProxieProxieType.loadbalance,
- ];
- Future<void> init(BuildContext context) async {
- this.context = context;
- watchExit();
- // if(Platform.isWindows){
- // createConsole();
- // hideConsole();
- // }
- await SharedPreferencesUtil().delete("last_successful_url");
- // init plugins
- await controllers.tray.initTray();
- controllers.window.initWindow();
- //controllers.protocol.initProtocol();
- await controllers.config.portDetection();
- // init clash config
- // init config
- await controllers.config.initConfig();
- await controllers.service.initConfig();
- await controllers.service.isService();
- // init service
- // await controllers.service.startService();
- // if (controllers.service.serviceStatus.value != RunningState.running) return;
- //await controllers.service.serviceModeSwitch(true);
- // init clash core
- await controllers.service.initClashCoreConfig();
- if (controllers.service.coreStatus.value != RunningState.running) return;
- await controllers.core.updateVersion();
- //initRegularlyUpdate();
- }
- void updateMsg(String msg) {
- msgStatus.value = msg;
- }
- Future<void> updateMode(String route) async {
- if(allowStatusUpdate){
- return;
- }
- modesSelect.value = route;
- final coreStatus = controllers.service.coreStatus.value;
- if( coreStatus == RunningState.running){
- controllers.core.fetchConfigUpdate({'mode': modesSelect.value});
- }
- }
- Future<void> updateRoute(String route) async {
- if(allowStatusUpdate){
- return;
- }
- // if(route == "tun"){
- // final res = await showNormalDialog( context,content: '启用网卡模式需要管理员',title: '提示', cancelText: '取消', enterText: '确认安装');
- // if (res != true) return;
- // controllers.service.serviceModeSwitch(true);
- // }
- routeModesSelect.value = route;
- LogHelper().d("当前ROUTE模式${routeModesSelect.value}");
- }
- Future<void> fetchNodes() async {
- nodeModes.value = await ApiService().getNode("/api/client/v4/nodes?vless=1");
- //await makeProxy();
- // if(controllers.service.coreStatus.value == RunningState.stoped){
- // await controllers.service.reloadClashCore();
- // }
- // if (controllers.service.coreStatus.value != RunningState.running) return;
- // await controllers.core.updateVersion();
- // await updateDate();
- //
- }
- Future<void> updateNode() async {
- NodeMode? targetNode;
- if (selectedNode.value == null) {
- targetNode = await findNodeWithMinUsers(nodeModes);
- } else {
- targetNode = selectedNode.value;
- }
- if (targetNode != null){
- selectNode(targetNode);
- await swift(targetNode.name ?? "");
- }
- }
- Future<void> startSysMode() async {
- await makeProxy();
- //await updateDate();
- }
- Future<void> startTunMode() async {
- await makeProxy();
- }
- Future<void> swift(String name) async {
- try{
- var g = "proxy";
- if(modesSelect.value == "global")
- {
- g = "GLOBAL";
- }
- await controllers.core.fetchSetProxieGroup(g, name);
- await updateDate();
- final conn = await controllers.core.fetchConnection();
- for (final it in conn.connections) {
- if (it.chains.contains(name)) controllers.core.fetchCloseConnections(it.id);
- }
- }catch (e) {
- //LogHelper().d(e.toString());
- }
- }
- // Future<ProxieProxiesItem> findProxieByName(String name) async {
- // return proxieGroups.firstWhere((proxie) => proxie['name'] == name, orElse: () => null);
- // }
- Future<ProxieProxiesItem?> findProxieByName(String name) async {
- ProxieProxiesItem? result;
- try {
- result = proxieGroups.firstWhere((proxie) => proxie.all!.contains(name));
- } catch (e) {
- // 在这里可以处理异常,或者只是简单地返回 null
- return null;
- }
- return result;
- }
- Future<void> makeProxy() async {
- await controllers.config.makeClashConfig(nodeModes);
- // await controllers.service.reloadClashCore();
- }
- Future<NodeMode> findNodeWithMinUsers(List<NodeMode> nodes) async {
- return nodes
- .where((node) => node.countryCode == "hk")
- .reduce((a, b) => a.onlineUsers! < b.onlineUsers! ? a : b);
- }
- Future<SystemProxyConfig> getSysProxy() async{
- return await SystemProxy.instance.get();
- }
- Future<void> TunProxySwitch(bool open) async {
- tunProxySwitchIng.value = true;
- routeModesSelect.value = open ? "tun": "sys";
- LogHelper().d("TunProxySwitch ----- 当前ROUTE模式${routeModesSelect.value}");
- tunProxySwitchIng.value = false;
- }
- Future<void> systemProxySwitch(bool open) async {
- systemProxySwitchIng.value = true;
- //await SystemProxy.instance.set(open ? controllers.core.proxyConfig : SystemProxyConfig());
- //wait controllers.config.setSystemProxy(open);
- if(open)
- {
- await openProxy();
- } else {
- await closeProxy();
- }
- systemProxySwitchIng.value = false;
- }
- Future<dynamic> _updateProxie() async {
- final proxie = await controllers.core.fetchProxie();
- final global = proxie.proxies["GLOBAL"]!;
- proxieGroups.value = global.all!
- .where((it) => !groupInternalTypes.contains(it) && groupTypes.contains(proxie.proxies[it]!.type))
- .map((it) => proxie.proxies[it]!)
- .toList();
- proxieProxies.value = global.all!
- .where((it) => !groupInternalTypes.contains(it) && !groupTypes.contains(proxie.proxies[it]!.type))
- .map((it) => proxie.proxies[it]!)
- .toList();
- if (controllers.core.config.value.mode == 'global') proxieGroups.insert(0, global);
- }
- Future<dynamic> _updateProxieProvider() async {
- proxieProviders.value = (await controllers.core.fetchProxieProvider()).providers.values.where((it) => it.vehicleType != 'Compatible').toList();
- for (final it in proxieProviders) {
- it.proxies.sort((a, b) {
- if (a.delay == 0) return 1;
- if (b.delay == 0) return -1;
- return a.delay - b.delay;
- });
- }
- }
- Future<void> updateDate() async {
- //LogHelper().d('controller.proxie.updateDate()');
- try
- {
- await controllers.core.updateConfig();
- await _updateProxie();
- await _updateProxieProvider();
- allProxies.clear();
- for (final provide in proxieProviders) {
- for (final it in provide.proxies) {
- allProxies[it.name] = it;
- }
- }
- for (final it in proxieProxies) {
- allProxies[it.name] = it;
- //LogHelper().d('controller.proxieProxies');
- }
- for (final it in proxieGroups) {
- allProxies[it.name] = it;
- //LogHelper().d('controller.proxieGroups');
- }
- proxieGroups.refresh();
- proxieProxies.refresh();
- proxieProviders.refresh();
- allProxies.refresh();
- } catch (e){
- LogHelper().d("updateDate -- ${e.toString()}");
- }
- }
- Future<void> handleSetProxieGroup(ProxieProxiesItem proxie, String value) async {
- if (proxie.now == value) return;
- await controllers.core.fetchSetProxieGroup(proxie.name, value);
- await updateDate();
- if (controllers.config.config.value.breakConnections) {
- final conn = await controllers.core.fetchConnection();
- for (final it in conn.connections) {
- if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
- }
- }
- }
- Future<void> handleSetSelectProxieGroup(NodeMode proxie, String value) async {
- if (proxie.name == value) return;
- await controllers.core.fetchSetProxieGroup(proxie.name ?? "", value);
- await updateDate();
- final conn = await controllers.core.fetchConnection();
- for (final it in conn.connections) {
- if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
- }
- }
- void watchExit() {
- // watch process kill
- // ref https://github.com/dart-lang/sdk/issues/12170
- if (Platform.isMacOS) {
- // windows not support https://github.com/dart-lang/sdk/issues/28603
- // for macos 任务管理器退出进程
- ProcessSignal.sigterm.watch().listen((_) {
- stdout.writeln('exit: sigterm');
- handleExit();
- });
- }
- // for macos, windows ctrl+c
- ProcessSignal.sigint.watch().listen((_) {
- stdout.writeln('exit: sigint');
- handleExit();
- });
- }
- void selectNode(NodeMode node) {
- controllers.global.selectedNode.value = node;
- _storeSelectedNode(node);
- }
- Future<void> _storeSelectedNode(NodeMode node) async {
- final prefs = await SharedPreferences.getInstance();
- // 为简化起见,我们只存储node的ID,但您可以根据需要存储更多信息
- prefs.setInt('selectedNodeId', node.id ?? -1);
- await loadSelectedNode();
- }
- Future<void> loadSelectedNode() async {
- final prefs = await SharedPreferences.getInstance();
- final selectedNodeId = prefs.getInt('selectedNodeId');
- if (selectedNodeId != null) {
- //selectedIndex.value = nodeModes.indexWhere((item) => item.id == selectedNodeId);
- selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
- }
- }
- void initRegularlyUpdate() {
- Future.delayed(const Duration(minutes: 5)).then((_) async {
- for (final it in controllers.config.config.value.subs) {
- try {
- if (it.url == null || it.url!.isEmpty) continue;
- if (((DateTime.now().millisecondsSinceEpoch ~/ 1000) - (it.updateTime ?? 0)) < controllers.config.config.value.updateInterval) continue;
- final chenged = await controllers.config.updateSub(it);
- if (!chenged) continue;
- if (it.name != controllers.config.config.value.selected) continue;
- // restart clash core
- await controllers.service.reloadClashCore();
- await Future.delayed(const Duration(seconds: 20));
- } catch (_) {}
- }
- initRegularlyUpdate();
- });
- }
- /// 打开代理
- Future<void> openProxy() async {
- int? port = controllers.config.mixedPort.value;
- if (port == 0) {
- port = null;
- }
- int? socksPort = controllers.config.mixedPort.value;
- if (socksPort == 0) {
- socksPort = null;
- }
- int? mixedPort = controllers.config.mixedPort.value;
- if (mixedPort == 0) {
- mixedPort = null;
- }
- port = port ?? mixedPort ?? 0;
- if (port != 0) {
- await proxyManager.setAsSystemProxy(
- ProxyTypes.http,
- "127.0.0.1",
- port,
- );
- await proxyManager.setAsSystemProxy(
- ProxyTypes.https,
- "127.0.0.1",
- port,
- );
- systemProxy = true;
- }
- socksPort = socksPort ?? mixedPort ?? 0;
- if (socksPort != 0) {
- if (!Platform.isWindows) {
- await proxyManager.setAsSystemProxy(
- ProxyTypes.socks,
- "127.0.0.1",
- socksPort,
- );
- }
- systemProxy = true;
- }
- }
- /// 关闭代理
- Future<void> closeProxy() async {
- proxyManager.cleanSystemProxy();
- systemProxy = false;
- }
- Future<void> stopAllCore() async {
- await systemProxySwitch(false);
- await controllers.service.stopClashCore();
- if(!controllers.service.serviceMode.value){{
- await killProcess(path.basename(Files.assetsCCore.path));
- }}
- if(!controllers.service.serviceMode.value){
- await killProcess(path.basename(Files.assetsClashService.path));
- }
- }
- Future<void> handleExit() async {
- await stopAllCore();
- await trayManager.destroy();
- await windowManager.destroy();
- // exit(0);
- }
- void handleApiError(dynamic error) {
- if (error is AppException) {
- LogHelper().d('API error with status code: ${error.statusCode}');
- statusCode.value = error.statusCode ?? -1;
- errorMsg.value = error.toString();
- } else {
- LogHelper().d('Other error: $error');
- errorMsg.value = error.toString();
- }
- }
- @override
- void dispose() {
- controllers.tray.dispose();
- controllers.window.dispose();
- //controllers.protocol.dispose();
- super.dispose();
- }
- }
|