GlobalController.dart 16 KB

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