/
AIDataService.cs
191 lines (155 loc) · 6.06 KB
/
AIDataService.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
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Configuration;
using System.Net;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using ApiAiSDK.Model;
using ApiAiSDK.Http;
using System.Diagnostics;
namespace ApiAiSDK
{
public class AIDataService
{
private readonly AIConfiguration config;
public string SessionId { get; }
public AIDataService(AIConfiguration config)
{
this.config = config;
if (string.IsNullOrEmpty(config.SessionId))
{
SessionId = Guid.NewGuid().ToString();
}
else
{
SessionId = config.SessionId;
}
}
public AIResponse Request(AIRequest request)
{
request.Language = config.Language.code;
request.Timezone = TimeZone.CurrentTimeZone.StandardName;
request.SessionId = SessionId;
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.Accept = "application/json";
httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
var jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);
if (config.DebugLog)
{
Debug.WriteLine("Request: " + jsonRequest);
}
using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
{
streamWriter.Write(jsonRequest);
streamWriter.Close();
}
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (config.DebugLog)
{
Debug.WriteLine("Response: " + result);
}
var aiResponse = JsonConvert.DeserializeObject<AIResponse>(result);
CheckForErrors(aiResponse);
return aiResponse;
}
}
catch (Exception e)
{
throw new AIServiceException(e);
}
}
public AIResponse VoiceRequest(Stream voiceStream, RequestExtras requestExtras = null)
{
var request = new AIRequest();
request.Language = config.Language.code;
request.Timezone = TimeZone.CurrentTimeZone.StandardName;
request.SessionId = SessionId;
if (requestExtras != null)
{
requestExtras.CopyTo(request);
}
try
{
var httpRequest = (HttpWebRequest)WebRequest.Create(config.RequestUrl);
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Headers.Add("Authorization", "Bearer " + config.ClientAccessToken);
var jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var jsonRequest = JsonConvert.SerializeObject(request, Formatting.None, jsonSettings);
if (config.DebugLog)
{
Debug.WriteLine("Request: " + jsonRequest);
}
var multipartClient = new MultipartHttpClient(httpRequest);
multipartClient.connect();
multipartClient.addStringPart("request", jsonRequest);
multipartClient.addFilePart("voiceData", "voice.wav", voiceStream);
multipartClient.finish();
var responseJsonString = multipartClient.getResponse();
if (config.DebugLog)
{
Debug.WriteLine("Response: " + responseJsonString);
}
var aiResponse = JsonConvert.DeserializeObject<AIResponse>(responseJsonString);
CheckForErrors(aiResponse);
return aiResponse;
}
catch (Exception e)
{
throw new AIServiceException(e);
}
}
public bool ResetContexts()
{
var cleanRequest = new AIRequest("empty_query_for_resetting_contexts");
cleanRequest.ResetContexts = true;
try {
var response = Request(cleanRequest);
return !response.IsError;
} catch (AIServiceException e) {
Debug.WriteLine("Exception while contexts clean." + e);
return false;
}
}
static void CheckForErrors(AIResponse aiResponse)
{
if (aiResponse == null)
{
throw new AIServiceException("API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.IsError)
{
throw new AIServiceException(aiResponse);
}
}
}
}