2using Newtonsoft.Json.Linq;
5using System.Collections.Generic;
7using System.Net.Http.Headers;
39 protected string URL =
"";
60 Debug.LogWarning(
"Exception has occurred: " + exception.Message);
61 HttpResponseMessage badRequestResponse =
new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
63 return badRequestResponse;
71 Debug.Log(
"[APIHandler] Set Endpoint to " +
URL);
72 handlingClient.BaseAddress =
new Uri(
URL);
80 apiHandlingClient.BaseAddress =
new Uri(
apiURL);
85 if (!url.StartsWith(
"https://", StringComparison.InvariantCultureIgnoreCase))
87 if (url.StartsWith(
"http:", StringComparison.InvariantCultureIgnoreCase))
90 Debug.LogWarning(
"URL must be a secured http endpoint for production.");
92 Debug.LogError(
"URL must be a securated http endpoint.");
97 url.Insert(0,
"https://");
105 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
107 HttpResponseMessage response;
125 public async
void GenerateAssistedLogin(
string authToken,
int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
128 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
129 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
132 string jsonContent =
"";
136 var userIdArray =
new int[1] { userId };
139 var graphqlRequest =
new
141 operationName =
"generateAuthCode",
143 query =
"mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
146 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
150 var graphqlRequest =
new
152 operationName =
"generateAuthCode",
153 variables =
new { input =
new { } },
154 query =
"mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
157 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
160 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
161 HttpResponseMessage response;
162 object responseContent;
166 string body = await response.Content.ReadAsStringAsync();
170 JObject jsonResponse = JObject.Parse(body);
172 if (failureResponse !=
null)
174 failure?.Invoke(response, failureResponse);
179 string code = jsonResponse[
"data"][
"generateAuthCode"][
"code"]?.ToString();
180 string expiresAt = jsonResponse[
"data"][
"generateAuthCode"][
"expiresAt"]?.ToString();
188 responseContent = assistedLogin;
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 });
198 success?.Invoke(response, responseContent);
204 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
205 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
207 var paramsInput =
new
211 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ?
"ASC" :
"DESC",
214 var graphqlRequest =
new
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"
221 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
222 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
223 HttpResponseMessage response;
224 object responseContent;
228 string body = await response.Content.ReadAsStringAsync();
230 JObject jsonResponse = JObject.Parse(body);
232 if (failureResponse !=
null)
238 var userMetricsJSON = jsonResponse[
"data"][
"userMetrics"];
239 var userMetricsResponse = JsonConvert.DeserializeObject<
UserMetricsResponse>(userMetricsJSON.ToString());
240 userMetricsResponse.
result.ForEach(u => u.RefreshDisplayFields());
241 responseContent = userMetricsResponse;
245 Debug.LogError($
"Error retrieving users: {ex.Message}");
246 response =
new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
247 responseContent =
new FailureResponse { Error =
"true", Message = ex.Message };
256 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
257 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
259 var graphqlRequest =
new
261 operationName =
"OrgDeviceLicenses",
269 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ?
"ASC" :
"DESC",
271 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 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
275 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
276 HttpResponseMessage response;
277 object responseContent;
281 string body = await response.Content.ReadAsStringAsync();
283 JObject jsonResponse = JObject.Parse(body);
285 if (failureResponse !=
null)
291 var orgDevicesJSON = jsonResponse[
"data"][
"orgDeviceLicenses"];
292 var deviceResponse = JsonConvert.DeserializeObject<
OrgDevicesResponse>(orgDevicesJSON.ToString());
293 deviceResponse.
result.ForEach(u => u.RefreshDisplayFields());
294 responseContent = deviceResponse;
298 Debug.LogError($
"Error retrieving devices: {ex.Message}");
299 response =
new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
300 responseContent =
new FailureResponse { Error =
"true", Message = ex.Message };
309 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
310 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
312 var paramsInput =
new
316 sortOrder = filterParams.sortOrder == FilterParams.SortOrder.Ascending ?
"ASC" :
"DESC",
319 var graphqlRequest =
new
321 operationName =
"userSessionHistory",
324 userId = sessionFilters.
userIDs[0],
328 @params = paramsInput,
330 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"
332 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
333 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
334 HttpResponseMessage response;
335 object responseContent;
339 string body = await response.Content.ReadAsStringAsync();
340 JObject jsonResponse = JObject.Parse(body);
342 if (failureResponse !=
null)
347 var sessionHistoryJSON = jsonResponse[
"data"][
"userSessionHistory"];
348 var sessionHistoryResponse = JsonConvert.DeserializeObject<
SessionHistoryResponse>(sessionHistoryJSON.ToString());
349 sessionHistoryResponse.
result.ForEach(u => u.RefreshDisplayFields());
350 responseContent = sessionHistoryResponse;
354 Debug.LogError($
"Error retrieving session history: {ex.Message}");
355 response =
new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
356 responseContent =
new FailureResponse { Error =
"true", Message = ex.Message };
363 Debug.Log($
"[Platform API] Logging in with token: {token}");
365 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", token);
366 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
368 Debug.Log($
"[Platform API] Sending login with a token.");
369 HttpResponseMessage response = await
apiHandlingClient.GetAsync(
"/v2/auth/validate-signature");
370 string body = await response.Content.ReadAsStringAsync();
371 Debug.Log($
"[Platform API] Body returned as {body}");
375 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
378 Debug.Log($
"[Platform API] Got a valid login response!");
386 Debug.Log(
"[Platform API] Calling Login.");
389 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(login));
390 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
392 Debug.Log(
"[Platform API] Call to post api login.");
393 HttpResponseMessage response = await
handlingClient.PostAsync(
"/login", loginRequestContent);
394 string body = await response.Content.ReadAsStringAsync();
395 Debug.Log(
"[Platform API] Got response body: " + body);
399 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
402 Debug.Log(
"[Platform API] Response content deserialized.");
409 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
410 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
412 HttpResponseMessage response = await
handlingClient.GetAsync(
string.Format(
"/user/{0}", userId));
413 string body = await response.Content.ReadAsStringAsync();
418 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
427 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
428 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
431 usersModulesRequest.
UserIds.Add(userId);
432 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(usersModulesRequest));
433 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
435 HttpResponseMessage response = await
handlingClient.PostAsync(
"/access/users", loginRequestContent);
436 string body = await response.Content.ReadAsStringAsync();
440 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
453 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
455 HttpResponseMessage response = await
apiHandlingClient.GetAsync(
string.Format(
"/v2/auth/quick-id/get-users?serialNumber={0}", serialNumber));
456 string body = await response.Content.ReadAsStringAsync();
458 Debug.Log($
"[Platform API] Body returned as {body}");
463 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
471 Debug.Log(
"[Platform API] Calling Quick ID login.");
474 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(login));
475 Debug.Log(
"[Platform API] Quick ID login request content: " + JsonUtility.ToJson(login));
476 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
478 Debug.Log(
"[Platform API] Call to post api Quick ID login.");
479 HttpResponseMessage response = await
apiHandlingClient.PostAsync(
"/v2/auth/quick-id/login", loginRequestContent);
480 string body = await response.Content.ReadAsStringAsync();
481 Debug.Log(
"[Platform API] Got response body: " + body);
487 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
493 loginResponseContent.Token = platformLoginResponse.
Token;
494 if (platformLoginResponse.User !=
null)
496 loginResponseContent.ID = platformLoginResponse.User.Id;
497 loginResponseContent.OrgId = platformLoginResponse.User.OrgId;
498 loginResponseContent.First = platformLoginResponse.User.FirstName;
499 loginResponseContent.Last = platformLoginResponse.User.LastName;
500 loginResponseContent.Email = platformLoginResponse.User.Email;
501 loginResponseContent.Role = platformLoginResponse.User.Role;
502 loginResponseContent.Org = platformLoginResponse.User.Org;
506 Debug.Log(
"[Platform API] Quick ID login response did not contain user data.");
510 Debug.Log(
"[Platform API] Response content deserialized and mapped.");
517 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
518 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
520 HttpContent joinSessionRequestContent =
new StringContent(joinData.ToJSON());
521 joinSessionRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
523 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", joinSessionRequestContent);
524 string body = await response.Content.ReadAsStringAsync();
528 responseContent =
null;
534 responseContent = joinSessionResponse;
542 Debug.Log(
"[Platform API Handler] Get Module Access");
544 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"*/*"));
546 string optionalParameters =
"";
547 Debug.Log($
"Checking for a serial number: {serialNumber}");
548 if (!
string.IsNullOrEmpty(serialNumber))
550 optionalParameters =
"?serial=" + serialNumber;
554 $
"[{GetType().Name}] Checking module access at: "
555 + String.Format(
"/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
559 String.Format(
"/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
561 string body = await response.Content.ReadAsStringAsync();
563 Debug.Log($
"[{GetType().Name}] GetModuleAccess return body: {body}");
564 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
575 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
576 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
580 HttpContent heartbeatRequestContent =
new StringContent(heartbeatData.ToJSON());
581 heartbeatRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
585 heartbeatRequestContent
587 string body = await response.Content.ReadAsStringAsync();
588 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
591 responseContent =
null;
600 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
601 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
603 HttpContent completeSessionRequestContent =
new StringContent(completionData.ToJSON());
604 completeSessionRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
606 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", completeSessionRequestContent);
607 string body = await response.Content.ReadAsStringAsync();
608 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
611 responseContent =
null;
620 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
621 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
623 HttpContent sessionEventRequestContent =
new StringContent(sessionEvent.ToJSON());
624 sessionEventRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
626 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", sessionEventRequestContent);
627 string body = await response.Content.ReadAsStringAsync();
628 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
631 responseContent =
null;
640 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
641 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
643 string endpoint =
"/modules";
644 if (platform !=
null && platform.Length > 0)
646 endpoint += $
"?platform={platform}";
649 Debug.Log($
"GetModuleList built endpoint: {endpoint}");
651 HttpResponseMessage response = await
handlingClient.GetAsync(endpoint);
652 string body = await response.Content.ReadAsStringAsync();
656 var responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
662 Debug.LogWarning(ex);
665 List<OrgModule> orgModules =
new List<OrgModule>();
666 JArray array = JArray.Parse(body);
669 var tokens = array.Children();
670 foreach (JToken selectedToken
in tokens)
673 orgModule.
Parse(selectedToken);
674 orgModules.Add(orgModule);
678 Debug.Log(orgModules.Count.ToString());
685 if (!String.IsNullOrEmpty(jsonResponse[
"errors"]?.ToString()))
687 string errorMessage = jsonResponse[
"errors"]?[0]?[
"message"]?.ToString() ??
"Unknown GraphQL error";
691 if (String.IsNullOrEmpty(jsonResponse[
"data"]?.ToString()) || String.IsNullOrEmpty(jsonResponse[
"data"][jsonDataObjectKey]?.ToString()))
696 Message =
"Invalid response format from server",
async void SendHeartbeat(string authToken, int sessionId)
HttpClient handlingClient
APIHandler(string endpointUrl)
async void GetUserMetricsForOrg(string authToken, int orgID, int page, FilterParams filterParams)
async void GetUserModules(string authToken, int userId)
async void QuickIDLogin(QuickIDLoginData login)
HttpResponseMessage HandleException(Exception exception)
void EnsureURLHasProtocol(ref string url)
async void JoinSession(string authToken, JoinSessionData joinData)
async void LoginWithToken(string token)
async void GetSessionHistory(string authToken, int page, SessionFilters sessionFilters, FilterParams filterParams)
async void CompleteSession(string authToken, CompleteSessionData completionData)
HttpClient apiHandlingClient
async void Login(LoginData login)
async void SendSessionEvent(string authToken, SessionEventData sessionEvent)
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 GetDevicesForOrg(string authToken, int orgID, int page, FilterParams filterParams)
delegate void APIResponse(ResponseType type, HttpResponseMessage message, object responseData)
void SetEndpoint(string endpointUrl)
APIResponse OnAPIResponse
async void GetModuleAccess(int moduleId, int userId, string serialNumber)
async void GetModuleList(string authToken, string platform)
List< UserMetric > result
@ RT_QUICK_ID_AUTH_GET_USERS
@ RT_GET_USER_METRICS_FOR_ORG