GlobalController.dart 17 KB

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