Documentation for the Unity C# Library
Loading...
Searching...
No Matches
PlatformAPIHandler.cs
Go to the documentation of this file.
1using Newtonsoft.Json;
2using System;
3using System.Text.RegularExpressions;
4using System.Net.Http;
5using System.Net.Http.Headers;
6using UnityEngine;
8using System.Collections.Generic;
9using Newtonsoft.Json.Linq;
10
11namespace PixoVR.Apex
12{
29
30 public class APIHandler
31 {
32 public delegate void APIResponse(ResponseType type, HttpResponseMessage message, object responseData);
33 public APIResponse OnAPIResponse;
34
35 protected string URL = "";
36 protected HttpClient handlingClient = null;
37
38 // Move to a separate plugin
39 protected string webURL = "";
40 protected HttpClient webHandlingClient = null;
41
42 // Need to migrate to this in the future
43 protected string apiURL = "";
44 protected HttpClient apiHandlingClient = null;
45
46
47 public APIHandler() : this(PlatformEndpoints.NorthAmerica_ProductionEnvironment)
48 {
49 }
50
51 public APIHandler(string endpointUrl)
52 {
53 handlingClient = new HttpClient();
54 SetEndpoint(endpointUrl);
55
56 webHandlingClient = new HttpClient();
57 apiHandlingClient = new HttpClient();
58 }
59
60 HttpResponseMessage HandleException(Exception exception)
61 {
62 Debug.LogWarning("Exception has occurred: " + exception.Message);
63 HttpResponseMessage badRequestResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
64 OnAPIResponse.Invoke(ResponseType.RT_FAILED_RESPONSE, badRequestResponse, null);
65 return badRequestResponse;
66 }
67
68 public void SetEndpoint(string endpointUrl)
69 {
70 if (!endpointUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
71 {
72 if (endpointUrl.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
73 {
74 Debug.LogWarning("Endpoint must be a secured http endpoint.");
75 Regex expression = new Regex(Regex.Escape("http"));
76 endpointUrl = expression.Replace(endpointUrl, "https", 1);
77 }
78 else
79 {
80 endpointUrl.Insert(0, "https://");
81 }
82 }
83
84 URL = endpointUrl;
85 Debug.Log("[APIHandler] Set Endpoint to " + URL);
86 handlingClient.BaseAddress = new Uri(URL);
87 }
88
89 public void SetWebEndpoint(string endpointUrl)
90 {
91 if (!endpointUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
92 {
93 if (endpointUrl.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
94 {
95 Debug.LogWarning("Endpoint must be a secured http endpoint.");
96 Regex expression = new Regex(Regex.Escape("http"));
97 endpointUrl = expression.Replace(endpointUrl, "https", 1);
98 }
99 else
100 {
101 endpointUrl.Insert(0, "https://");
102 }
103 }
104
105 webURL = endpointUrl;
106 webHandlingClient.BaseAddress = new Uri(webURL);
107 }
108
109 public void SetPlatformEndpoint(string endpointUrl)
110 {
111 if (!endpointUrl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
112 {
113 if (endpointUrl.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
114 {
115 Debug.LogWarning("Endpoint must be a secured http endpoint.");
116 Regex expression = new Regex(Regex.Escape("http"));
117 endpointUrl = expression.Replace(endpointUrl, "https", 1);
118 }
119 else
120 {
121 endpointUrl.Insert(0, "https://");
122 }
123 }
124
125 apiURL = endpointUrl;
126 apiHandlingClient.BaseAddress = new Uri(apiURL);
127 }
128
129 public async void Ping()
130 {
131 handlingClient.DefaultRequestHeaders.Clear();
132 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
133
134 HttpResponseMessage response;
135 try
136 {
137 response = await handlingClient.GetAsync("/ping");
138 }
139 catch (Exception ex)
140 {
141 response = HandleException(ex);
142 }
143
144 OnAPIResponse.Invoke(ResponseType.RT_PING, response, null);
145 }
146
147 public async void GenerateAssistedLogin(string authToken, int userId)
148 {
149 webHandlingClient.DefaultRequestHeaders.Clear();
150 webHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
151 webHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
152 webHandlingClient.DefaultRequestHeaders.Add("x-access-token", authToken);
153
154 HttpResponseMessage response = await webHandlingClient.GetAsync(string.Format("api/user/{0}/assisted-login", userId));
155 string body = await response.Content.ReadAsStringAsync();
156 Debug.Log(body);
157 object responseContent = JsonConvert.DeserializeObject<GeneratedAssistedLogin>(body);
158 GeneratedAssistedLogin assistedLogin = responseContent as GeneratedAssistedLogin;
159 if ((responseContent as GeneratedAssistedLogin).HasErrored())
160 {
161 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
162 }
163
164 OnAPIResponse.Invoke(ResponseType.RT_GEN_AUTH_LOGIN, response, responseContent);
165 }
166
167 public async void LoginWithToken(string token)
168 {
169 apiHandlingClient.DefaultRequestHeaders.Clear();
170 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
171 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
172
173 HttpResponseMessage response = await apiHandlingClient.GetAsync("/v2/auth/validate-signature");
174 string body = await response.Content.ReadAsStringAsync();
175 object responseContent = JsonConvert.DeserializeObject<UserLoginResponseContent>(body);
176 if ((responseContent as UserLoginResponseContent).HasErrored())
177 {
178 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
179 }
180
181 object loginResponseContent = (responseContent as UserLoginResponseContent).User;
182
183 OnAPIResponse.Invoke(ResponseType.RT_LOGIN, response, loginResponseContent);
184
185 }
186
187 public async void Login(LoginData login)
188 {
189 Debug.Log("[Platform API] Calling Login.");
190 handlingClient.DefaultRequestHeaders.Clear();
191
192 HttpContent loginRequestContent = new StringContent(JsonUtility.ToJson(login));
193 loginRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
194
195 Debug.Log("[Platform API] Call to post api login.");
196 HttpResponseMessage response = await handlingClient.PostAsync("/login", loginRequestContent);
197 string body = await response.Content.ReadAsStringAsync();
198 Debug.Log("[Platform API] Got response body.");
199 object responseContent = JsonConvert.DeserializeObject<LoginResponseContent>(body);
200 if ((responseContent as LoginResponseContent).HasErrored())
201 {
202 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
203 }
204
205 Debug.Log("[Platform API] Response content deserialized.");
206 OnAPIResponse.Invoke(ResponseType.RT_LOGIN, response, responseContent);
207 }
208
209 public async void GetUserData(string authToken, int userId)
210 {
211 handlingClient.DefaultRequestHeaders.Clear();
212 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
213 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
214
215 HttpResponseMessage response = await handlingClient.GetAsync(string.Format("/user/{0}", userId));
216 string body = await response.Content.ReadAsStringAsync();
217 object responseContent = JsonConvert.DeserializeObject<GetUserResponseContent>(body);
218 GetUserResponseContent userInfo = responseContent as GetUserResponseContent;
219 if ((responseContent as GetUserResponseContent).HasErrored())
220 {
221 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
222 }
223
224 OnAPIResponse.Invoke(ResponseType.RT_GET_USER, response, responseContent);
225 }
226
227 public async void GetUserModules(string authToken, int userId)
228 {
229 handlingClient.DefaultRequestHeaders.Clear();
230 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
231 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
232
233 UserModulesRequestData usersModulesRequest = new UserModulesRequestData();
234 usersModulesRequest.UserIds.Add(userId);
235 HttpContent loginRequestContent = new StringContent(JsonUtility.ToJson(usersModulesRequest));
236 loginRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
237
238 HttpResponseMessage response = await handlingClient.PostAsync("/access/users", loginRequestContent);
239 string body = await response.Content.ReadAsStringAsync();
240 object responseContent = JsonConvert.DeserializeObject<GetUserModulesResponse>(body);
241 if ((responseContent as GetUserModulesResponse).HasErrored())
242 {
243 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
244 }
245 else
246 {
247 (responseContent as GetUserModulesResponse).ParseData();
248 }
249
250 OnAPIResponse.Invoke(ResponseType.RT_GET_USER_MODULES, response, responseContent);
251 }
252
253 public async void JoinSession(string authToken, JoinSessionData joinData)
254 {
255 handlingClient.DefaultRequestHeaders.Clear();
256 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
257 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
258
259 HttpContent joinSessionRequestContent = new StringContent(joinData.ToJSON());
260 joinSessionRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
261
262 HttpResponseMessage response = await handlingClient.PostAsync("/event", joinSessionRequestContent);
263 string body = await response.Content.ReadAsStringAsync();
264 object responseContent = JsonConvert.DeserializeObject<JoinSessionResponse>(body);
265 if ((responseContent as FailureResponse).HasErrored())
266 {
267 responseContent = null;
268 }
269 else
270 {
271 JoinSessionResponse joinSessionResponse = (responseContent as JoinSessionResponse);
272 joinSessionResponse.ParseData();
273 responseContent = joinSessionResponse;
274 }
275
276 OnAPIResponse.Invoke(ResponseType.RT_SESSION_JOINED, response, responseContent);
277 }
278
279 public async void GetModuleAccess(int moduleId, int userId, string serialNumber)
280 {
281 Debug.Log("[Platform API Handler] Get Module Access");
282 handlingClient.DefaultRequestHeaders.Clear();
283 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
284
285 string optionalParameters = "";
286 if(serialNumber.Length > 0)
287 {
288 optionalParameters = "?serial=" + serialNumber;
289 }
290
291 Debug.Log("Checkingm module access at: " + String.Format("/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters));
292
293 HttpResponseMessage response = await handlingClient.GetAsync(String.Format("/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters));
294 string body = await response.Content.ReadAsStringAsync();
295
296 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
297 if (!(responseContent as FailureResponse).HasErrored())
298 {
299 responseContent = JsonConvert.DeserializeObject<UserAccessResponseContent>(body);
300
301 }
302 OnAPIResponse.Invoke(ResponseType.RT_GET_USER_ACCESS, response, responseContent);
303 }
304
305 public async void SendHeartbeat(string authToken, int sessionId)
306 {
307 apiHandlingClient.DefaultRequestHeaders.Clear();
308 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
309 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
310
311 HeartbeatData heartbeatData = new HeartbeatData(sessionId);
312
313 HttpContent heartbeatRequestContent = new StringContent(heartbeatData.ToJSON());
314 heartbeatRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
315
316 HttpResponseMessage response = await apiHandlingClient.PostAsync("/heartbeat/pulse", heartbeatRequestContent);
317 string body = await response.Content.ReadAsStringAsync();
318 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
319 if ((responseContent as FailureResponse).HasErrored())
320 {
321 responseContent = null;
322 }
323
324 OnAPIResponse.Invoke(ResponseType.RT_HEARTBEAT, response, responseContent);
325 }
326
327 public async void CompleteSession(string authToken, CompleteSessionData completionData)
328 {
329 handlingClient.DefaultRequestHeaders.Clear();
330 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
331 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
332
333 HttpContent completeSessionRequestContent = new StringContent(completionData.ToJSON());
334 completeSessionRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
335
336 HttpResponseMessage response = await handlingClient.PostAsync("/event", completeSessionRequestContent);
337 string body = await response.Content.ReadAsStringAsync();
338 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
339 if ((responseContent as FailureResponse).HasErrored())
340 {
341 responseContent = null;
342 }
343
344 OnAPIResponse.Invoke(ResponseType.RT_SESSION_COMPLETE, response, responseContent);
345 }
346
347 public async void SendSessionEvent(string authToken, SessionEventData sessionEvent)
348 {
349 handlingClient.DefaultRequestHeaders.Clear();
350 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
351 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
352
353 HttpContent sessionEventRequestContent = new StringContent(sessionEvent.ToJSON());
354 sessionEventRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
355
356 HttpResponseMessage response = await handlingClient.PostAsync("/event", sessionEventRequestContent);
357 string body = await response.Content.ReadAsStringAsync();
358 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
359 if ((responseContent as FailureResponse).HasErrored())
360 {
361 responseContent = null;
362 }
363
364 OnAPIResponse.Invoke(ResponseType.RT_SESSION_EVENT, response, responseContent);
365 }
366
367 public async void GetModuleList(string authToken, string platform)
368 {
369 handlingClient.DefaultRequestHeaders.Clear();
370 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
371 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
372
373 HttpResponseMessage response = await handlingClient.GetAsync(string.Format("/modules?platform={0}", platform));
374 string body = await response.Content.ReadAsStringAsync();
375 object responseContent = null;
376 List<OrgModule> orgModules = new List<OrgModule>();
377 JArray array = JArray.Parse(body);
378 if(array != null)
379 {
380 var tokens = array.Children();
381 foreach(JToken selectedToken in tokens)
382 {
383 OrgModule orgModule = new OrgModule(selectedToken);
384 orgModules.Add(orgModule);
385 }
386 }
387
388 Debug.Log(orgModules.Count.ToString());
389
390 if(orgModules.Count <= 0)
391 {
392 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
393 }
394 else
395 {
396 responseContent = orgModules;
397 }
398
399 OnAPIResponse.Invoke(ResponseType.RT_GET_MODULES_LIST, response, responseContent);
400 }
401 }
402}
async void SendHeartbeat(string authToken, int sessionId)
async void GenerateAssistedLogin(string authToken, int userId)
APIHandler(string endpointUrl)
async void GetUserModules(string authToken, int userId)
HttpResponseMessage HandleException(Exception exception)
async void JoinSession(string authToken, JoinSessionData joinData)
async void LoginWithToken(string token)
async void CompleteSession(string authToken, CompleteSessionData completionData)
async void Login(LoginData login)
async void SendSessionEvent(string authToken, SessionEventData sessionEvent)
void SetPlatformEndpoint(string endpointUrl)
async void GetUserData(string authToken, int userId)
delegate void APIResponse(ResponseType type, HttpResponseMessage message, object responseData)
void SetEndpoint(string endpointUrl)
void SetWebEndpoint(string endpointUrl)
async void GetModuleAccess(int moduleId, int userId, string serialNumber)
async void GetModuleList(string authToken, string platform)
[Serializable]
Definition ApexTypes.cs:150