Documentation for the Unity C# Library
Loading...
Searching...
No Matches
PlatformAPIHandler.cs
Go to the documentation of this file.
1using Newtonsoft.Json;
2using Newtonsoft.Json.Linq;
4using System;
5using System.Collections.Generic;
6using System.Net.Http;
7using System.Net.Http.Headers;
8using UnityEditor.PackageManager;
9using UnityEngine;
10
11namespace PixoVR.Apex
12{
32
33 public class APIHandler
34 {
35 public delegate void APIResponse(ResponseType type, HttpResponseMessage message, object responseData);
36 public APIResponse OnAPIResponse;
37
38 protected string URL = "";
39 protected HttpClient handlingClient = null;
40
41
42 // Need to migrate to this in the future
43 protected string apiURL = "";
44 protected HttpClient apiHandlingClient = null;
45
46 public APIHandler()
47 : this(PlatformEndpoints.NorthAmerica_ProductionEnvironment) { }
48
49 public APIHandler(string endpointUrl)
50 {
51 handlingClient = new HttpClient();
52 SetEndpoint(endpointUrl);
53
54 apiHandlingClient = new HttpClient();
55 }
56
57 HttpResponseMessage HandleException(Exception exception)
58 {
59 Debug.LogWarning("Exception has occurred: " + exception.Message);
60 HttpResponseMessage badRequestResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
61 OnAPIResponse.Invoke(ResponseType.RT_FAILED_RESPONSE, badRequestResponse, null);
62 return badRequestResponse;
63 }
64
65 public void SetEndpoint(string endpointUrl)
66 {
67 EnsureURLHasProtocol(ref endpointUrl);
68
69 URL = endpointUrl;
70 Debug.Log("[APIHandler] Set Endpoint to " + URL);
71 handlingClient.BaseAddress = new Uri(URL);
72 }
73
74 public void SetPlatformEndpoint(string endpointUrl)
75 {
76 EnsureURLHasProtocol(ref endpointUrl);
77
78 apiURL = endpointUrl;
79 apiHandlingClient.BaseAddress = new Uri(apiURL);
80 }
81
82 private void EnsureURLHasProtocol(ref string url)
83 {
84 if (!url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
85 {
86 if (url.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
87 {
88#if UNITY_EDITOR
89 Debug.LogWarning("URL must be a secured http endpoint for production.");
90#else
91 Debug.LogError("URL must be a securated http endpoint.");
92#endif
93 }
94 else
95 {
96 url.Insert(0, "https://");
97 }
98 }
99 }
100
101 public async void Ping(Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
102 {
103 handlingClient.DefaultRequestHeaders.Clear();
104 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
105
106 HttpResponseMessage response;
107 try
108 {
109 response = await handlingClient.GetAsync("/ping");
110 }
111 catch (Exception ex)
112 {
113 response = HandleException(ex);
114 failure?.Invoke(response, new FailureResponse { Error = "True", HttpCode = "400", Message = "Failed " });
115 }
116
117 success?.Invoke(response, null);
118 }
119
121 {
122 public int[] userIds;
123 }
124
125 public async void GenerateAssistedLogin(string authToken, int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
126 {
127 apiHandlingClient.DefaultRequestHeaders.Clear();
128 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
129 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
130
131 // Create the GraphQL request payload
132 string jsonContent = "";
133
134 if (userId >= 0)
135 {
136 var userIdArray = new int[1] { userId };
137 var input = new { input = new GenerateAuthCodeInput { userIds = userIdArray } };
138 // Create the GraphQL request payload
139 var graphqlRequest = new
140 {
141 operationName = "generateAuthCode",
142 variables = input,
143 query = "mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
144 };
145
146 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
147 }
148 else
149 {
150 var graphqlRequest = new
151 {
152 operationName = "generateAuthCode",
153 variables = new { input = new { } },
154 query = "mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
155 };
156
157 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
158 }
159
160 HttpContent requestContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
161 HttpResponseMessage response;
162 object responseContent = null;
163 try
164 {
165 response = await apiHandlingClient.PostAsync("/v2/query", requestContent);
166 string body = await response.Content.ReadAsStringAsync();
167 Debug.Log(body);
168
169 // Parse the GraphQL response structure
170 JObject jsonResponse = JObject.Parse(body);
171 var failureResponse = GetGQLFailureResponse(jsonResponse, "generateAuthCode");
172 if (failureResponse != null)
173 {
174 failure?.Invoke(response, failureResponse);
175 return;
176 }
177
178 // Extract the relevant data from the GraphQL response
179 string code = jsonResponse["data"]["generateAuthCode"]["code"]?.ToString();
180 string expiresAt = jsonResponse["data"]["generateAuthCode"]["expiresAt"]?.ToString();
181
182 // Create the GeneratedAssistedLogin object with the extracted data
184 {
185 AssistedLogin = new AssistedLoginCode { AuthCode = code, Expires = expiresAt },
186 };
187
188 responseContent = assistedLogin;
189 }
190 catch (Exception ex)
191 {
192 Debug.LogError($"Error generating assisted login: {ex.Message}");
193 response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
194 failure?.Invoke(response, new FailureResponse { Error = "true", Message = ex.Message });
195 return;
196 }
197
198 success?.Invoke(response, responseContent);
199 }
200
201 public async void GetUserMetricsForOrg(string authToken, int orgID, int page, FilterParams filterParams, Action<UserMetricsResponse, object> success, Action<HttpResponseMessage, FailureResponse> failure)
202 {
203 apiHandlingClient.DefaultRequestHeaders.Clear();
204 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
205 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
206
207 var paramsInput = new
208 {
209 search = filterParams.searchText,
210 sortField = filterParams.sortField,
211 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ? "ASC" : "DESC",
212 };
213
214 var graphqlRequest = new
215 {
216 operationName = "userMetrics",
217 variables = new { orgId = orgID, limit = 10, page = page, @params = paramsInput },
218 query = "query userMetrics($orgId: ID!, $limit: Int, $page: Int, $params: GenericQueryParamsInput) { userMetrics(orgId: $orgId, limit: $limit, page: $page, params: $params) { result { id firstName lastName username email role orgId org { id name } createdAt orgUnitId orgUnit { id name externalId } lastModuleId lastModule { id abbreviation description } sessionCount lastActiveAt isInModule } pageInfo { totalCount page offset pageSize previousPage nextPage } } }\r\n"
219 };
220
221 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
222 HttpContent requestContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
223 HttpResponseMessage response;
224 object responseContent;
225 try
226 {
227 response = await apiHandlingClient.PostAsync("/v2/query", requestContent);
228 string body = await response.Content.ReadAsStringAsync();
229
230 JObject jsonResponse = JObject.Parse(body);
231 var failureResponse = GetGQLFailureResponse(jsonResponse, "userMetrics");
232 if (failureResponse != null)
233 {
234 OnAPIResponse.Invoke(ResponseType.RT_GET_USER_METRICS_FOR_ORG, response, failureResponse);
235 failure?.Invoke(response, failureResponse);
236 return;
237 }
238
239 var userMetricsJSON = jsonResponse["data"]["userMetrics"];
240 var userMetricsResponse = JsonConvert.DeserializeObject<UserMetricsResponse>(userMetricsJSON.ToString());
241 userMetricsResponse.result.ForEach(u => u.RefreshDisplayFields());
242 responseContent = userMetricsResponse;
243
244 success?.Invoke(userMetricsResponse, response);
245 }
246 catch (Exception ex)
247 {
248 Debug.LogError($"Error retrieving users: {ex.Message}");
249 response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
250 responseContent = new FailureResponse { Error = "true", Message = ex.Message };
251 failure?.Invoke(response, responseContent as FailureResponse);
252 }
253 }
254
255 public async void GetDevicesForOrg(string authToken, int orgID, int page, FilterParams filterParams, Action<HttpResponseMessage, OrgDevicesResponse> success, Action<HttpResponseMessage, FailureResponse> failure)
256 {
257 apiHandlingClient.DefaultRequestHeaders.Clear();
258 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
259 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
260
261 var graphqlRequest = new
262 {
263 operationName = "OrgDeviceLicenses",
264 variables = new
265 {
266 orgId = orgID,
267 limit = 25,
268 page = page,
269 search = filterParams.searchText,
270 sortField = filterParams.sortField,
271 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ? "ASC" : "DESC",
272 },
273 query = "query OrgDeviceLicenses($orgId: ID!, $limit: Int!, $page: Int!, $search: String, $sortField: String, $sortOrder: SortOrder) { orgDeviceLicenses(orgId: $orgId, limit: $limit, page: $page, search: $search, deviceLicenseParams: { sortField: $sortField, sortOrder: $sortOrder }) { result { id name serial manufacturer macAddress model notes online batteryLevel lastSeen location { city region country continent timezone latitude longitude formatter } expiresAt org { id name } deviceType currentApp { id abbreviation description } user { fullname email username } } pageInfo { totalCount page offset pageSize previousPage nextPage } } }\r\n"
274 };
275
276 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
277 HttpContent requestContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
278 HttpResponseMessage response;
279 OrgDevicesResponse responseContent = null;
280 try
281 {
282 response = await apiHandlingClient.PostAsync("/v2/query", requestContent);
283 string body = await response.Content.ReadAsStringAsync();
284
285 JObject jsonResponse = JObject.Parse(body);
286 var failureResponse = GetGQLFailureResponse(jsonResponse, "orgDeviceLicenses");
287 if (failureResponse != null)
288 {
289 failure?.Invoke(response, failureResponse);
290 return;
291 }
292
293 var orgDevicesJSON = jsonResponse["data"]["orgDeviceLicenses"];
294 var deviceResponse = JsonConvert.DeserializeObject<OrgDevicesResponse>(orgDevicesJSON.ToString());
295 deviceResponse.result.ForEach(u => u.RefreshDisplayFields());
296 responseContent = deviceResponse;
297 }
298 catch (Exception ex)
299 {
300 Debug.LogError($"Error retrieving devices: {ex.Message}");
301 response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
302 failure?.Invoke(response, new FailureResponse { Error = "true", Message = ex.Message });
303 return;
304 }
305
306 success?.Invoke(response, responseContent);
307 }
308
309 public async void GetSessionHistory(string authToken, int page, SessionFilters sessionFilters, FilterParams filterParams, Action<HttpResponseMessage, SessionHistoryResponse> success, Action<HttpResponseMessage, FailureResponse> failure)
310 {
311 apiHandlingClient.DefaultRequestHeaders.Clear();
312 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
313 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
314
315 var paramsInput = new
316 {
317 search = filterParams.searchText,
318 sortField = filterParams.sortField,
319 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ? "ASC" : "DESC",
320 };
321
322 var graphqlRequest = new
323 {
324 operationName = "userSessionHistory",
325 variables = new
326 {
327 userId = sessionFilters.userIDs[0],
328 limit = 10,
329 page = page,
330
331 @params = paramsInput,
332 },
333 query = "query userSessionHistory($userId: ID!, $limit: Int, $page: Int, $params: GenericQueryParamsInput ){ userSessionHistory(userId: $userId, limit: $limit, page: $page, params: $params) { result { id userId moduleId module { id abbreviation description } rawScore maxScore status result startedAt completedAt } pageInfo { totalCount page offset pageSize previousPage nextPage } } }\r\n"
334 };
335
336 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
337 HttpContent requestContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
338 HttpResponseMessage response;
339 SessionHistoryResponse responseContent;
340 try
341 {
342 response = await apiHandlingClient.PostAsync("/v2/query", requestContent);
343 string body = await response.Content.ReadAsStringAsync();
344 JObject jsonResponse = JObject.Parse(body);
345 var failureResponse = GetGQLFailureResponse(jsonResponse, "userSessionHistory");
346 if (failureResponse != null)
347 {
348 failure?.Invoke(response, failureResponse);
349 return;
350 }
351 var sessionHistoryJSON = jsonResponse["data"]["userSessionHistory"];
352 var sessionHistoryResponse = JsonConvert.DeserializeObject<SessionHistoryResponse>(sessionHistoryJSON.ToString());
353 sessionHistoryResponse.result.ForEach(u => u.RefreshDisplayFields());
354 responseContent = sessionHistoryResponse;
355 }
356 catch (Exception ex)
357 {
358 Debug.LogError($"Error retrieving session history: {ex.Message}");
359 response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
360 failure?.Invoke(response, new FailureResponse { Error = "true", Message = ex.Message });
361 return;
362 }
363
364 success?.Invoke(response, responseContent);
365 }
366
367 public async void LoginWithToken(string token)
368 {
369 Debug.Log($"[Platform API] Logging in with token: {token}");
370 apiHandlingClient.DefaultRequestHeaders.Clear();
371 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
372 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
373
374 Debug.Log($"[Platform API] Sending login with a token.");
375 HttpResponseMessage response = await apiHandlingClient.GetAsync("/v2/auth/validate-signature");
376 string body = await response.Content.ReadAsStringAsync();
377 Debug.Log($"[Platform API] Body returned as {body}");
378 object responseContent = JsonConvert.DeserializeObject<UserLoginResponseContent>(body);
379 if ((responseContent as UserLoginResponseContent).HasErrored())
380 {
381 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
382 }
383
384 Debug.Log($"[Platform API] Got a valid login response!");
385 object loginResponseContent = (responseContent as UserLoginResponseContent).User;
386
387 OnAPIResponse.Invoke(ResponseType.RT_LOGIN, response, loginResponseContent);
388 }
389
390 public async void Login(LoginData login)
391 {
392 Debug.Log("[Platform API] Calling Login.");
393 handlingClient.DefaultRequestHeaders.Clear();
394
395 HttpContent loginRequestContent = new StringContent(JsonUtility.ToJson(login));
396 loginRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
397
398 Debug.Log("[Platform API] Call to post api login.");
399 HttpResponseMessage response = await handlingClient.PostAsync("/login", loginRequestContent);
400 string body = await response.Content.ReadAsStringAsync();
401 Debug.Log("[Platform API] Got response body: " + body);
402 object responseContent = JsonConvert.DeserializeObject<LoginResponseContent>(body);
403 if ((responseContent as LoginResponseContent).HasErrored())
404 {
405 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
406 }
407
408 Debug.Log("[Platform API] Response content deserialized.");
409 OnAPIResponse.Invoke(ResponseType.RT_LOGIN, response, responseContent);
410 }
411
412 public async void GetUserData(string authToken, int userId)
413 {
414 handlingClient.DefaultRequestHeaders.Clear();
415 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
416 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
417
418 HttpResponseMessage response = await handlingClient.GetAsync(string.Format("/user/{0}", userId));
419 string body = await response.Content.ReadAsStringAsync();
420 object responseContent = JsonConvert.DeserializeObject<GetUserResponseContent>(body);
421 GetUserResponseContent userInfo = responseContent as GetUserResponseContent;
422 if ((responseContent as GetUserResponseContent).HasErrored())
423 {
424 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
425 }
426
427 OnAPIResponse.Invoke(ResponseType.RT_GET_USER, response, responseContent);
428 }
429
430 public async void GetUserModules(string authToken, int userId)
431 {
432 handlingClient.DefaultRequestHeaders.Clear();
433 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
434 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
435
436 UserModulesRequestData usersModulesRequest = new UserModulesRequestData();
437 usersModulesRequest.UserIds.Add(userId);
438 HttpContent loginRequestContent = new StringContent(JsonUtility.ToJson(usersModulesRequest));
439 loginRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
440
441 HttpResponseMessage response = await handlingClient.PostAsync("/access/users", loginRequestContent);
442 string body = await response.Content.ReadAsStringAsync();
443 object responseContent = JsonConvert.DeserializeObject<GetUserModulesResponse>(body);
444 if ((responseContent as GetUserModulesResponse).HasErrored())
445 {
446 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
447 }
448 else
449 {
450 (responseContent as GetUserModulesResponse).ParseData();
451 }
452
453 OnAPIResponse.Invoke(ResponseType.RT_GET_USER_MODULES, response, responseContent);
454 }
455
456 public async void GetQuickIDAuthenticationUsers(string serialNumber)
457 {
458 apiHandlingClient.DefaultRequestHeaders.Clear();
459 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
460
461 HttpResponseMessage response = await apiHandlingClient.GetAsync(string.Format("/v2/auth/quick-id/get-users?serialNumber={0}", serialNumber));
462 string body = await response.Content.ReadAsStringAsync();
463
464 Debug.Log($"[Platform API] Body returned as {body}");
465
466 object responseContent = JsonConvert.DeserializeObject<QuickIDAuthGetUsersResponse>(body);
467 if ((responseContent as QuickIDAuthGetUsersResponse).HasErrored())
468 {
469 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
470 }
471
472 OnAPIResponse.Invoke(ResponseType.RT_QUICK_ID_AUTH_GET_USERS, response, responseContent);
473 }
474
475 public async void QuickIDLogin(QuickIDLoginData login)
476 {
477 Debug.Log("[Platform API] Calling Quick ID login.");
478 apiHandlingClient.DefaultRequestHeaders.Clear();
479
480 HttpContent loginRequestContent = new StringContent(JsonUtility.ToJson(login));
481 Debug.Log("[Platform API] Quick ID login request content: " + JsonUtility.ToJson(login));
482 loginRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
483
484 Debug.Log("[Platform API] Call to post api Quick ID login.");
485 HttpResponseMessage response = await apiHandlingClient.PostAsync("/v2/auth/quick-id/login", loginRequestContent);
486 string body = await response.Content.ReadAsStringAsync();
487 Debug.Log("[Platform API] Got response body: " + body);
488 object responseContent = JsonConvert.DeserializeObject<PlatformLoginResponse>(body);
489
490 var loginResponseContent = new LoginResponseContent();
491 if ((responseContent as PlatformLoginResponse).HasErrored())
492 {
493 responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
494 }
495 else
496 {
497 var platformLoginResponse = responseContent as PlatformLoginResponse;
498
499 loginResponseContent.Token = platformLoginResponse.Token;
500 if (platformLoginResponse.User != null)
501 {
502 loginResponseContent.ID = platformLoginResponse.User.Id;
503 loginResponseContent.OrgId = platformLoginResponse.User.OrgId;
504 loginResponseContent.First = platformLoginResponse.User.FirstName;
505 loginResponseContent.Last = platformLoginResponse.User.LastName;
506 loginResponseContent.Email = platformLoginResponse.User.Email;
507 loginResponseContent.Role = platformLoginResponse.User.Role;
508 loginResponseContent.Org = platformLoginResponse.User.Org;
509 }
510 else
511 {
512 Debug.Log("[Platform API] Quick ID login response did not contain user data.");
513 }
514 }
515
516 Debug.Log("[Platform API] Response content deserialized and mapped.");
517 OnAPIResponse.Invoke(ResponseType.RT_QUICK_ID_AUTH_LOGIN, response, loginResponseContent);
518 }
519
520 public async void GetModuleAccess(int moduleId, int userId, string serialNumber)
521 {
522 Debug.Log("[Platform API Handler] Get Module Access");
523 handlingClient.DefaultRequestHeaders.Clear();
524 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
525
526 string optionalParameters = "";
527 Debug.Log($"Checking for a serial number: {serialNumber}");
528 if (!string.IsNullOrEmpty(serialNumber))
529 {
530 optionalParameters = "?serial=" + serialNumber;
531 }
532
533 Debug.Log(
534 $"[{GetType().Name}] Checking module access at: "
535 + String.Format("/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
536 );
537
538 HttpResponseMessage response = await handlingClient.GetAsync(
539 String.Format("/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
540 );
541 string body = await response.Content.ReadAsStringAsync();
542
543 Debug.Log($"[{GetType().Name}] GetModuleAccess return body: {body}");
544 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
545 if (!(responseContent as FailureResponse).HasErrored())
546 {
547 responseContent = JsonConvert.DeserializeObject<UserAccessResponseContent>(body);
548 }
549 OnAPIResponse.Invoke(ResponseType.RT_GET_USER_ACCESS, response, responseContent);
550 }
551
552 public async void SendHeartbeat(string authToken, int sessionId, Action<HttpResponseMessage, object> success = null, Action<HttpResponseMessage, FailureResponse> failure = null)
553 {
554 apiHandlingClient.DefaultRequestHeaders.Clear();
555 apiHandlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
556 apiHandlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
557
558 HeartbeatData heartbeatData = new HeartbeatData(sessionId);
559
560 HttpContent heartbeatRequestContent = new StringContent(heartbeatData.ToJSON());
561 heartbeatRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
562
563 HttpResponseMessage response = await apiHandlingClient.PostAsync(
564 "/heartbeat/pulse",
565 heartbeatRequestContent
566 );
567 string body = await response.Content.ReadAsStringAsync();
568 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
569 if ((responseContent as FailureResponse).HasErrored())
570 {
571 failure?.Invoke(response, responseContent as FailureResponse);
572 return;
573 }
574
575 success?.Invoke(response, null);
576 }
577
578 public async void JoinSession(string authToken, JoinSessionData joinData, Action<HttpResponseMessage, JoinSessionResponse> success, Action<HttpResponseMessage, FailureResponse> failure)
579 {
580 handlingClient.DefaultRequestHeaders.Clear();
581 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
582 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
583
584 HttpContent joinSessionRequestContent = new StringContent(joinData.ToJSON());
585 joinSessionRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
586
587 HttpResponseMessage response = await handlingClient.PostAsync("/event", joinSessionRequestContent);
588 string body = await response.Content.ReadAsStringAsync();
589 object responseContent = JsonConvert.DeserializeObject<JoinSessionResponse>(body);
590 if ((responseContent as FailureResponse).HasErrored())
591 {
592 failure?.Invoke(response, responseContent as FailureResponse);
593 return;
594 }
595 else
596 {
597 JoinSessionResponse joinSessionResponse = (responseContent as JoinSessionResponse);
598 joinSessionResponse.ParseData();
599 responseContent = joinSessionResponse;
600 }
601
602 success?.Invoke(response, responseContent as JoinSessionResponse);
603 }
604
605 public async void CompleteSession(string authToken, CompleteSessionData completionData, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
606 {
607 handlingClient.DefaultRequestHeaders.Clear();
608 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
609 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
610
611 HttpContent completeSessionRequestContent = new StringContent(completionData.ToJSON());
612 completeSessionRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
613
614 HttpResponseMessage response = await handlingClient.PostAsync("/event", completeSessionRequestContent);
615 string body = await response.Content.ReadAsStringAsync();
616 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
617 if ((responseContent as FailureResponse).HasErrored())
618 {
619 failure?.Invoke(response, responseContent as FailureResponse);
620 return;
621 }
622
623 success?.Invoke(response, null);
624 }
625
626 public async void SendSessionEvent(string authToken, SessionEventData sessionEvent, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
627 {
628 handlingClient.DefaultRequestHeaders.Clear();
629 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
630 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
631
632 HttpContent sessionEventRequestContent = new StringContent(sessionEvent.ToJSON());
633 sessionEventRequestContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");
634
635 HttpResponseMessage response = await handlingClient.PostAsync("/event", sessionEventRequestContent);
636 string body = await response.Content.ReadAsStringAsync();
637 object responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
638 if ((responseContent as FailureResponse).HasErrored())
639 {
640 failure?.Invoke(response, responseContent as FailureResponse);
641 return;
642 }
643
644 success?.Invoke(response, null);
645 }
646
647 public async void GetModuleList(string authToken, string platform)
648 {
649 handlingClient.DefaultRequestHeaders.Clear();
650 handlingClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
651 handlingClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
652
653 string endpoint = "/modules";
654 if (platform != null && platform.Length > 0)
655 {
656 endpoint += $"?platform={platform}";
657 }
658
659 Debug.Log($"GetModuleList built endpoint: {endpoint}");
660
661 HttpResponseMessage response = await handlingClient.GetAsync(endpoint);
662 string body = await response.Content.ReadAsStringAsync();
663
664 try
665 {
666 var responseContent = JsonConvert.DeserializeObject<FailureResponse>(body);
667 OnAPIResponse.Invoke(ResponseType.RT_GET_MODULES_LIST, response, responseContent);
668 return;
669 }
670 catch (Exception ex)
671 {
672 Debug.LogWarning(ex);
673 }
674
675 List<OrgModule> orgModules = new List<OrgModule>();
676 JArray array = JArray.Parse(body);
677 if (array != null)
678 {
679 var tokens = array.Children();
680 foreach (JToken selectedToken in tokens)
681 {
682 OrgModule orgModule = ScriptableObject.CreateInstance<OrgModule>();
683 orgModule.Parse(selectedToken);
684 orgModules.Add(orgModule);
685 }
686 }
687
688 Debug.Log(orgModules.Count.ToString());
689 OnAPIResponse.Invoke(ResponseType.RT_GET_MODULES_LIST, response, orgModules);
690 }
691
692 private FailureResponse GetGQLFailureResponse(JObject jsonResponse, string jsonDataObjectKey)
693 {
694
695 if (!String.IsNullOrEmpty(jsonResponse["errors"]?.ToString()))
696 {
697 string errorMessage = jsonResponse["errors"]?[0]?["message"]?.ToString() ?? "Unknown GraphQL error";
698 return new FailureResponse { Error = "true", Message = errorMessage };
699 }
700
701 if (String.IsNullOrEmpty(jsonResponse["data"]?.ToString()) || String.IsNullOrEmpty(jsonResponse["data"][jsonDataObjectKey]?.ToString()))
702 {
703 return new FailureResponse
704 {
705 Error = "true",
706 Message = "Invalid response format from server",
707 };
708 }
709
710 return null;
711 }
712 }
713}
APIHandler(string endpointUrl)
async void GetUserModules(string authToken, int userId)
async void GetUserMetricsForOrg(string authToken, int orgID, int page, FilterParams filterParams, Action< UserMetricsResponse, object > success, Action< HttpResponseMessage, FailureResponse > failure)
async void QuickIDLogin(QuickIDLoginData login)
HttpResponseMessage HandleException(Exception exception)
void EnsureURLHasProtocol(ref string url)
async void CompleteSession(string authToken, CompleteSessionData completionData, Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
async void LoginWithToken(string token)
async void Login(LoginData login)
FailureResponse GetGQLFailureResponse(JObject jsonResponse, string jsonDataObjectKey)
void SetPlatformEndpoint(string endpointUrl)
async void GenerateAssistedLogin(string authToken, int userId, Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
async void GetQuickIDAuthenticationUsers(string serialNumber)
async void GetUserData(string authToken, int userId)
async void GetSessionHistory(string authToken, int page, SessionFilters sessionFilters, FilterParams filterParams, Action< HttpResponseMessage, SessionHistoryResponse > success, Action< HttpResponseMessage, FailureResponse > failure)
async void SendHeartbeat(string authToken, int sessionId, Action< HttpResponseMessage, object > success=null, Action< HttpResponseMessage, FailureResponse > failure=null)
delegate void APIResponse(ResponseType type, HttpResponseMessage message, object responseData)
async void SendSessionEvent(string authToken, SessionEventData sessionEvent, Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
async void Ping(Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
void SetEndpoint(string endpointUrl)
async void GetDevicesForOrg(string authToken, int orgID, int page, FilterParams filterParams, Action< HttpResponseMessage, OrgDevicesResponse > success, Action< HttpResponseMessage, FailureResponse > failure)
async void JoinSession(string authToken, JoinSessionData joinData, Action< HttpResponseMessage, JoinSessionResponse > success, Action< HttpResponseMessage, FailureResponse > failure)
async void GetModuleAccess(int moduleId, int userId, string serialNumber)
async void GetModuleList(string authToken, string platform)
[Serializable]
Definition ApexTypes.cs:164
void Parse(JToken token)
Definition ApexTypes.cs:394
[Serializable]
Definition ApexTypes.cs:609
List< UserMetric > result
Definition ApexTypes.cs:716