Repository navigation
Expand file tree
/
Copy pathRestSharpCommandProcessor.cs
More file actions
380 lines (322 loc) · 12.7 KB
/
Copy pathRestSharpCommandProcessor.cs
File metadata and controls
380 lines (322 loc) · 12.7 KB
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
//------------------------------------------------------------------------------
// <copyright company="LeanKit Inc.">
// Copyright (c) LeanKit Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using LeanKit.API.Client.Library.Exceptions;
using LeanKit.API.Client.Library.TransferObjects;
using LeanKit.API.Client.Library.Validation;
using Newtonsoft.Json;
using RestSharp;
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
using UnauthorizedAccessException = LeanKit.API.Client.Library.Exceptions.UnauthorizedAccessException;
namespace LeanKit.API.Client.Library
{
public class RestSharpCommandProcessor : IRestCommandProcessor
{
private readonly string _leanKitUserAgent = "LeanKit.API.Client";
private readonly IntegrationSettings _settings;
private readonly IValidationService _validationService;
public RestSharpCommandProcessor(IValidationService validationService, IntegrationSettings settings)
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
_leanKitUserAgent += "/" + version;
_validationService = validationService;
_settings = settings;
}
public T Get<T>(ILeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.GET) { Resource = resource, RequestFormat = DataFormat.Json });
}
public T Get<T>(ILeanKitAccountAuth accountAuth, string resource, object body) where T : new()
{
var restRequest = new RestRequest(Method.GET) { Resource = resource, RequestFormat = DataFormat.Json };
restRequest.AddBody(body);
return Process<T>(accountAuth, restRequest);
}
public T Post<T>(ILeanKitAccountAuth accountAuth, string resource, object body) where T : new()
{
var restRequest = new RestRequest(Method.POST)
{
Resource = resource,
RequestFormat = DataFormat.Json,
JsonSerializer = new JsonSerializer()
};
restRequest.AddBody(body);
return Process<T>(accountAuth, restRequest);
}
public T Post<T>(ILeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.POST) { Resource = resource, RequestFormat = DataFormat.Json });
}
public T PostFile<T>(ILeanKitAccountAuth accountAuth, string resource, Dictionary<string, object> parameters, string fileName, string mimeType, byte[] fileBytes) where T : new()
{
var boundary = string.Format("----------{0:N}", Guid.NewGuid());
var contentType = "multipart/form-data; boundary=" + boundary;
var formBytes = GetMultipartFormData(parameters, boundary, fileName, mimeType, fileBytes);
var request = WebRequest.Create(accountAuth.GetAccountUrl() + resource) as HttpWebRequest;
if (request == null) throw new Exception("Error posting file. Could not create HttpWebRequest");
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = formBytes.Length;
request.UserAgent = _leanKitUserAgent;
AddAuth(request, accountAuth);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(formBytes, 0, formBytes.Length);
requestStream.Close();
}
var response = request.GetResponse() as HttpWebResponse;
var responseStream = new StreamReader(response.GetResponseStream());
var result = responseStream.ReadToEnd();
response.Close();
//var task = PostFileAsync(accountAuth, resource, parameters, fileName, fileBytes);
//var result = task.Result;
if (string.IsNullOrEmpty(result)) return new T();
var asyncResponse = JsonConvert.DeserializeObject<AsyncResponse2>(result);
if (asyncResponse == null || asyncResponse.ReplyData == null || asyncResponse.ReplyData.Length == 0) return new T();
var rawJson = asyncResponse.ReplyData[0].ToString();
if (string.IsNullOrEmpty(rawJson)) return new T();
var authUserDateFormat = _settings.DateFormat + " hh:mm:ss t";
var retVal = JsonConvert.DeserializeObject<T>(rawJson, new JsonSerializerSettings
{
Error = HandleError,
DateFormatString = authUserDateFormat
});
return retVal;
}
public AssetFile Download(ILeanKitAccountAuth accountAuth, string resource)
{
var request = WebRequest.Create(accountAuth.GetAccountUrl() + resource) as HttpWebRequest;
if (request == null) throw new Exception("Error downloading file. Could not create HttpWebRequest");
request.UserAgent = _leanKitUserAgent;
AddAuth(request, accountAuth);
var response = request.GetResponse() as HttpWebResponse;
byte[] fileBytes;
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[4096];
using (var ms = new MemoryStream())
{
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
fileBytes = ms.ToArray();
}
}
return new AssetFile
{
FileBytes = fileBytes,
ContentType = response.ContentType,
ContentLength = response.ContentLength
};
}
private static byte[] GetMultipartFormData(Dictionary<string, object> parameters, string boundary, string fileName, string mimeType, byte[] fileBytes)
{
var encoding = Encoding.UTF8;
var stream = new MemoryStream();
var count = 0;
foreach (var p in parameters)
{
if (count > 0)
stream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
var data = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, p.Key, p.Value);
stream.Write(encoding.GetBytes(data), 0, encoding.GetByteCount(data));
count++;
}
if (count > 0)
stream.Write(encoding.GetBytes("\r\n"), 0, encoding.GetByteCount("\r\n"));
if (string.IsNullOrEmpty(mimeType)) mimeType = "application/octet-stream";
var header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", boundary, fileName, mimeType);
stream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));
stream.Write(fileBytes, 0, fileBytes.Length);
var footer = string.Format("\r\n--{0}--\r\n", boundary);
stream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));
stream.Position = 0;
var formData = new byte[stream.Length];
stream.Read(formData, 0, formData.Length);
stream.Close();
return formData;
}
private T Process<T>(ILeanKitAccountAuth accountAuth, IRestRequest request) where T : new()
{
var errorMessages = _validationService.ValidateRequest((RestRequest) request);
if (errorMessages.Count > 0)
{
var ex = new ValidationException("Provided request parameters are invalid.");
ex.Data["ErrorMessages"] = errorMessages;
throw ex;
}
var client = new RestClient
{
BaseUrl = new Uri(accountAuth.GetAccountUrl()),
Authenticator = GetAuthenticator(accountAuth),
UserAgent = _leanKitUserAgent
};
var response = RetryRequest(request, accountAuth, client);
var asyncResponse = response.Data;
if (string.IsNullOrEmpty(asyncResponse.ReplyData))
{
return new T();
}
var rawJson = asyncResponse.ReplyData;
var authUserDateFormat = _settings.DateFormat + " hh:mm:ss tt";
rawJson = rawJson.Substring(1, rawJson.Length - 2);
var retVal = JsonConvert.DeserializeObject<T>(rawJson, new JsonSerializerSettings
{
Error = HandleError,
DateFormatString = authUserDateFormat
});
return retVal;
}
private static IRestResponse<AsyncResponse> RetryRequest(IRestRequest request, ILeanKitAccountAuth accountAuth,
RestClient client)
{
IRestResponse<AsyncResponse> response = new RestResponse<AsyncResponse>();
for (var tryCount = 0; tryCount <= 10; tryCount++)
{
try
{
response = client.Execute<AsyncResponse>(request);
ValidateResponse(response, accountAuth, request);
break;
}
catch (NoDataException)
{
return response;
}
catch (Exception)
{
if (tryCount == 10) throw;
Thread.Sleep(1000);
}
}
return response;
}
private static void HandleError(object sender, ErrorEventArgs e)
{
e.ErrorContext.Handled = true;
}
private static Uri GetRequestUri(string fullUrl)
{
return new Uri(fullUrl);
}
private static void ValidateResponse(IRestResponse<AsyncResponse> response,
ILeanKitAccountAuth leanKitAccountAuth,
IRestRequest request)
{
var requestedResource = GetRequestUri(leanKitAccountAuth.GetAccountUrl());
var logAuthString = FormatApiRequestInfo(leanKitAccountAuth, request, true);
if (response == null)
{
throw new LeanKitAPIException("A failure occurred retrieving the response from the API.");
}
if (response.ResponseUri != null && response.ResponseUri.Host != requestedResource.Host)
{
throw new InvalidAPIResourceException();
}
if (response.ResponseStatus == ResponseStatus.Error)
{
throw new LeanKitAPIException(response.ErrorException);
}
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
throw new UnauthorizedAccessException(response.StatusDescription + ": " + logAuthString);
}
AsyncResponse responseData = response.Data;
if (responseData == null)
{
throw new LeanKitAPIException("Unable to process the response from the API.");
}
switch ((ResponseCode) responseData.ReplyCode)
{
case ResponseCode.UnauthorizedAccess:
throw new UnauthorizedAccessException(responseData.ReplyText + ": " + logAuthString);
case ResponseCode.NoData:
throw new NoDataException(responseData.ReplyText);
case ResponseCode.FatalException:
case ResponseCode.MinorException:
case ResponseCode.UserException:
throw new LeanKitAPIException(responseData.ReplyText, (ResponseCode) responseData.ReplyCode);
}
//check to make sure there is data
if (string.IsNullOrEmpty(responseData.ReplyData))
{
throw new LeanKitAPIException(responseData.ReplyText + ": " + logAuthString, (ResponseCode) responseData.ReplyCode);
}
}
private static string FormatApiRequestInfo(ILeanKitAccountAuth leanKitAccountAuth, IRestRequest request, bool hidePassword = false)
{
var accountAuthStringStringBuilder = new StringBuilder();
accountAuthStringStringBuilder.Append("Attempted Authentication Information: ");
accountAuthStringStringBuilder.Append("Hostname: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Hostname != null
? leanKitAccountAuth.Hostname + ", "
: "Unknown, ");
var basicAuth = leanKitAccountAuth as LeanKitBasicAuth;
if (basicAuth != null)
{
accountAuthStringStringBuilder.Append("Username: ");
accountAuthStringStringBuilder.Append(basicAuth.Username != null
? basicAuth.Username + ", "
: "Unknown, ");
if (!hidePassword)
{
accountAuthStringStringBuilder.Append("Password: ");
accountAuthStringStringBuilder.Append(basicAuth.Password != null
? basicAuth.Password + ", "
: "Unknown, ");
}
}
var tokenAuth = leanKitAccountAuth as LeanKitTokenAuth;
if (tokenAuth != null && !hidePassword)
{
accountAuthStringStringBuilder.Append("Token: ");
accountAuthStringStringBuilder.Append(tokenAuth.Token != null
? tokenAuth.Token + ", "
: "Unknown, ");
}
accountAuthStringStringBuilder.Append("Resource: ");
accountAuthStringStringBuilder.Append(request.Resource != null ? request.Resource + ", " : "Unknown, ");
return accountAuthStringStringBuilder.ToString();
}
private static void AddAuth(WebRequest request, ILeanKitAccountAuth auth)
{
if (auth is LeanKitBasicAuth)
{
var basicAuth = auth as LeanKitBasicAuth;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(basicAuth.Username + ":" + basicAuth.Password)));
}
else if (auth is LeanKitTokenAuth)
{
request.Headers.Add("Authorization", "Token " + (auth as LeanKitTokenAuth).Token);
}
}
private static IAuthenticator GetAuthenticator(ILeanKitAccountAuth auth)
{
if (auth is LeanKitBasicAuth)
{
var basicAuth = auth as LeanKitBasicAuth;
return new HttpBasicAuthenticator(basicAuth.Username, basicAuth.Password);
}
if (auth is LeanKitTokenAuth)
{
return new TokenAuthenticator((auth as LeanKitTokenAuth).Token);
}
throw new ArgumentException("Unknown ILeanKitAccountAuth type");
}
}
}