GlobalController.dart 11 KB

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