config.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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:9799'.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: ${node.v2Sni}, 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. //
  82. Future<void> makeInitConfig() async{
  83. var mode = controllers.global.modesSelect;
  84. var initconfig = '''
  85. mixed-port: ${mixedPort.value}
  86. allow-lan: true
  87. bind-address: '*'
  88. mode: $mode
  89. log-level: info
  90. external-controller: '127.0.0.1:${ApiAddressPort.value}'
  91. unified-delay: false
  92. geodata-mode: true
  93. tcp-concurrent: false
  94. find-process-mode: strict
  95. global-client-fingerprint: chrome
  96. proxies:
  97. rules:
  98. - GEOIP,CN,DIRECT
  99. - MATCH,DIRECT
  100. ''';
  101. await Files.makeInitProxyConfig.writeAsString(initconfig);
  102. config.value.selected = 'init_proxy.yaml';
  103. await readClashCoreApi();
  104. }
  105. Future<void> makeClashConfig(List<NodeMode> nodes) async{
  106. // if( Files.makeProxyConfig.existsSync()){
  107. // Files.makeProxyConfig.deleteSync(recursive: true);
  108. // }
  109. //await portDetection();
  110. var stack = "system";
  111. if( Platform.isWindows){
  112. stack = "gvisor";
  113. }
  114. var dnsPort = 1035;
  115. if(clashCoreTunEnable.value == true)
  116. {
  117. dnsPort = 1035;
  118. }
  119. var dnsEnab = true;
  120. if(clashCoreTunEnable.value == true){
  121. dnsEnab = true;
  122. }
  123. var mode = controllers.global.modesSelect;
  124. var proxies = nodes.map(nodeToYaml).toList();
  125. var proxyGroups = '''
  126. proxy-groups:
  127. - name: proxy
  128. type: select
  129. proxies:
  130. - ${nodes.map((node) => node.name).join('\n - ')}
  131. ''';
  132. var rules = '''
  133. rules:
  134. - GEOSITE,geolocation-!cn,proxy
  135. - GEOSITE,cn,DIRECT
  136. - GEOIP,CN,DIRECT
  137. - MATCH,proxy
  138. ''';
  139. //
  140. var initconfig = '''
  141. mixed-port: ${mixedPort.value}
  142. allow-lan: true
  143. bind-address: '*'
  144. mode: $mode
  145. log-level: info
  146. external-controller: '127.0.0.1:${ApiAddressPort.value}'
  147. unified-delay: false
  148. geodata-mode: true
  149. tcp-concurrent: false
  150. find-process-mode: strict
  151. global-client-fingerprint: chrome
  152. dns:
  153. enable: $dnsEnab
  154. listen: :$dnsPort
  155. ipv6: false
  156. enhanced-mode: redir-host
  157. # fake-ip-range: 28.0.0.1/8
  158. # fake-ip-filter:
  159. # - '*'
  160. # - '+.lan'
  161. default-nameserver:
  162. - 119.29.29.29
  163. - 223.5.5.5
  164. nameserver:
  165. - 'tls://8.8.4.4#proxy'
  166. - 'https://1.0.0.1/dns-query#proxy'
  167. proxy-server-nameserver:
  168. - tls://223.5.5.5
  169. nameserver-policy:
  170. "geosite:cn": [tls://119.29.29.29, tls://223.5.5.5]
  171. tun:
  172. enable: ${clashCoreTunEnable.value}
  173. stack: $stack
  174. # stack: gvisor
  175. #dns-hijack:
  176. # - 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
  177. auto-route: true # auto set global route for Windows
  178. # It is recommended to use `interface-name`
  179. auto-detect-interface: true # auto detect interface, conflict with `interface-name`
  180. proxies:
  181. ${proxies.join('\n')}
  182. $proxyGroups
  183. $rules
  184. ''';
  185. await Files.makeProxyConfig.writeAsString(initconfig);
  186. config.value.selected = 'proxy.yaml';
  187. await readClashCoreApi();
  188. }
  189. Future<void> save() async {
  190. await Files.configConfig.writeAsString(json.encode(config.toJson()));
  191. }
  192. Future<void> readClashCoreApi() async {
  193. final configStr = await File(path.join(Paths.config.path, config.value.selected)).readAsString();
  194. //print("config ---- $configStr");
  195. // final emoji = EmojiParser();
  196. // final b = emoji.unemojify(_config);
  197. final configJson = loadYaml(configStr.replaceAll(EmojiParser.REGEX_EMOJI, 'emoji'));
  198. // print(_json["external-controller"]);
  199. // https://github.com/dart-lang/yaml/issues/53
  200. // final _extControl = RegExp(r'''(?<!#\s*)external-controller:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  201. // final _secret = RegExp(r'''(?<!#\s*)secret:\s+['"]?([^'"]+?)['"]?\s''').firstMatch(_config)?.group(1);
  202. clashCoreApiAddress.value = configJson["external-controller"] ?? '127.0.0.1:9090';
  203. print("clash api address ${clashCoreApiAddress.value}");
  204. clashCoreApiSecret.value = (configJson["secret"] ?? '');
  205. mixedPort.value = (configJson["mixed-port"] ?? 9788);
  206. clashCoreTunEnable.value = configJson["tun"]?["enable"] == true;
  207. clashCoreDns.value = '';
  208. if (configJson["dns"]?["enable"] == true && (configJson["dns"]["listen"] ?? '').isNotEmpty) {
  209. final dns = (configJson["dns"]["listen"] as String).split(":");
  210. final ip = dns[0];
  211. final port = dns[1];
  212. if (port == '53') {
  213. clashCoreDns.value = ip == '0.0.0.0' ? '127.0.0.1' : ip;
  214. }
  215. }
  216. }
  217. Future<void> setSerivcePort(int port) async {
  218. config.value.servicePort = port;
  219. await save();
  220. config.refresh();
  221. }
  222. Future<void> setLanguage(String language) async {
  223. config.value.language = language;
  224. await save();
  225. config.refresh();
  226. }
  227. Future<void> setSystemProxy(bool open) async {
  228. config.value.setSystemProxy = open;
  229. await save();
  230. config.refresh();
  231. }
  232. Future<void> setUpdateInterval(int value) async {
  233. config.value.updateInterval = value;
  234. await save();
  235. config.refresh();
  236. }
  237. Future<void> setUpdateSubsAtStart(bool value) async {
  238. config.value.updateSubsAtStart = value;
  239. await save();
  240. config.refresh();
  241. }
  242. Future<void> setSelectd(String selected) async {
  243. config.value.selected = selected;
  244. await save();
  245. config.refresh();
  246. }
  247. Future<void> setSerivePort(int port) async {
  248. config.value.servicePort = port;
  249. await save();
  250. config.refresh();
  251. }
  252. Future<bool> updateSub(ConfigSub sub) async {
  253. if ((sub.url ?? '').isEmpty) return false;
  254. final res = await dio.get(sub.url!);
  255. final subInfo = res.headers['subscription-userinfo'];
  256. final file = File(path.join(Paths.config.path, sub.name));
  257. final oldConfig = await file.exists() ? await file.readAsString() : '';
  258. final changed = oldConfig != res.data;
  259. if (changed) await file.writeAsString(res.data);
  260. sub.updateTime = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  261. sub.info = null;
  262. if (subInfo != null) {
  263. // final info = Map.fromEntries(
  264. // subInfo.first.split(RegExp(r';\s*')).where((s) => s.isNotEmpty).map((e) => e.split('=')).map((e) => MapEntry(e[0], int.parse(e[1]))));
  265. final entries = subInfo.first.split(RegExp(r';\s*'))
  266. .where((s) => s.isNotEmpty)
  267. .map((e) => e.split('='))
  268. .toList();
  269. final info = <String, dynamic>{};
  270. for (var entry in entries) {
  271. info[entry[0]] = int.parse(entry[1]);
  272. }
  273. sub.info = ConfigSubInfo.fromJson(info);
  274. }
  275. await setSub(sub.name, sub);
  276. return changed;
  277. }
  278. Future<void> setSub(String subName, ConfigSub sub) async {
  279. final idx = config.value.subs.indexWhere((it) => it.name == subName);
  280. config.value.subs[idx] = sub;
  281. if (subName != sub.name) {
  282. final file = File(path.join(Paths.config.path, subName));
  283. if (await file.exists()) await file.rename(path.join(Paths.config.path, sub.name));
  284. }
  285. await save();
  286. config.refresh();
  287. }
  288. Future<void> addSub(ConfigSub sub) async {
  289. config.value.subs.add(sub);
  290. final file = File(path.join(Paths.config.path, sub.name));
  291. if (!await file.exists()) await file.create();
  292. await save();
  293. config.refresh();
  294. }
  295. Future<void> deleteSub(String subName) async {
  296. final file = File(path.join(Paths.config.path, subName));
  297. if (await file.exists()) await file.delete();
  298. config.value.subs.removeWhere((it) => it.name == subName);
  299. await save();
  300. config.refresh();
  301. }
  302. Future<void> setBreakConnections(bool value) async {
  303. config.value.breakConnections = value;
  304. await save();
  305. config.refresh();
  306. }
  307. Future<void> portDetection() async {
  308. bool isOk = await isPortOccupied(mixedPort.value);
  309. if(isOk){
  310. mixedPort.value = await getFreePort();
  311. }
  312. //await Future.delayed(const Duration(seconds: 5)); // 等待5秒
  313. isOk = await isPortOccupied(ApiAddressPort.value);
  314. if(isOk){
  315. ApiAddressPort.value = await getFreePort();
  316. }
  317. //await Future.delayed(const Duration(seconds: 5)); // 等待5秒
  318. // if(!controllers.service.isRunning){
  319. // isOk = await isPortOccupied(servicePort.value);
  320. // if(isOk){
  321. // servicePort.value = await getFreePort();
  322. // setSerivcePort(servicePort.value);
  323. // }
  324. // }
  325. }
  326. Future<int> getFreePort() async {
  327. var server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
  328. int port = server.port;
  329. await server.close();
  330. return port;
  331. }
  332. Future<bool> isPortOccupied(int port) async {
  333. bool isOccupied = false;
  334. ServerSocket? server;
  335. try {
  336. server = await ServerSocket.bind(InternetAddress.loopbackIPv4, port);
  337. } catch (e) {
  338. isOccupied = true;
  339. } finally {
  340. await server?.close();
  341. }
  342. return isOccupied;
  343. }
  344. }