config.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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:naiyouwl/app/controller/controllers.dart';
  8. import 'package:yaml/yaml.dart';
  9. import 'package:path/path.dart' as path;
  10. import 'package:flutter_emoji/flutter_emoji.dart';
  11. import '../data/model/NodeMode.dart';
  12. final Map<String, dynamic> _defaultConfig = {
  13. 'selected': 'example.yaml',
  14. 'updateInterval': 86400,
  15. 'updateSubsAtStart': false,
  16. 'setSystemProxy': false,
  17. 'startAtLogin': false,
  18. 'breakConnections': false,
  19. 'language': 'zh_CN',
  20. 'port': 9899,
  21. 'subs': [],
  22. };
  23. class ConfigController extends GetxController {
  24. late final dio;
  25. var config = Config.fromJson(_defaultConfig).obs;
  26. var clashCoreApiAddress = '127.0.0.1:9090'.obs;
  27. var clashCoreApiSecret = ''.obs;
  28. var clashCoreDns = ''.obs;
  29. var clashCoreTunEnable = false.obs;
  30. var servicePort = 9899.obs;
  31. var mixedPort = 9788.obs;
  32. var ApiAddressPort = 9799.obs;
  33. Future<void> initConfig() async {
  34. // var port = await getFreePort();
  35. //dio.addSentry();
  36. dio = Dio(BaseOptions(baseUrl: clashCoreApiAddress.value));
  37. if (!await Paths.config.exists()) await Paths.config.create(recursive: true);
  38. if (!await Files.configCountryMmdb.exists()) await Files.assetsCountryMmdb.copy(Files.configCountryMmdb.path);
  39. if (!await Files.configGeoIP.exists()) await Files.assetsGeoIP.copy(Files.configGeoIP.path);
  40. if (!await Files.configGeosite.exists()) await Files.assetsGeosite.copy(Files.configGeosite.path);
  41. if (Platform.isWindows && !await Files.configWintun.exists()) await Files.assetsWintun.copy(Files.configWintun.path);
  42. final locale = Get.deviceLocale!;
  43. _defaultConfig['language'] = '${locale.languageCode}_${locale.countryCode}';
  44. if (await Files.configConfig.exists()) {
  45. final local = json.decode(await Files.configConfig.readAsString());
  46. config.value = Config.fromJson({..._defaultConfig, ...local});
  47. } else {
  48. config.value = Config.fromJson(_defaultConfig);
  49. }
  50. // bool bg = await isPortOccupied(config.value.servicePort);
  51. // if(bg) {
  52. // config.value.servicePort = await getFreePort();
  53. // }
  54. if (config.value.subs.isEmpty) {
  55. if (!await Files.configExample.exists()) {
  56. await Files.assetsExample.copy(Files.configExample.path);
  57. }
  58. config.value.subs.add(ConfigSub(name: 'example.yaml', url: '', updateTime: 0));
  59. config.value.selected = 'example.yaml';
  60. }
  61. await save();
  62. await makeInitConfig();
  63. }
  64. String nodeToYaml(NodeMode node) {
  65. switch (node.type) {
  66. case 'trojan':
  67. return ''' - { name: ${node.name}, type: ${node.type}, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, udp: 1 }''';
  68. case 'shadowsocks':
  69. return ''' - { name: ${node.name}, type: ss, server: ${node.host}, port: ${node.port}, password: ${node.passwd}, cipher: ${node.method}, udp: 1 }''';
  70. case 'v2ray':
  71. final type = (node.vless == 1) ? 'vless' : 'vmess';
  72. if (type == 'vless') {
  73. 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} } }''';
  74. } else {
  75. return ''' - { name: ${node.name}, type: $type, server: ${node.host}, port: ${node.port}, uuid: ${node.uuid}, alterId: ${node.v2AlterId}, cipher: ${node.method}, udp: 1 }''';
  76. }
  77. default:
  78. return '';
  79. }
  80. }
  81. Future<void> makeInitConfig() async{
  82. var mode = controllers.global.modesSelect;
  83. var initconfig = '''
  84. mixed-port: ${mixedPort.value}
  85. allow-lan: true
  86. bind-address: '*'
  87. mode: $mode
  88. log-level: info
  89. external-controller: '127.0.0.1:${ApiAddressPort.value}'
  90. unified-delay: false
  91. geodata-mode: true
  92. tcp-concurrent: false
  93. find-process-mode: strict
  94. global-client-fingerprint: chrome
  95. proxies:
  96. rules:
  97. - GEOIP,CN,DIRECT
  98. - MATCH,DIRECT
  99. ''';
  100. await Files.makeInitProxyConfig.writeAsString(initconfig);
  101. config.value.selected = 'init_proxy.yaml';
  102. await readClashCoreApi();
  103. }
  104. Future<void> makeClashConfig(List<NodeMode> nodes) async{
  105. // if( Files.makeProxyConfig.existsSync()){
  106. // Files.makeProxyConfig.deleteSync(recursive: true);
  107. // }
  108. var stack = "system";
  109. if( Platform.isWindows){
  110. stack = "gvisor";
  111. }
  112. var dnsPort = 1553;
  113. if(clashCoreTunEnable.value == true)
  114. {
  115. dnsPort = 53;
  116. }
  117. var dnsEnab = false;
  118. if(clashCoreTunEnable.value == true){
  119. dnsEnab = true;
  120. }
  121. var mode = controllers.global.modesSelect;
  122. var proxies = nodes.map(nodeToYaml).toList();
  123. var proxyGroups = '''
  124. proxy-groups:
  125. - name: proxy
  126. type: select
  127. proxies:
  128. - ${nodes.map((node) => node.name).join('\n - ')}
  129. ''';
  130. var rules = '''
  131. rules:
  132. - GEOSITE,OpenAI,proxy
  133. - GEOSITE,TikTok,proxy
  134. - GEOSITE,github,proxy
  135. - GEOSITE,twitter,proxy
  136. - GEOSITE,youtube,proxy
  137. - GEOSITE,google,proxy
  138. - GEOSITE,telegram,proxy
  139. - GEOSITE,netflix,proxy
  140. - GEOSITE,geolocation-!cn,proxy
  141. - GEOSITE,cn,DIRECT
  142. - GEOIP,google,proxy
  143. - GEOIP,netflix,proxy
  144. - GEOIP,telegram,proxy
  145. - GEOIP,twitter,proxy
  146. - GEOIP,CN,DIRECT
  147. - MATCH,proxy
  148. ''';
  149. var initconfig = '''
  150. mixed-port: ${mixedPort.value}
  151. allow-lan: true
  152. bind-address: '*'
  153. mode: $mode
  154. log-level: info
  155. external-controller: '127.0.0.1:${ApiAddressPort.value}'
  156. unified-delay: false
  157. geodata-mode: true
  158. tcp-concurrent: false
  159. find-process-mode: strict
  160. global-client-fingerprint: chrome
  161. dns:
  162. nameserver:
  163. - 114.114.114.114
  164. - 119.29.29.29
  165. - https://doh.pub/dns-query
  166. - https://dns.alidns.com/dns-query
  167. fallback:
  168. - https://dns.cloudflare.com/dns-query
  169. - "[2001:da8::666]:53"
  170. - https://public.dns.iij.jp/dns-query
  171. - https://jp.tiar.app/dns-query
  172. - https://jp.tiarap.org/dns-query
  173. - tls://dot.tiar.app
  174. enable: $dnsEnab
  175. ipv6: false
  176. # enhanced-mode: redir-host
  177. enhanced-mode: fake-ip
  178. fake-ip-range: 198.18.0.1/16
  179. listen: 0.0.0.0:$dnsPort
  180. fake-ip-filter:
  181. - "*.lan"
  182. default-nameserver:
  183. - 114.114.114.114
  184. - 119.29.29.29
  185. - "[2001:da8::666]:53"
  186. tun:
  187. enable: ${clashCoreTunEnable.value}
  188. stack: $stack
  189. # stack: gvisor
  190. dns-hijack:
  191. - 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
  192. auto-route: true # auto set global route for Windows
  193. # It is recommended to use `interface-name`
  194. auto-detect-interface: true # auto detect interface, conflict with `interface-name`
  195. proxies:
  196. ${proxies.join('\n')}
  197. $proxyGroups
  198. $rules
  199. ''';
  200. await Files.makeProxyConfig.writeAsString(initconfig);
  201. config.value.selected = 'proxy.yaml';
  202. await readClashCoreApi();
  203. }
  204. Future<void> save() async {
  205. await Files.configConfig.writeAsString(json.encode(config.toJson()));
  206. }
  207. Future<void> readClashCoreApi() async {
  208. final configStr = await File(path.join(Paths.config.path, config.value.selected)).readAsString();
  209. // final emoji = EmojiParser();
  210. // final b = emoji.unemojify(_config);
  211. final configJson = loadYaml(configStr.replaceAll(EmojiParser.REGEX_EMOJI, 'emoji'));
  212. // print(_json["external-controller"]);
  213. // https://github.com/dart-lang/yaml/issues/53
  214. // final _extControl = RegExp(r'''(?<!#\s*)external-controller:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  215. // final _secret = RegExp(r'''(?<!#\s*)secret:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  216. clashCoreApiAddress.value = (configJson["external-controller"] ?? '127.0.0.1:9090').replaceAll('0.0.0.0', '127.0.0.1');
  217. clashCoreApiSecret.value = (configJson["secret"] ?? '');
  218. clashCoreTunEnable.value = configJson["tun"]?["enable"] == true;
  219. clashCoreDns.value = '';
  220. if (configJson["dns"]?["enable"] == true && (configJson["dns"]["listen"] ?? '').isNotEmpty) {
  221. final dns = (configJson["dns"]["listen"] as String).split(":");
  222. final ip = dns[0];
  223. final port = dns[1];
  224. if (port == '53') {
  225. clashCoreDns.value = ip == '0.0.0.0' ? '127.0.0.1' : ip;
  226. }
  227. }
  228. }
  229. Future<void> setSerivcePort(int port) async {
  230. config.value.servicePort = port;
  231. await save();
  232. config.refresh();
  233. }
  234. Future<void> setLanguage(String language) async {
  235. config.value.language = language;
  236. await save();
  237. config.refresh();
  238. }
  239. Future<void> setSystemProxy(bool open) async {
  240. config.value.setSystemProxy = open;
  241. await save();
  242. config.refresh();
  243. }
  244. Future<void> setUpdateInterval(int value) async {
  245. config.value.updateInterval = value;
  246. await save();
  247. config.refresh();
  248. }
  249. Future<void> setUpdateSubsAtStart(bool value) async {
  250. config.value.updateSubsAtStart = value;
  251. await save();
  252. config.refresh();
  253. }
  254. Future<void> setSelectd(String selected) async {
  255. config.value.selected = selected;
  256. await save();
  257. config.refresh();
  258. }
  259. Future<bool> updateSub(ConfigSub sub) async {
  260. if ((sub.url ?? '').isEmpty) return false;
  261. final res = await dio.get(sub.url!);
  262. final subInfo = res.headers['subscription-userinfo'];
  263. final file = File(path.join(Paths.config.path, sub.name));
  264. final oldConfig = await file.exists() ? await file.readAsString() : '';
  265. final changed = oldConfig != res.data;
  266. if (changed) await file.writeAsString(res.data);
  267. sub.updateTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  268. sub.info = null;
  269. if (subInfo != null) {
  270. // final info = Map.fromEntries(
  271. // subInfo.first.split(RegExp(r';\s*')).where((s) => s.isNotEmpty).map((e) => e.split('=')).map((e) => MapEntry(e[0], int.parse(e[1]))));
  272. final entries = subInfo.first.split(RegExp(r';\s*'))
  273. .where((s) => s.isNotEmpty)
  274. .map((e) => e.split('='))
  275. .toList();
  276. final info = <String, dynamic>{};
  277. for (var entry in entries) {
  278. info[entry[0]] = int.parse(entry[1]);
  279. }
  280. sub.info = ConfigSubInfo.fromJson(info);
  281. }
  282. await setSub(sub.name, sub);
  283. return changed;
  284. }
  285. Future<void> setSub(String subName, ConfigSub sub) async {
  286. final idx = config.value.subs.indexWhere((it) => it.name == subName);
  287. config.value.subs[idx] = sub;
  288. if (subName != sub.name) {
  289. final file = File(path.join(Paths.config.path, subName));
  290. if (await file.exists()) await file.rename(path.join(Paths.config.path, sub.name));
  291. }
  292. await save();
  293. config.refresh();
  294. }
  295. Future<void> addSub(ConfigSub sub) async {
  296. config.value.subs.add(sub);
  297. final file = File(path.join(Paths.config.path, sub.name));
  298. if (!await file.exists()) await file.create();
  299. await save();
  300. config.refresh();
  301. }
  302. Future<void> deleteSub(String subName) async {
  303. final file = File(path.join(Paths.config.path, subName));
  304. if (await file.exists()) await file.delete();
  305. config.value.subs.removeWhere((it) => it.name == subName);
  306. await save();
  307. config.refresh();
  308. }
  309. Future<void> setBreakConnections(bool value) async {
  310. config.value.breakConnections = value;
  311. await save();
  312. config.refresh();
  313. }
  314. Future<void> portDetection() async {
  315. bool isOk = await isPortOccupied(mixedPort.value);
  316. if(isOk){
  317. mixedPort.value = await getFreePort();
  318. }
  319. //await Future.delayed(const Duration(seconds: 5)); // 等待5秒
  320. isOk = await isPortOccupied(ApiAddressPort.value);
  321. if(isOk){
  322. ApiAddressPort.value = await getFreePort();
  323. }
  324. //await Future.delayed(const Duration(seconds: 5)); // 等待5秒
  325. if(!controllers.service.isRunning){
  326. isOk = await isPortOccupied(servicePort.value);
  327. if(isOk){
  328. servicePort.value = await getFreePort();
  329. }
  330. }
  331. }
  332. Future<int> getFreePort() async {
  333. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  334. int port = server.port;
  335. await server.close();
  336. return port;
  337. }
  338. Future<bool> isPortOccupied(int port) async {
  339. bool isOccupied = false;
  340. ServerSocket? server;
  341. try {
  342. server = await ServerSocket.bind(InternetAddress.loopbackIPv4, port);
  343. } catch (e) {
  344. isOccupied = true;
  345. } finally {
  346. await server?.close();
  347. }
  348. return isOccupied;
  349. }
  350. }