GlobalController.dart 17 KB

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