GlobalController.dart 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import 'dart:io';
  2. import 'package:flutter/widgets.dart';
  3. import 'package:get/get.dart';
  4. import 'package:naiyouwl/app/bean/proxie.dart';
  5. import 'package:naiyouwl/app/common/LogHelper.dart';
  6. import 'package:naiyouwl/app/common/SharedPreferencesUtil.dart';
  7. import 'package:naiyouwl/app/controller/controllers.dart';
  8. import 'package:naiyouwl/app/data/model/NodeMode.dart';
  9. import 'package:naiyouwl/app/network/api_service.dart';
  10. import 'package:naiyouwl/app/network/dio_client.dart';
  11. import 'package:naiyouwl/app/utils/shell.dart';
  12. import 'package:naiyouwl/app/utils/system_proxy.dart';
  13. import 'package:naiyouwl/app/utils/utils.dart';
  14. import 'package:proxy_manager/proxy_manager.dart';
  15. import 'package:shared_preferences/shared_preferences.dart';
  16. import 'package:tray_manager/tray_manager.dart';
  17. import 'package:window_manager/window_manager.dart';
  18. import 'package:path/path.dart' as path;
  19. import 'package:wl_base_help/wl_base_help.dart';
  20. import '../const/const.dart';
  21. class GlobalController extends GetxController {
  22. final proxyManager = ProxyManager();
  23. bool systemProxy = false;
  24. late BuildContext context;
  25. final List<String> modes = ['rule', 'global'];
  26. final List<String> routeModes = ['sys', 'tun'];
  27. var msgStatus = "未连接".obs;
  28. var routeModesSelect = "sys".obs;
  29. var modesSelect = "rule".obs;
  30. var nodeModes = <NodeMode>[].obs;
  31. var isLoading = false.obs;
  32. var errorMsg = ''.obs;
  33. var statusCode = 0.obs;
  34. var selectMageNode = false.obs;
  35. var systemProxySwitchIng = false.obs;
  36. var tunProxySwitchIng = false.obs;
  37. bool allowStatusUpdate = false;
  38. final _wlBaseHelpPlugin = WlBaseHelp();
  39. final selectedNode = Rx<NodeMode?>(null);
  40. // 策略组
  41. var proxieGroups = <ProxieProxiesItem>[].obs;
  42. // 代理集
  43. var proxieProviders = <ProxieProviderItem>[].obs;
  44. // 代理
  45. var proxieProxies = <ProxieProxiesItem>[].obs;
  46. // 所有节点
  47. var allProxies = <String, ProxieProxiesItem>{}.obs;
  48. final List<String> groupInternalTypes = ['DIRECT', 'REJECT', 'GLOBAL'];
  49. final List<String> groupTypes = [
  50. ProxieProxieType.selector,
  51. ProxieProxieType.urltest,
  52. ProxieProxieType.fallback,
  53. ProxieProxieType.loadbalance,
  54. ];
  55. Future<void> init(BuildContext context) async {
  56. this.context = context;
  57. watchExit();
  58. // if(Platform.isWindows){
  59. // createConsole();
  60. // hideConsole();
  61. // }
  62. await SharedPreferencesUtil().delete("last_successful_url");
  63. // init plugins
  64. await controllers.tray.initTray();
  65. controllers.window.initWindow();
  66. //controllers.protocol.initProtocol();
  67. await controllers.config.portDetection();
  68. // init clash config
  69. // init config
  70. await controllers.config.initConfig();
  71. await controllers.service.initConfig();
  72. await controllers.service.isService();
  73. // init service
  74. // await controllers.service.startService();
  75. // if (controllers.service.serviceStatus.value != RunningState.running) return;
  76. //await controllers.service.serviceModeSwitch(true);
  77. // init clash core
  78. await controllers.service.initClashCoreConfig();
  79. if (controllers.service.coreStatus.value != RunningState.running) return;
  80. await controllers.core.updateVersion();
  81. //initRegularlyUpdate();
  82. }
  83. void updateMsg(String msg) {
  84. msgStatus.value = msg;
  85. }
  86. Future<void> updateMode(String route) async {
  87. if(allowStatusUpdate){
  88. return;
  89. }
  90. modesSelect.value = route;
  91. final coreStatus = controllers.service.coreStatus.value;
  92. if( coreStatus == RunningState.running){
  93. controllers.core.fetchConfigUpdate({'mode': modesSelect.value});
  94. }
  95. }
  96. Future<void> updateRoute(String route) async {
  97. if(allowStatusUpdate){
  98. return;
  99. }
  100. // if(route == "tun"){
  101. // final res = await showNormalDialog( context,content: '启用网卡模式需要管理员',title: '提示', cancelText: '取消', enterText: '确认安装');
  102. // if (res != true) return;
  103. // controllers.service.serviceModeSwitch(true);
  104. // }
  105. routeModesSelect.value = route;
  106. LogHelper().d("当前ROUTE模式${routeModesSelect.value}");
  107. }
  108. Future<void> fetchNodes() async {
  109. nodeModes.value = await ApiService().getNode("/api/client/v4/nodes?vless=1");
  110. //await makeProxy();
  111. // if(controllers.service.coreStatus.value == RunningState.stoped){
  112. // await controllers.service.reloadClashCore();
  113. // }
  114. // if (controllers.service.coreStatus.value != RunningState.running) return;
  115. // await controllers.core.updateVersion();
  116. // await updateDate();
  117. //
  118. }
  119. Future<void> updateNode() async {
  120. NodeMode? targetNode;
  121. if (selectedNode.value == null) {
  122. targetNode = await findNodeWithMinUsers(nodeModes);
  123. } else {
  124. targetNode = selectedNode.value;
  125. }
  126. if (targetNode != null){
  127. selectNode(targetNode);
  128. await swift(targetNode.name ?? "");
  129. }
  130. }
  131. Future<void> showConsole() async {
  132. await _wlBaseHelpPlugin.showConsole();
  133. }
  134. Future<void> hideConsole() async {
  135. await _wlBaseHelpPlugin.hideConsole();
  136. }
  137. Future<void> startSysMode() async {
  138. await makeProxy();
  139. //await updateDate();
  140. }
  141. Future<void> startTunMode() async {
  142. await makeProxy();
  143. }
  144. Future<void> swift(String name) async {
  145. try{
  146. var g = "proxy";
  147. if(modesSelect.value == "global")
  148. {
  149. g = "GLOBAL";
  150. }
  151. await controllers.core.fetchSetProxieGroup(g, name);
  152. await updateDate();
  153. final conn = await controllers.core.fetchConnection();
  154. for (final it in conn.connections) {
  155. if (it.chains.contains(name)) controllers.core.fetchCloseConnections(it.id);
  156. }
  157. }catch (e) {
  158. //LogHelper().d(e.toString());
  159. }
  160. }
  161. // Future<ProxieProxiesItem> findProxieByName(String name) async {
  162. // return proxieGroups.firstWhere((proxie) => proxie['name'] == name, orElse: () => null);
  163. // }
  164. Future<ProxieProxiesItem?> findProxieByName(String name) async {
  165. ProxieProxiesItem? result;
  166. try {
  167. result = proxieGroups.firstWhere((proxie) => proxie.all!.contains(name));
  168. } catch (e) {
  169. // 在这里可以处理异常,或者只是简单地返回 null
  170. return null;
  171. }
  172. return result;
  173. }
  174. Future<void> makeProxy() async {
  175. await controllers.config.makeClashConfig(nodeModes);
  176. // await controllers.service.reloadClashCore();
  177. }
  178. Future<NodeMode> findNodeWithMinUsers(List<NodeMode> nodes) async {
  179. return nodes
  180. .where((node) => node.countryCode == "hk")
  181. .reduce((a, b) => a.onlineUsers! < b.onlineUsers! ? a : b);
  182. }
  183. Future<SystemProxyConfig> getSysProxy() async{
  184. return await SystemProxy.instance.get();
  185. }
  186. Future<void> TunProxySwitch(bool open) async {
  187. tunProxySwitchIng.value = true;
  188. routeModesSelect.value = open ? "tun": "sys";
  189. LogHelper().d("TunProxySwitch ----- 当前ROUTE模式${routeModesSelect.value}");
  190. tunProxySwitchIng.value = false;
  191. }
  192. Future<void> systemProxySwitch(bool open) async {
  193. systemProxySwitchIng.value = true;
  194. //await SystemProxy.instance.set(open ? controllers.core.proxyConfig : SystemProxyConfig());
  195. await controllers.config.setSystemProxy(open);
  196. if(open)
  197. {
  198. await openProxy();
  199. } else {
  200. await closeProxy();
  201. }
  202. systemProxySwitchIng.value = false;
  203. }
  204. Future<dynamic> _updateProxie() async {
  205. final proxie = await controllers.core.fetchProxie();
  206. final global = proxie.proxies["GLOBAL"]!;
  207. proxieGroups.value = global.all!
  208. .where((it) => !groupInternalTypes.contains(it) && groupTypes.contains(proxie.proxies[it]!.type))
  209. .map((it) => proxie.proxies[it]!)
  210. .toList();
  211. proxieProxies.value = global.all!
  212. .where((it) => !groupInternalTypes.contains(it) && !groupTypes.contains(proxie.proxies[it]!.type))
  213. .map((it) => proxie.proxies[it]!)
  214. .toList();
  215. if (controllers.core.config.value.mode == 'global') proxieGroups.insert(0, global);
  216. }
  217. Future<dynamic> _updateProxieProvider() async {
  218. proxieProviders.value = (await controllers.core.fetchProxieProvider()).providers.values.where((it) => it.vehicleType != 'Compatible').toList();
  219. for (final it in proxieProviders) {
  220. it.proxies.sort((a, b) {
  221. if (a.delay == 0) return 1;
  222. if (b.delay == 0) return -1;
  223. return a.delay - b.delay;
  224. });
  225. }
  226. }
  227. Future<void> updateDate() async {
  228. //LogHelper().d('controller.proxie.updateDate()');
  229. try
  230. {
  231. await controllers.core.updateConfig();
  232. await _updateProxie();
  233. await _updateProxieProvider();
  234. allProxies.clear();
  235. for (final provide in proxieProviders) {
  236. for (final it in provide.proxies) {
  237. allProxies[it.name] = it;
  238. }
  239. }
  240. for (final it in proxieProxies) {
  241. allProxies[it.name] = it;
  242. //LogHelper().d('controller.proxieProxies');
  243. }
  244. for (final it in proxieGroups) {
  245. allProxies[it.name] = it;
  246. //LogHelper().d('controller.proxieGroups');
  247. }
  248. proxieGroups.refresh();
  249. proxieProxies.refresh();
  250. proxieProviders.refresh();
  251. allProxies.refresh();
  252. } catch (e){
  253. LogHelper().d("updateDate -- ${e.toString()}");
  254. }
  255. }
  256. Future<void> handleSetProxieGroup(ProxieProxiesItem proxie, String value) async {
  257. if (proxie.now == value) return;
  258. await controllers.core.fetchSetProxieGroup(proxie.name, value);
  259. await updateDate();
  260. if (controllers.config.config.value.breakConnections) {
  261. final conn = await controllers.core.fetchConnection();
  262. for (final it in conn.connections) {
  263. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  264. }
  265. }
  266. }
  267. Future<void> handleSetSelectProxieGroup(NodeMode proxie, String value) async {
  268. if (proxie.name == value) return;
  269. await controllers.core.fetchSetProxieGroup(proxie.name ?? "", value);
  270. await updateDate();
  271. final conn = await controllers.core.fetchConnection();
  272. for (final it in conn.connections) {
  273. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  274. }
  275. }
  276. void watchExit() {
  277. // watch process kill
  278. // ref https://github.com/dart-lang/sdk/issues/12170
  279. if (Platform.isMacOS) {
  280. // windows not support https://github.com/dart-lang/sdk/issues/28603
  281. // for macos 任务管理器退出进程
  282. ProcessSignal.sigterm.watch().listen((_) {
  283. stdout.writeln('exit: sigterm');
  284. handleExit();
  285. });
  286. }
  287. // for macos, windows ctrl+c
  288. ProcessSignal.sigint.watch().listen((_) {
  289. stdout.writeln('exit: sigint');
  290. handleExit();
  291. });
  292. }
  293. void selectNode(NodeMode node) {
  294. controllers.global.selectedNode.value = node;
  295. _storeSelectedNode(node);
  296. }
  297. Future<void> _storeSelectedNode(NodeMode node) async {
  298. final prefs = await SharedPreferences.getInstance();
  299. // 为简化起见,我们只存储node的ID,但您可以根据需要存储更多信息
  300. prefs.setInt('selectedNodeId', node.id ?? -1);
  301. await loadSelectedNode();
  302. }
  303. Future<void> loadSelectedNode() async {
  304. final prefs = await SharedPreferences.getInstance();
  305. final selectedNodeId = prefs.getInt('selectedNodeId');
  306. if (selectedNodeId != null) {
  307. //selectedIndex.value = nodeModes.indexWhere((item) => item.id == selectedNodeId);
  308. selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
  309. }
  310. }
  311. void initRegularlyUpdate() {
  312. Future.delayed(const Duration(minutes: 5)).then((_) async {
  313. for (final it in controllers.config.config.value.subs) {
  314. try {
  315. if (it.url == null || it.url!.isEmpty) continue;
  316. if (((DateTime.now().millisecondsSinceEpoch ~/ 1000) - (it.updateTime ?? 0)) < controllers.config.config.value.updateInterval) continue;
  317. final chenged = await controllers.config.updateSub(it);
  318. if (!chenged) continue;
  319. if (it.name != controllers.config.config.value.selected) continue;
  320. // restart clash core
  321. await controllers.service.reloadClashCore();
  322. await Future.delayed(const Duration(seconds: 20));
  323. } catch (_) {}
  324. }
  325. initRegularlyUpdate();
  326. });
  327. }
  328. /// 打开代理
  329. Future<void> openProxy() async {
  330. int? port = controllers.config.mixedPort.value;
  331. if (port == 0) {
  332. port = null;
  333. }
  334. int? socksPort = controllers.config.mixedPort.value;
  335. if (socksPort == 0) {
  336. socksPort = null;
  337. }
  338. int? mixedPort = controllers.config.mixedPort.value;
  339. if (mixedPort == 0) {
  340. mixedPort = null;
  341. }
  342. port = port ?? mixedPort ?? 0;
  343. if (port != 0) {
  344. if(Platform.isWindows){
  345. String loa = '127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*';
  346. int? exitCode;
  347. // Process sysproxy = await Process.start(Files.assetsSysProxyWin.path,,mode: ProcessStartMode.inheritStdio);
  348. // sysproxy.exitCode.then((code) => exitCode = code);
  349. try {
  350. var result = await Process.run(
  351. Files.assetsSysProxyWin.path,
  352. ['global','127.0.0.1:$port',loa],
  353. runInShell: true,
  354. );
  355. LogHelper().d(result.stderr);
  356. LogHelper().d(result.stdout);
  357. } on ProcessException catch (e) {
  358. //.e('Failed to start $coreName: ${e.message}');
  359. throw Exception('Failed to start sysproxy: ${e.message}');
  360. }
  361. } else {
  362. await proxyManager.setAsSystemProxy(
  363. ProxyTypes.http,
  364. "127.0.0.1",
  365. port,
  366. );
  367. await proxyManager.setAsSystemProxy(
  368. ProxyTypes.https,
  369. "127.0.0.1",
  370. port,
  371. );
  372. systemProxy = true;
  373. }
  374. }
  375. //
  376. // port = port ?? mixedPort ?? 0;
  377. // if (port != 0) {
  378. // }
  379. socksPort = socksPort ?? mixedPort ?? 0;
  380. if (socksPort != 0) {
  381. if (!Platform.isWindows) {
  382. await proxyManager.setAsSystemProxy(
  383. ProxyTypes.socks,
  384. "127.0.0.1",
  385. socksPort,
  386. );
  387. }
  388. systemProxy = true;
  389. }
  390. }
  391. /// 关闭代理
  392. Future<void> closeProxy() async {
  393. //
  394. if (Platform.isWindows) {
  395. try {
  396. var result = await Process.run(
  397. Files.assetsSysProxyWin.path,
  398. ['set','1','','',''],
  399. runInShell: true,
  400. );
  401. LogHelper().d(result.stderr);
  402. LogHelper().d(result.stdout);
  403. } on ProcessException catch (e) {
  404. //.e('Failed to start $coreName: ${e.message}');
  405. throw Exception('Failed to start sysproxy: ${e.message}');
  406. }
  407. }
  408. proxyManager.cleanSystemProxy();
  409. systemProxy = false;
  410. }
  411. Future<void> stopAllCore() async {
  412. await systemProxySwitch(false);
  413. await controllers.service.stopClashCore();
  414. if(!controllers.service.serviceMode.value){{
  415. await killProcess(path.basename(Files.assetsCCore.path));
  416. }}
  417. if(!controllers.service.serviceMode.value){
  418. await killProcess(path.basename(Files.assetsClashService.path));
  419. }
  420. }
  421. Future<void> handleExit() async {
  422. await stopAllCore();
  423. await trayManager.destroy();
  424. await windowManager.destroy();
  425. // exit(0);
  426. }
  427. void handleApiError(dynamic error) {
  428. if (error is AppException) {
  429. LogHelper().d('API error with status code: ${error.statusCode}');
  430. statusCode.value = error.statusCode ?? -1;
  431. errorMsg.value = error.toString();
  432. } else {
  433. LogHelper().d('Other error: $error');
  434. errorMsg.value = error.toString();
  435. }
  436. }
  437. @override
  438. void dispose() {
  439. controllers.tray.dispose();
  440. controllers.window.dispose();
  441. //controllers.protocol.dispose();
  442. super.dispose();
  443. }
  444. }