GlobalController.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. await swift(targetNode.name);
  106. }
  107. }
  108. Future<void> startSysMode() async {
  109. await makeProxy();
  110. //await updateDate();
  111. }
  112. Future<void> startTunMode() async {
  113. await makeProxy();
  114. }
  115. Future<void> swift(String name) async {
  116. try{
  117. var g = "proxy";
  118. if(modesSelect.value == "global")
  119. {
  120. g = "GLOBAL";
  121. }
  122. await controllers.core.fetchSetProxieGroup(g, name);
  123. await updateDate();
  124. final conn = await controllers.core.fetchConnection();
  125. for (final it in conn.connections) {
  126. if (it.chains.contains(name)) controllers.core.fetchCloseConnections(it.id);
  127. }
  128. }catch (e) {
  129. log.debug(e.toString());
  130. }
  131. }
  132. // Future<ProxieProxiesItem> findProxieByName(String name) async {
  133. // return proxieGroups.firstWhere((proxie) => proxie['name'] == name, orElse: () => null);
  134. // }
  135. Future<ProxieProxiesItem?> findProxieByName(String name) async {
  136. ProxieProxiesItem? result;
  137. try {
  138. result = proxieGroups.firstWhere((proxie) => proxie.all!.contains(name));
  139. } catch (e) {
  140. // 在这里可以处理异常,或者只是简单地返回 null
  141. return null;
  142. }
  143. return result;
  144. }
  145. Future<void> makeProxy() async {
  146. await controllers.config.makeClashConfig(nodeModes);
  147. // await controllers.service.reloadClashCore();
  148. }
  149. Future<NodeMode> findNodeWithMinUsers(List<NodeMode> nodes) async {
  150. return nodes
  151. .where((node) => node.countryCode == "hk")
  152. .reduce((a, b) => a.onlineUsers < b.onlineUsers ? a : b);
  153. }
  154. Future<SystemProxyConfig> getSysProxy() async{
  155. return await SystemProxy.instance.get();
  156. }
  157. Future<void> systemProxySwitch(bool open) async {
  158. systemProxySwitchIng.value = true;
  159. await SystemProxy.instance.set(open ? controllers.core.proxyConfig : SystemProxyConfig());
  160. await controllers.config.setSystemProxy(open);
  161. systemProxySwitchIng.value = false;
  162. }
  163. Future<dynamic> _updateProxie() async {
  164. final proxie = await controllers.core.fetchProxie();
  165. final global = proxie.proxies["GLOBAL"]!;
  166. proxieGroups.value = global.all!
  167. .where((it) => !groupInternalTypes.contains(it) && groupTypes.contains(proxie.proxies[it]!.type))
  168. .map((it) => proxie.proxies[it]!)
  169. .toList();
  170. proxieProxies.value = global.all!
  171. .where((it) => !groupInternalTypes.contains(it) && !groupTypes.contains(proxie.proxies[it]!.type))
  172. .map((it) => proxie.proxies[it]!)
  173. .toList();
  174. if (controllers.core.config.value.mode == 'global') proxieGroups.insert(0, global);
  175. }
  176. Future<dynamic> _updateProxieProvider() async {
  177. proxieProviders.value = (await controllers.core.fetchProxieProvider()).providers.values.where((it) => it.vehicleType != 'Compatible').toList();
  178. for (final it in proxieProviders) {
  179. it.proxies.sort((a, b) {
  180. if (a.delay == 0) return 1;
  181. if (b.delay == 0) return -1;
  182. return a.delay - b.delay;
  183. });
  184. }
  185. }
  186. Future<void> updateDate() async {
  187. log.debug('controller.proxie.updateDate()');
  188. await controllers.core.updateConfig();
  189. await _updateProxie();
  190. await _updateProxieProvider();
  191. allProxies.clear();
  192. for (final provide in proxieProviders) {
  193. for (final it in provide.proxies) {
  194. allProxies[it.name] = it;
  195. }
  196. }
  197. for (final it in proxieProxies) {
  198. allProxies[it.name] = it;
  199. }
  200. for (final it in proxieGroups) {
  201. allProxies[it.name] = it;
  202. }
  203. proxieGroups.refresh();
  204. proxieProxies.refresh();
  205. proxieProviders.refresh();
  206. allProxies.refresh();
  207. }
  208. Future<void> handleSetProxieGroup(ProxieProxiesItem proxie, String value) async {
  209. if (proxie.now == value) return;
  210. await controllers.core.fetchSetProxieGroup(proxie.name, value);
  211. await updateDate();
  212. if (controllers.config.config.value.breakConnections) {
  213. final conn = await controllers.core.fetchConnection();
  214. for (final it in conn.connections) {
  215. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  216. }
  217. }
  218. }
  219. Future<void> handleSetSelectProxieGroup(NodeMode proxie, String value) async {
  220. if (proxie.name == value) return;
  221. await controllers.core.fetchSetProxieGroup(proxie.name, value);
  222. await updateDate();
  223. final conn = await controllers.core.fetchConnection();
  224. for (final it in conn.connections) {
  225. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  226. }
  227. }
  228. void watchExit() {
  229. // watch process kill
  230. // ref https://github.com/dart-lang/sdk/issues/12170
  231. if (Platform.isMacOS) {
  232. // windows not support https://github.com/dart-lang/sdk/issues/28603
  233. // for macos 任务管理器退出进程
  234. ProcessSignal.sigterm.watch().listen((_) {
  235. stdout.writeln('exit: sigterm');
  236. handleExit();
  237. });
  238. }
  239. // for macos, windows ctrl+c
  240. ProcessSignal.sigint.watch().listen((_) {
  241. stdout.writeln('exit: sigint');
  242. handleExit();
  243. });
  244. }
  245. void selectNode(NodeMode node) {
  246. controllers.global.selectedNode.value = node;
  247. _storeSelectedNode(node);
  248. }
  249. Future<void> _storeSelectedNode(NodeMode node) async {
  250. final prefs = await SharedPreferences.getInstance();
  251. // 为简化起见,我们只存储node的ID,但您可以根据需要存储更多信息
  252. prefs.setInt('selectedNodeId', node.id);
  253. await loadSelectedNode();
  254. }
  255. Future<void> loadSelectedNode() async {
  256. final prefs = await SharedPreferences.getInstance();
  257. final selectedNodeId = prefs.getInt('selectedNodeId');
  258. if (selectedNodeId != null) {
  259. //selectedIndex.value = nodeModes.indexWhere((item) => item.id == selectedNodeId);
  260. selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
  261. }
  262. }
  263. void initRegularlyUpdate() {
  264. Future.delayed(const Duration(minutes: 5)).then((_) async {
  265. for (final it in controllers.config.config.value.subs) {
  266. try {
  267. if (it.url == null || it.url!.isEmpty) continue;
  268. if (((DateTime.now().millisecondsSinceEpoch ~/ 1000) - (it.updateTime ?? 0)) < controllers.config.config.value.updateInterval) continue;
  269. final chenged = await controllers.config.updateSub(it);
  270. if (!chenged) continue;
  271. if (it.name != controllers.config.config.value.selected) continue;
  272. // restart clash core
  273. await controllers.service.reloadClashCore();
  274. await Future.delayed(const Duration(seconds: 20));
  275. } catch (_) {}
  276. }
  277. initRegularlyUpdate();
  278. });
  279. }
  280. Future<void> handleExit() async {
  281. await controllers.service.stopService();
  282. await trayManager.destroy();
  283. await windowManager.destroy();
  284. // exit(0);
  285. }
  286. @override
  287. void dispose() {
  288. controllers.tray.dispose();
  289. controllers.window.dispose();
  290. //controllers.protocol.dispose();
  291. super.dispose();
  292. }
  293. }