GlobalController.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. 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. await SharedPreferencesUtil().delete("last_successful_url");
  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. LogHelper().d(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. LogHelper().d('controller.proxie.updateDate()');
  195. try
  196. {
  197. await controllers.core.updateConfig();
  198. await _updateProxie();
  199. await _updateProxieProvider();
  200. allProxies.clear();
  201. for (final provide in proxieProviders) {
  202. for (final it in provide.proxies) {
  203. allProxies[it.name] = it;
  204. }
  205. }
  206. for (final it in proxieProxies) {
  207. allProxies[it.name] = it;
  208. LogHelper().d('controller.proxieProxies');
  209. }
  210. for (final it in proxieGroups) {
  211. allProxies[it.name] = it;
  212. LogHelper().d('controller.proxieGroups');
  213. }
  214. proxieGroups.refresh();
  215. proxieProxies.refresh();
  216. proxieProviders.refresh();
  217. allProxies.refresh();
  218. } catch (e){
  219. LogHelper().d("updateDate -- ${e.toString()}");
  220. }
  221. }
  222. Future<void> handleSetProxieGroup(ProxieProxiesItem proxie, String value) async {
  223. if (proxie.now == value) return;
  224. await controllers.core.fetchSetProxieGroup(proxie.name, value);
  225. await updateDate();
  226. if (controllers.config.config.value.breakConnections) {
  227. final conn = await controllers.core.fetchConnection();
  228. for (final it in conn.connections) {
  229. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  230. }
  231. }
  232. }
  233. Future<void> handleSetSelectProxieGroup(NodeMode proxie, String value) async {
  234. if (proxie.name == value) return;
  235. await controllers.core.fetchSetProxieGroup(proxie.name ?? "", value);
  236. await updateDate();
  237. final conn = await controllers.core.fetchConnection();
  238. for (final it in conn.connections) {
  239. if (it.chains.contains(proxie.name)) controllers.core.fetchCloseConnections(it.id);
  240. }
  241. }
  242. void watchExit() {
  243. // watch process kill
  244. // ref https://github.com/dart-lang/sdk/issues/12170
  245. if (Platform.isMacOS) {
  246. // windows not support https://github.com/dart-lang/sdk/issues/28603
  247. // for macos 任务管理器退出进程
  248. ProcessSignal.sigterm.watch().listen((_) {
  249. stdout.writeln('exit: sigterm');
  250. handleExit();
  251. });
  252. }
  253. // for macos, windows ctrl+c
  254. ProcessSignal.sigint.watch().listen((_) {
  255. stdout.writeln('exit: sigint');
  256. handleExit();
  257. });
  258. }
  259. void selectNode(NodeMode node) {
  260. controllers.global.selectedNode.value = node;
  261. _storeSelectedNode(node);
  262. }
  263. Future<void> _storeSelectedNode(NodeMode node) async {
  264. final prefs = await SharedPreferences.getInstance();
  265. // 为简化起见,我们只存储node的ID,但您可以根据需要存储更多信息
  266. prefs.setInt('selectedNodeId', node.id ?? -1);
  267. await loadSelectedNode();
  268. }
  269. Future<void> loadSelectedNode() async {
  270. final prefs = await SharedPreferences.getInstance();
  271. final selectedNodeId = prefs.getInt('selectedNodeId');
  272. if (selectedNodeId != null) {
  273. //selectedIndex.value = nodeModes.indexWhere((item) => item.id == selectedNodeId);
  274. selectedNode.value = nodeModes.firstWhere((node) => node.id == selectedNodeId);
  275. }
  276. }
  277. void initRegularlyUpdate() {
  278. Future.delayed(const Duration(minutes: 5)).then((_) async {
  279. for (final it in controllers.config.config.value.subs) {
  280. try {
  281. if (it.url == null || it.url!.isEmpty) continue;
  282. if (((DateTime.now().millisecondsSinceEpoch ~/ 1000) - (it.updateTime ?? 0)) < controllers.config.config.value.updateInterval) continue;
  283. final chenged = await controllers.config.updateSub(it);
  284. if (!chenged) continue;
  285. if (it.name != controllers.config.config.value.selected) continue;
  286. // restart clash core
  287. await controllers.service.reloadClashCore();
  288. await Future.delayed(const Duration(seconds: 20));
  289. } catch (_) {}
  290. }
  291. initRegularlyUpdate();
  292. });
  293. }
  294. Future<void> handleExit() async {
  295. await systemProxySwitch(false);
  296. await controllers.service.stopService();
  297. await trayManager.destroy();
  298. await windowManager.destroy();
  299. // exit(0);
  300. }
  301. void handleApiError(dynamic error) {
  302. if (error is AppException) {
  303. LogHelper().d('API error with status code: ${error.statusCode}');
  304. statusCode.value = error.statusCode ?? -1;
  305. errorMsg.value = error.toString();
  306. } else {
  307. LogHelper().d('Other error: $error');
  308. errorMsg.value = error.toString();
  309. }
  310. }
  311. @override
  312. void dispose() {
  313. controllers.tray.dispose();
  314. controllers.window.dispose();
  315. //controllers.protocol.dispose();
  316. super.dispose();
  317. }
  318. }