/
ApiClient.cs
383 lines (340 loc) · 14.2 KB
/
ApiClient.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using System.Web;
using System.Linq;
using System.Net;
using System.Text;
using UnityEngine.Networking;
using MoralisUnity.Web3Api;
using WebRequest = MoralisUnity.Web3Api.Models.WebRequest;
using Newtonsoft.Json;
using Cysharp.Threading.Tasks;
using MoralisUnity.Web3Api.Core;
using MoralisUnity.Web3Api.Core.Models;
using UnityEngine;
using Object = System.Object;
namespace MoralisUnity.Web3Api.Client
{
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend.
/// </summary>
public class ApiClient
{
private readonly Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class.
/// </summary>
/// <param name="basePath">The base path.</param>
public ApiClient(String basePath="http://localhost:3063/api/v2")
{
BasePath = basePath;
RestClient = new UniversalWebClient();
_defaultHeaderMap.Add("x-moralis-platform", "UNITY SDK");
_defaultHeaderMap.Add("x-moralis-platform-version", "v1.2.10");
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path</value>
public string BasePath { get; set; }
/// <summary>
/// Gets or sets the RestClient.
/// </summary>
/// <value>An instance of the RestClient</value>
//public RestClient RestClient { get; set; }
public UniversalWebClient RestClient { get; set; }
/// <summary>
/// Gets the default header.
/// </summary>
public Dictionary<String, String> DefaultHeader
{
get { return _defaultHeaderMap; }
}
/// <summary>
/// Makes the HTTP request (Sync).
/// </summary>
/// <param name="path">URL path.</param>
/// <param name="method">HTTP method.</param>
/// <param name="queryParams">Query parameters.</param>
/// <param name="postBody">HTTP body (POST request).</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="formParams">Form parameters.</param>
/// <param name="fileParams">File parameters.</param>
/// <param name="authSettings">Authentication settings.</param>
/// <returns>Object</returns>
public async UniTask<Tuple<HttpStatusCode, Dictionary<string, string>, string>> CallApi(String path, Method method, Dictionary<String, String> queryParams, String postBody,
Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
Dictionary<String, FileParameter> fileParams, String[] authSettings)
{
bool paramsAdded = false;
//var request = new RestRequest(path, method);
Models.WebRequest request = new Models.WebRequest();
request.Resource = BasePath;
request.Path = path;
request.Method = method.ToString().ToUpper();
UpdateParamsForAuth(queryParams, headerParams, authSettings);
if (!String.IsNullOrWhiteSpace(postBody))
{
request.Data = new MemoryStream(Encoding.UTF8.GetBytes(postBody));
}
if (_defaultHeaderMap.Count > 0)
{
if (request.Headers == null)
{
request.Headers = new List<KeyValuePair<string, string>>();
}
// add default header, if any
foreach (var defaultHeader in _defaultHeaderMap)
{
request.Headers.Add(new KeyValuePair<string, string>(defaultHeader.Key, defaultHeader.Value));
}
}
if (headerParams.Count > 0)
{
if (request.Headers == null)
{
request.Headers = new List<KeyValuePair<string, string>>();
}
// add header parameter, if any
foreach (var param in headerParams)
{
if (!String.IsNullOrEmpty(param.Key) && !String.IsNullOrEmpty(param.Value))
{
request.Headers.Add(new KeyValuePair<string, string>(param.Key, param.Value));
}
}
}
if (queryParams.Count > 0)
{
// add query parameter, if any
foreach (var param in queryParams)
{
if (paramsAdded == false)
{
paramsAdded = true;
request.Method = $"{request.Method}?{param.Key}={UnityWebRequest.EscapeURL(param.Value)}";
}
else
{
request.Method = $"{request.Method}&{param.Key}={UnityWebRequest.EscapeURL(param.Value)}";
}
}
}
// add form parameter, if any
if (formParams != null && formParams.Count > 0)
{
string data = JsonConvert.SerializeObject(formParams);
request.Data = new MemoryStream(Encoding.UTF8.GetBytes(data));
}
// add file parameter, if any
if (fileParams != null && fileParams.Count > 0)
{
string data = JsonConvert.SerializeObject(fileParams);
request.Data = new MemoryStream(Encoding.UTF8.GetBytes(data));
}
//request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
return await RestClient.ExecuteAsync(request);
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value)
{
_defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Escape string (url-encoded).
/// </summary>
/// <param name="str">String to be escaped.</param>
/// <returns>Escaped string.</returns>
public string EscapeString(string str)
{
#if UNITY_2017_1_OR_NEWER
return UnityEngine.Networking.UnityWebRequest.EscapeURL(str);
#else
return HttpUtility.UrlEncode(str);
#endif
}
/// <summary>
/// Create FileParameter based on Stream.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="stream">Input stream.</param>
/// <returns>FileParameter.</returns>
public FileParameter ParameterToFile(string name, Stream stream)
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Position = 0;
if (stream is FileStream)
return FileParameter.Create(name, buffer, Path.GetFileName(((FileStream)stream).Name));
else
return FileParameter.Create(name, buffer, "no_file_name_provided");
}
/// <summary>
/// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
/// If parameter is a list of string, join the list with ",".
/// Otherwise just return the string.
/// </summary>
/// <param name="obj">The parameter (header, path, query, form).</param>
/// <returns>Formatted string.</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime)
// Return a formatted date string - Can be customized with Configuration.DateTimeFormat
// Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
// For example: 2009-06-15T13:45:30.0000000
return ((DateTime)obj).ToString(Configuration.DateTimeFormat);
else if (obj is List<string>)
return String.Join(",", (obj as List<string>).ToArray());
else if (obj is string || obj is int || obj is long || obj is decimal || obj is bool || obj is float || obj is double || obj is byte || obj is char)
{
return obj.ToString();
}
else
return JsonConvert.SerializeObject(obj);
}
/// <summary>
/// Convert a number to a HEX string.
/// </summary>
/// <param name="val">Value to convert</param>
/// <returns>Hex string.</returns>
public string ParameterToHex(long val)
{
string resp = $"0x{val.ToString("X")}";
return resp;
}
/// <summary>
/// Deserialize the JSON string into a proper object.
/// </summary>
/// <param name="content">HTTP body (e.g. string, JSON).</param>
/// <param name="type">Object type.</param>
/// <param name="headers">HTTP headers.</param>
/// <returns>Object representation of the JSON string.</returns>
public object Deserialize(string content, Type type, Dictionary<string, string> headers=null)
{
if (type == typeof(Object)) // return an object
{
return content;
}
if (type == typeof(Stream))
{
var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
? Path.GetTempPath()
: Configuration.TempFolderPath;
var fileName = filePath + Guid.NewGuid();
if (headers != null)
{
//var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
//var match = regex.Match(headers.ToString());
//if (match.Success)
if (headers.ContainsKey("Content-Disposition"))
{
string cntDisp = headers["Content-Disposition"];
fileName = filePath + cntDisp.Replace("\"", "").Replace("'", "");
}
}
File.WriteAllText(fileName, content);
return new FileStream(fileName, FileMode.Open);
}
if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(content, null, System.Globalization.DateTimeStyles.RoundtripKind);
}
if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return ConvertType(content, type);
}
// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>JSON string.</returns>
public string Serialize(object obj)
{
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e)
{
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Get the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
return apiKeyPrefix + " " + apiKeyValue;
else
return apiKeyValue;
}
/// <summary>
/// Update parameters based on authentication.
/// </summary>
/// <param name="queryParams">Query parameters.</param>
/// <param name="headerParams">Header parameters.</param>
/// <param name="authSettings">Authentication settings.</param>
public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> headerParams, string[] authSettings)
{
if (authSettings == null || authSettings.Length == 0)
return;
foreach (string auth in authSettings)
{
// determine which one to use
switch(auth)
{
case "ApiKeyAuth":
headerParams["X-API-Key"] = GetApiKeyWithPrefix("X-API-Key");
break;
default:
//TODO show warning about security definition not found
break;
}
}
}
/// <summary>
/// Encode string in base64 format.
/// </summary>
/// <param name="text">String to be encoded.</param>
/// <returns>Encoded string.</returns>
public static string Base64Encode(string text)
{
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
/// <summary>
/// Dynamically cast the object into target type.
/// </summary>
/// <param name="fromObject">Object to be casted</param>
/// <param name="toObject">Target type</param>
/// <returns>Casted object</returns>
public static Object ConvertType(Object fromObject, Type toObject) {
return Convert.ChangeType(fromObject, toObject);
}
}
}