GlobalController.dart 17 KB

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