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. //
  151. // return;
  152. // }
  153. modesSelect.value = route;
  154. final coreStatus = controllers.service.coreStatus.value;
  155. if( coreStatus == RunningState.running){
  156. controllers.core.fetchConfigUpdate({'mode': modesSelect.value});
  157. }
  158. }
  159. Future<void> updateRoute(String route) async {
  160. if(allowStatusUpdate){
  161. return;
  162. }
  163. // if(route == "tun"){
  164. // final res = await showNormalDialog( context,content: '启用网卡模式需要管理员',title: '提示', cancelText: '取消', enterText: '确认安装');
  165. // if (res != true) return;
  166. // controllers.service.serviceModeSwitch(true);
  167. // }
  168. routeModesSelect.value = route;
  169. LogHelper().d("当前ROUTE模式${routeModesSelect.value}");
  170. }
  171. Future<void> fetchNodes() async {
  172. nodeModes.value = await ApiService().getNode("/api/client/v4/nodes?vless=1");
  173. //await makeProxy();
  174. // if(controllers.service.coreStatus.value == RunningState.stoped){
  175. // await controllers.service.reloadClashCore();
  176. // }
  177. // if (controllers.service.coreStatus.value != RunningState.running) return;
  178. // await controllers.core.updateVersion();
  179. // await updateDate();
  180. //
  181. }
  182. Future<void> updateNode() async {
  183. NodeMode? targetNode;
  184. if (selectedNode.value == null) {
  185. targetNode = await findNodeWithMinUsers(nodeModes);
  186. } else {
  187. targetNode = selectedNode.value;
  188. }
  189. if (targetNode != null){
  190. selectNode(targetNode);
  191. await swift(targetNode.name ?? "");
  192. }
  193. }
  194. Future<void> showConsole() async {
  195. await _wlBaseHelpPlugin.showConsole();
  196. }
  197. Future<void> hideConsole() async {
  198. await _wlBaseHelpPlugin.hideConsole();
  199. }
  200. Future<void> startSysMode() async {
  201. await makeProxy();
  202. //await updateDate();
  203. }
  204. Future<void> startTunMode() async {
  205. await makeProxy();
  206. }
  207. Future<void> swift(String name) async {
  208. try{
  209. var g = "proxy";
  210. if(modesSelect.value == "global")
  211. {
  212. g = "GLOBAL";
  213. }
  214. await controllers.core.fetchSetProxieGroup(g, name);
  215. await updateDate();
  216. final conn = await controllers.core.fetchConnection();
  217. for (final it in conn.connections) {
  218. if (it.chains.contains(name)) controllers.core.fetchCloseConnections(it.id);
  219. }
  220. }catch (e) {
  221. //LogHelper().d(e.toString());
  222. }
  223. }
  224. // Future<ProxieProxiesItem> findProxieByName(String name) async {
  225. // return proxieGroups.firstWhere((proxie) => proxie['name'] == name, orElse: () => null);
  226. // }
  227. Future<ProxieProxiesItem?> findProxieByName(String name) async {
  228. ProxieProxiesItem? result;
  229. try {
  230. result = proxieGroups.firstWhere((proxie) => proxie.all!.contains(name));
  231. } catch (e) {
  232. // 在这里可以处理异常,或者只是简单地返回 null
  233. return null;
  234. }
  235. return result;
  236. }
  237. Future<void> makeProxy() async {
  238. await controllers.config.makeClashConfig(nodeModes);
  239. // await controllers.service.reloadClashCore();
  240. }
  241. Future<NodeMode> findNodeWithMinUsers(List<NodeMode> nodes) async {
  242. return nodes
  243. .where((node) => node.countryCode == "hk")
  244. .reduce((a, b) => a.onlineUsers! < b.onlineUsers! ? a : b);
  245. }
  246. Future<SystemProxyConfig> getSysProxy() async{
  247. return await SystemProxy.instance.get();
  248. }
  249. Future<void> TunProxySwitch(bool open) async {
  250. tunProxySwitchIng.value = true;
  251. routeModesSelect.value = open ? "tun": "sys";
  252. LogHelper().d("TunProxySwitch ----- 当前ROUTE模式${routeModesSelect.value}");
  253. tunProxySwitchIng.value = false;
  254. }
  255. Future<void> systemProxySwitch(bool open) async {
  256. systemProxySwitchIng.value = true;
  257. //await SystemProxy.instance.set(open ? controllers.core.proxyConfig : SystemProxyConfig());
  258. await controllers.config.setSystemProxy(open);
  259. if(open)
  260. {
  261. await openProxy();
  262. } else {
  263. await closeProxy();
  264. }
  265. systemProxySwitchIng.value = false;
  266. }
  267. Future<dynamic> _updateProxie() async {
  268. final proxie = await controllers.core.fetchProxie();
  269. final global = proxie.proxies["GLOBAL"]!;
  270. proxieGroups.value = global.all!
  271. .where((it) => !groupInternalTypes.contains(it) && groupTypes.contains(proxie.proxies[it]!.type))
  272. .map((it) => proxie.proxies[it]!)
  273. .toList();
  274. proxieProxies.value = global.all!
  275. .where((it) => !groupInternalTypes.contains(it) && !groupTypes.contains(proxie.proxies[it]!.type))
  276. .map((it) => proxie.proxies[it]!)
  277. .toList();
  278. if (controllers.core.config.value.mode == 'global') proxieGroups.insert(0, global);
  279. }
  280. Future<dynamic> _updateProxieProvider() async {
  281. proxieProviders.value = (await controllers.core.fetchProxieProvider()).providers.values.where((it) => it.vehicleType != 'Compatible').toList();
  282. for (final it in proxieProviders) {
  283. it.proxies.sort((a, b) {
  284. if (a.delay == 0) return 1;
  285. if (b.delay == 0) return -1;
  286. return a.delay - b.delay;
  287. });
  288. }
  289. }
  290. Future<void> updateDate() async {
  291. //LogHelper().d('controller.proxie.updateDate()');
  292. try
  293. {
  294. await controllers.core.updateConfig();
  295. await _updateProxie();
  296. await _updateProxieProvider();
  297. allProxies.clear();
  298. for (final provide in proxieProviders) {
  299. for (final it in provide.proxies) {
  300. allProxies[it.name] = it;
  301. }
  302. }
  303. for (final it in proxieProxies) {
  304. allProxies[it.name] = it;
  305. //LogHelper().d('controller.proxieProxies');
  306. }
  307. for (final it in proxieGroups) {
  308. allProxies[it.name] = it;
  309. //LogHelper().d('controller.proxieGroups');
  310. }
  311. proxieGroups.refresh();
  312. proxieProxies.refresh();
  313. proxieProviders.refresh();
  314. allProxies.refresh();
  315. } catch (e){
  316. LogHelper().d("updateDate -- ${e.toString()}");
  317. }
  318. }
  319. Future<void> handleSetProxieGroup(ProxieProxiesItem proxie, String value) async {
  320. if (proxie.now == value) return;
  321. await controllers.core.fetchSetProxieGroup(proxie.name, value);
  322. await updateDate();
  323. if (controllers.config.config.value.breakConnections) {
  324. final conn = await controllers.core.fetchConnection();
  325. for (final it in conn.connections) {
  326. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  327. }
  328. }
  329. }
  330. Future<void> handleSetSelectProxieGroup(NodeMode proxie, String value) async {
  331. if (proxie.name == value) return;
  332. await controllers.core.fetchSetProxieGroup(proxie.name ?? "", value);
  333. await updateDate();
  334. final conn = await controllers.core.fetchConnection();
  335. for (final it in conn.connections) {
  336. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  337. }
  338. }
  339. void watchExit() {
  340. // watch process kill
  341. // ref https://github.com/dart-lang/sdk/issues/12170
  342. if (Platform.isMacOS) {
  343. // windows not support https://github.com/dart-lang/sdk/issues/28603
  344. // for macos 任务管理器退出进程
  345. ProcessSignal.sigterm.watch().listen((_) {
  346. stdout.writeln('exit: sigterm');
  347. handleExit();
  348. });
  349. }
  350. // for macos, windows ctrl+c
  351. ProcessSignal.sigint.watch().listen((_) {
  352. stdout.writeln('exit: sigint');
  353. handleExit();
  354. });
  355. }
  356. void selectNode(NodeMode node) {
  357. controllers.global.selectedNode.value = node;
  358. _storeSelectedNode(node);
  359. }
  360. Future<void> _storeSelectedNode(NodeMode node) async {
  361. final prefs = await SharedPreferences.getInstance();
  362. // 为简化起见,我们只存储node的ID,但您可以根据需要存储更多信息
  363. prefs.setInt('selectedNodeId', node.id ?? -1);
  364. await loadSelectedNode();
  365. }
  366. Future<void> loadSelectedNode() async {
  367. final prefs = await SharedPreferences.getInstance();
  368. final selectedNodeId = prefs.getInt('selectedNodeId');
  369. if (selectedNodeId != null) {
  370. //selectedIndex.value = nodeModes.indexWhere((item) => item.id == selectedNodeId);
  371. selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
  372. }
  373. }
  374. void initRegularlyUpdate() {
  375. Future.delayed(const Duration(minutes: 5)).then((_) async {
  376. for (final it in controllers.config.config.value.subs) {
  377. try {
  378. if (it.url == null || it.url!.isEmpty) continue;
  379. if (((DateTime.now().millisecondsSinceEpoch ~/ 1000) - (it.updateTime ?? 0)) < controllers.config.config.value.updateInterval) continue;
  380. final chenged = await controllers.config.updateSub(it);
  381. if (!chenged) continue;
  382. if (it.name != controllers.config.config.value.selected) continue;
  383. // restart clash core
  384. await controllers.service.reloadClashCore();
  385. await Future.delayed(const Duration(seconds: 20));
  386. } catch (_) {}
  387. }
  388. initRegularlyUpdate();
  389. });
  390. }
  391. /// 打开代理
  392. Future<void> openProxy() async {
  393. int? port = controllers.config.mixedPort.value;
  394. if (port == 0) {
  395. port = null;
  396. }
  397. int? socksPort = controllers.config.mixedPort.value;
  398. if (socksPort == 0) {
  399. socksPort = null;
  400. }
  401. int? mixedPort = controllers.config.mixedPort.value;
  402. if (mixedPort == 0) {
  403. mixedPort = null;
  404. }
  405. port = port ?? mixedPort ?? 0;
  406. if (port != 0) {
  407. if(Platform.isWindows){
  408. 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.*';
  409. int? exitCode;
  410. // Process sysproxy = await Process.start(Files.assetsSysProxyWin.path,,mode: ProcessStartMode.inheritStdio);
  411. // sysproxy.exitCode.then((code) => exitCode = code);
  412. try {
  413. var result = await Process.run(
  414. Files.assetsSysProxyWin.path,
  415. ['global','127.0.0.1:$port',loa],
  416. runInShell: true,
  417. );
  418. LogHelper().d(result.stderr);
  419. LogHelper().d(result.stdout);
  420. } on ProcessException catch (e) {
  421. //.e('Failed to start $coreName: ${e.message}');
  422. throw Exception('Failed to start sysproxy: ${e.message}');
  423. }
  424. } else {
  425. await proxyManager.setAsSystemProxy(
  426. ProxyTypes.http,
  427. "127.0.0.1",
  428. port,
  429. );
  430. await proxyManager.setAsSystemProxy(
  431. ProxyTypes.https,
  432. "127.0.0.1",
  433. port,
  434. );
  435. systemProxy = true;
  436. }
  437. }
  438. //
  439. // port = port ?? mixedPort ?? 0;
  440. // if (port != 0) {
  441. // }
  442. socksPort = socksPort ?? mixedPort ?? 0;
  443. if (socksPort != 0) {
  444. if (!Platform.isWindows) {
  445. await proxyManager.setAsSystemProxy(
  446. ProxyTypes.socks,
  447. "127.0.0.1",
  448. socksPort,
  449. );
  450. }
  451. systemProxy = true;
  452. }
  453. }
  454. /// 关闭代理
  455. Future<void> closeProxy() async {
  456. //
  457. if (Platform.isWindows) {
  458. try {
  459. var result = await Process.run(
  460. Files.assetsSysProxyWin.path,
  461. ['set','1','','',''],
  462. runInShell: true,
  463. );
  464. LogHelper().d(result.stderr);
  465. LogHelper().d(result.stdout);
  466. } on ProcessException catch (e) {
  467. //.e('Failed to start $coreName: ${e.message}');
  468. throw Exception('Failed to start sysproxy: ${e.message}');
  469. }
  470. }
  471. proxyManager.cleanSystemProxy();
  472. systemProxy = false;
  473. }
  474. Future<void> stopAllCore() async {
  475. await systemProxySwitch(false);
  476. await controllers.service.stopClashCore();
  477. if(!controllers.service.serviceMode.value){{
  478. await onKillProcess(path.basename(Files.assetsCCore.path));
  479. await killProcess(path.basename(Files.assetsCCore.path));
  480. }}
  481. if(!controllers.service.serviceMode.value){
  482. await killProcess(path.basename(Files.assetsClashService.path));
  483. }
  484. }
  485. Future<void> handleExit() async {
  486. await stopAllCore();
  487. await trayManager.destroy();
  488. await windowManager.destroy();
  489. // exit(0);
  490. }
  491. void handleApiError(dynamic error) {
  492. if (error is AppException) {
  493. LogHelper().d('API error with status code: ${error.statusCode}');
  494. statusCode.value = error.statusCode ?? -1;
  495. errorMsg.value = error.toString();
  496. } else {
  497. LogHelper().d('Other error: $error');
  498. errorMsg.value = error.toString();
  499. }
  500. }
  501. @override
  502. void dispose() {
  503. controllers.tray.dispose();
  504. controllers.window.dispose();
  505. //controllers.protocol.dispose();
  506. super.dispose();
  507. }
  508. }