-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Connection.cs
791 lines (694 loc) · 34.6 KB
/
Connection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Octokit.Internal;
#if !HAS_ENVIRONMENT
using System.Runtime.InteropServices;
#endif
namespace Octokit
{
// NOTE: Every request method must go through the `RunRequest` code path. So if you need to add a new method
// ensure it goes through there. :)
/// <summary>
/// A connection for making HTTP requests against URI endpoints.
/// </summary>
public class Connection : IConnection
{
static readonly Uri _defaultGitHubApiUrl = GitHubClient.GitHubApiUrl;
static readonly ICredentialStore _anonymousCredentials = new InMemoryCredentialStore(Credentials.Anonymous);
readonly Authenticator _authenticator;
readonly JsonHttpPipeline _jsonPipeline;
readonly IHttpClient _httpClient;
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
public Connection(ProductHeaderValue productInformation)
: this(productInformation, _defaultGitHubApiUrl, _anonymousCredentials)
{
}
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
/// <param name="httpClient">
/// The client to use for executing requests
/// </param>
public Connection(ProductHeaderValue productInformation, IHttpClient httpClient)
: this(productInformation, _defaultGitHubApiUrl, _anonymousCredentials, httpClient, new SimpleJsonSerializer())
{
}
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
/// <param name="baseAddress">
/// The address to point this client to such as https://api.github.com or the URL to a GitHub Enterprise
/// instance</param>
public Connection(ProductHeaderValue productInformation, Uri baseAddress)
: this(productInformation, baseAddress, _anonymousCredentials)
{
}
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
/// <param name="credentialStore">Provides credentials to the client when making requests</param>
public Connection(ProductHeaderValue productInformation, ICredentialStore credentialStore)
: this(productInformation, _defaultGitHubApiUrl, credentialStore)
{
}
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
/// <param name="baseAddress">
/// The address to point this client to such as https://api.github.com or the URL to a GitHub Enterprise
/// instance</param>
/// <param name="credentialStore">Provides credentials to the client when making requests</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public Connection(ProductHeaderValue productInformation, Uri baseAddress, ICredentialStore credentialStore)
: this(productInformation, baseAddress, credentialStore, new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault), new SimpleJsonSerializer())
{
}
/// <summary>
/// Creates a new connection instance used to make requests of the GitHub API.
/// </summary>
/// <remarks>
/// See more information regarding User-Agent requirements here: https://developer.github.com/v3/#user-agent-required
/// </remarks>
/// <param name="productInformation">
/// The name (and optionally version) of the product using this library, the name of your GitHub organization, or your GitHub username (in that order of preference). This is sent to the server as part of
/// the user agent for analytics purposes, and used by GitHub to contact you if there are problems.
/// </param>
/// <param name="baseAddress">
/// The address to point this client to such as https://api.github.com or the URL to a GitHub Enterprise
/// instance</param>
/// <param name="credentialStore">Provides credentials to the client when making requests</param>
/// <param name="httpClient">A raw <see cref="IHttpClient"/> used to make requests</param>
/// <param name="serializer">Class used to serialize and deserialize JSON requests</param>
public Connection(
ProductHeaderValue productInformation,
Uri baseAddress,
ICredentialStore credentialStore,
IHttpClient httpClient,
IJsonSerializer serializer)
{
Ensure.ArgumentNotNull(productInformation, nameof(productInformation));
Ensure.ArgumentNotNull(baseAddress, nameof(baseAddress));
Ensure.ArgumentNotNull(credentialStore, nameof(credentialStore));
Ensure.ArgumentNotNull(httpClient, nameof(httpClient));
Ensure.ArgumentNotNull(serializer, nameof(serializer));
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture, "The base address '{0}' must be an absolute URI",
baseAddress), nameof(baseAddress));
}
UserAgent = FormatUserAgent(productInformation);
BaseAddress = baseAddress;
_authenticator = new Authenticator(credentialStore);
_httpClient = httpClient;
_jsonPipeline = new JsonHttpPipeline(serializer);
}
/// <summary>
/// Gets the latest API Info - this will be null if no API calls have been made
/// </summary>
/// <returns><seealso cref="ApiInfo"/> representing the information returned as part of an Api call</returns>
public ApiInfo GetLastApiInfo()
{
// We've chosen to not wrap the _lastApiInfo in a lock. Originally the code was returning a reference - so there was a danger of
// on thread writing to the object while another was reading. Now we are cloning the ApiInfo on request - thus removing the need (or overhead)
// of putting locks in place.
// See https://github.com/octokit/octokit.net/pull/855#discussion_r36774884
return _lastApiInfo == null ? null : _lastApiInfo.Clone();
}
private ApiInfo _lastApiInfo;
public Task<IApiResponse<T>> Get<T>(Uri uri, IDictionary<string, string> parameters, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return SendData<T>(uri.ApplyParameters(parameters), HttpMethod.Get, null, accepts, null, CancellationToken.None);
}
public Task<IApiResponse<T>> Get<T>(Uri uri, IDictionary<string, string> parameters, string accepts, CancellationToken cancellationToken)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return SendData<T>(uri.ApplyParameters(parameters), HttpMethod.Get, null, accepts, null, cancellationToken);
}
public Task<IApiResponse<T>> Get<T>(Uri uri, TimeSpan timeout)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return SendData<T>(uri, HttpMethod.Get, null, null, null, timeout, CancellationToken.None);
}
/// <summary>
/// Performs an asynchronous HTTP GET request that expects a <seealso cref="IResponse"/> containing HTML.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="parameters">Querystring parameters for the request</param>
/// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
public Task<IApiResponse<string>> GetHtml(Uri uri, IDictionary<string, string> parameters)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return GetHtml(new Request
{
Method = HttpMethod.Get,
BaseAddress = BaseAddress,
Endpoint = uri.ApplyParameters(parameters)
});
}
public Task<IApiResponse<T>> Patch<T>(Uri uri, object body)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
return SendData<T>(uri, HttpVerb.Patch, body, null, null, CancellationToken.None);
}
public Task<IApiResponse<T>> Patch<T>(Uri uri, object body, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
return SendData<T>(uri, HttpVerb.Patch, body, accepts, null, CancellationToken.None);
}
/// <summary>
/// Performs an asynchronous HTTP POST request.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
public async Task<HttpStatusCode> Post(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await SendData<object>(uri, HttpMethod.Post, null, null, null, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
public async Task<HttpStatusCode> Post(Uri uri, object body, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await SendData<object>(uri, HttpMethod.Post, body, accepts, null, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
public Task<IApiResponse<T>> Post<T>(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
return SendData<T>(uri, HttpMethod.Post, null, null, null, CancellationToken.None);
}
public Task<IApiResponse<T>> Post<T>(Uri uri, object body, string accepts, string contentType)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
return SendData<T>(uri, HttpMethod.Post, body, accepts, contentType, CancellationToken.None);
}
public Task<IApiResponse<T>> Post<T>(Uri uri, object body, string accepts, string contentType, IDictionary<string, string> parameters)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
return SendData<T>(uri.ApplyParameters(parameters), HttpMethod.Post, body, accepts, contentType, CancellationToken.None);
}
/// <summary>
/// Performs an asynchronous HTTP POST request.
/// Attempts to map the response body to an object of type <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">The type to map the response to</typeparam>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="body">The object to serialize as the body of the request</param>
/// <param name="accepts">Specifies accepted response media types.</param>
/// <param name="contentType">Specifies the media type of the request body</param>
/// <param name="twoFactorAuthenticationCode">Two Factor Authentication Code</param>
/// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
public Task<IApiResponse<T>> Post<T>(Uri uri, object body, string accepts, string contentType, string twoFactorAuthenticationCode)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
Ensure.ArgumentNotNullOrEmptyString(twoFactorAuthenticationCode, nameof(twoFactorAuthenticationCode));
return SendData<T>(uri, HttpMethod.Post, body, accepts, contentType, CancellationToken.None, twoFactorAuthenticationCode);
}
public Task<IApiResponse<T>> Post<T>(Uri uri, object body, string accepts, string contentType, TimeSpan timeout)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
return SendData<T>(uri, HttpMethod.Post, body, accepts, contentType, timeout, CancellationToken.None);
}
public Task<IApiResponse<T>> Post<T>(Uri uri, object body, string accepts, string contentType, Uri baseAddress)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(body, nameof(body));
return SendData<T>(uri, HttpMethod.Post, body, accepts, contentType, CancellationToken.None, baseAddress: baseAddress);
}
public Task<IApiResponse<T>> Put<T>(Uri uri, object body)
{
return SendData<T>(uri, HttpMethod.Put, body, null, null, CancellationToken.None);
}
public Task<IApiResponse<T>> Put<T>(Uri uri, object body, string twoFactorAuthenticationCode)
{
return SendData<T>(uri,
HttpMethod.Put,
body,
null,
null,
CancellationToken.None,
twoFactorAuthenticationCode);
}
public Task<IApiResponse<T>> Put<T>(Uri uri, object body, string twoFactorAuthenticationCode, string accepts)
{
return SendData<T>(uri,
HttpMethod.Put,
body,
accepts,
null,
CancellationToken.None,
twoFactorAuthenticationCode);
}
Task<IApiResponse<T>> SendData<T>(
Uri uri,
HttpMethod method,
object body,
string accepts,
string contentType,
TimeSpan timeout,
CancellationToken cancellationToken,
string twoFactorAuthenticationCode = null,
Uri baseAddress = null)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.GreaterThanZero(timeout, nameof(timeout));
var request = new Request
{
Method = method,
BaseAddress = baseAddress ?? BaseAddress,
Endpoint = uri,
Timeout = timeout
};
return SendDataInternal<T>(body, accepts, contentType, cancellationToken, twoFactorAuthenticationCode, request);
}
Task<IApiResponse<T>> SendData<T>(
Uri uri,
HttpMethod method,
object body,
string accepts,
string contentType,
CancellationToken cancellationToken,
string twoFactorAuthenticationCode = null,
Uri baseAddress = null)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var request = new Request
{
Method = method,
BaseAddress = baseAddress ?? BaseAddress,
Endpoint = uri
};
return SendDataInternal<T>(body, accepts, contentType, cancellationToken, twoFactorAuthenticationCode, request);
}
Task<IApiResponse<T>> SendDataInternal<T>(object body, string accepts, string contentType, CancellationToken cancellationToken, string twoFactorAuthenticationCode, Request request)
{
if (!string.IsNullOrEmpty(accepts))
{
request.Headers["Accept"] = accepts;
}
if (!string.IsNullOrEmpty(twoFactorAuthenticationCode))
{
request.Headers["X-GitHub-OTP"] = twoFactorAuthenticationCode;
}
if (body != null)
{
request.Body = body;
// Default Content Type per: http://developer.github.com/v3/
request.ContentType = contentType ?? "application/x-www-form-urlencoded";
}
return Run<T>(request, cancellationToken);
}
/// <summary>
/// Performs an asynchronous HTTP PATCH request.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
public async Task<HttpStatusCode> Patch(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var request = new Request
{
Method = HttpVerb.Patch,
BaseAddress = BaseAddress,
Endpoint = uri
};
var response = await Run<object>(request, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP PATCH request.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="accepts">Specifies accept response media type</param>
/// <returns><seealso cref="IResponse"/> representing the received HTTP response</returns>
public async Task<HttpStatusCode> Patch(Uri uri, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
var response = await SendData<object>(uri, new HttpMethod("PATCH"), null, accepts, null, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP PUT request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Put(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var request = new Request
{
Method = HttpMethod.Put,
BaseAddress = BaseAddress,
Endpoint = uri
};
var response = await Run<object>(request, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP PUT request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="accepts">Specifies accepted response media types.</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Put(Uri uri, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
var response = await SendData<object>(uri, HttpMethod.Put, null, accepts, null, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Delete(Uri uri)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var request = new Request
{
Method = HttpMethod.Delete,
BaseAddress = BaseAddress,
Endpoint = uri
};
var response = await Run<object>(request, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="twoFactorAuthenticationCode">Two Factor Code</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Delete(Uri uri, string twoFactorAuthenticationCode)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
var response = await SendData<object>(uri, HttpMethod.Delete, null, null, null, CancellationToken.None, twoFactorAuthenticationCode).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Delete(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
var request = new Request
{
Method = HttpMethod.Delete,
Body = data,
BaseAddress = BaseAddress,
Endpoint = uri
};
var response = await Run<object>(request, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request that expects an empty response.
/// </summary>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
/// <param name="accepts">Specifies accept response media type</param>
/// <returns>The returned <seealso cref="HttpStatusCode"/></returns>
public async Task<HttpStatusCode> Delete(Uri uri, object data, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
var response = await SendData<object>(uri, HttpMethod.Delete, data, accepts, null, CancellationToken.None).ConfigureAwait(false);
return response.HttpResponse.StatusCode;
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request.
/// </summary>
/// <typeparam name="T">The API resource's type.</typeparam>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
public Task<IApiResponse<T>> Delete<T>(Uri uri, object data)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(data, nameof(data));
return SendData<T>(uri, HttpMethod.Delete, data, null, null, CancellationToken.None);
}
/// <summary>
/// Performs an asynchronous HTTP DELETE request.
/// Attempts to map the response body to an object of type <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">The type to map the response to</typeparam>
/// <param name="uri">URI endpoint to send request to</param>
/// <param name="data">The object to serialize as the body of the request</param>
/// <param name="accepts">Specifies accept response media type</param>
public Task<IApiResponse<T>> Delete<T>(Uri uri, object data, string accepts)
{
Ensure.ArgumentNotNull(uri, nameof(uri));
Ensure.ArgumentNotNull(accepts, nameof(accepts));
return SendData<T>(uri, HttpMethod.Delete, data, accepts, null, CancellationToken.None);
}
/// <summary>
/// Base address for the connection.
/// </summary>
public Uri BaseAddress { get; private set; }
public string UserAgent { get; private set; }
/// <summary>
/// Gets the <seealso cref="ICredentialStore"/> used to provide credentials for the connection.
/// </summary>
public ICredentialStore CredentialStore
{
get { return _authenticator.CredentialStore; }
}
/// <summary>
/// Gets or sets the credentials used by the connection.
/// </summary>
/// <remarks>
/// You can use this property if you only have a single hard-coded credential. Otherwise, pass in an
/// <see cref="ICredentialStore"/> to the constructor.
/// Setting this property will change the <see cref="ICredentialStore"/> to use
/// the default <see cref="InMemoryCredentialStore"/> with just these credentials.
/// </remarks>
public Credentials Credentials
{
get
{
var credentialTask = CredentialStore.GetCredentials();
if (credentialTask == null) return Credentials.Anonymous;
return credentialTask.Result ?? Credentials.Anonymous;
}
// Note this is for convenience. We probably shouldn't allow this to be mutable.
set
{
Ensure.ArgumentNotNull(value, nameof(value));
_authenticator.CredentialStore = new InMemoryCredentialStore(value);
}
}
async Task<IApiResponse<string>> GetHtml(IRequest request)
{
request.Headers.Add("Accept", AcceptHeaders.StableVersionHtml);
var response = await RunRequest(request, CancellationToken.None).ConfigureAwait(false);
return new ApiResponse<string>(response, response.Body as string);
}
async Task<IApiResponse<T>> Run<T>(IRequest request, CancellationToken cancellationToken)
{
_jsonPipeline.SerializeRequest(request);
var response = await RunRequest(request, cancellationToken).ConfigureAwait(false);
return _jsonPipeline.DeserializeResponse<T>(response);
}
// THIS IS THE METHOD THAT EVERY REQUEST MUST GO THROUGH!
async Task<IResponse> RunRequest(IRequest request, CancellationToken cancellationToken)
{
request.Headers.Add("User-Agent", UserAgent);
await _authenticator.Apply(request).ConfigureAwait(false);
var response = await _httpClient.Send(request, cancellationToken).ConfigureAwait(false);
if (response != null)
{
// Use the clone method to avoid keeping hold of the original (just in case it effect the lifetime of the whole response
_lastApiInfo = response.ApiInfo.Clone();
}
HandleErrors(response);
return response;
}
static readonly Dictionary<HttpStatusCode, Func<IResponse, Exception>> _httpExceptionMap =
new Dictionary<HttpStatusCode, Func<IResponse, Exception>>
{
{ HttpStatusCode.Unauthorized, GetExceptionForUnauthorized },
{ HttpStatusCode.Forbidden, GetExceptionForForbidden },
{ HttpStatusCode.NotFound, response => new NotFoundException(response) },
{ (HttpStatusCode)422, response => new ApiValidationException(response) },
{ (HttpStatusCode)451, response => new LegalRestrictionException(response) }
};
static void HandleErrors(IResponse response)
{
Func<IResponse, Exception> exceptionFunc;
if (_httpExceptionMap.TryGetValue(response.StatusCode, out exceptionFunc))
{
throw exceptionFunc(response);
}
if ((int)response.StatusCode >= 400)
{
throw new ApiException(response);
}
}
static Exception GetExceptionForUnauthorized(IResponse response)
{
var twoFactorType = ParseTwoFactorType(response);
return twoFactorType == TwoFactorType.None
? new AuthorizationException(response)
: new TwoFactorRequiredException(response, twoFactorType);
}
static Exception GetExceptionForForbidden(IResponse response)
{
string body = response.Body as string ?? "";
if (body.Contains("rate limit exceeded"))
{
return new RateLimitExceededException(response);
}
if (body.Contains("number of login attempts exceeded"))
{
return new LoginAttemptsExceededException(response);
}
if (body.Contains("abuse-rate-limits") || body.Contains("abuse detection mechanism"))
{
return new AbuseException(response);
}
return new ForbiddenException(response);
}
internal static TwoFactorType ParseTwoFactorType(IResponse restResponse)
{
if (restResponse == null || restResponse.Headers == null || !restResponse.Headers.Any()) return TwoFactorType.None;
var otpHeader = restResponse.Headers.FirstOrDefault(header =>
header.Key.Equals("X-GitHub-OTP", StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(otpHeader.Value)) return TwoFactorType.None;
var factorType = otpHeader.Value;
var parts = factorType.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 0 && parts[0] == "required")
{
var secondPart = parts.Length > 1 ? parts[1].Trim() : null;
switch (secondPart)
{
case "sms":
return TwoFactorType.Sms;
case "app":
return TwoFactorType.AuthenticatorApp;
default:
return TwoFactorType.Unknown;
}
}
return TwoFactorType.None;
}
static string FormatUserAgent(ProductHeaderValue productInformation)
{
return string.Format(CultureInfo.InvariantCulture, "{0} ({1}; {2}; Octokit {3})",
productInformation,
GetPlatformInformation(),
GetCultureInformation(),
GetVersionInformation());
}
private static string _platformInformation;
static string GetPlatformInformation()
{
if (string.IsNullOrEmpty(_platformInformation))
{
try
{
_platformInformation = string.Format(CultureInfo.InvariantCulture,
#if !HAS_ENVIRONMENT
"{0}; {1}",
RuntimeInformation.OSDescription.Trim(),
RuntimeInformation.OSArchitecture.ToString().ToLowerInvariant().Trim()
#else
"{0} {1}; {2}",
Environment.OSVersion.Platform,
Environment.OSVersion.Version.ToString(3),
Environment.Is64BitOperatingSystem ? "amd64" : "x86"
#endif
);
}
catch
{
_platformInformation = "Unknown Platform";
}
}
return _platformInformation;
}
static string GetCultureInformation()
{
return CultureInfo.CurrentCulture.Name;
}
private static string _versionInformation;
static string GetVersionInformation()
{
if (string.IsNullOrEmpty(_versionInformation))
{
_versionInformation = typeof(IGitHubClient)
.GetTypeInfo()
.Assembly
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
}
return _versionInformation;
}
/// <summary>
/// Set the GitHub Api request timeout.
/// </summary>
/// <param name="timeout">The Timeout value</param>
public void SetRequestTimeout(TimeSpan timeout)
{
_httpClient.SetRequestTimeout(timeout);
}
}
}