2using System.Collections.Generic;
5using System.Net.Http.Headers;
7using Newtonsoft.Json.Linq;
38 protected string URL =
"";
59 Debug.LogWarning(
"Exception has occurred: " + exception.Message);
60 HttpResponseMessage badRequestResponse =
new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
62 return badRequestResponse;
70 Debug.Log(
"[APIHandler] Set Endpoint to " +
URL);
71 handlingClient.BaseAddress =
new Uri(
URL);
79 apiHandlingClient.BaseAddress =
new Uri(
apiURL);
84 if (!url.StartsWith(
"https://", StringComparison.InvariantCultureIgnoreCase))
86 if (url.StartsWith(
"http:", StringComparison.InvariantCultureIgnoreCase))
89 Debug.LogWarning(
"URL must be a secured http endpoint for production.");
91 Debug.LogError(
"URL must be a securated http endpoint.");
96 url.Insert(0,
"https://");
104 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
106 HttpResponseMessage response;
124 public async
void GenerateAssistedLogin(
string authToken,
int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
127 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
128 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
131 string jsonContent =
"";
135 var userIdArray =
new int[1] { userId };
138 var graphqlRequest =
new
140 operationName =
"generateAuthCode",
142 query =
"mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
145 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
149 var graphqlRequest =
new
151 operationName =
"generateAuthCode",
152 variables =
new { input =
new { } },
153 query =
"mutation generateAuthCode($input: AuthCodeInput!) { generateAuthCode(input: $input) { code expiresAt __typename }}",
156 jsonContent = JsonConvert.SerializeObject(graphqlRequest);
159 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
160 HttpResponseMessage response;
161 object responseContent;
165 string body = await response.Content.ReadAsStringAsync();
169 JObject jsonResponse = JObject.Parse(body);
171 if (failureResponse !=
null)
173 failure?.Invoke(response, failureResponse);
178 string code = jsonResponse[
"data"][
"generateAuthCode"][
"code"]?.ToString();
179 string expiresAt = jsonResponse[
"data"][
"generateAuthCode"][
"expiresAt"]?.ToString();
187 responseContent = assistedLogin;
191 Debug.LogError($
"Error generating assisted login: {ex.Message}");
192 response =
new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
193 failure?.Invoke(response,
new FailureResponse { Error =
"true", Message = ex.Message });
197 success?.Invoke(response, responseContent);
203 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
204 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
206 var graphqlRequest =
new
208 operationName =
"userMetrics",
209 variables =
new { orgId = orgID, limit = 10, page = page },
210 query =
"query userMetrics($orgId: ID!, $limit: Int, $page: Int, $search: String) { userMetrics(orgId: $orgId, limit: $limit, page: $page, search: $search) { result { id firstName lastName username email role createdAt orgUnitId orgUnit { id name externalId } lastModuleId lastModule { id abbreviation description } sessionCount lastActiveAt isInModule } pageInfo { totalCount page offset pageSize previousPage nextPage } } }"
213 string jsonContent = JsonConvert.SerializeObject(graphqlRequest);
214 HttpContent requestContent =
new StringContent(jsonContent, System.Text.Encoding.UTF8,
"application/json");
215 HttpResponseMessage response;
216 object responseContent;
220 string body = await response.Content.ReadAsStringAsync();
222 JObject jsonResponse = JObject.Parse(body);
224 if (failureResponse !=
null)
230 var userMetricsJSON = jsonResponse[
"data"][
"userMetrics"];
231 responseContent = JsonConvert.DeserializeObject<
UserMetricsResponse>(userMetricsJSON.ToString());
235 Debug.LogError($
"Error retrieving users: {ex.Message}");
236 response =
new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
237 responseContent =
new FailureResponse { Error =
"true", Message = ex.Message };
245 Debug.Log($
"[Platform API] Logging in with token: {token}");
247 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", token);
248 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
250 Debug.Log($
"[Platform API] Sending login with a token.");
251 HttpResponseMessage response = await
apiHandlingClient.GetAsync(
"/v2/auth/validate-signature");
252 string body = await response.Content.ReadAsStringAsync();
253 Debug.Log($
"[Platform API] Body returned as {body}");
257 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
260 Debug.Log($
"[Platform API] Got a valid login response!");
268 Debug.Log(
"[Platform API] Calling Login.");
271 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(login));
272 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
274 Debug.Log(
"[Platform API] Call to post api login.");
275 HttpResponseMessage response = await
handlingClient.PostAsync(
"/login", loginRequestContent);
276 string body = await response.Content.ReadAsStringAsync();
277 Debug.Log(
"[Platform API] Got response body: " + body);
281 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
284 Debug.Log(
"[Platform API] Response content deserialized.");
291 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
292 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
294 HttpResponseMessage response = await
handlingClient.GetAsync(
string.Format(
"/user/{0}", userId));
295 string body = await response.Content.ReadAsStringAsync();
300 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
309 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
310 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
313 usersModulesRequest.
UserIds.Add(userId);
314 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(usersModulesRequest));
315 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
317 HttpResponseMessage response = await
handlingClient.PostAsync(
"/access/users", loginRequestContent);
318 string body = await response.Content.ReadAsStringAsync();
322 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
335 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
337 HttpResponseMessage response = await
apiHandlingClient.GetAsync(
string.Format(
"/v2/auth/quick-id/get-users?serialNumber={0}", serialNumber));
338 string body = await response.Content.ReadAsStringAsync();
340 Debug.Log($
"[Platform API] Body returned as {body}");
345 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
353 Debug.Log(
"[Platform API] Calling Quick ID login.");
356 HttpContent loginRequestContent =
new StringContent(JsonUtility.ToJson(login));
357 Debug.Log(
"[Platform API] Quick ID login request content: " + JsonUtility.ToJson(login));
358 loginRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
360 Debug.Log(
"[Platform API] Call to post api Quick ID login.");
361 HttpResponseMessage response = await
apiHandlingClient.PostAsync(
"/v2/auth/quick-id/login", loginRequestContent);
362 string body = await response.Content.ReadAsStringAsync();
363 Debug.Log(
"[Platform API] Got response body: " + body);
369 responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
375 loginResponseContent.Token = platformLoginResponse.
Token;
376 if (platformLoginResponse.User !=
null)
378 loginResponseContent.ID = platformLoginResponse.User.Id;
379 loginResponseContent.OrgId = platformLoginResponse.User.OrgId;
380 loginResponseContent.First = platformLoginResponse.User.FirstName;
381 loginResponseContent.Last = platformLoginResponse.User.LastName;
382 loginResponseContent.Email = platformLoginResponse.User.Email;
383 loginResponseContent.Role = platformLoginResponse.User.Role;
384 loginResponseContent.Org = platformLoginResponse.User.Org;
388 Debug.Log(
"[Platform API] Quick ID login response did not contain user data.");
392 Debug.Log(
"[Platform API] Response content deserialized and mapped.");
399 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
400 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
402 HttpContent joinSessionRequestContent =
new StringContent(joinData.ToJSON());
403 joinSessionRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
405 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", joinSessionRequestContent);
406 string body = await response.Content.ReadAsStringAsync();
410 responseContent =
null;
416 responseContent = joinSessionResponse;
424 Debug.Log(
"[Platform API Handler] Get Module Access");
426 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"*/*"));
428 string optionalParameters =
"";
429 Debug.Log($
"Checking for a serial number: {serialNumber}");
430 if (!
string.IsNullOrEmpty(serialNumber))
432 optionalParameters =
"?serial=" + serialNumber;
436 $
"[{GetType().Name}] Checking module access at: "
437 + String.Format(
"/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
441 String.Format(
"/access/user/{0}/module/{1}{2}", userId, moduleId, optionalParameters)
443 string body = await response.Content.ReadAsStringAsync();
445 Debug.Log($
"[{GetType().Name}] GetModuleAccess return body: {body}");
446 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
457 apiHandlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
458 apiHandlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
462 HttpContent heartbeatRequestContent =
new StringContent(heartbeatData.ToJSON());
463 heartbeatRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
467 heartbeatRequestContent
469 string body = await response.Content.ReadAsStringAsync();
470 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
473 responseContent =
null;
482 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
483 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
485 HttpContent completeSessionRequestContent =
new StringContent(completionData.ToJSON());
486 completeSessionRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
488 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", completeSessionRequestContent);
489 string body = await response.Content.ReadAsStringAsync();
490 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
493 responseContent =
null;
502 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
503 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
505 HttpContent sessionEventRequestContent =
new StringContent(sessionEvent.ToJSON());
506 sessionEventRequestContent.Headers.ContentType =
new MediaTypeWithQualityHeaderValue(
"application/json");
508 HttpResponseMessage response = await
handlingClient.PostAsync(
"/event", sessionEventRequestContent);
509 string body = await response.Content.ReadAsStringAsync();
510 object responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
513 responseContent =
null;
522 handlingClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Bearer", authToken);
523 handlingClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(
"application/json"));
525 string endpoint =
"/modules";
526 if (platform !=
null && platform.Length > 0)
528 endpoint += $
"?platform={platform}";
531 Debug.Log($
"GetModuleList built endpoint: {endpoint}");
533 HttpResponseMessage response = await
handlingClient.GetAsync(endpoint);
534 string body = await response.Content.ReadAsStringAsync();
538 var responseContent = JsonConvert.DeserializeObject<
FailureResponse>(body);
544 Debug.LogWarning(ex);
547 List<OrgModule> orgModules =
new List<OrgModule>();
548 JArray array = JArray.Parse(body);
551 var tokens = array.Children();
552 foreach (JToken selectedToken
in tokens)
555 orgModule.
Parse(selectedToken);
556 orgModules.Add(orgModule);
560 Debug.Log(orgModules.Count.ToString());
567 if (!String.IsNullOrEmpty(jsonResponse[
"errors"]?.ToString()))
569 string errorMessage = jsonResponse[
"errors"]?[0]?[
"message"]?.ToString() ??
"Unknown GraphQL error";
573 if (String.IsNullOrEmpty(jsonResponse[
"data"]?.ToString()) || String.IsNullOrEmpty(jsonResponse[
"data"][jsonDataObjectKey]?.ToString()))
578 Message =
"Invalid response format from server",
async void SendHeartbeat(string authToken, int sessionId)
HttpClient handlingClient
APIHandler(string endpointUrl)
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 GetUserMetricsForOrg(string authToken, int orgID, int page)
async void LoginWithToken(string token)
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)
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)
@ RT_QUICK_ID_AUTH_GET_USERS
@ RT_GET_USER_METRICS_FOR_ORG