| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using System.Net.Http.Headers; |
| | | 3 | | using System.Text; |
| | | 4 | | |
| | | 5 | | namespace TeleFlow.Telegram; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Default <see cref="ITelegramTransport"/> implementation that sends Telegram Bot API requests through <see cref="Http |
| | | 9 | | /// It is used by the generated client pipeline unless an application registers a custom transport. |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed class HttpClientTelegramTransport : ITelegramTransport, IDisposable |
| | | 12 | | { |
| | | 13 | | private readonly HttpClient _httpClient; |
| | | 14 | | private readonly bool _ownsHttpClient; |
| | | 15 | | private bool _disposed; |
| | | 16 | | |
| | | 17 | | public HttpClientTelegramTransport(HttpClient httpClient) |
| | 2 | 18 | | : this(httpClient, ownsHttpClient: false) |
| | | 19 | | { |
| | 2 | 20 | | } |
| | | 21 | | |
| | | 22 | | private HttpClientTelegramTransport(HttpClient httpClient, bool ownsHttpClient) |
| | | 23 | | { |
| | 288 | 24 | | ArgumentNullException.ThrowIfNull(httpClient); |
| | 288 | 25 | | _httpClient = httpClient; |
| | 288 | 26 | | _ownsHttpClient = ownsHttpClient; |
| | 288 | 27 | | } |
| | | 28 | | |
| | | 29 | | internal static HttpClientTelegramTransport CreateOwned(HttpClient httpClient) |
| | | 30 | | { |
| | 286 | 31 | | return new HttpClientTelegramTransport(httpClient, ownsHttpClient: true); |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public async Task<TelegramTransportResponse> SendAsync( |
| | | 35 | | TelegramTransportRequest request, |
| | | 36 | | CancellationToken cancellationToken = default) |
| | | 37 | | { |
| | 76 | 38 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 75 | 39 | | ArgumentNullException.ThrowIfNull(request); |
| | | 40 | | |
| | 75 | 41 | | using var message = new HttpRequestMessage(HttpMethod.Post, request.Uri) |
| | 75 | 42 | | { |
| | 75 | 43 | | Content = BuildContent(request.Content) |
| | 75 | 44 | | }; |
| | | 45 | | |
| | | 46 | | try |
| | | 47 | | { |
| | 75 | 48 | | using var response = await _httpClient.SendAsync(message, cancellationToken).ConfigureAwait(false); |
| | 71 | 49 | | var body = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); |
| | | 50 | | |
| | 71 | 51 | | return TelegramTransportResponse.FromOwnedBytes( |
| | 71 | 52 | | (int)response.StatusCode, |
| | 71 | 53 | | body, |
| | 71 | 54 | | CopyHeaders(response)); |
| | | 55 | | } |
| | 1 | 56 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 57 | | { |
| | 1 | 58 | | throw; |
| | | 59 | | } |
| | 3 | 60 | | catch (HttpRequestException exception) |
| | | 61 | | { |
| | 3 | 62 | | throw new TelegramNetworkException( |
| | 3 | 63 | | $"Telegram request '{request.MethodName}' failed because the HTTP transport failed.", |
| | 3 | 64 | | exception, |
| | 3 | 65 | | request.MethodName, |
| | 3 | 66 | | exception.StatusCode is null ? null : (int)exception.StatusCode); |
| | | 67 | | } |
| | 71 | 68 | | } |
| | | 69 | | |
| | | 70 | | public void Dispose() |
| | | 71 | | { |
| | 281 | 72 | | if (_disposed) |
| | | 73 | | { |
| | 1 | 74 | | return; |
| | | 75 | | } |
| | | 76 | | |
| | 280 | 77 | | _disposed = true; |
| | | 78 | | |
| | 280 | 79 | | if (_ownsHttpClient) |
| | | 80 | | { |
| | 278 | 81 | | _httpClient.Dispose(); |
| | | 82 | | } |
| | 280 | 83 | | } |
| | | 84 | | |
| | | 85 | | private static HttpContent BuildContent(TelegramTransportContent content) |
| | | 86 | | { |
| | 75 | 87 | | return content switch |
| | 75 | 88 | | { |
| | 68 | 89 | | TelegramJsonTransportContent json => new StringContent(json.Json, Encoding.UTF8, "application/json"), |
| | 7 | 90 | | TelegramMultipartTransportContent multipart => BuildMultipartContent(multipart), |
| | 0 | 91 | | _ => throw new InvalidOperationException( |
| | 0 | 92 | | $"Unsupported Telegram transport content type '{content.GetType().FullName}'.") |
| | 75 | 93 | | }; |
| | | 94 | | } |
| | | 95 | | |
| | | 96 | | [SuppressMessage( |
| | | 97 | | "Reliability", |
| | | 98 | | "CA2000:Dispose objects before losing scope", |
| | | 99 | | Justification = "Part content ownership is transferred to MultipartFormDataContent, which is disposed by the req |
| | | 100 | | private static MultipartFormDataContent BuildMultipartContent(TelegramMultipartTransportContent multipart) |
| | | 101 | | { |
| | 7 | 102 | | var content = new MultipartFormDataContent(); |
| | | 103 | | |
| | 34 | 104 | | foreach (var field in multipart.Fields) |
| | | 105 | | { |
| | 10 | 106 | | content.Add(new StringContent(field.Value, Encoding.UTF8), field.Name); |
| | | 107 | | } |
| | | 108 | | |
| | 28 | 109 | | foreach (var file in multipart.Files) |
| | | 110 | | { |
| | 7 | 111 | | var streamContent = new StreamContent(new NonDisposingReadStream(file.Content)); |
| | 7 | 112 | | if (!string.IsNullOrWhiteSpace(file.ContentType)) |
| | | 113 | | { |
| | 0 | 114 | | streamContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType); |
| | | 115 | | } |
| | | 116 | | |
| | 7 | 117 | | content.Add(streamContent, file.Name, file.FileName); |
| | | 118 | | } |
| | | 119 | | |
| | 7 | 120 | | return content; |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | private static Dictionary<string, IReadOnlyList<string>> CopyHeaders(HttpResponseMessage response) |
| | | 124 | | { |
| | 71 | 125 | | var headers = new Dictionary<string, IReadOnlyList<string>>(StringComparer.OrdinalIgnoreCase); |
| | | 126 | | |
| | 150 | 127 | | foreach (var header in response.Headers) |
| | | 128 | | { |
| | 4 | 129 | | headers[header.Key] = header.Value.ToArray(); |
| | | 130 | | } |
| | | 131 | | |
| | 426 | 132 | | foreach (var header in response.Content.Headers) |
| | | 133 | | { |
| | 142 | 134 | | headers[header.Key] = header.Value.ToArray(); |
| | | 135 | | } |
| | | 136 | | |
| | 71 | 137 | | return headers; |
| | | 138 | | } |
| | | 139 | | |
| | | 140 | | private sealed class NonDisposingReadStream : Stream |
| | | 141 | | { |
| | | 142 | | [SuppressMessage( |
| | | 143 | | "Usage", |
| | | 144 | | "CA2213:Disposable fields should be disposed", |
| | | 145 | | Justification = "This wrapper deliberately does not own the caller-provided InputFile stream.")] |
| | | 146 | | private readonly Stream _inner; |
| | | 147 | | |
| | 7 | 148 | | public NonDisposingReadStream(Stream inner) |
| | | 149 | | { |
| | 7 | 150 | | ArgumentNullException.ThrowIfNull(inner); |
| | 7 | 151 | | _inner = inner; |
| | 7 | 152 | | } |
| | | 153 | | |
| | 7 | 154 | | public override bool CanRead => _inner.CanRead; |
| | | 155 | | |
| | 28 | 156 | | public override bool CanSeek => _inner.CanSeek; |
| | | 157 | | |
| | 0 | 158 | | public override bool CanWrite => false; |
| | | 159 | | |
| | 14 | 160 | | public override long Length => _inner.Length; |
| | | 161 | | |
| | | 162 | | public override long Position |
| | | 163 | | { |
| | 14 | 164 | | get => _inner.Position; |
| | 0 | 165 | | set => _inner.Position = value; |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | public override void Flush() |
| | | 169 | | { |
| | 0 | 170 | | } |
| | | 171 | | |
| | | 172 | | public override int Read(byte[] buffer, int offset, int count) |
| | | 173 | | { |
| | 0 | 174 | | return _inner.Read(buffer, offset, count); |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | public override int Read(Span<byte> buffer) |
| | | 178 | | { |
| | 0 | 179 | | return _inner.Read(buffer); |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | public override ValueTask<int> ReadAsync( |
| | | 183 | | Memory<byte> buffer, |
| | | 184 | | CancellationToken cancellationToken = default) |
| | | 185 | | { |
| | 14 | 186 | | return _inner.ReadAsync(buffer, cancellationToken); |
| | | 187 | | } |
| | | 188 | | |
| | | 189 | | public override long Seek(long offset, SeekOrigin origin) |
| | | 190 | | { |
| | 0 | 191 | | return _inner.Seek(offset, origin); |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | public override void SetLength(long value) |
| | | 195 | | { |
| | 0 | 196 | | throw new NotSupportedException(); |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | public override void Write(byte[] buffer, int offset, int count) |
| | | 200 | | { |
| | 0 | 201 | | throw new NotSupportedException(); |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | protected override void Dispose(bool disposing) |
| | | 205 | | { |
| | | 206 | | // Stream ownership stays with the caller-provided InputFile. |
| | 7 | 207 | | base.Dispose(disposing); |
| | 7 | 208 | | } |
| | | 209 | | } |
| | | 210 | | } |