config.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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 (!await Files.configGeoIP.exists()) await Files.assetsGeoIP.copy(Files.configGeoIP.path);
  37. if (!await Files.configGeosite.exists()) await Files.assetsGeosite.copy(Files.configGeosite.path);
  38. if (Platform.isWindows && !await Files.configWintun.exists()) await Files.assetsWintun.copy(Files.configWintun.path);
  39. final locale = Get.deviceLocale!;
  40. _defaultConfig['language'] = '${locale.languageCode}_${locale.countryCode}';
  41. if (await Files.configConfig.exists()) {
  42. final local = json.decode(await Files.configConfig.readAsString());
  43. config.value = Config.fromJson({..._defaultConfig, ...local});
  44. } else {
  45. config.value = Config.fromJson(_defaultConfig);
  46. }
  47. bool bg = await isPortOccupied(config.value.servicePort);
  48. if(bg) {
  49. config.value.servicePort = await getFreePort();
  50. }
  51. if (config.value.subs.isEmpty) {
  52. if (!await Files.configExample.exists()) {
  53. await Files.assetsExample.copy(Files.configExample.path);
  54. }
  55. config.value.subs.add(ConfigSub(name: 'example.yaml', url: '', updateTime: 0));
  56. config.value.selected = 'example.yaml';
  57. }
  58. await save();
  59. await readClashCoreApi();
  60. }
  61. String nodeToYaml(NodeMode node) {
  62. switch (node.type) {
  63. case 'trojan':
  64. return ''' - { name: ${node.name}, type: ${node.type}, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, udp: 1 }''';
  65. case 'shadowsocks':
  66. return ''' - { name: ${node.name}, type: ss, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, cipher: ${node.method}, udp: 1 }''';
  67. case 'v2ray':
  68. final type = (node.vless == 1) ? 'vless' : 'vmess';
  69. if (type == 'vless') {
  70. 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} } }''';
  71. } else {
  72. return ''' - { name: ${node.name}, type: $type, server: ${node.host}, port: ${node.port}, uuid: ${node.uuid}, alterId: ${node.v2AlterId}, cipher: ${node.method}, udp: 1 }''';
  73. }
  74. default:
  75. return '';
  76. }
  77. }
  78. Future<void> makeClashConfig(List<NodeMode> nodes) async{
  79. if( Files.makeProxyConfig.existsSync()){
  80. Files.makeProxyConfig.deleteSync(recursive: true);
  81. }
  82. var stack = "system";
  83. if( Platform.isWindows){
  84. stack = "gvisor";
  85. }
  86. var dnsPort = 1553;
  87. if(clashCoreTunEnable.value == true)
  88. {
  89. dnsPort = 53;
  90. }
  91. var mixedport = 9888;
  92. bool bg = await isPortOccupied(mixedport);
  93. if(bg) {
  94. mixedport = await getFreePort();
  95. }
  96. var extePort = 9777;
  97. final ac = await isPortOccupied(extePort);
  98. if(ac) {
  99. extePort = await getFreePort();
  100. }
  101. var proxies = nodes.map(nodeToYaml).toList();
  102. var proxyGroups = '''
  103. proxy-groups:
  104. - name: proxy
  105. type: select
  106. proxies:
  107. - ${nodes.map((node) => node.name).join('\n - ')}
  108. ''';
  109. var rules = '''
  110. rules:
  111. - GEOIP,CN,DIRECT
  112. - MATCH,proxy
  113. ''';
  114. var initconfig = '''
  115. mixed-port: $mixedport
  116. allow-lan: true
  117. bind-address: '*'
  118. mode: Rule
  119. log-level: info
  120. external-controller: '127.0.0.1:$extePort'
  121. unified-delay: false
  122. geodata-mode: true
  123. tcp-concurrent: false
  124. find-process-mode: strict
  125. global-client-fingerprint: chrome
  126. dns:
  127. nameserver:
  128. - 114.114.114.114
  129. - 119.29.29.29
  130. - https://doh.pub/dns-query
  131. - https://dns.alidns.com/dns-query
  132. fallback:
  133. - https://dns.cloudflare.com/dns-query
  134. - "[2001:da8::666]:53"
  135. - https://public.dns.iij.jp/dns-query
  136. - https://jp.tiar.app/dns-query
  137. - https://jp.tiarap.org/dns-query
  138. - tls://dot.tiar.app
  139. enable: true
  140. ipv6: false
  141. # enhanced-mode: redir-host
  142. enhanced-mode: fake-ip
  143. fake-ip-range: 198.18.0.1/16
  144. listen: 0.0.0.0:$dnsPort
  145. fake-ip-filter:
  146. - "*.lan"
  147. default-nameserver:
  148. - 114.114.114.114
  149. - 119.29.29.29
  150. - "[2001:da8::666]:53"
  151. tun:
  152. enable: ${clashCoreTunEnable.value}
  153. stack: $stack
  154. # stack: gvisor
  155. dns-hijack:
  156. - 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
  157. auto-route: true # auto set global route for Windows
  158. # It is recommended to use `interface-name`
  159. auto-detect-interface: true # auto detect interface, conflict with `interface-name`
  160. proxies:
  161. ${proxies.join('\n')}
  162. $proxyGroups
  163. $rules
  164. ''';
  165. await Files.makeProxyConfig.writeAsString(initconfig);
  166. config.value.selected = 'proxy.yaml';
  167. // await readClashCoreApi();
  168. }
  169. Future<void> save() async {
  170. await Files.configConfig.writeAsString(json.encode(config.toJson()));
  171. }
  172. Future<void> readClashCoreApi() async {
  173. final configStr = await File(path.join(Paths.config.path, config.value.selected)).readAsString();
  174. // final emoji = EmojiParser();
  175. // final b = emoji.unemojify(_config);
  176. final configJson = loadYaml(configStr.replaceAll(EmojiParser.REGEX_EMOJI, 'emoji'));
  177. // print(_json["external-controller"]);
  178. // https://github.com/dart-lang/yaml/issues/53
  179. // final _extControl = RegExp(r'''(?<!#\s*)external-controller:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  180. // final _secret = RegExp(r'''(?<!#\s*)secret:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  181. clashCoreApiAddress.value = (configJson["external-controller"] ?? '127.0.0.1:9090').replaceAll('0.0.0.0', '127.0.0.1');
  182. clashCoreApiSecret.value = (configJson["secret"] ?? '');
  183. clashCoreTunEnable.value = configJson["tun"]?["enable"] == true;
  184. clashCoreDns.value = '';
  185. if (configJson["dns"]?["enable"] == true && (configJson["dns"]["listen"] ?? '').isNotEmpty) {
  186. final dns = (configJson["dns"]["listen"] as String).split(":");
  187. final ip = dns[0];
  188. final port = dns[1];
  189. if (port == '53') {
  190. clashCoreDns.value = ip == '0.0.0.0' ? '127.0.0.1' : ip;
  191. }
  192. }
  193. }
  194. Future<void> setLanguage(String language) async {
  195. config.value.language = language;
  196. await save();
  197. config.refresh();
  198. }
  199. Future<void> setSystemProxy(bool open) async {
  200. config.value.setSystemProxy = open;
  201. await save();
  202. config.refresh();
  203. }
  204. Future<void> setUpdateInterval(int value) async {
  205. config.value.updateInterval = value;
  206. await save();
  207. config.refresh();
  208. }
  209. Future<void> setUpdateSubsAtStart(bool value) async {
  210. config.value.updateSubsAtStart = value;
  211. await save();
  212. config.refresh();
  213. }
  214. Future<void> setSelectd(String selected) async {
  215. config.value.selected = selected;
  216. await save();
  217. config.refresh();
  218. }
  219. Future<bool> updateSub(ConfigSub sub) async {
  220. if ((sub.url ?? '').isEmpty) return false;
  221. final res = await dio.get(sub.url!);
  222. final subInfo = res.headers['subscription-userinfo'];
  223. final file = File(path.join(Paths.config.path, sub.name));
  224. final oldConfig = await file.exists() ? await file.readAsString() : '';
  225. final changed = oldConfig != res.data;
  226. if (changed) await file.writeAsString(res.data);
  227. sub.updateTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  228. sub.info = null;
  229. if (subInfo != null) {
  230. // final info = Map.fromEntries(
  231. // subInfo.first.split(RegExp(r';\s*')).where((s) => s.isNotEmpty).map((e) => e.split('=')).map((e) => MapEntry(e[0], int.parse(e[1]))));
  232. final entries = subInfo.first.split(RegExp(r';\s*'))
  233. .where((s) => s.isNotEmpty)
  234. .map((e) => e.split('='))
  235. .toList();
  236. final info = <String, dynamic>{};
  237. for (var entry in entries) {
  238. info[entry[0]] = int.parse(entry[1]);
  239. }
  240. sub.info = ConfigSubInfo.fromJson(info);
  241. }
  242. await setSub(sub.name, sub);
  243. return changed;
  244. }
  245. Future<void> setSub(String subName, ConfigSub sub) async {
  246. final idx = config.value.subs.indexWhere((it) => it.name == subName);
  247. config.value.subs[idx] = sub;
  248. if (subName != sub.name) {
  249. final file = File(path.join(Paths.config.path, subName));
  250. if (await file.exists()) await file.rename(path.join(Paths.config.path, sub.name));
  251. }
  252. await save();
  253. config.refresh();
  254. }
  255. Future<void> addSub(ConfigSub sub) async {
  256. config.value.subs.add(sub);
  257. final file = File(path.join(Paths.config.path, sub.name));
  258. if (!await file.exists()) await file.create();
  259. await save();
  260. config.refresh();
  261. }
  262. Future<void> deleteSub(String subName) async {
  263. final file = File(path.join(Paths.config.path, subName));
  264. if (await file.exists()) await file.delete();
  265. config.value.subs.removeWhere((it) => it.name == subName);
  266. await save();
  267. config.refresh();
  268. }
  269. Future<void> setBreakConnections(bool value) async {
  270. config.value.breakConnections = value;
  271. await save();
  272. config.refresh();
  273. }
  274. Future<int> getFreePort() async {
  275. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  276. int port = server.port;
  277. await server.close();
  278. return port;
  279. }
  280. Future<bool> isPortOccupied(int port) async {
  281. bool isOccupied = false;
  282. ServerSocket? server;
  283. try {
  284. server = await ServerSocket.bind(InternetAddress.loopbackIPv4, port);
  285. } catch (e) {
  286. isOccupied = true;
  287. } finally {
  288. await server?.close();
  289. }
  290. return isOccupied;
  291. }
  292. }