| | | 1 | | using System.Net.Http.Headers; |
| | | 2 | | using System.Reflection; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | using Elsa.Extensions; |
| | | 5 | | using Elsa.Http.ContentWriters; |
| | | 6 | | using Elsa.Http.UIHints; |
| | | 7 | | using Elsa.Workflows; |
| | | 8 | | using Elsa.Workflows.Attributes; |
| | | 9 | | using Elsa.Workflows.UIHints; |
| | | 10 | | using Elsa.Workflows.Models; |
| | | 11 | | using Microsoft.Extensions.Logging; |
| | | 12 | | |
| | | 13 | | namespace Elsa.Http; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// An activity that downloads a file from a given URL. |
| | | 17 | | /// </summary> |
| | | 18 | | [Activity("Elsa", "HTTP", "Downloads a file from a given URL.", DisplayName = "Download File", Kind = ActivityKind.Task) |
| | | 19 | | [Output(IsSerializable = false)] |
| | | 20 | | public class DownloadHttpFile : Activity<HttpFile>, IActivityPropertyDefaultValueProvider |
| | | 21 | | { |
| | | 22 | | /// <inheritdoc /> |
| | 21 | 23 | | public DownloadHttpFile([CallerFilePath] string? source = null, [CallerLineNumber] int? line = null) : base(source, |
| | | 24 | | { |
| | 21 | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// The URL to download the file from. |
| | | 29 | | /// </summary> |
| | | 30 | | [Input(DisplayName = "URL", Description = "The URL to download the file from.")] |
| | 84 | 31 | | public Input<Uri?> Url { get; set; } = null!; |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// The HTTP method to use when sending the request. |
| | | 35 | | /// </summary> |
| | | 36 | | [Input( |
| | | 37 | | Description = "The HTTP method to use when sending the request.", |
| | | 38 | | Options = new[] |
| | | 39 | | { |
| | | 40 | | "GET", "POST", "PUT" |
| | | 41 | | }, |
| | | 42 | | DefaultValue = "GET", |
| | | 43 | | UIHint = InputUIHints.DropDown |
| | | 44 | | )] |
| | 105 | 45 | | public Input<string> Method { get; set; } = new("GET"); |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// A list of expected status codes to handle. |
| | | 49 | | /// </summary> |
| | | 50 | | [Input( |
| | | 51 | | Description = "A list of expected status codes to handle.", |
| | | 52 | | UIHint = InputUIHints.MultiText, |
| | | 53 | | DefaultValueProvider = typeof(FlowSendHttpRequest) |
| | | 54 | | )] |
| | 82 | 55 | | public Input<ICollection<int>> ExpectedStatusCodes { get; set; } = null!; |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// The content to send with the request. Can be a string, an object, a byte array or a stream. |
| | | 59 | | /// </summary> |
| | | 60 | | [Input(Name = "Content", Description = "The content to send with the request. Can be a string, an object, a byte arr |
| | 63 | 61 | | public Input<object?> RequestContent { get; set; } = null!; |
| | | 62 | | |
| | | 63 | | /// <summary> |
| | | 64 | | /// The content type to use when sending the request. |
| | | 65 | | /// </summary> |
| | | 66 | | [Input( |
| | | 67 | | DisplayName = "Content Type", |
| | | 68 | | Description = "The content type to use when sending the request.", |
| | | 69 | | UIHandler = typeof(HttpContentTypeOptionsProvider), |
| | | 70 | | UIHint = InputUIHints.DropDown |
| | | 71 | | )] |
| | 63 | 72 | | public Input<string?> RequestContentType { get; set; } = null!; |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// The Authorization header value to send with the request. |
| | | 76 | | /// </summary> |
| | | 77 | | /// <example>Bearer {some-access-token}</example> |
| | | 78 | | [Input(Description = "The Authorization header value to send with the request. For example: Bearer {some-access-toke |
| | 84 | 79 | | public Input<string?> Authorization { get; set; } = null!; |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// A value that allows to add the Authorization header without validation. |
| | | 83 | | /// </summary> |
| | | 84 | | [Input(Description = "A value that allows to add the Authorization header without validation.", Category = "Security |
| | 63 | 85 | | public Input<bool> DisableAuthorizationHeaderValidation { get; set; } = null!; |
| | | 86 | | |
| | | 87 | | /// <summary> |
| | | 88 | | /// The headers to send along with the request. |
| | | 89 | | /// </summary> |
| | | 90 | | [Input( |
| | | 91 | | Description = "The headers to send along with the request.", |
| | | 92 | | UIHint = InputUIHints.JsonEditor, |
| | | 93 | | Category = "Advanced" |
| | | 94 | | )] |
| | 84 | 95 | | public Input<HttpHeaders?> RequestHeaders { get; set; } = new(new HttpHeaders()); |
| | | 96 | | |
| | | 97 | | /// <summary> |
| | | 98 | | /// The HTTP response. |
| | | 99 | | /// </summary> |
| | | 100 | | [Output(IsSerializable = false)] |
| | 40 | 101 | | public Output<HttpResponseMessage> Response { get; set; } = null!; |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// The HTTP response status code |
| | | 105 | | /// </summary> |
| | | 106 | | [Output(Description = "The HTTP response status code")] |
| | 40 | 107 | | public Output<int> StatusCode { get; set; } = null!; |
| | | 108 | | |
| | | 109 | | /// <summary> |
| | | 110 | | /// The downloaded content stream, if any. |
| | | 111 | | /// </summary> |
| | | 112 | | [Output(Description = "The downloaded content stream, if any.", IsSerializable = false)] |
| | 40 | 113 | | public Output<Stream?> ResponseContentStream { get; set; } = null!; |
| | | 114 | | |
| | | 115 | | /// <summary> |
| | | 116 | | /// The downloaded content bytes, if any. |
| | | 117 | | /// </summary> |
| | | 118 | | [Output(Description = "The downloaded content bytes, if any.", IsSerializable = false)] |
| | 40 | 119 | | public Output<byte[]?> ResponseContentBytes { get; set; } = null!; |
| | | 120 | | |
| | | 121 | | /// <summary> |
| | | 122 | | /// The response headers that were received. |
| | | 123 | | /// </summary> |
| | | 124 | | [Output(Description = "The response headers that were received.")] |
| | 40 | 125 | | public Output<HttpHeaders?> ResponseHeaders { get; set; } = null!; |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// The response content headers that were received. |
| | | 129 | | /// </summary> |
| | | 130 | | [Output(DisplayName = "Content Headers", Description = "The response content headers that were received.")] |
| | 40 | 131 | | public Output<HttpHeaders?> ResponseContentHeaders { get; set; } = null!; |
| | | 132 | | |
| | | 133 | | /// <inheritdoc /> |
| | | 134 | | protected override async ValueTask ExecuteAsync(ActivityExecutionContext context) |
| | | 135 | | { |
| | 21 | 136 | | await TrySendAsync(context); |
| | 21 | 137 | | } |
| | | 138 | | |
| | | 139 | | private async Task TrySendAsync(ActivityExecutionContext context) |
| | | 140 | | { |
| | 21 | 141 | | var request = PrepareRequest(context); |
| | 21 | 142 | | var logger = (ILogger)context.GetRequiredService(typeof(ILogger<>).MakeGenericType(GetType())); |
| | 21 | 143 | | var httpClientFactory = context.GetRequiredService<IHttpClientFactory>(); |
| | 21 | 144 | | var httpClient = httpClientFactory.CreateClient(nameof(SendHttpRequestBase)); |
| | 21 | 145 | | var cancellationToken = context.CancellationToken; |
| | | 146 | | |
| | | 147 | | try |
| | | 148 | | { |
| | 21 | 149 | | var response = await httpClient.SendAsync(request, cancellationToken); |
| | 19 | 150 | | var file = await GetFileFromResponse(context, response, request); |
| | 19 | 151 | | var statusCode = (int)response.StatusCode; |
| | 19 | 152 | | var responseHeaders = new HttpHeaders(response.Headers); |
| | 19 | 153 | | var responseContentHeaders = new HttpHeaders(response.Content.Headers); |
| | | 154 | | |
| | 19 | 155 | | context.Set(Response, response); |
| | 19 | 156 | | context.Set(ResponseContentStream, file?.Stream); |
| | 19 | 157 | | context.Set(Result, file); |
| | 19 | 158 | | context.Set(StatusCode, statusCode); |
| | 19 | 159 | | context.Set(ResponseHeaders, responseHeaders); |
| | 19 | 160 | | context.Set(ResponseContentHeaders, responseContentHeaders); |
| | 19 | 161 | | if (ResponseContentBytes.HasTarget(context)) context.Set(ResponseContentBytes, file?.GetBytes()); |
| | | 162 | | |
| | 19 | 163 | | await HandleResponseAsync(context, response); |
| | 19 | 164 | | } |
| | 1 | 165 | | catch (HttpRequestException e) |
| | | 166 | | { |
| | 1 | 167 | | logger.LogWarning(e, "An error occurred while sending an HTTP request"); |
| | 1 | 168 | | context.AddExecutionLogEntry("Error", e.Message, payload: new |
| | 1 | 169 | | { |
| | 1 | 170 | | StackTrace = e.StackTrace |
| | 1 | 171 | | }); |
| | 1 | 172 | | context.JournalData.Add("Error", e.Message); |
| | 1 | 173 | | await HandleRequestExceptionAsync(context, e); |
| | 1 | 174 | | } |
| | 1 | 175 | | catch (TaskCanceledException e) |
| | | 176 | | { |
| | 1 | 177 | | logger.LogWarning(e, "An error occurred while sending an HTTP request"); |
| | 1 | 178 | | context.AddExecutionLogEntry("Error", e.Message, payload: new |
| | 1 | 179 | | { |
| | 1 | 180 | | StackTrace = e.StackTrace |
| | 1 | 181 | | }); |
| | 1 | 182 | | context.JournalData.Add("Cancelled", true); |
| | 1 | 183 | | await HandleTaskCanceledExceptionAsync(context, e); |
| | | 184 | | } |
| | 21 | 185 | | } |
| | | 186 | | |
| | | 187 | | /// <summary> |
| | | 188 | | /// Handles the response. |
| | | 189 | | /// </summary> |
| | | 190 | | private async Task HandleResponseAsync(ActivityExecutionContext context, HttpResponseMessage response) |
| | | 191 | | { |
| | 19 | 192 | | var expectedStatusCodes = ExpectedStatusCodes.GetOrDefault(context) ?? new List<int>(0); |
| | 19 | 193 | | var statusCode = (int)response.StatusCode; |
| | 19 | 194 | | var hasMatchingStatusCode = expectedStatusCodes.Contains(statusCode); |
| | 19 | 195 | | var outcome = expectedStatusCodes.Any() ? hasMatchingStatusCode ? statusCode.ToString() : "Unmatched status code |
| | 19 | 196 | | var outcomes = new List<string>(); |
| | | 197 | | |
| | 19 | 198 | | if (outcome != null) |
| | 19 | 199 | | outcomes.Add(outcome); |
| | | 200 | | |
| | 19 | 201 | | outcomes.Add("Done"); |
| | 19 | 202 | | await context.CompleteActivityWithOutcomesAsync(outcomes.ToArray()); |
| | 19 | 203 | | } |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Handles an exception that occurred while sending the request. |
| | | 207 | | /// </summary> |
| | | 208 | | private async Task HandleRequestExceptionAsync(ActivityExecutionContext context, HttpRequestException exception) |
| | | 209 | | { |
| | 1 | 210 | | await context.CompleteActivityWithOutcomesAsync("Failed to connect"); |
| | 1 | 211 | | } |
| | | 212 | | |
| | | 213 | | /// <summary> |
| | | 214 | | /// Handles <see cref="TaskCanceledException"/> that occurred while sending the request. |
| | | 215 | | /// </summary> |
| | | 216 | | private async Task HandleTaskCanceledExceptionAsync(ActivityExecutionContext context, TaskCanceledException exceptio |
| | | 217 | | { |
| | 1 | 218 | | await context.CompleteActivityWithOutcomesAsync("Timeout"); |
| | 1 | 219 | | } |
| | | 220 | | |
| | | 221 | | private async Task<HttpFile?> GetFileFromResponse(ActivityExecutionContext context, HttpResponseMessage httpResponse |
| | | 222 | | { |
| | 19 | 223 | | var httpContent = httpResponse.Content; |
| | 19 | 224 | | if (!HasContent(httpContent)) |
| | 3 | 225 | | return null; |
| | | 226 | | |
| | 16 | 227 | | var cancellationToken = context.CancellationToken; |
| | 16 | 228 | | var contentStream = await httpContent.ReadAsStreamAsync(cancellationToken); |
| | 16 | 229 | | var responseHeaders = httpResponse.Headers; |
| | 16 | 230 | | var contentHeaders = httpContent.Headers; |
| | 16 | 231 | | var contentType = contentHeaders.ContentType?.MediaType!; |
| | 16 | 232 | | var filename = contentHeaders.ContentDisposition?.FileName ?? httpRequestMessage.RequestUri!.Segments.LastOrDefa |
| | 16 | 233 | | var eTag = responseHeaders.ETag?.Tag; |
| | | 234 | | |
| | 16 | 235 | | return new HttpFile(contentStream, filename, contentType, eTag); |
| | 19 | 236 | | } |
| | | 237 | | |
| | 19 | 238 | | private static bool HasContent(HttpContent httpContent) => httpContent.Headers.ContentLength > 0; |
| | | 239 | | |
| | | 240 | | private HttpRequestMessage PrepareRequest(ActivityExecutionContext context) |
| | | 241 | | { |
| | 21 | 242 | | var method = Method.GetOrDefault(context) ?? "GET"; |
| | 21 | 243 | | var url = Url.Get(context); |
| | 21 | 244 | | var request = new HttpRequestMessage(new HttpMethod(method), url); |
| | 21 | 245 | | var headers = context.GetHeaders(RequestHeaders); |
| | 21 | 246 | | var authorization = Authorization.GetOrDefault(context); |
| | 21 | 247 | | var addAuthorizationWithoutValidation = DisableAuthorizationHeaderValidation.GetOrDefault(context); |
| | | 248 | | |
| | 21 | 249 | | if (!string.IsNullOrWhiteSpace(authorization)) |
| | 2 | 250 | | if (addAuthorizationWithoutValidation) |
| | 0 | 251 | | request.Headers.TryAddWithoutValidation("Authorization", authorization); |
| | | 252 | | else |
| | 2 | 253 | | request.Headers.Authorization = AuthenticationHeaderValue.Parse(authorization); |
| | | 254 | | |
| | 42 | 255 | | foreach (var header in headers) |
| | 0 | 256 | | request.Headers.Add(header.Key, header.Value.AsEnumerable()); |
| | | 257 | | |
| | 21 | 258 | | var contentType = RequestContentType.GetOrDefault(context); |
| | 21 | 259 | | var content = RequestContent.GetOrDefault(context); |
| | | 260 | | |
| | 21 | 261 | | if (contentType != null && content != null) |
| | | 262 | | { |
| | 0 | 263 | | var factories = context.GetServices<IHttpContentFactory>(); |
| | 0 | 264 | | var factory = SelectContentWriter(contentType, factories); |
| | 0 | 265 | | request.Content = factory.CreateHttpContent(content, contentType); |
| | | 266 | | } |
| | | 267 | | |
| | 21 | 268 | | return request; |
| | | 269 | | } |
| | | 270 | | |
| | | 271 | | private IHttpContentFactory SelectContentWriter(string? contentType, IEnumerable<IHttpContentFactory> factories) |
| | | 272 | | { |
| | 0 | 273 | | if (string.IsNullOrWhiteSpace(contentType)) |
| | 0 | 274 | | return new JsonContentFactory(); |
| | | 275 | | |
| | 0 | 276 | | var parsedContentType = new System.Net.Mime.ContentType(contentType); |
| | 0 | 277 | | return factories.FirstOrDefault(httpContentFactory => httpContentFactory.SupportedContentTypes.Any(c => c == par |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | object IActivityPropertyDefaultValueProvider.GetDefaultValue(PropertyInfo property) |
| | | 281 | | { |
| | 0 | 282 | | if (property.Name == nameof(ExpectedStatusCodes)) |
| | 0 | 283 | | return new List<int> |
| | 0 | 284 | | { |
| | 0 | 285 | | 200 |
| | 0 | 286 | | }; |
| | | 287 | | |
| | 0 | 288 | | return null!; |
| | | 289 | | } |
| | | 290 | | } |