You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConfigConverter.cs 9.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using Shadowsocks.Interop.Utils;
  2. using Shadowsocks.Models;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Json;
  9. using System.Text.Json;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace Shadowsocks.CLI
  13. {
  14. public class ConfigConverter
  15. {
  16. /// <summary>
  17. /// Gets or sets whether to prefix group name to server names.
  18. /// </summary>
  19. public bool PrefixGroupName { get; set; }
  20. /// <summary>
  21. /// Gets or sets the list of servers that are not in any groups.
  22. /// </summary>
  23. public List<Server> Servers { get; set; } = new();
  24. public ConfigConverter(bool prefixGroupName = false) => PrefixGroupName = prefixGroupName;
  25. /// <summary>
  26. /// Collects servers from ss:// links or SIP008 delivery links.
  27. /// </summary>
  28. /// <param name="uris">URLs to collect servers from.</param>
  29. /// <param name="cancellationToken">A token that may be used to cancel the asynchronous operation.</param>
  30. /// <returns>A task that represents the asynchronous operation.</returns>
  31. public async Task FromUrls(IEnumerable<Uri> uris, CancellationToken cancellationToken = default)
  32. {
  33. var sip008Links = new List<Uri>();
  34. foreach (var uri in uris)
  35. {
  36. switch (uri.Scheme)
  37. {
  38. case "ss":
  39. {
  40. if (Server.TryParse(uri, out var server))
  41. Servers.Add(server);
  42. break;
  43. }
  44. case "https":
  45. sip008Links.Add(uri);
  46. break;
  47. }
  48. }
  49. if (sip008Links.Count > 0)
  50. {
  51. var httpClient = new HttpClient
  52. {
  53. Timeout = TimeSpan.FromSeconds(30.0)
  54. };
  55. var tasks = sip008Links.Select(async x => await httpClient.GetFromJsonAsync<Group>(x, JsonHelper.snakeCaseJsonDeserializerOptions, cancellationToken))
  56. .ToList();
  57. while (tasks.Count > 0)
  58. {
  59. var finishedTask = await Task.WhenAny(tasks);
  60. var group = await finishedTask;
  61. if (group != null)
  62. Servers.AddRange(group.Servers);
  63. tasks.Remove(finishedTask);
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// Collects servers from SIP008 JSON files.
  69. /// </summary>
  70. /// <param name="paths">JSON file paths.</param>
  71. /// <param name="cancellationToken">A token that may be used to cancel the read operation.</param>
  72. /// <returns>A task that represents the asynchronous read operation.</returns>
  73. public async Task FromSip008Json(IEnumerable<string> paths, CancellationToken cancellationToken = default)
  74. {
  75. foreach (var path in paths)
  76. {
  77. using var jsonFile = new FileStream(path, FileMode.Open);
  78. var group = await JsonSerializer.DeserializeAsync<Group>(jsonFile, JsonHelper.snakeCaseJsonDeserializerOptions, cancellationToken);
  79. if (group != null)
  80. {
  81. if (PrefixGroupName && !string.IsNullOrEmpty(group.Name))
  82. group.Servers.ForEach(x => x.Name = $"{group.Name} - {x.Name}");
  83. Servers.AddRange(group.Servers);
  84. }
  85. }
  86. }
  87. /// <summary>
  88. /// Collects servers from outbounds in V2Ray JSON files.
  89. /// </summary>
  90. /// <param name="paths">JSON file paths.</param>
  91. /// <param name="cancellationToken">A token that may be used to cancel the read operation.</param>
  92. /// <returns>A task that represents the asynchronous read operation.</returns>
  93. public async Task FromV2rayJson(IEnumerable<string> paths, CancellationToken cancellationToken = default)
  94. {
  95. foreach (var path in paths)
  96. {
  97. using var jsonFile = new FileStream(path, FileMode.Open);
  98. var v2rayConfig = await JsonSerializer.DeserializeAsync<Interop.V2Ray.Config>(jsonFile, JsonHelper.camelCaseJsonDeserializerOptions, cancellationToken);
  99. if (v2rayConfig?.Outbounds != null)
  100. {
  101. foreach (var outbound in v2rayConfig.Outbounds)
  102. {
  103. if (outbound.Protocol == "shadowsocks"
  104. && outbound.Settings is JsonElement jsonElement)
  105. {
  106. var jsonText = jsonElement.GetRawText();
  107. var ssConfig = JsonSerializer.Deserialize<Interop.V2Ray.Protocols.Shadowsocks.OutboundConfigurationObject>(jsonText, JsonHelper.camelCaseJsonDeserializerOptions);
  108. if (ssConfig != null)
  109. foreach (var ssServer in ssConfig.Servers)
  110. {
  111. var server = new Server
  112. {
  113. Name = outbound.Tag,
  114. Host = ssServer.Address,
  115. Port = ssServer.Port,
  116. Method = ssServer.Method,
  117. Password = ssServer.Password
  118. };
  119. Servers.Add(server);
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. /// <summary>
  127. /// Converts saved servers to ss:// URLs.
  128. /// </summary>
  129. /// <returns>A list of ss:// URLs.</returns>
  130. public List<Uri> ToUrls()
  131. {
  132. var urls = new List<Uri>();
  133. foreach (var server in Servers)
  134. urls.Add(server.ToUrl());
  135. return urls;
  136. }
  137. /// <summary>
  138. /// Converts saved servers to SIP008 JSON.
  139. /// </summary>
  140. /// <param name="path">JSON file path.</param>
  141. /// <param name="cancellationToken">A token that may be used to cancel the write operation.</param>
  142. /// <returns>A task that represents the asynchronous write operation.</returns>
  143. public Task ToSip008Json(string path, CancellationToken cancellationToken = default)
  144. {
  145. var group = new Group();
  146. group.Servers.AddRange(Servers);
  147. var fullPath = Path.GetFullPath(path);
  148. var directoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException("Invalid path", nameof(path));
  149. Directory.CreateDirectory(directoryPath);
  150. using var jsonFile = new FileStream(fullPath, FileMode.Create);
  151. return JsonSerializer.SerializeAsync(jsonFile, group, JsonHelper.snakeCaseJsonSerializerOptions, cancellationToken);
  152. }
  153. /// <summary>
  154. /// Converts saved servers to V2Ray outbounds.
  155. /// </summary>
  156. /// <param name="path">JSON file path.</param>
  157. /// <param name="prefixGroupName">Whether to prefix group name to server names.</param>
  158. /// <param name="cancellationToken">A token that may be used to cancel the write operation.</param>
  159. /// <returns>A task that represents the asynchronous write operation.</returns>
  160. public Task ToV2rayJson(string path, CancellationToken cancellationToken = default)
  161. {
  162. var v2rayConfig = new Interop.V2Ray.Config
  163. {
  164. Outbounds = new()
  165. };
  166. foreach (var server in Servers)
  167. {
  168. var ssOutbound = Interop.V2Ray.OutboundObject.GetShadowsocks(server);
  169. v2rayConfig.Outbounds.Add(ssOutbound);
  170. }
  171. // enforce outbound tag uniqueness
  172. var serversWithDuplicateTags = v2rayConfig.Outbounds.GroupBy(x => x.Tag)
  173. .Where(x => x.Count() > 1);
  174. foreach (var serversWithSameTag in serversWithDuplicateTags)
  175. {
  176. var duplicates = serversWithSameTag.ToList();
  177. for (var i = 0; i < duplicates.Count; i++)
  178. {
  179. duplicates[i].Tag = $"{duplicates[i].Tag} {i}";
  180. }
  181. }
  182. var fullPath = Path.GetFullPath(path);
  183. var directoryPath = Path.GetDirectoryName(fullPath) ?? throw new ArgumentException("Invalid path", nameof(path));
  184. Directory.CreateDirectory(directoryPath);
  185. using var jsonFile = new FileStream(fullPath, FileMode.Create);
  186. return JsonSerializer.SerializeAsync(jsonFile, v2rayConfig, JsonHelper.camelCaseJsonSerializerOptions, cancellationToken);
  187. }
  188. }
  189. }