service.dart 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import 'dart:io';
  2. import 'dart:async';
  3. import 'dart:convert';
  4. import 'package:dio/dio.dart';
  5. import 'package:get/get.dart';
  6. import 'package:naiyouwl/app/bean/ClashServiceInfo.dart';
  7. import 'package:naiyouwl/app/const/const.dart';
  8. import 'package:naiyouwl/app/controller/controllers.dart';
  9. import 'package:naiyouwl/app/utils/logger.dart';
  10. import 'package:naiyouwl/app/utils/shell.dart';
  11. import 'package:naiyouwl/app/utils/system_dns.dart';
  12. import 'package:naiyouwl/app/utils/system_proxy.dart';
  13. import 'package:naiyouwl/app/utils/utils.dart';
  14. import 'package:path/path.dart' as path;
  15. import 'package:flutter/foundation.dart';
  16. import 'package:bot_toast/bot_toast.dart';
  17. import 'package:web_socket_channel/io.dart';
  18. final headers = {"User-Agent": "ccore-for-flutter/0.0.1"};
  19. class ServiceController extends GetxController {
  20. late final _dio ;
  21. var serviceMode = false.obs;
  22. var servicePort = 0.obs;
  23. var coreStatus = RunningState.stoped.obs;
  24. var serviceStatus = RunningState.stoped.obs;
  25. Process? clashServiceProcess;
  26. bool get isRunning => serviceStatus.value == RunningState.running && coreStatus.value == RunningState.running;
  27. bool get isCanOperationService =>
  28. ![RunningState.starting, RunningState.stopping].contains(serviceStatus.value) &&
  29. ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  30. bool get isCanOperationCore =>
  31. serviceStatus.value == RunningState.running && ![RunningState.starting, RunningState.stopping].contains(coreStatus.value);
  32. ServiceController(
  33. ) {
  34. }
  35. Future<void> initConfig() async{
  36. servicePort.value = controllers.config.config.value.port;
  37. print('http://127.0.0.1:${servicePort.value}');
  38. _dio = Dio(BaseOptions(baseUrl: 'http://127.0.0.1:${servicePort.value}', headers: headers));
  39. }
  40. Future<void> startService() async {
  41. serviceStatus.value = RunningState.starting;
  42. if (Platform.isLinux) {
  43. await fixBinaryExecutePermissions(Files.assetsClashService);
  44. await fixBinaryExecutePermissions(Files.assetsClashCore);
  45. }
  46. try {
  47. final data = await fetchInfo();
  48. serviceMode.value = data.mode == 'service-mode';
  49. } catch (e) {
  50. await startUserModeService();
  51. if (serviceStatus.value == RunningState.error) return;
  52. }
  53. serviceStatus.value = RunningState.running;
  54. }
  55. Future<void> fixBinaryExecutePermissions(File file) async {
  56. final stat = await file.stat();
  57. // 0b001000000
  58. final has = (stat.mode & 64) == 64;
  59. if (has) return;
  60. await Process.run('chmod', ['+x', file.path]);
  61. }
  62. Future<void> startUserModeService() async {
  63. serviceMode.value = false;
  64. try {
  65. int? exitCode;
  66. clashServiceProcess = await Process.start(Files.assetsClashService.path, ['user-mode'], mode: ProcessStartMode.inheritStdio);
  67. clashServiceProcess!.exitCode.then((code) => exitCode = code);
  68. while (true) {
  69. await Future.delayed(const Duration(milliseconds: 200));
  70. if (exitCode == 101) {
  71. BotToast.showText(text: 'clash-service exit with code: $exitCode,After 10 seconds, try to restart');
  72. log.error('After 10 seconds, try to restart');
  73. await Future.delayed(const Duration(seconds: 10));
  74. await startUserModeService();
  75. break;
  76. } else if (exitCode != null) {
  77. serviceStatus.value = RunningState.error;
  78. break;
  79. }
  80. try {
  81. await _dio.post('/info');
  82. break;
  83. } catch (_) {}
  84. }
  85. } catch (e) {
  86. serviceStatus.value = RunningState.error;
  87. BotToast.showText(text: e.toString());
  88. }
  89. }
  90. Future<void> stopService() async {
  91. serviceStatus.value = RunningState.stopping;
  92. if (coreStatus.value == RunningState.running) await stopClashCore();
  93. if (!serviceMode.value) {
  94. if (clashServiceProcess != null) {
  95. clashServiceProcess!.kill();
  96. clashServiceProcess = null;
  97. } else if (kDebugMode) {
  98. await killProcess(path.basename(Files.assetsClashService.path));
  99. }
  100. }
  101. serviceStatus.value = RunningState.stoped;
  102. }
  103. // for macos
  104. Future<void> waitServiceStart() async {
  105. while (true) {
  106. await Future.delayed(const Duration(milliseconds: 100));
  107. try {
  108. await _dio.post('/info');
  109. break;
  110. } catch (_) {}
  111. }
  112. }
  113. // for windows
  114. Future<void> waitServiceStop() async {
  115. while (true) {
  116. await Future.delayed(const Duration(milliseconds: 100));
  117. try {
  118. await _dio.post('/info');
  119. } catch (e) {
  120. break;
  121. }
  122. }
  123. }
  124. Future<ClashServiceInfo> fetchInfo() async {
  125. final res = await _dio.post('/info');
  126. return ClashServiceInfo.fromJson(res.data);
  127. }
  128. IOWebSocketChannel fetchLogWs() {
  129. return IOWebSocketChannel.connect(Uri.parse('ws://127.0.0.1:${servicePort.value}/logs'), headers: headers);
  130. }
  131. Future<void> fetchStart(String name) async {
  132. await fetchStop();
  133. final res = await _dio.post<String>('/start', data: {
  134. "args": ['-d', Paths.config.path, '-f', path.join(Paths.config.path, name)]
  135. });
  136. if (json.decode(res.data!)["code"] != 0) throw json.decode(res.data!)["msg"];
  137. }
  138. Future<void> fetchStop() async {
  139. try {
  140. await _dio.post('/stop');
  141. } catch (e) {
  142. return;
  143. }
  144. }
  145. Future<void> install() async {
  146. final res = await runAsAdmin(Files.assetsClashService.path, ["stop", "uninstall", "install", "start"]);
  147. log.debug('install', res.stdout, res.stderr);
  148. if (res.exitCode != 0) throw res.stderr;
  149. await waitServiceStart();
  150. }
  151. Future<void> uninstall() async {
  152. final res = await runAsAdmin(Files.assetsClashService.path, ["stop", "uninstall"]);
  153. log.debug('uninstall', res.stdout, res.stderr);
  154. if (res.exitCode != 0) throw res.stderr;
  155. await waitServiceStop();
  156. }
  157. Future<void> serviceModeSwitch(bool open) async {
  158. if (serviceStatus.value == RunningState.running) await stopService();
  159. try {
  160. open ? await install() : await uninstall();
  161. } catch (e) {
  162. BotToast.showText(text: e.toString());
  163. }
  164. await startService();
  165. await startClashCore();
  166. }
  167. Future<void> startClashCore() async {
  168. try {
  169. coreStatus.value = RunningState.starting;
  170. await fetchStart(controllers.config.config.value.selected);
  171. controllers.core.setApi(controllers.config.clashCoreApiAddress.value, controllers.config.clashCoreApiSecret.value);
  172. while (true) {
  173. await Future.delayed(const Duration(milliseconds: 200));
  174. final info = await fetchInfo();
  175. print("core --- info $info");
  176. if (info.status == 'running') {
  177. try {
  178. await controllers.core.fetchHello();
  179. break;
  180. } catch (_) {}
  181. } else {
  182. throw 'clash-core start error';
  183. }
  184. }
  185. await controllers.core.updateConfig();
  186. if (Platform.isMacOS &&
  187. controllers.service.serviceMode.value &&
  188. controllers.config.clashCoreTunEnable.value &&
  189. controllers.config.clashCoreDns.isNotEmpty) {
  190. await MacSystemDns.instance.set([controllers.config.clashCoreDns.value]);
  191. }
  192. if (controllers.config.config.value.setSystemProxy) await SystemProxy.instance.set(controllers.core.proxyConfig);
  193. coreStatus.value = RunningState.running;
  194. } catch (e) {
  195. log.error("core -- $e");
  196. BotToast.showText(text: e.toString());
  197. coreStatus.value = RunningState.error;
  198. }
  199. }
  200. Future<void> stopClashCore() async {
  201. coreStatus.value = RunningState.stopping;
  202. if (Platform.isMacOS &&
  203. controllers.service.serviceMode.value &&
  204. controllers.config.clashCoreTunEnable.value &&
  205. controllers.config.clashCoreDns.isNotEmpty) {
  206. await MacSystemDns.instance.set([]);
  207. }
  208. if (controllers.config.config.value.setSystemProxy) await SystemProxy.instance.set(SystemProxyConfig());
  209. await fetchStop();
  210. coreStatus.value = RunningState.stoped;
  211. }
  212. Future<void> reloadClashCore() async {
  213. BotToast.showText(text: '正在重启 Core ……');
  214. await stopClashCore();
  215. await controllers.config.readClashCoreApi();
  216. await startClashCore();
  217. if (coreStatus.value == RunningState.error) {
  218. BotToast.showText(text: '重启失败');
  219. } else {
  220. await controllers.core.updateVersion();
  221. BotToast.showText(text: '重启成功');
  222. }
  223. }
  224. Future<int> getFreePort() async {
  225. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  226. int port = server.port;
  227. await server.close();
  228. return port;
  229. }
  230. }