GlobalController.dart 11 KB

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