GlobalController.dart 12 KB

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