MdpApiPullImport.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. using System.Text.Json;
  2. using System.Text.RegularExpressions;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  4. internal static class MdpApiPullImport
  5. {
  6. private static readonly Regex Token = new("""'([^']*)'|"([^"]*)"|([^\s'"]+)""");
  7. internal static MdpApiPullPlan Read(string kind, string text, string? selection)
  8. {
  9. if (string.IsNullOrWhiteSpace(text) || text.Length > 65536)
  10. throw new MdpApiPullException("PULL_IMPORT_INVALID");
  11. if (kind == "curl") return Curl(text);
  12. using var json = JsonDocument.Parse(text, new JsonDocumentOptions { MaxDepth = 32 });
  13. return kind switch
  14. {
  15. "openapi" => OpenApi(json.RootElement, selection),
  16. "postman" => Postman(json.RootElement, selection),
  17. _ => throw new MdpApiPullException("PULL_IMPORT_INVALID")
  18. };
  19. }
  20. private static MdpApiPullPlan OpenApi(JsonElement root, string? selection)
  21. {
  22. var server = First(MdpApiPullPlan.Value(root, "servers"));
  23. var endpoint = Text(server, "url");
  24. var paths = MdpApiPullPlan.Value(root, "paths");
  25. if (endpoint is null || paths.ValueKind != JsonValueKind.Object)
  26. throw new MdpApiPullException("PULL_IMPORT_INVALID");
  27. var candidates = new List<(string Path, string Method, JsonElement Operation)>();
  28. foreach (var path in paths.EnumerateObject())
  29. {
  30. foreach (var method in new[] { "get", "post" })
  31. if (path.Value.ValueKind == JsonValueKind.Object && path.Value.TryGetProperty(method, out var operation)
  32. && operation.ValueKind == JsonValueKind.Object)
  33. candidates.Add((path.Name, method, operation));
  34. }
  35. var chosen = Choose(candidates, candidate => candidate.Method.ToUpperInvariant() + " " + candidate.Path, selection);
  36. var query = MdpApiPullPlan.Value(chosen.Operation, "parameters");
  37. var names = query.ValueKind == JsonValueKind.Array ? query.EnumerateArray()
  38. .Where(parameter => Text(parameter, "in") == "query").Select(parameter => Text(parameter, "name")).ToArray() : [];
  39. var mode = names.Contains("cursor") ? "cursor" : names.Contains("offset") ? "offset" : names.Contains("page") ? "page" : "single";
  40. var wire = Build(endpoint.TrimEnd('/') + chosen.Path, chosen.Method);
  41. var security = MdpApiPullPlan.Value(chosen.Operation, "security");
  42. var requirements = First(security.ValueKind == JsonValueKind.Undefined
  43. ? MdpApiPullPlan.Value(root, "security") : security);
  44. if (requirements.ValueKind == JsonValueKind.Object)
  45. {
  46. var identifier = requirements.EnumerateObject().Select(entry => entry.Name).FirstOrDefault();
  47. var schemes = MdpApiPullPlan.Value(root, "components.securitySchemes");
  48. if (identifier is not null && schemes.ValueKind == JsonValueKind.Object && schemes.TryGetProperty(identifier, out var scheme))
  49. wire = wire with { Auth = AuthKind(Text(scheme, "type")) is "none" && Text(scheme, "scheme") == "basic"
  50. ? "basic" : AuthKind(Text(scheme, "type")) };
  51. }
  52. return wire with
  53. {
  54. Mode = mode, PositionParameter = mode == "single" ? "page" : mode,
  55. PageSizeParameter = names.Contains("pageSize") ? "pageSize" : "limit",
  56. FirstPosition = mode == "offset" ? 0 : 1,
  57. NextCursorPath = mode == "cursor" ? "nextCursor" : null,
  58. ResponsePath = OpenApiResponsePath(chosen.Operation)
  59. };
  60. }
  61. private static string OpenApiResponsePath(JsonElement operation)
  62. {
  63. var schema = MdpApiPullPlan.Value(operation, "responses.200.content.application/json.schema");
  64. if (schema.ValueKind != JsonValueKind.Object)
  65. return "";
  66. var arrays = FindArrays(schema, "", 0).Take(2).ToArray();
  67. return arrays.Length == 1 ? arrays[0] : "";
  68. static IEnumerable<string> FindArrays(JsonElement current, string path, int depth)
  69. {
  70. if (Text(current, "type") == "array")
  71. {
  72. yield return path;
  73. yield break;
  74. }
  75. var properties = MdpApiPullPlan.Value(current, "properties");
  76. if (depth >= 5 || properties.ValueKind != JsonValueKind.Object)
  77. yield break;
  78. foreach (var property in properties.EnumerateObject())
  79. {
  80. if (property.Name.Length == 0 || property.Name.Contains('.'))
  81. continue;
  82. var child = path.Length == 0 ? property.Name : path + "." + property.Name;
  83. foreach (var array in FindArrays(property.Value, child, depth + 1))
  84. yield return array;
  85. }
  86. }
  87. }
  88. private static MdpApiPullPlan Postman(JsonElement root, string? selection)
  89. {
  90. var candidates = new List<JsonElement>();
  91. Walk(root);
  92. var selected = Choose(candidates, entry => Text(entry, "name") ?? "", selection);
  93. var request = MdpApiPullPlan.Value(selected, "request");
  94. if (request.ValueKind == JsonValueKind.Undefined) request = selected;
  95. var uri = Text(request, "url") ?? Text(request, "url.raw");
  96. var method = Text(request, "method");
  97. if (uri is null || method is null) throw new MdpApiPullException("PULL_IMPORT_INVALID");
  98. var plan = Build(uri, method);
  99. var example = Text(First(MdpApiPullPlan.Value(selected, "response")), "body");
  100. var dataPath = "";
  101. if (example is not null)
  102. {
  103. try
  104. {
  105. using var sample = JsonDocument.Parse(example);
  106. dataPath = new[] { "data.list", "data.items", "data", "items", "orders", "records" }
  107. .FirstOrDefault(name => MdpApiPullPlan.Value(sample.RootElement, name).ValueKind == JsonValueKind.Array) ?? "";
  108. }
  109. catch (JsonException) { /* The operator chooses a path for incomplete examples. */ }
  110. }
  111. return plan with { Auth = AuthKind(Text(request, "auth.type")), ResponsePath = dataPath };
  112. void Walk(JsonElement item)
  113. {
  114. if (MdpApiPullPlan.Value(item, "request").ValueKind == JsonValueKind.Object
  115. || MdpApiPullPlan.Value(item, "method").ValueKind == JsonValueKind.String)
  116. candidates.Add(item);
  117. var children = MdpApiPullPlan.Value(item, "item");
  118. if (children.ValueKind == JsonValueKind.Array)
  119. foreach (var child in children.EnumerateArray()) Walk(child);
  120. }
  121. }
  122. private static T Choose<T>(List<T> candidates, Func<T, string> name, string? selection)
  123. {
  124. var matches = candidates.Where(candidate => selection is null || name(candidate) == selection).Take(2).ToArray();
  125. return matches.Length == 1 ? matches[0]
  126. : throw new MdpApiPullException(matches.Length > 1 ? "PULL_IMPORT_SELECT_OPERATION" : "PULL_IMPORT_INVALID");
  127. }
  128. private static MdpApiPullPlan Curl(string text)
  129. {
  130. var args = Token.Matches(text.Replace("\\\r\n", "").Replace("\\\n", ""))
  131. .Select(match => match.Groups.Cast<Group>().Skip(1).First(group => group.Success).Value).ToArray();
  132. if (args.Length < 2 || args[0] != "curl") throw new MdpApiPullException("PULL_IMPORT_INVALID");
  133. var method = "GET";
  134. var auth = "none";
  135. var index = 1;
  136. string? url = null;
  137. for (; index < args.Length; index++)
  138. {
  139. var current = args[index];
  140. if (current is "-X" or "--request") method = Arg();
  141. else if (current == "--url") url = Arg();
  142. else if (current is "-u" or "--user") { Arg(); auth = "basic"; }
  143. else if (current is "-d" or "--data" or "--data-raw" or "--data-binary" or "--json") { Arg(); method = "POST"; }
  144. else if (current is "-H" or "--header")
  145. {
  146. var header = Arg().Split(':', 2)[0].Trim();
  147. if (header is "X-API-Key" or "Api-Key") auth = "apiKey";
  148. }
  149. else if (Uri.TryCreate(current, UriKind.Absolute, out var endpoint) && endpoint.Scheme is "http" or "https"
  150. && url is null)
  151. url = current;
  152. else if (current is not ("-s" or "-S" or "--silent" or "--show-error"))
  153. throw new MdpApiPullException("PULL_IMPORT_UNSUPPORTED_OPTION");
  154. }
  155. return Build(url ?? "", method) with { Auth = auth };
  156. string Arg() => ++index < args.Length ? args[index] : throw new MdpApiPullException("PULL_IMPORT_INVALID");
  157. }
  158. private static MdpApiPullPlan Build(string url, string method)
  159. {
  160. if (!Uri.TryCreate(url, UriKind.Absolute, out var endpoint) || endpoint.Scheme != "https"
  161. || endpoint.UserInfo.Length != 0 || method.ToUpperInvariant() is not ("GET" or "POST")
  162. || url.Contains('{') || url.Contains('}'))
  163. throw new MdpApiPullException("PULL_IMPORT_INVALID");
  164. var clean = new UriBuilder(endpoint) { Query = "", Fragment = "" }.Uri.AbsoluteUri;
  165. return new MdpApiPullPlan(clean, method.ToUpperInvariant(), Mode: "single");
  166. }
  167. private static string AuthKind(string? type) => type?.ToLowerInvariant() switch
  168. {
  169. "oauth2" => "oauth2", "basic" => "basic", "apikey" => "apiKey", _ => "none"
  170. };
  171. private static JsonElement First(JsonElement array) =>
  172. array.ValueKind == JsonValueKind.Array && array.GetArrayLength() > 0 ? array[0] : default;
  173. private static string? Text(JsonElement node, string path) =>
  174. MdpApiPullPlan.Value(node, path) is { ValueKind: JsonValueKind.String } entry ? entry.GetString() : null;
  175. }