GlobalController.dart 11 KB

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