GlobalController.dart 14 KB

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