service.dart 8.1 KB

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