-
Notifications
You must be signed in to change notification settings - Fork 451
/
DropboxRequestHandler.cs
1053 lines (948 loc) · 40.9 KB
/
DropboxRequestHandler.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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
// <copyright file="DropboxRequestHandler.cs" company="Dropbox Inc">
// Copyright (c) Dropbox Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace Dropbox.Api
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Dropbox.Api.Common;
using Dropbox.Api.Stone;
using Newtonsoft.Json.Linq;
/// <summary>
/// The object used to to make requests to the Dropbox API.
/// </summary>
internal sealed class DropboxRequestHandler : ITransport
{
private const int TokenExpirationBuffer = 300;
/// <summary>
/// The API version.
/// </summary>
private const string ApiVersion = "2";
/// <summary>
/// The dropbox API argument header.
/// </summary>
private const string DropboxApiArgHeader = "Dropbox-API-Arg";
/// <summary>
/// The dropbox API result header.
/// </summary>
private const string DropboxApiResultHeader = "Dropbox-API-Result";
/// <summary>
/// The member id of the selected user.
/// </summary>
private readonly string selectUser;
/// <summary>
/// The member id of the selected admin.
/// </summary>
private readonly string selectAdmin;
/// <summary>
/// The path root value used to make API call.
/// </summary>
private readonly PathRoot pathRoot;
/// <summary>
/// The configuration options for dropbox client.
/// </summary>
private readonly DropboxRequestHandlerOptions options;
/// <summary>
/// The default http client instance.
/// </summary>
private readonly HttpClient defaultHttpClient = new HttpClient();
/// <summary>
/// The default long poll http client instance.
/// </summary>
private readonly HttpClient defaultLongPollHttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(480) };
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandler"/> class.
/// </summary>
/// <param name="options">The configuration options for dropbox client.</param>
/// <param name="selectUser">The member id of the selected user.</param>
/// <param name="selectAdmin">The member id of the selected admin.</param>
/// <param name="pathRoot">The path root to make requests from.</param>
public DropboxRequestHandler(
DropboxRequestHandlerOptions options,
string selectUser = null,
string selectAdmin = null,
PathRoot pathRoot = null)
{
this.options = options ?? throw new ArgumentNullException("options");
this.selectUser = selectUser;
this.selectAdmin = selectAdmin;
this.pathRoot = pathRoot;
}
/// <summary>
/// The known route styles.
/// </summary>
internal enum RouteStyle
{
/// <summary>
/// RPC style means that the argument and result of a route are contained in the
/// HTTP body.
/// </summary>
Rpc,
/// <summary>
/// Download style means that the route argument goes in a <c>Dropbox-API-Args</c>
/// header, and the result comes back in a <c>Dropbox-API-Result</c> header. The
/// HTTP response body contains a binary payload.
/// </summary>
Download,
/// <summary>
/// Upload style means that the route argument goes in a <c>Dropbox-API-Arg</c>
/// header. The HTTP request body contains a binary payload. The result comes
/// back in a <c>Dropbox-API-Result</c> header.
/// </summary>
Upload,
}
/// <summary>
/// Sends the upload request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<TResponse> ITransport.SendRpcRequestAsync<TRequest, TResponse, TError>(
TRequest request,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Rpc, serializedArg)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
return JsonReader.Read(res.ObjectResult, responseDecoder);
}
/// <summary>
/// Sends the upload request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="body">The content to be uploaded.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<TResponse> ITransport.SendUploadRequestAsync<TRequest, TResponse, TError>(
TRequest request,
Stream body,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder, true);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Upload, serializedArg, body)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
return JsonReader.Read(res.ObjectResult, responseDecoder);
}
/// <summary>
/// Sends the download request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<IDownloadResponse<TResponse>> ITransport.SendDownloadRequestAsync<TRequest, TResponse, TError>(
TRequest request,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder, true);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Download, serializedArg)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
var response = JsonReader.Read(res.ObjectResult, responseDecoder);
return new DownloadResponse<TResponse>(response, res.HttpResponse);
}
/// <summary>
/// Uses the refresh token to obtain a new access token.
/// </summary>
/// <param name="scopeList">The scope list.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public async Task<bool> RefreshAccessToken(string[] scopeList = null)
{
if (this.options.OAuth2RefreshToken == null || this.options.AppKey == null)
{
// Cannot refresh token if you do not have at a minimum refresh token and app key
return false;
}
var url = "https://api.dropbox.com/oauth2/token";
var parameters = new Dictionary<string, string>
{
{ "refresh_token", this.options.OAuth2RefreshToken },
{ "grant_type", "refresh_token" },
{ "client_id", this.options.AppKey },
};
if (!string.IsNullOrEmpty(this.options.AppSecret))
{
parameters["client_secret"] = this.options.AppSecret;
}
if (scopeList != null)
{
parameters["scope"] = string.Join(" ", scopeList);
}
var bodyContent = new FormUrlEncodedContent(parameters);
var response = await this.defaultHttpClient.PostAsync(url, bodyContent).ConfigureAwait(false);
// if response is an invalid grant, we want to throw this exception rather than the one thrown in
// response.EnsureSuccessStatusCode();
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (reason == "invalid_grant")
{
throw AuthException.Decode(reason, () => new AuthException(this.GetRequestId(response)));
}
}
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var json = JObject.Parse(await response.Content.ReadAsStringAsync());
string accessToken = json["access_token"].ToString();
DateTime tokenExpiration = DateTime.Now.AddSeconds(json["expires_in"].ToObject<int>());
this.options.OAuth2AccessToken = accessToken;
this.options.OAuth2AccessTokenExpiresAt = tokenExpiration;
return true;
}
return false;
}
/// <summary>
/// The public dispose.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Set the value for Dropbox-Api-Path-Root header.
/// </summary>
/// <param name="pathRoot">The path root object.</param>
/// <returns>A <see cref="DropboxClient"/> instance with Dropbox-Api-Path-Root header set.</returns>
internal DropboxRequestHandler WithPathRoot(PathRoot pathRoot)
{
if (pathRoot == null)
{
throw new ArgumentNullException("pathRoot");
}
return new DropboxRequestHandler(
this.options,
selectUser: this.selectUser,
selectAdmin: this.selectAdmin,
pathRoot: pathRoot);
}
/// <summary>
/// Requests the JSON string with retry.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="routeStyle">The route style.</param>
/// <param name="requestArg">The request argument.</param>
/// <param name="body">The body to upload if <paramref name="routeStyle"/>
/// is <see cref="RouteStyle.Upload"/>.</param>
/// <returns>The asynchronous task with the result.</returns>
private async Task<Result> RequestJsonStringWithRetry(
string host,
string routeName,
string auth,
RouteStyle routeStyle,
string requestArg,
Stream body = null)
{
var attempt = 0;
var hasRefreshed = false;
var maxRetries = this.options.MaxClientRetries;
var r = new Random();
if (routeStyle == RouteStyle.Upload)
{
if (body == null)
{
throw new ArgumentNullException("body");
}
// to support retry logic, the body stream must be seekable
// if it isn't we won't retry
if (!body.CanSeek)
{
maxRetries = 0;
}
}
await this.CheckAndRefreshAccessToken();
try
{
while (true)
{
try
{
return await this.RequestJsonString(host, routeName, auth, routeStyle, requestArg, body)
.ConfigureAwait(false);
}
catch (AuthException e)
{
if (e.Message == "expired_access_token")
{
if (hasRefreshed)
{
throw;
}
else
{
await this.RefreshAccessToken();
hasRefreshed = true;
}
}
else
{
// dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
// do not count a rate limiting error as an attempt
if (++attempt > maxRetries)
{
throw;
}
}
}
catch (RateLimitException)
{
throw;
}
catch (RetryException)
{
// dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
// do not count a rate limiting error as an attempt
if (++attempt > maxRetries)
{
throw;
}
}
// use exponential backoff
var backoff = TimeSpan.FromSeconds(Math.Pow(2, attempt) * r.NextDouble());
#if PORTABLE40
await TaskEx.Delay(backoff);
#else
await Task.Delay(backoff).ConfigureAwait(false);
#endif
if (body != null)
{
body.Position = 0;
}
}
}
finally
{
body?.Dispose();
}
}
/// <summary>
/// Attempts to extract the value of a field named <c>error</c> from <paramref name="text"/>
/// if it is a valid JSON object.
/// </summary>
/// <param name="text">The text to check.</param>
/// <returns>The contents of the error field if present, otherwise <paramref name="text" />.</returns>
private string CheckForError(string text)
{
try
{
var obj = JObject.Parse(text);
if (obj.TryGetValue("error", out JToken error))
{
return error.ToString();
}
return text;
}
catch (Exception)
{
return text;
}
}
/// <summary>
/// Requests the JSON string.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="routeStyle">The route style.</param>
/// <param name="requestArg">The request argument.</param>
/// <param name="body">The body to upload if <paramref name="routeStyle"/>
/// is <see cref="RouteStyle.Upload"/>.</param>
/// <returns>The asynchronous task with the result.</returns>
private async Task<Result> RequestJsonString(
string host,
string routeName,
string auth,
RouteStyle routeStyle,
string requestArg,
Stream body = null)
{
var hostname = this.options.HostMap[host];
var uri = this.GetRouteUri(hostname, routeName);
var request = new HttpRequestMessage(HttpMethod.Post, uri);
if (auth == AuthType.User || auth == AuthType.Team)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.options.OAuth2AccessToken);
}
else if (auth == AuthType.App)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", this.options.OAuth2AccessToken);
}
else if (auth == AuthType.NoAuth)
{
}
else
{
throw new ArgumentException("Invalid auth type", auth);
}
request.Headers.TryAddWithoutValidation("User-Agent", this.options.UserAgent);
if (this.selectUser != null)
{
request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-User", this.selectUser);
}
if (this.selectAdmin != null)
{
request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-Admin", this.selectAdmin);
}
if (this.pathRoot != null)
{
request.Headers.TryAddWithoutValidation(
"Dropbox-Api-Path-Root",
JsonWriter.Write(this.pathRoot, PathRoot.Encoder));
}
var completionOption = HttpCompletionOption.ResponseContentRead;
switch (routeStyle)
{
case RouteStyle.Rpc:
request.Content = new StringContent(requestArg, Encoding.UTF8, "application/json");
break;
case RouteStyle.Download:
request.Headers.Add(DropboxApiArgHeader, requestArg);
// This is required to force libcurl remove default content type header.
request.Content = new StringContent(string.Empty);
request.Content.Headers.ContentType = null;
completionOption = HttpCompletionOption.ResponseHeadersRead;
break;
case RouteStyle.Upload:
request.Headers.Add(DropboxApiArgHeader, requestArg);
if (body == null)
{
throw new ArgumentNullException("body");
}
request.Content = new CustomStreamContent(body);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
break;
default:
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"Unknown route style: {0}",
routeStyle));
}
var disposeResponse = true;
var response = await this.GetHttpClient(host).SendAsync(request, completionOption).ConfigureAwait(false);
var requestId = this.GetRequestId(response);
try
{
if ((int)response.StatusCode >= 500)
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new RetryException(requestId, (int)response.StatusCode, message: text, uri: uri);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new BadInputException(requestId, text, uri);
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw AuthException.Decode(reason, () => new AuthException(this.GetRequestId(response)));
}
else if ((int)response.StatusCode == 429)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw RateLimitException.Decode(reason, () => new RateLimitException(this.GetRequestId(response)));
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw AccessException.Decode(reason, () => new AccessException(this.GetRequestId(response)));
}
else if ((int)response.StatusCode == 422)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw PathRootException.Decode(reason, () => new PathRootException(this.GetRequestId(response)));
}
else if (response.StatusCode == HttpStatusCode.Conflict ||
response.StatusCode == HttpStatusCode.NotFound)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new Result
{
IsError = true,
ObjectResult = reason,
RequestId = this.GetRequestId(response),
};
}
else if ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299)
{
if (routeStyle == RouteStyle.Download)
{
disposeResponse = false;
return new Result
{
IsError = false,
ObjectResult = response.Headers.GetValues(DropboxApiResultHeader).FirstOrDefault(),
HttpResponse = response,
};
}
else
{
return new Result
{
IsError = false,
ObjectResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false),
};
}
}
else
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new HttpException(requestId, (int)response.StatusCode, text, uri);
}
}
finally
{
if (disposeResponse)
{
response.Dispose();
}
}
}
private async Task<bool> CheckAndRefreshAccessToken()
{
bool canRefresh = this.options.OAuth2RefreshToken != null && this.options.AppKey != null;
bool needsRefresh = (this.options.OAuth2AccessTokenExpiresAt.HasValue && DateTime.Now.AddSeconds(TokenExpirationBuffer) >= this.options.OAuth2AccessTokenExpiresAt.Value) ||
(this.options.OAuth2RefreshToken != null && !this.options.OAuth2AccessTokenExpiresAt.HasValue);
bool needsToken = this.options.OAuth2AccessToken == null;
if ((needsRefresh || needsToken) && canRefresh)
{
return await this.RefreshAccessToken();
}
return false;
}
/// <summary>
/// Gets the URI for a route.
/// </summary>
/// <param name="hostname">The hostname for the request.</param>
/// <param name="routeName">Name of the route.</param>
/// <returns>The uri for this route.</returns>
private Uri GetRouteUri(string hostname, string routeName)
{
var builder = new UriBuilder("https", hostname)
{
Path = "/" + ApiVersion + routeName,
};
return builder.Uri;
}
/// <summary>
/// Gets the Dropbox request id.
/// </summary>
/// <param name="response">Response.</param>
/// <returns>The request id.</returns>
private string GetRequestId(HttpResponseMessage response)
{
if (response.Headers.TryGetValues("X-Dropbox-Request-Id", out IEnumerable<string> requestId))
{
return requestId.FirstOrDefault();
}
return null;
}
/// <summary>
/// Get http client for given host.
/// </summary>
/// <param name="host">The host type.</param>
/// <returns>The <see cref="HttpClient"/>.</returns>
private HttpClient GetHttpClient(string host)
{
if (host == HostType.ApiNotify)
{
return this.options.LongPollHttpClient ?? this.defaultLongPollHttpClient;
}
else
{
return this.options.HttpClient ?? this.defaultHttpClient;
}
}
/// <summary>
/// The actual disposing logic.
/// </summary>
/// <param name="disposing">If is disposing.</param>
private void Dispose(bool disposing)
{
if (disposing)
{
// HttpClient is safe for multiple disposal.
this.defaultHttpClient.Dispose();
this.defaultLongPollHttpClient.Dispose();
}
}
/// <summary>
/// Used to return un-typed result information to the layer that can interpret the
/// object types.
/// </summary>
private class Result
{
/// <summary>
/// Gets or sets a value indicating whether this instance is an error.
/// </summary>
/// <value>
/// <c>true</c> if this instance is an error; otherwise, <c>false</c>.
/// </value>
public bool IsError { get; set; }
/// <summary>
/// Gets or sets the un-typed object result, this will be parsed into the
/// specific response or error type for the route.
/// </summary>
/// <value>
/// The object result.
/// </value>
public string ObjectResult { get; set; }
/// <summary>
/// Gets or sets the Dropbox request id.
/// </summary>
/// <value>The request id.</value>
public string RequestId { get; set; }
/// <summary>
/// Gets or sets the HTTP response, this is only set if the route was a download route.
/// </summary>
/// <value>
/// The HTTP response.
/// </value>
public HttpResponseMessage HttpResponse { get; set; }
}
/// <summary>
/// An implementation of the <see cref="T:Dropbox.Api.Stone.IDownloadResponse`1"/> interface.
/// </summary>
/// <typeparam name="TResponse">The type of the response.</typeparam>
private class DownloadResponse<TResponse> : IDownloadResponse<TResponse>
{
/// <summary>
/// The HTTP response containing the body content.
/// </summary>
private HttpResponseMessage httpResponse;
/// <summary>
/// Initializes a new instance of the <see cref="DownloadResponse{TResponse}"/> class.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="httpResponseMessage">The HTTP response message.</param>
public DownloadResponse(TResponse response, HttpResponseMessage httpResponseMessage)
{
this.Response = response;
this.httpResponse = httpResponseMessage;
}
/// <summary>Gets the response.</summary>
/// <value>The response.</value>
public TResponse Response { get; private set; }
/// <summary>
/// Asynchronously gets the content as a <see cref="Stream" />.
/// </summary>
/// <returns>The downloaded content as a stream.</returns>
public Task<Stream> GetContentAsStreamAsync()
{
return this.httpResponse.Content.ReadAsStreamAsync();
}
/// <summary>
/// Asynchronously gets the content as a <see cref="byte" /> array.
/// </summary>
/// <returns>The downloaded content as a byte array.</returns>
public Task<byte[]> GetContentAsByteArrayAsync()
{
return this.httpResponse.Content.ReadAsByteArrayAsync();
}
/// <summary>
/// Asynchronously gets the content as <see cref="string" />.
/// </summary>
/// <returns>The downloaded content as a string.</returns>
public Task<string> GetContentAsStringAsync()
{
return this.httpResponse.Content.ReadAsStringAsync();
}
/// <summary>
/// Disposes of the <see cref="HttpResponseMessage"/> in this instance.
/// </summary>
public void Dispose()
{
if (this.httpResponse != null)
{
this.httpResponse.Dispose();
this.httpResponse = null;
}
}
}
}
/// <summary>
/// The stream content which doesn't dispose the underlying stream. This
/// is useful for retry.
/// </summary>
internal class CustomStreamContent : StreamContent
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomStreamContent"/> class.
/// </summary>
/// <param name="content">The stream content.</param>
public CustomStreamContent(Stream content)
: base(content)
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
// Do not dispose the stream.
}
}
/// <summary>
/// The type of api hosts.
/// </summary>
internal class HostType
{
/// <summary>
/// Host type for api.
/// </summary>
public const string Api = "api";
/// <summary>
/// Host type for api content.
/// </summary>
public const string ApiContent = "content";
/// <summary>
/// Host type for api notify.
/// </summary>
public const string ApiNotify = "notify";
}
/// <summary>
/// The type of api auth.
/// </summary>
internal class AuthType
{
/// <summary>
/// Auth type for user auth.
/// </summary>
public const string User = "user";
/// <summary>
/// Auth type for team auth.
/// </summary>
public const string Team = "team";
/// <summary>
/// Host type for app auth.
/// </summary>
public const string App = "app";
/// <summary>
/// Host type for no auth.
/// </summary>
public const string NoAuth = "noauth";
}
/// <summary>
/// The class which contains configurations for the request handler.
/// </summary>
internal sealed class DropboxRequestHandlerOptions
{
/// <summary>
/// The default api domain.
/// </summary>
private const string DefaultApiDomain = "api.dropboxapi.com";
/// <summary>
/// The default api content domain.
/// </summary>
private const string DefaultApiContentDomain = "content.dropboxapi.com";
/// <summary>
/// The default api notify domain.
/// </summary>
private const string DefaultApiNotifyDomain = "notify.dropboxapi.com";
/// <summary>
/// The base user agent, used to construct all user agent strings.
/// </summary>
private const string BaseUserAgent = "OfficialDropboxDotNetSDKv2";
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandlerOptions"/> class.
/// </summary>
/// <param name="config">The client configuration.</param>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
public DropboxRequestHandlerOptions(DropboxClientConfig config, string oauth2AccessToken, string oauth2RefreshToken, DateTime? oauth2AccessTokenExpiresAt, string appKey, string appSecret)
: this(
oauth2AccessToken,
oauth2RefreshToken,
oauth2AccessTokenExpiresAt,
appKey,
appSecret,
config.MaxRetriesOnError,
config.UserAgent,
DefaultApiDomain,
DefaultApiContentDomain,
DefaultApiNotifyDomain,
config.HttpClient,
config.LongPollHttpClient)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandlerOptions"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
/// <param name="maxRetriesOnError">The maximum retries on a 5xx error.</param>
/// <param name="userAgent">The user agent to use when making requests.</param>
/// <param name="apiHostname">The hostname that will process api requests;
/// this is for internal Dropbox use only.</param>
/// <param name="apiContentHostname">The hostname that will process api content requests;
/// this is for internal Dropbox use only.</param>
/// <param name="apiNotifyHostname">The hostname that will process api notify requests;
/// this is for internal Dropbox use only.</param>
/// <param name="httpClient">The custom http client. If not provided, a default
/// http client will be created.</param>
/// <param name="longPollHttpClient">The custom http client for long poll. If not provided, a default
/// http client with longer timeout will be created.</param>
public DropboxRequestHandlerOptions(
string oauth2AccessToken,
string oauth2RefreshToken,
DateTime? oauth2AccessTokenExpiresAt,
string appKey,
string appSecret,
int maxRetriesOnError,
string userAgent,
string apiHostname,
string apiContentHostname,
string apiNotifyHostname,
HttpClient httpClient,
HttpClient longPollHttpClient)
{
var type = typeof(DropboxRequestHandlerOptions);
#if PORTABLE40
var assembly = type.Assembly;
#else
var assembly = type.GetTypeInfo().Assembly;
#endif
var name = new AssemblyName(assembly.FullName);
var sdkVersion = name.Version.ToString();
this.UserAgent = userAgent == null
? string.Join("/", BaseUserAgent, sdkVersion)
: string.Join("/", userAgent, BaseUserAgent, sdkVersion);
this.HttpClient = httpClient;
this.LongPollHttpClient = longPollHttpClient;
this.OAuth2AccessToken = oauth2AccessToken;
this.OAuth2RefreshToken = oauth2RefreshToken;
this.OAuth2AccessTokenExpiresAt = oauth2AccessTokenExpiresAt;
this.AppKey = appKey;
this.AppSecret = appSecret;
this.MaxClientRetries = maxRetriesOnError;
this.HostMap = new Dictionary<string, string>
{
{ HostType.Api, apiHostname },
{ HostType.ApiContent, apiContentHostname },
{ HostType.ApiNotify, apiNotifyHostname },
};