GlobalController.dart 11 KB

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