GlobalController.dart 14 KB

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