18 using Newtonsoft.Json;
21 using System.Threading.Tasks;
22 using RestSharp.Authenticators;
36 public RestClient
Client {
get;
set; }
39 private readonly
string _userId;
40 private readonly
string _token;
42 private LeanAuthenticator _authenticator;
52 _userId = userId.ToStringInvariant();
63 var request =
new RestRequest(
"authenticate", Method.GET);
65 if (TryRequest(request, out response))
84 result = resultTuple.Item2;
85 return resultTuple.Item1;
97 var responseContent =
string.Empty;
101 SetAuthenticator(request);
104 var restsharpResponse = await
Client.ExecuteAsync(request).ConfigureAwait(
false);
107 if (restsharpResponse.ErrorException !=
null)
109 Log.
Error($
"ApiConnection.TryRequest({request.Resource}): Error: {restsharpResponse.ErrorException.Message}");
110 return new Tuple<bool, T>(
false,
null);
113 if (!restsharpResponse.IsSuccessful)
115 Log.
Error($
"ApiConnect.TryRequest({request.Resource}): Content: {restsharpResponse.Content}");
118 responseContent = restsharpResponse.Content;
119 result = JsonConvert.DeserializeObject<T>(responseContent, _jsonSettings);
121 if (result ==
null || !result.Success)
123 Log.
Debug($
"ApiConnection.TryRequest({request.Resource}): Raw response: '{responseContent}'");
124 return new Tuple<bool, T>(
false, result);
127 catch (Exception err)
129 Log.
Error($
"ApiConnection.TryRequest({request.Resource}): Error: {err.Message}, Response content: {responseContent}");
130 return new Tuple<bool, T>(
false,
null);
133 return new Tuple<bool, T>(
true, result);
136 private void SetAuthenticator(RestRequest request)
140 var currentAuth = _authenticator;
141 if (currentAuth ==
null || newTimeStamp - currentAuth.TimeStamp > 7000)
147 var authenticator =
new HttpBasicAuthenticator(_userId, hash);
148 _authenticator = currentAuth =
new LeanAuthenticator(authenticator, newTimeStamp);
150 Client.Authenticator = currentAuth.Authenticator;
153 request.AddHeader(
"Timestamp", currentAuth.TimeStampStr);
156 private class LeanAuthenticator
158 public int TimeStamp {
get; }
159 public string TimeStampStr {
get; }
160 public HttpBasicAuthenticator Authenticator {
get; }
161 public LeanAuthenticator(HttpBasicAuthenticator authenticator,
int timeStamp)
163 TimeStamp = timeStamp;
164 Authenticator = authenticator;
165 TimeStampStr = timeStamp.ToStringInvariant();