-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBase.cs
77 lines (68 loc) · 3.21 KB
/
Base.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
using System;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WitSharp.Objects;
namespace WitSharp
{
public abstract class Base
{
internal HttpClient RestClient { get; }
internal Base()
{
RestClient = new HttpClient {BaseAddress = new Uri("https://api.wit.ai")};
RestClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", WitClient.Token);
RestClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
RestClient.DefaultRequestHeaders.Add("Accept", "application/vnd.wit.20200220+json");
}
protected static ContextObject DefaultContext
=> new ContextObject {Locale = "en_GB", ReferenceTime = DateTimeOffset.Now, Timezone = "Europe/Londer"};
internal string SnowFlake
{
get
{
var random = new Random(Guid.NewGuid().GetHashCode());
var date = new DateTime(2020, 02, 20, 06, 06, 06);
var buffer = new byte[(int) Math.Round(Math.Log(Math.Sqrt(date.Ticks)))];
random.NextBytes(buffer);
return
$"X0-{Math.Abs((decimal) BitConverter.ToUInt64(buffer, 0)).ToString(CultureInfo.InvariantCulture).Substring(0, 12)}";
}
}
internal HttpContent CreateContent(object content)
=> new StringContent(JsonConvert.SerializeObject(content,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}),
Encoding.UTF8, "application/json");
internal void Process(HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode)
throw new HttpRequestException($"HTTP ({message.StatusCode}): {Response(message.StatusCode)}");
}
internal async Task<T> ProcessAsync<T>(HttpResponseMessage message)
{
if (!message.IsSuccessStatusCode)
throw new HttpRequestException($"HTTP ({message.StatusCode}): {Response(message.StatusCode)}");
return JsonConvert.DeserializeObject<T>(await message.Content.ReadAsStringAsync(),
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
}
private string Response(HttpStatusCode code)
{
switch (code)
{
case HttpStatusCode.BadRequest:
return
"Missing Body/Content-Type | Unknown Content-Type | Speech Reconginition Failed | Invalid Parameters.";
case HttpStatusCode.Unauthorized: return "Wrong authentication key.";
case HttpStatusCode.RequestTimeout: return "Request timed out. Client was too slow to send data.";
case HttpStatusCode.InternalServerError:
return "Something went wrong on Wit's side, our experts are probably fixing it.";
case HttpStatusCode.ServiceUnavailable: return "Something is very wrong on Wit's side.";
default: return string.Empty;
}
}
}
}