core.dart 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import 'package:dio/dio.dart';
  2. import 'package:get/get.dart';
  3. import 'package:naiyouwl/app/bean/clash_core.dart';
  4. import 'package:naiyouwl/app/bean/connect.dart';
  5. import 'package:naiyouwl/app/bean/proxie.dart';
  6. import 'package:naiyouwl/app/bean/rule.dart';
  7. import 'package:naiyouwl/app/controller/controllers.dart';
  8. import 'package:naiyouwl/app/utils/logger.dart';
  9. import 'package:naiyouwl/app/utils/system_proxy.dart';
  10. import 'package:web_socket_channel/io.dart';
  11. class CoreController extends GetxController {
  12. late final dio = Dio(BaseOptions(
  13. baseUrl: 'http://127.0.0.1:9090',
  14. ))..interceptors.add(FriendlyErrorInterceptor());
  15. var version = ClashCoreVersion(premium: true, version: '').obs;
  16. var address = ''.obs;
  17. var secret = ''.obs;
  18. var config = ClashCoreConfig(
  19. port: 0,
  20. socksPort: 0,
  21. redirPort: 0,
  22. tproxyPort: 0,
  23. mixedPort: 0,
  24. allowLan: false,
  25. bindAddress: '',
  26. mode: 'rule',
  27. logLevel: '',
  28. ipv6: false,
  29. ).obs;
  30. var ruleProvider = RuleProvider(providers: {}).obs;
  31. var rule = Rule(rules: []).obs;
  32. CoreController();
  33. SystemProxyConfig get proxyConfig {
  34. final mixedPort = config.value.mixedPort == 0 ? null : config.value.mixedPort;
  35. final httpPort = mixedPort ?? config.value.port;
  36. final httpsPort = mixedPort ?? config.value.port;
  37. final socksPort = mixedPort ?? config.value.socksPort;
  38. return SystemProxyConfig(
  39. http: httpPort == 0 ? null : '127.0.0.1:$httpPort',
  40. https: httpsPort == 0 ? null : '127.0.0.1:$httpsPort',
  41. socks: socksPort == 0 ? null : '127.0.0.1:$socksPort',
  42. );
  43. }
  44. setApi(String apiAddress, String apiSecret) {
  45. address.value = apiAddress;
  46. secret.value = apiSecret;
  47. dio.options.baseUrl = 'http://${address.value}';
  48. dio.options.headers['Authorization'] = 'Bearer ${secret.value}';
  49. }
  50. Future<dynamic> fetchHello() async {
  51. return await dio.get('/');
  52. }
  53. Future<void> updateVersion() async {
  54. final res = await dio.get('/version');
  55. version.value = ClashCoreVersion.fromJson(res.data);
  56. }
  57. Future<void> updateConfig() async {
  58. final res = await dio.get('/configs');
  59. config.value = ClashCoreConfig.fromJson(res.data);
  60. }
  61. Future<void> fetchConfigUpdate(Map<String, dynamic> config) async {
  62. await dio.patch('/configs', data: config);
  63. await updateConfig();
  64. }
  65. // type updateConfigRequest struct {
  66. // Path string `json:"path"`
  67. // Payload string `json:"payload"`
  68. // }
  69. // https://github.com/Dreamacro/clash/blob/c231fd14666d6ea05d6a75eaba6db69f9eee5ae9/hub/route/configs.go#L95
  70. Future<void> fetchReloadConfig(Map<String, String> config) async {
  71. await dio.put('/configs', data: config);
  72. }
  73. Future<void> fetchCloseConnections(String id) async {
  74. await dio.delete('/connections/${Uri.encodeComponent(id)}');
  75. }
  76. IOWebSocketChannel fetchConnectionsWs() {
  77. return IOWebSocketChannel.connect(
  78. Uri.parse('ws://${address.value}/connections'),
  79. headers: {"Authorization": dio.options.headers["Authorization"]},
  80. );
  81. }
  82. Future updateRuleProvider() async {
  83. final res = await dio.get('/providers/rules');
  84. ruleProvider.value = RuleProvider.fromJson(res.data);
  85. ruleProvider.refresh();
  86. }
  87. Future updateRule() async {
  88. final res = await dio.get('/rules');
  89. rule.value = Rule.fromJson(res.data);
  90. rule.refresh();
  91. }
  92. Future<void> fetchRuleProviderUpdate(String name) async {
  93. await dio.put('/providers/rules/${Uri.encodeComponent(name)}');
  94. }
  95. Future<Proxie> fetchProxie() async {
  96. final res = await dio.get('/proxies');
  97. return Proxie.fromJson(res.data);
  98. }
  99. Future<ProxieProvider> fetchProxieProvider() async {
  100. final res = await dio.get('/providers/proxies');
  101. return ProxieProvider.fromJson(res.data);
  102. }
  103. Future<void> fetchProxieProviderHealthCheck(String provider) async {
  104. await dio.get('/providers/proxies/${Uri.encodeComponent(provider)}/healthcheck');
  105. }
  106. Future<void> fetchSetProxieGroup(String group, String value) async {
  107. await dio.put('/proxies/${Uri.encodeComponent(group)}', data: {'name': value});
  108. }
  109. Future<void> fetchProxieProviderUpdate(String name) async {
  110. await dio.put('/providers/proxies/${Uri.encodeComponent(name)}');
  111. }
  112. Future<int> fetchProxieDelay(String name) async {
  113. final query = {'timeout': 5000, 'url': 'http://www.gstatic.com/generate_204'};
  114. final res = await dio.get('/proxies/${Uri.encodeComponent(name)}/delay', queryParameters: query);
  115. return res.data['delay'] ?? 0;
  116. }
  117. Future<Connect> fetchConnection() async {
  118. final res = await dio.get('/connections');
  119. return Connect.fromJson(res.data);
  120. }
  121. }
  122. class FriendlyErrorInterceptor extends Interceptor {
  123. @override
  124. Future onError(DioError err, ErrorInterceptorHandler handler) async {
  125. String message = 'core未知错误';
  126. if (err.type == DioErrorType.connectTimeout ||
  127. err.type == DioErrorType.sendTimeout ||
  128. err.type == DioErrorType.receiveTimeout) {
  129. message = '连接core超时,请检查您的网络';
  130. } else if (err.type == DioErrorType.cancel) {
  131. message = 'core 请求已被取消';
  132. } else if (err.type == DioErrorType.response) {
  133. message = 'core 服务端响应错误: ${err.response?.statusCode} ${err.response?.statusMessage}';
  134. } else if (err.type == DioErrorType.other) {
  135. message = 'core 其他错误: ${err.message}';
  136. }
  137. log.debug(message);
  138. return DioError(error: message, requestOptions: err.requestOptions);
  139. }
  140. }