GlobalController.dart 14 KB

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