GlobalController.dart 13 KB

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