Repository navigation
Expand file tree
/
Copy pathRestSharpCommandProcessor.cs
More file actions
306 lines (254 loc) · 10.3 KB
/
Copy pathRestSharpCommandProcessor.cs
File metadata and controls
306 lines (254 loc) · 10.3 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
//------------------------------------------------------------------------------
// <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.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 Newtonsoft.Json.Converters;
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 IntegrationSettings _settings;
private readonly IValidationService _validationService;
public RestSharpCommandProcessor(IValidationService validationService, IntegrationSettings settings)
{
_validationService = validationService;
_settings = settings;
}
public T Get<T>(LeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.GET) {Resource = resource, RequestFormat = DataFormat.Json});
}
public T Get<T>(LeanKitAccountAuth 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>(LeanKitAccountAuth 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>(LeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.POST) {Resource = resource, RequestFormat = DataFormat.Json});
}
public T PostFile<T>(LeanKitAccountAuth 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.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(accountAuth.Username + ":" + accountAuth.Password)));
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;
var isoDateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = authUserDateFormat };
var retVal = JsonConvert.DeserializeObject<T>(rawJson, new JsonSerializerSettings
{
Error = HandleError,
Converters = { isoDateTimeConverter }
});
return retVal;
}
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>(LeanKitAccountAuth 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 = accountAuth.GetAccountUrl(),
Authenticator = new HttpBasicAuthenticator(accountAuth.Username, accountAuth.Password)
};
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;
var isoDateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = authUserDateFormat };
rawJson = rawJson.Substring(1, rawJson.Length - 2);
var retVal = JsonConvert.DeserializeObject<T>(rawJson, new JsonSerializerSettings
{
Error = HandleError,
Converters = {isoDateTimeConverter}
});
return retVal;
}
private static IRestResponse<AsyncResponse> RetryRequest(IRestRequest request, LeanKitAccountAuth 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,
LeanKitAccountAuth 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.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(LeanKitAccountAuth 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, ");
accountAuthStringStringBuilder.Append("Username: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Username != null
? leanKitAccountAuth.Username + ", "
: "Unknown, ");
if (!hidePassword)
{
accountAuthStringStringBuilder.Append("Password: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Password != null
? leanKitAccountAuth.Password + ", "
: "Unknown, ");
}
accountAuthStringStringBuilder.Append("Resource: ");
accountAuthStringStringBuilder.Append(request.Resource != null ? request.Resource + ", " : "Unknown, ");
return accountAuthStringStringBuilder.ToString();
}
}
}