config.dart 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import 'dart:io';
  2. import 'dart:convert';
  3. import 'package:dio/dio.dart';
  4. import 'package:get/get.dart';
  5. import 'package:naiyouwl/app/bean/config.dart';
  6. import 'package:naiyouwl/app/const/const.dart';
  7. import 'package:yaml/yaml.dart';
  8. import 'package:path/path.dart' as path;
  9. import 'package:flutter_emoji/flutter_emoji.dart';
  10. import '../data/model/NodeMode.dart';
  11. final Map<String, dynamic> _defaultConfig = {
  12. 'selected': 'example.yaml',
  13. 'updateInterval': 86400,
  14. 'updateSubsAtStart': false,
  15. 'setSystemProxy': false,
  16. 'startAtLogin': false,
  17. 'breakConnections': false,
  18. 'language': 'zh_CN',
  19. 'port': 9899,
  20. 'subs': [],
  21. };
  22. class ConfigController extends GetxController {
  23. late final dio;
  24. var config = Config.fromJson(_defaultConfig).obs;
  25. var clashCoreApiAddress = '127.0.0.1:9090'.obs;
  26. var clashCoreApiSecret = ''.obs;
  27. var clashCoreDns = ''.obs;
  28. var clashCoreTunEnable = false.obs;
  29. var servicePort = 0.obs;
  30. Future<void> initConfig() async {
  31. // var port = await getFreePort();
  32. //dio.addSentry();
  33. dio = Dio(BaseOptions(baseUrl: clashCoreApiAddress.value));
  34. if (!await Paths.config.exists()) await Paths.config.create(recursive: true);
  35. if (!await Files.configCountryMmdb.exists()) await Files.assetsCountryMmdb.copy(Files.configCountryMmdb.path);
  36. if (Platform.isWindows && !await Files.configWintun.exists()) await Files.assetsWintun.copy(Files.configWintun.path);
  37. final locale = Get.deviceLocale!;
  38. _defaultConfig['language'] = '${locale.languageCode}_${locale.countryCode}';
  39. if (await Files.configConfig.exists()) {
  40. final local = json.decode(await Files.configConfig.readAsString());
  41. config.value = Config.fromJson({..._defaultConfig, ...local});
  42. } else {
  43. config.value = Config.fromJson(_defaultConfig);
  44. }
  45. //config.value.port = port;
  46. if (config.value.subs.isEmpty) {
  47. if (!await Files.configExample.exists())
  48. await Files.assetsExample.copy(Files.configExample.path);
  49. config.value.subs.add(ConfigSub(name: 'example.yaml', url: '', updateTime: 0));
  50. config.value.selected = 'example.yaml';
  51. }
  52. await save();
  53. await readClashCoreApi();
  54. }
  55. String nodeToYaml(NodeMode node) {
  56. switch (node.type) {
  57. case 'trojan':
  58. return ''' - { name: ${node.name}, type: ${node.type}, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, udp: 1 }''';
  59. case 'shadowsocks':
  60. return ''' - { name: ${node.name}, type: ss, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, cipher: ${node.method}, udp: 1 }''';
  61. case 'v2ray':
  62. final type = (node.vless == 1) ? 'vless' : 'vmess';
  63. if (type == 'vless') {
  64. return ''' - { name: ${node.name}, type: $type, server: ${node.host}, port: ${node.port}, uuid: ${node.uuid}, alterId: ${node.v2AlterId}, udp: 1, flow: xtls-rprx-vision, servername: www.amazon.com, tls: true, reality-opts: { public-key: ${node.vlessPulkey} } }''';
  65. } else {
  66. return ''' - { name: ${node.name}, type: $type, server: ${node.host}, port: ${node.port}, uuid: ${node.uuid}, alterId: ${node.v2AlterId}, cipher: ${node.method}, udp: 1 }''';
  67. }
  68. default:
  69. return '';
  70. }
  71. }
  72. Future<void> makeClashConfig(List<NodeMode> nodes) async{
  73. var mixedport = 9888;
  74. bool bg = await isPortOccupied(mixedport);
  75. if(bg) {
  76. mixedport = await getFreePort();
  77. }
  78. var extePort = 9777;
  79. final ac = await isPortOccupied(extePort);
  80. if(ac) {
  81. extePort = await getFreePort();
  82. }
  83. var proxies = nodes.map(nodeToYaml).toList();
  84. var proxyGroups = '''
  85. proxy-groups:
  86. - name: proxy
  87. type: select
  88. proxies:
  89. - ${nodes.map((node) => node.name).join('\n - ')}
  90. ''';
  91. var rules = '''
  92. rules:
  93. - GEOIP,CN,DIRECT
  94. - MATCH,proxy
  95. ''';
  96. var initconfig = '''
  97. mixed-port: $mixedport
  98. allow-lan: true
  99. bind-address: '*'
  100. mode: Rule
  101. log-level: info
  102. external-controller: '127.0.0.1:$extePort'
  103. proxies:
  104. ${proxies.join('\n')}
  105. $proxyGroups
  106. $rules
  107. ''';
  108. await Files.makeProxyConfig.writeAsString(initconfig);
  109. config.value.selected = 'proxy.yaml';
  110. }
  111. Future<void> save() async {
  112. await Files.configConfig.writeAsString(json.encode(config.toJson()));
  113. }
  114. Future<void> readClashCoreApi() async {
  115. final configStr = await File(path.join(Paths.config.path, config.value.selected)).readAsString();
  116. // final emoji = EmojiParser();
  117. // final b = emoji.unemojify(_config);
  118. final configJson = loadYaml(configStr.replaceAll(EmojiParser.REGEX_EMOJI, 'emoji'));
  119. // print(_json["external-controller"]);
  120. // https://github.com/dart-lang/yaml/issues/53
  121. // final _extControl = RegExp(r'''(?<!#\s*)external-controller:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  122. // final _secret = RegExp(r'''(?<!#\s*)secret:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  123. clashCoreApiAddress.value = (configJson["external-controller"] ?? '127.0.0.1:9090').replaceAll('0.0.0.0', '127.0.0.1');
  124. clashCoreApiSecret.value = (configJson["secret"] ?? '');
  125. clashCoreTunEnable.value = configJson["tun"]?["enable"] == true;
  126. clashCoreDns.value = '';
  127. if (configJson["dns"]?["enable"] == true && (configJson["dns"]["listen"] ?? '').isNotEmpty) {
  128. final dns = (configJson["dns"]["listen"] as String).split(":");
  129. final ip = dns[0];
  130. final port = dns[1];
  131. if (port == '53') {
  132. clashCoreDns.value = ip == '0.0.0.0' ? '127.0.0.1' : ip;
  133. }
  134. }
  135. }
  136. Future<void> setLanguage(String language) async {
  137. config.value.language = language;
  138. await save();
  139. config.refresh();
  140. }
  141. Future<void> setSystemProxy(bool open) async {
  142. config.value.setSystemProxy = open;
  143. await save();
  144. config.refresh();
  145. }
  146. Future<void> setUpdateInterval(int value) async {
  147. config.value.updateInterval = value;
  148. await save();
  149. config.refresh();
  150. }
  151. Future<void> setUpdateSubsAtStart(bool value) async {
  152. config.value.updateSubsAtStart = value;
  153. await save();
  154. config.refresh();
  155. }
  156. Future<void> setSelectd(String selected) async {
  157. config.value.selected = selected;
  158. await save();
  159. config.refresh();
  160. }
  161. Future<bool> updateSub(ConfigSub sub) async {
  162. if ((sub.url ?? '').isEmpty) return false;
  163. final res = await dio.get(sub.url!);
  164. final subInfo = res.headers['subscription-userinfo'];
  165. final file = File(path.join(Paths.config.path, sub.name));
  166. final oldConfig = await file.exists() ? await file.readAsString() : '';
  167. final changed = oldConfig != res.data;
  168. if (changed) await file.writeAsString(res.data);
  169. sub.updateTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  170. sub.info = null;
  171. if (subInfo != null) {
  172. // final info = Map.fromEntries(
  173. // subInfo.first.split(RegExp(r';\s*')).where((s) => s.isNotEmpty).map((e) => e.split('=')).map((e) => MapEntry(e[0], int.parse(e[1]))));
  174. final entries = subInfo.first.split(RegExp(r';\s*'))
  175. .where((s) => s.isNotEmpty)
  176. .map((e) => e.split('='))
  177. .toList();
  178. final info = <String, dynamic>{};
  179. for (var entry in entries) {
  180. info[entry[0]] = int.parse(entry[1]);
  181. }
  182. sub.info = ConfigSubInfo.fromJson(info);
  183. }
  184. await setSub(sub.name, sub);
  185. return changed;
  186. }
  187. Future<void> setSub(String subName, ConfigSub sub) async {
  188. final idx = config.value.subs.indexWhere((it) => it.name == subName);
  189. config.value.subs[idx] = sub;
  190. if (subName != sub.name) {
  191. final file = File(path.join(Paths.config.path, subName));
  192. if (await file.exists()) await file.rename(path.join(Paths.config.path, sub.name));
  193. }
  194. await save();
  195. config.refresh();
  196. }
  197. Future<void> addSub(ConfigSub sub) async {
  198. config.value.subs.add(sub);
  199. final file = File(path.join(Paths.config.path, sub.name));
  200. if (!await file.exists()) await file.create();
  201. await save();
  202. config.refresh();
  203. }
  204. Future<void> deleteSub(String subName) async {
  205. final file = File(path.join(Paths.config.path, subName));
  206. if (await file.exists()) await file.delete();
  207. config.value.subs.removeWhere((it) => it.name == subName);
  208. await save();
  209. config.refresh();
  210. }
  211. Future<void> setBreakConnections(bool value) async {
  212. config.value.breakConnections = value;
  213. await save();
  214. config.refresh();
  215. }
  216. Future<int> getFreePort() async {
  217. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  218. int port = server.port;
  219. await server.close();
  220. return port;
  221. }
  222. Future<bool> isPortOccupied(int port) async {
  223. bool isOccupied = false;
  224. ServerSocket? server;
  225. try {
  226. server = await ServerSocket.bind(InternetAddress.loopbackIPv4, port);
  227. } catch (e) {
  228. isOccupied = true;
  229. } finally {
  230. await server?.close();
  231. }
  232. return isOccupied;
  233. }
  234. }