GlobalController.dart 11 KB

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