Documentation for the Unity C# Library
Loading...
Searching...
No Matches
ApexSystem.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.Net.Http;
4using System.Text.RegularExpressions;
5using System.Threading.Tasks;
6using Newtonsoft.Json;
10using TinCan;
11using UnityEngine;
12using UnityEngine.XR;
13
14#if MANAGE_XR
15using MXR.SDK;
16#endif
17
18namespace PixoVR.Apex
19{
20 public delegate void PlatformResponse(ResponseType type, bool wasSuccessful, object responseData);
21
22 [DefaultExecutionOrder(-50)]
23 public class ApexSystem : ApexSingleton<ApexSystem>
24 {
25 private static readonly string TAG = "ApexSystem";
26 private enum VersionParts : int
27 {
28 Major = 0,
29 Minor,
30 Patch,
31 }
32
33 public static string ServerIP
34 {
35 get { return Instance.serverIP; }
36 set { }
37 }
38
39 public static int ModuleID
40 {
41 get { return Instance.moduleID; }
42 set { Instance.moduleID = value; }
43 }
44
45 public static string ModuleName
46 {
47 get { return Instance.moduleName; }
48 set { Instance.moduleName = value; }
49 }
50
51 public static string ModuleVersion
52 {
53 get { return Instance.moduleVersion; }
54 set { Instance.moduleVersion = value; }
55 }
56
57 public static string ScenarioID
58 {
59 get { return Instance.scenarioID; }
60 set { Instance.scenarioID = value; }
61 }
62
64 {
65 get { return Instance.currentActiveLogin; }
66 set { }
67 }
68
69 public static bool RunSetupOnAwake
70 {
71 get { return Instance.runSetupOnAwake; }
72 set { Instance.runSetupOnAwake = value; }
73 }
74
75 public static bool LoginCheckModuleAccess
76 {
77 get { return Instance.loginCheckModuleAccess; }
78 set { }
79 }
80
81 public static string DeviceSerialNumber
82 {
83 get { return Instance.deviceSerialNumber; }
84 set { }
85 }
86
87 public static string PassedLoginToken
88 {
89 get
90 {
91 Debug.unityLogger.Log(LogType.Log, TAG, $"Getting passed login token as {Instance.loginToken} in instance {Instance.gameObject.name}");
92 return Instance.loginToken;
93 }
94
95 protected set
96 {
97 Debug.unityLogger.Log(LogType.Error, TAG, $"Setting passed login token to {value}");
98 Instance.loginToken = value;
99 }
100 }
101
102 public static string OptionalData
103 {
104 get { return Instance.optionalParameter; }
105 set { Instance.optionalParameter = value; }
106 }
107
108 public static string CurrentExitTarget
109 {
110 get { return Instance.currentExitTargetParameter; }
111 set
112 {
113 if (value != null)
114 {
115 Instance.currentExitTargetParameter = value;
116 }
117 else
118 {
119 Instance.currentExitTargetParameter = "";
120 }
121
122 if (Instance.currentExitTargetParameter.Contains("://"))
123 {
124 TargetType = "url";
125 }
126 else
127 {
128 TargetType = "app";
129 }
130 }
131 }
132
133 public static string TargetType
134 {
135 get { return Instance.targetTypeParameter; }
136 private set { Instance.targetTypeParameter = value; }
137 }
138
139 [SerializeField, EndpointDisplay]
141
142 [SerializeField]
143 protected string serverIP = "";
144
145 [SerializeField]
146 protected int moduleID = 0;
147
148 [SerializeField]
149 protected string moduleName = "Generic";
150
151 [SerializeField]
152 protected string moduleVersion = "0.00.00";
153
154 [SerializeField]
155 protected string scenarioID = "Generic";
156
157 [SerializeField]
158 public bool runSetupOnAwake = true;
159
160 [SerializeField]
161 public bool loginCheckModuleAccess = true;
162
163 [SerializeField]
164 protected float heartbeatTime = 5.0f;
165
166 protected string webSocketUrl;
167 protected string deviceID;
168 protected string deviceModel;
169 protected string platform;
170 protected string clientIP;
171 protected Guid currentSessionID;
172 protected int heartbeatSessionID;
173 protected float heartbeatTimer;
174 protected bool sessionInProgress;
175 protected bool userAccessVerified = false;
176 protected string deviceSerialNumber = "";
177 protected bool hasParsedArguments = false;
178
179 protected string loginToken = "";
180 protected string optionalParameter = "";
181 protected string currentExitTargetParameter = "";
182 protected string targetTypeParameter = "";
183
186 protected ApexWebsocket webSocket;
187 protected Task<bool> socketConnectTask;
188 protected Task socketDisconnectTask;
189
192
195
198
201
204
207
210
213
217 public PlatformResponse OnPlatformResponse = null;
226
233 void Awake()
235 Debug.unityLogger.Log(LogType.Log, TAG, $"ApexSystem found on {gameObject.name}");
237 {
238 Debug.unityLogger.Log(LogType.Log, TAG, "Instance already initialized.");
240
243#if UNITY_IOS || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
245#endif
246 if (runSetupOnAwake)
248 Debug.unityLogger.Log(LogType.Log, TAG, "Running on awake!");
249 SetupAPI();
252 DontDestroyOnLoad(gameObject);
253#if MANAGE_XR && !UNITY_EDITOR
254 Debug.unityLogger.Log(LogType.Log, TAG, "Using ManageXR");
255 InitMXRSDK();
256#endif
258
259#if MANAGE_XR
260 async void InitMXRSDK()
261 {
262 Debug.unityLogger.Log(LogType.Log, TAG, "Initializing the ManageXR SDK");
263 await MXRManager.InitAsync();
264 MXRManager.System.OnDeviceStatusChange += OnDeviceStatusChanged;
265 deviceSerialNumber = MXRManager.System.DeviceStatus.serial;
266 Debug.unityLogger.Log(LogType.Log, TAG, $"Device serial set to {deviceSerialNumber}");
268
269 void OnDeviceStatusChanged(DeviceStatus newDeviceStatus)
271 deviceSerialNumber = newDeviceStatus.serial;
272 Debug.unityLogger.Log(LogType.Log, TAG, $"Device serial number changed to {deviceSerialNumber}");
274#endif
277 {
278 Application.deepLinkActivated += OnDeepLinkActivated;
279 if (!string.IsNullOrEmpty(Application.absoluteURL))
280 {
281 // Cold start and Application.absoluteURL not null so process Deep Link.
282 OnDeepLinkActivated(Application.absoluteURL);
283 }
284 }
285
286 void OnDeepLinkActivated(string url)
287 {
288 // Update DeepLink Manager global variable, so URL can be accessed from anywhere.
289 var urlArguments = PixoPlatformUtilities.ParseURLArguments(url);
290 _ParsePassedData(urlArguments);
291 }
292
294 {
295 Debug.unityLogger.Log(LogType.Log, TAG, "SetupPlatformConfiguration");
296
297#if UNITY_ANDROID
299 {
300 Debug.unityLogger.Log(LogType.Log, TAG, "Found pixoconfig.cnf");
301
302 string configContent = PixoAndroidUtils.ReadFileFromSharedStorage("pixoconfig.cnf");
303
304 if (configContent.Length > 0)
305 {
306 Debug.unityLogger.Log(LogType.Log, TAG, "Configuration is not empty.");
307 ConfigurationTypes configData = JsonConvert.DeserializeObject<ConfigurationTypes>(configContent);
308 if (configData == null)
309 {
310 Debug.unityLogger.Log(LogType.Log, TAG, "Failed to deserialize the config.");
311 return;
312 }
313
314 // Parse out the platform target to utilize the unity built in config values
315 if (configData.Platform.Contains("NA", StringComparison.CurrentCultureIgnoreCase))
316 {
317 if (configData.Platform.Contains("Production", StringComparison.CurrentCultureIgnoreCase))
318 {
319 Debug.unityLogger.Log(LogType.Log, TAG, "NA Production platform target.");
320 PlatformTargetServer = PlatformServer.NA_PRODUCTION;
321 }
322
323 if (configData.Platform.Contains("Dev", StringComparison.CurrentCultureIgnoreCase))
325 Debug.unityLogger.Log(LogType.Log, TAG, "NA Dev platform target.");
327 }
328
329 if (configData.Platform.Contains("Stage", StringComparison.CurrentCultureIgnoreCase))
330 {
331 Debug.unityLogger.Log(LogType.Log, TAG, "NA Stage platform target.");
333 }
335 else if (configData.Platform.Contains("SA", StringComparison.CurrentCultureIgnoreCase))
336 {
337 Debug.unityLogger.Log(LogType.Log, TAG, "SA Production platform target.");
338 PlatformTargetServer = PlatformServer.SA_PRODUCTION;
339 }
340
341 // TODO (MGruber): Add a custom value, but this requires multiple configuration values to be saved.
342 // Need to save the normal headset api endpoint, web api endpoint and platform api endpoint. 3 VALUES! D:
343 }
344 }
345#endif
346 }
347
348 void SetupAPI()
349 {
350 Debug.unityLogger.Log(LogType.Log, TAG, "Mac Address: " + ApexUtils.GetMacAddress());
351 if (serverIP.Length == 0)
352 {
354 }
355
357
358 if (apexAPIHandler != null)
359 {
360 Debug.unityLogger.Log(LogType.Log, TAG, "Apex API Handler is not null!");
361 }
362
363 // TODO: Move to new plugin
365 apexAPIHandler.OnAPIResponse += OnAPIResponse;
366
367 if (webSocket != null)
368 {
370 {
372 }
373 }
374
375 webSocket = new ApexWebsocket();
377 webSocket.OnConnectFailed.AddListener((reason) => OnWebSocketConnectFailed(reason));
378 webSocket.OnReceive.AddListener((data) => OnWebSocketReceive(data));
379 webSocket.OnClosed.AddListener((reason) => OnWebSocketClosed(reason));
380
382
384 {
385 var applicationArugments = PixoPlatformUtilities.ParseApplicationArguments();
386 _ParsePassedData(applicationArugments);
387 Debug.unityLogger.Log(LogType.Log, TAG, $"Login Token: {(string.IsNullOrEmpty(PassedLoginToken) ? "<Null>" : PassedLoginToken)}");
388 hasParsedArguments = true;
389 }
390 }
391
392 void _ExitApplication(string nextExitApplication)
393 {
394 Debug.unityLogger.Log(LogType.Log, TAG, "ApexSystem::_ExitApplication");
395 if (nextExitApplication == null)
397 nextExitApplication = "";
398 }
399
400 string returnTargetType = "app";
401
402 if (nextExitApplication.Contains("://"))
403 {
404 returnTargetType = "url";
405 }
406
407 Debug.unityLogger.Log(LogType.Log, TAG, "" + nextExitApplication + " " + returnTargetType);
408
409 string parameters = "";
410
411 Debug.unityLogger.Log(LogType.Log, TAG, "Building parameters for url.");
412
413 if (CurrentActiveLogin != null)
414 {
415 parameters += "pixotoken=" + CurrentActiveLogin.Token;
416 }
417 else if (!string.IsNullOrEmpty(PassedLoginToken))
418 {
419 parameters += "pixotoken=" + PassedLoginToken;
420 }
421
422 if (optionalParameter != null)
423 {
424 if (optionalParameter.Length > 0)
425 {
426 if (parameters.Length > 0)
427 parameters += "&";
428 parameters += "optional=" + optionalParameter;
429 }
430 }
431
432 if (nextExitApplication.Length > 0)
433 {
434 if (parameters.Length > 0)
435 parameters += "&";
436 parameters += "returntarget=" + nextExitApplication;
437 }
438
439 if (returnTargetType.Length > 0)
441 if (parameters.Length > 0)
442 parameters += "&";
443 parameters += "targettype=" + returnTargetType;
444 }
445
446 Debug.unityLogger.Log(LogType.Log, TAG, "Checking the return target parameter.");
447
448 if (!string.IsNullOrEmpty(CurrentExitTarget))
449 {
450 Debug.unityLogger.Log(LogType.Log, TAG, "Had a valid return target parameter.");
451 if (targetTypeParameter.Equals("url", StringComparison.OrdinalIgnoreCase))
452 {
453 Debug.unityLogger.Log(LogType.Log, TAG, "Return Target is a URL.");
454
455 string returnURL = CurrentExitTarget;
456 if (!string.IsNullOrEmpty(parameters))
457 {
458 if (!returnURL.Contains('?'))
459 returnURL += "?";
460 else
461 returnURL += "&";
462
463 returnURL += parameters;
464 }
465 Debug.unityLogger.Log(LogType.Log, TAG, "Custom Target: " + returnURL);
467 return;
468 }
469 else
470 {
471 Debug.unityLogger.Log(LogType.Log, TAG, $"Return Target is a package name. {CurrentExitTarget}");
472
473 List<string> keys = new List<string>(),
474 values = new List<string>();
475
476 Debug.unityLogger.Log(LogType.Log, TAG, "Adding pixo token.");
477
478 if (CurrentActiveLogin != null)
479 {
480 keys.Add("pixotoken");
481 values.Add(CurrentActiveLogin.Token);
482 }
483 else if (!string.IsNullOrEmpty(PassedLoginToken))
484 {
485 keys.Add("pixotoken");
486 values.Add(PassedLoginToken);
487 }
488
489 Debug.unityLogger.Log(LogType.Log, TAG, "Adding optional.");
490
491 if (!string.IsNullOrEmpty(optionalParameter))
492 {
493 keys.Add("optional");
494 values.Add(optionalParameter);
495 }
496
497 Debug.unityLogger.Log(LogType.Log, TAG, "Adding return target.");
498
499 if (!string.IsNullOrEmpty(nextExitApplication))
500 {
501 keys.Add("returntarget");
502 values.Add(nextExitApplication);
503 }
504
505 Debug.unityLogger.Log(LogType.Log, TAG, "Adding return target type.");
506
507 if (!string.IsNullOrEmpty(returnTargetType))
508 {
509 keys.Add("targettype");
510 values.Add(returnTargetType);
511 }
512
513 PixoPlatformUtilities.OpenApplication(CurrentExitTarget, keys.ToArray(), values.ToArray());
514 return;
515 }
516 }
517
519 }
520
521 string GetEndpointFromTarget(PlatformServer target)
522 {
523 return target.ToUrlString();
524 }
525
526 string GetWebEndpointFromPlatformTarget(PlatformServer target)
527 {
528 int targetValue = (int)target;
529 WebPlatformServer webTarget = (WebPlatformServer)targetValue;
530
531 return webTarget.ToUrlString();
532 }
533
534 string GetPlatformEndpointFromPlatformTarget(PlatformServer target)
535 {
536 int targetValue = (int)target;
537 APIPlatformServer apiTarget = (APIPlatformServer)targetValue;
538
539 return apiTarget.ToUrlString();
540 }
541
543 {
545
546 if (webSocketUrl.Contains("://"))
547 {
548 webSocketUrl = webSocketUrl.Split(new string[] { "://" }, 2, StringSplitOptions.RemoveEmptyEntries)[1];
549 }
550
551 if (webSocketUrl.Contains("/"))
552 {
553 webSocketUrl = webSocketUrl.Split(new string[] { "/" }, 2, StringSplitOptions.RemoveEmptyEntries)[0];
554 }
555
556 webSocketUrl = "wss://" + webSocketUrl + "/ws";
557 }
558
559 void Start()
560 {
562 {
563 Debug.unityLogger.Log(LogType.Warning, TAG, $"{moduleVersion} is an invalid module version.");
564 }
565 deviceID = SystemInfo.deviceUniqueIdentifier;
566 deviceModel = SystemInfo.deviceModel;
567 platform =
568 XRSettings.loadedDeviceName.Length > 0 ? XRSettings.loadedDeviceName : Application.platform.ToString();
569 clientIP = Utils.ApexUtils.GetLocalIP();
570 }
571
572 private void FixedUpdate()
573 {
574 if (webSocket != null)
575 {
577 }
578
580 {
581 heartbeatTimer -= Time.fixedDeltaTime;
583 if (heartbeatTimer <= 0.0f)
584 {
587 }
588 }
589 }
591 void ConnectWebsocket()
592 {
593 socketConnectTask = Task.Run(() => webSocket.Connect(new Uri(webSocketUrl)));
594 }
595
597 {
598 socketDisconnectTask = Task.Run(() => webSocket.CloseSocket());
599 }
600
602 {
603 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket connected successfully.");
604 }
605
606 void OnWebSocketConnectFailed(string reason)
608 Debug.unityLogger.Log(LogType.Error, TAG, "Websocket failed to connect with error: " + reason);
609 }
610
611 void OnWebSocketReceive(string data)
612 {
613 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket received: " + data);
614 try
615 {
616 if (data.Contains("auth_code"))
617 {
618 var authCode = JsonConvert.DeserializeObject<AuthorizationCode>(data);
619 OnAuthorizationCodeReceived.Invoke(authCode.Code);
621
622 if (data.Contains("Token", StringComparison.OrdinalIgnoreCase))
623 {
624 object loginResponse = JsonConvert.DeserializeObject<LoginResponseContent>(data);
625 HandleLogin(true, loginResponse);
626 }
627 }
628 catch (Exception ex)
629 {
630 Debug.unityLogger.Log(LogType.Log, TAG, ex.Message);
631 }
632 }
633
634 void OnWebSocketClosed(System.Net.WebSockets.WebSocketCloseStatus reason)
635 {
636 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket closed with reason: " + reason);
637 }
638
640 {
641 if (IsModuleVersionOnlyNumerical() == false)
642 return false;
643
644 string[] moduleVersionParts = moduleVersion.Split('.');
645
646 if (moduleVersionParts.Length != 3)
647 return false;
648
649 if (!IsModuleMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Major]))
650 return false;
651
652 if (!IsModuleNonMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Minor]))
653 return false;
655 if (!IsModuleNonMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Patch]))
656 return false;
657
658 return true;
660
661 static readonly Regex VersionValidator = new Regex(@"^[0123456789.]+$");
662
664 {
665 return VersionValidator.IsMatch(moduleVersion);
666 }
667
668 bool IsModuleNonMajorVersionPartValid(string modulePart)
669 {
670 if (modulePart.Length <= 0)
671 return false;
672
673 if (modulePart.Length > 2)
674 return false;
675
676 return true;
677 }
678
679 bool IsModuleMajorVersionPartValid(string modulePart)
680 {
681 if (modulePart.Length <= 0)
682 return false;
683
684 if (modulePart.StartsWith("0"))
685 return false;
686
687 return true;
688 }
689
690 public static void ExitApplication(string nextExitTarget = "")
691 {
692 Instance._ExitApplication(nextExitTarget);
693 }
694
695 public static bool RequestAuthorizationCode()
696 {
697 return Instance._RequestAuthorizationCode();
698 }
699
700 public static void ChangePlatformServer(PlatformServer newServer)
701 {
702 Instance._ChangePlatformServer(newServer);
703 }
704
705 public static void Ping()
706 {
707 Instance._Ping();
708 }
710 public static bool LoginWithToken()
712 Debug.unityLogger.Log(LogType.Log, TAG, $"Login with token of token {(string.IsNullOrEmpty(PassedLoginToken) ? "<none>" : PassedLoginToken)}");
714 }
715
716 public static bool LoginWithToken(string token)
717 {
718 return Instance._LoginWithToken(token);
719 }
720
721 public static bool Login(LoginData login)
722 {
723 return Instance._Login(login);
724 }
725
726 public static bool Login(string username, string password)
728 return Instance._Login(username, password);
729 }
730
731 public static bool CheckModuleAccess(int targetModuleID = -1)
732 {
733 return Instance._CheckModuleAccess(targetModuleID);
734 }
735
736 public static bool JoinSession(string scenarioID = null, Extension contextExtension = null)
737 {
738 return Instance._JoinSession(scenarioID, contextExtension);
739 }
740
741 public static bool CompleteSession(
742 SessionData currentSessionData,
743 Extension contextExtension = null,
744 Extension resultExtension = null
745 )
746 {
747 return Instance._CompleteSession(currentSessionData, contextExtension, resultExtension);
749
750 public static bool SendSimpleSessionEvent(string action, string targetObject, Extension contextExtension)
751 {
752 return Instance._SendSimpleSessionEvent(action, targetObject, contextExtension);
754
755 public static bool SendSessionEvent(Statement eventStatement)
756 {
757 return Instance._SendSessionEvent(eventStatement);
759
760 public static bool GetCurrentUser()
761 {
762 return GetUser();
763 }
765 public static bool GetUser(int userId = -1)
766 {
767 return Instance._GetUser(userId);
768 }
770 public static bool GetCurrentUserModules()
771 {
772 return GetUserModules();
773 }
775 public static bool GetUserModules(int userId = -1)
776 {
777 return Instance._GetUserModules(userId);
778 }
780 public static bool GetModulesList(string platformName)
781 {
782 return Instance._GetModuleList(platformName);
783 }
785 public static bool GetQuickIDAuthUsers(string serialNumber)
786 {
787 return Instance._GetQuickIDAuthUsers(serialNumber);
788 }
790 public static bool QuickIDLogin(string serialNumber, string username)
791 {
792 return Instance._QuickIDLogin(serialNumber, username);
793 }
794
795 protected void _ChangePlatformServer(PlatformServer newServer)
796 {
797 PlatformTargetServer = newServer;
799 SetupAPI();
800 }
801
802 protected void _Ping()
805 }
806
807 protected bool _LoginWithToken(string token)
809 Debug.unityLogger.Log(LogType.Log, TAG, $"Calling LoginWithToken ({token})");
810 if (token.Length <= 0)
811 {
812 return false;
814
815 Debug.unityLogger.Log(LogType.Log, TAG, $"Logging in with token: {token}");
817
818 return true;
819 }
820
821 protected bool _Login(LoginData login)
822 {
823 Debug.unityLogger.Log(LogType.Log, TAG, "_Login called.");
824 if (apexAPIHandler == null)
825 {
826 Debug.unityLogger.Log(LogType.Log, TAG, "API Handler is null.");
827 OnLoginFailed.Invoke(
829 "There was an error reaching the platform, please contact your administrator."
830 )
831 );
832 return false;
834
835 if (login.Login.Length <= 0)
836 {
837 Debug.unityLogger.Log(LogType.Log, TAG, "[Login] No user name.");
838 OnLoginFailed.Invoke(GenerateFailureResponse("No username or email entered."));
839 return false;
840 }
841
842 if (login.Password.Length <= 0)
844 Debug.unityLogger.Log(LogType.Log, TAG, "[Login] No password.");
845 login.Password = "<empty>";
846 }
847
848 apexAPIHandler.Login(login);
849
850 Debug.unityLogger.Log(LogType.Log, TAG, "Login called.");
851
852 return true;
853 }
854
855 protected bool _Login(string username, string password)
856 {
857 return _Login(new LoginData(username, password));
858 }
859
860 protected FailureResponse GenerateFailureResponse(string message)
861 {
862 FailureResponse failureResponse = new FailureResponse();
863 failureResponse.Error = "true";
864 failureResponse.HttpCode = "400";
865 failureResponse.Message = message;
866
867 return failureResponse;
868 }
870 protected void _ParsePassedData(Dictionary<string, string> arguments)
871 {
872 Debug.unityLogger.Log(LogType.Log, TAG, "Parsing passed data.");
873 if (arguments == null)
874 {
875 Debug.unityLogger.Log(LogType.Log, TAG, "No arguments found for the application.");
876 return;
877 }
878
879 if (arguments.ContainsKey("optional"))
880 optionalParameter = arguments["optional"];
881
882 if (arguments.ContainsKey("returntarget"))
883 CurrentExitTarget = arguments["returntarget"];
884
885 if (arguments.ContainsKey("targettype"))
886 TargetType = arguments["targettype"];
887
888 Debug.unityLogger.Log(LogType.Log, TAG, "Is the token already set?");
889 if (string.IsNullOrEmpty(PassedLoginToken))
890 {
891 Debug.unityLogger.Log(LogType.Log, TAG, "Token is not set, but does the arguments contain a token?");
892 if (arguments.ContainsKey("pixotoken"))
893 {
894 Debug.unityLogger.Log(LogType.Log, TAG, "Token was found in the arguments.");
895 string token = arguments["pixotoken"];
896 Debug.unityLogger.Log(LogType.Log, TAG, $"Found pixotoken {token}.");
897 if (!string.IsNullOrEmpty(token))
898 {
899 PassedLoginToken = string.Copy(token);
900 }
901 }
902 }
904
905 protected bool _CheckModuleAccess(int targetModuleID = -1)
906 {
907 Debug.unityLogger.Log(LogType.Log, TAG, "_CheckModuleAccess called.");
909 if (currentActiveLogin == null)
910 {
911 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot check user's module access with no active login.");
912 return false;
913 }
914
915 if (targetModuleID <= -1)
916 {
917 targetModuleID = moduleID;
919
920 Debug.unityLogger.Log(LogType.Log, TAG, $"Checking module access of module {targetModuleID} from user {currentActiveLogin.ID} and device serial number {(string.IsNullOrEmpty(deviceSerialNumber) == true ? "---" : deviceSerialNumber)}");
922
923 return true;
924 }
925
926 protected bool _JoinSession(string newScenarioID = null, Extension contextExtension = null)
927 {
928 if (currentActiveLogin == null)
929 {
930 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot join session with no active login.");
931 return false;
932 }
933
934 if (userAccessVerified == false)
935 {
936 return false;
937 }
938
939 if (newScenarioID != null)
940 {
941 scenarioID = newScenarioID;
942 }
943
944 if (sessionInProgress == true)
945 {
946 Debug.unityLogger.Log(LogType.Error, TAG,
947 "Session is already in progress."
948 + " The previous session didn't complete or a new session was started during an active session."
949 );
950 }
951
952 currentSessionID = Guid.NewGuid();
954 Statement sessionStatement = new Statement();
955 Agent sessionActor = new Agent();
956 sessionActor.mbox = currentActiveLogin.Email;
957
958 Verb sessionVerb = new Verb();
959 sessionVerb.id = ApexVerbs.JOINED_SESSION;
960 sessionVerb.display = new LanguageMap();
961 sessionVerb.display.Add("en", "Joined Session");
962
963 Activity sessionActivity = new Activity();
964 sessionActivity.id = string.Format("https://pixovr.com/xapi/objects/{0}/{1}", moduleID, scenarioID);
965
966 Context sessionContext = new Context();
967 sessionContext.registration = currentSessionID;
968 sessionContext.revision = moduleVersion;
969 sessionContext.platform = platform;
970
971 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
972
973 sessionStatement.actor = sessionActor;
974 sessionStatement.verb = sessionVerb;
975 sessionStatement.target = sessionActivity;
976 sessionStatement.context = sessionContext;
977
978 JoinSessionData sessionData = new JoinSessionData();
979 sessionData.DeviceId = deviceID;
980 sessionData.IpAddress = clientIP;
981 sessionData.ModuleId = moduleID;
982 sessionData.Uuid = currentSessionID.ToString();
983 sessionData.EventType = ApexEventTypes.PIXOVR_SESSION_JOINED;
984 sessionData.JsonData = sessionStatement;
985
987
988 return true;
989 }
990
991 protected bool _SendSimpleSessionEvent(string verbName, string targetObject, Extension contextExtension)
992 {
993 if (userAccessVerified == false)
994 return false;
995
996 if (verbName == null)
997 return false;
998
999 if (verbName.Length == 0)
1000 return false;
1001
1002 Statement sessionStatement = new Statement();
1003 Agent sessionActor = new Agent();
1004 sessionActor.mbox = currentActiveLogin.Email;
1005
1006 Verb sessionVerb = new Verb();
1007 sessionVerb.id = new Uri("https://pixovr.com/xapi/verbs/" + verbName.Replace(' ', '_').ToLower());
1008 sessionVerb.display = new LanguageMap();
1009 sessionVerb.display.Add("en", verbName);
1010
1011 Activity sessionActivity = new Activity();
1012 sessionActivity.id = string.Format(
1013 "https://pixovr.com/xapi/objects/{0}/{1}/{2}",
1014 moduleID,
1015 scenarioID,
1016 targetObject.Replace(' ', '_').ToLower()
1017 );
1018
1019 Context sessionContext = new Context();
1020 sessionContext.registration = currentSessionID;
1021 sessionContext.revision = moduleVersion;
1022 sessionContext.platform = platform;
1023
1024 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
1025
1026 sessionStatement.actor = sessionActor;
1027 sessionStatement.verb = sessionVerb;
1028 sessionStatement.target = sessionActivity;
1029 sessionStatement.context = sessionContext;
1030
1031 SessionEventData sessionEvent = new SessionEventData();
1032 sessionEvent.DeviceId = deviceID;
1033 sessionEvent.ModuleId = ModuleID;
1034 sessionEvent.Uuid = currentSessionID.ToString();
1035 sessionEvent.EventType = ApexEventTypes.PIXOVR_SESSION_EVENT;
1036 sessionEvent.JsonData = sessionStatement;
1037
1040 return true;
1041 }
1042
1043 protected bool _SendSessionEvent(Statement eventStatement)
1044 {
1045 if (userAccessVerified == false)
1046 {
1047 return false;
1048 }
1049
1050 if (currentActiveLogin == null)
1051 {
1052 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot send a session event with no active login.");
1053 return false;
1054 }
1055
1056 if (sessionInProgress == false)
1057 {
1058 Debug.unityLogger.Log(LogType.Error, TAG, "No session in progress to send event for.");
1059 return false;
1060 }
1061
1062 if (eventStatement == null)
1063 {
1064 Debug.unityLogger.Log(LogType.Error, TAG, "No event data to send.");
1065 return false;
1066 }
1067
1068 if (eventStatement.actor != null)
1069 {
1070 Debug.unityLogger.Log(LogType.Warning, TAG, "Actor data should not be filled out.");
1071 }
1072
1073 if (eventStatement.verb == null)
1074 {
1075 Debug.unityLogger.Log(LogType.Error, TAG, "Verb missing from eventStatement.");
1076 return false;
1077 }
1078
1079 if (eventStatement.verb.id == null)
1080 {
1081 Debug.unityLogger.Log(LogType.Error, TAG, "verb.id missing from eventStatement.");
1082 return false;
1083 }
1084
1085 if (eventStatement.target == null)
1086 {
1087 Debug.unityLogger.Log(LogType.Error, TAG, "Object (target) missing from eventStatement.");
1088 return false;
1089 }
1090
1091 eventStatement.actor = new Agent();
1092 eventStatement.actor.mbox = currentActiveLogin.Email;
1093
1094 if (eventStatement.context == null)
1095 {
1096 eventStatement.context = new Context();
1097 }
1098
1099 eventStatement.context.registration = currentSessionID;
1100 eventStatement.context.revision = ModuleVersion;
1101 eventStatement.context.platform = platform;
1102
1103 eventStatement.context.extensions = AppendStandardContextExtension(eventStatement.context.extensions);
1104
1105 SessionEventData sessionEvent = new SessionEventData();
1106 sessionEvent.DeviceId = deviceID;
1107 sessionEvent.ModuleId = ModuleID;
1108 sessionEvent.Uuid = currentSessionID.ToString();
1109 sessionEvent.EventType = ApexEventTypes.PIXOVR_SESSION_EVENT;
1110 sessionEvent.JsonData = eventStatement;
1111
1113
1114 return true;
1115 }
1116
1117 protected bool _CompleteSession(
1118 SessionData currentSessionData,
1119 Extension contextExtension,
1120 Extension resultExtension
1121 )
1122 {
1123 if (userAccessVerified == false)
1124 {
1125 return false;
1126 }
1127
1128 if (currentActiveLogin == null)
1129 {
1130 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot complete session with no active login.");
1131 return false;
1132 }
1133
1134 if (sessionInProgress == false)
1135 {
1136 Debug.unityLogger.Log(LogType.Error, TAG, "No session in progress to complete.");
1137 return false;
1138 }
1139
1140 // Create our actor
1141 Agent sessionActor = new Agent();
1142 sessionActor.mbox = currentActiveLogin.Email;
1143
1144 // Create our verb
1145 Verb sessionVerb = new Verb();
1146 sessionVerb.id = ApexVerbs.COMPLETED_SESSION;
1147 sessionVerb.display = new LanguageMap();
1148 sessionVerb.display.Add("en", "Completed Session");
1149
1150 // Create the session activity
1151 Activity sessionActivity = new Activity();
1152 sessionActivity.id = string.Format("https://pixovr.com/xapi/objects/{0}/{1}", moduleID, scenarioID);
1153
1154 // Create our context
1155 Context sessionContext = new Context();
1156 sessionContext.registration = currentSessionID;
1157 sessionContext.revision = moduleVersion;
1158 sessionContext.platform = platform;
1159
1160 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
1161
1162 // Create our results
1163 Result sessionResult = new Result();
1164 sessionResult.completion = currentSessionData.Complete;
1165 sessionResult.success = currentSessionData.Success;
1166 // Add score to the results
1167 sessionResult.score = new Score();
1168 sessionResult.score.min = currentSessionData.MinimumScore;
1169 sessionResult.score.max = currentSessionData.MaximumScore;
1170 sessionResult.score.raw = currentSessionData.Score;
1171 sessionResult.score.scaled = DetermineScaledScore(
1172 currentSessionData.ScaledScore,
1173 currentSessionData.Score,
1174 currentSessionData.MaximumScore
1175 );
1176 sessionResult.duration = TimeSpan.FromSeconds(currentSessionData.Duration);
1177 if (resultExtension != null)
1178 {
1179 sessionResult.extensions = new Extensions(resultExtension.ToJObject());
1180 }
1181
1182 // Create our statement and add the pieces
1183 Statement sessionStatement = new Statement();
1184 sessionStatement.actor = sessionActor;
1185 sessionStatement.verb = sessionVerb;
1186 sessionStatement.target = sessionActivity;
1187 sessionStatement.context = sessionContext;
1188 sessionStatement.result = sessionResult;
1189
1190 CompleteSessionData sessionData = new CompleteSessionData();
1191 sessionData.DeviceId = deviceID;
1192 sessionData.ModuleId = moduleID;
1193 sessionData.Uuid = currentSessionID.ToString();
1194 sessionData.EventType = ApexEventTypes.PIXOVR_SESSION_COMPLETE;
1195 sessionData.JsonData = sessionStatement;
1196 sessionData.SessionDuration = currentSessionData.Duration;
1197 sessionData.Score = currentSessionData.Score;
1198 sessionData.ScoreMin = currentSessionData.MinimumScore;
1199 sessionData.ScoreMax = currentSessionData.MaximumScore;
1200 sessionData.ScoreScaled = DetermineScaledScore(
1201 currentSessionData.ScaledScore,
1202 currentSessionData.Score,
1203 currentSessionData.MaximumScore
1204 );
1205
1207
1208 return true;
1209 }
1210
1211 protected bool _SendHeartbeat()
1212 {
1213 Debug.unityLogger.Log(LogType.Log, TAG, "Sending heartbeat...");
1214 if (!sessionInProgress)
1215 return false;
1216
1217 if (currentActiveLogin == null)
1218 return false;
1219
1221
1222 return true;
1223 }
1224
1225 protected bool _GetUser(int userId = -1)
1226 {
1227 if (currentActiveLogin == null)
1228 return false;
1229
1230 if (userId < 0)
1231 {
1232 userId = currentActiveLogin.ID;
1233 }
1234
1236 return true;
1237 }
1238
1239 protected bool _GetUserModules(int userId = -1)
1240 {
1241 if (currentActiveLogin == null)
1242 return false;
1243
1244 if (userId < 0)
1245 {
1246 userId = currentActiveLogin.ID;
1247 }
1248
1250 return true;
1251 }
1252
1253 protected bool _GetModuleList(string platformName)
1254 {
1255 if (currentActiveLogin == null)
1256 return false;
1257
1259 return true;
1260 }
1261
1262 protected bool _GetQuickIDAuthUsers(string serialNumber)
1263 {
1264 if (String.IsNullOrEmpty(serialNumber)) return false;
1266 return true;
1267 }
1268
1269
1270 protected bool _QuickIDLogin(string serialNumber, string username)
1271 {
1272 if (String.IsNullOrEmpty(serialNumber) || string.IsNullOrEmpty(username)) return false;
1273 var loginData = new QuickIDLoginData(serialNumber, username);
1274 apexAPIHandler.QuickIDLogin(loginData);
1275 return true;
1276 }
1277
1278 private float DetermineScaledScore(float scaledScore, float score, float maxScore)
1279 {
1280 float determinedScaledScore = scaledScore;
1281
1282 if (scaledScore < Mathf.Epsilon && score >= Mathf.Epsilon)
1283 {
1284 determinedScaledScore = (score / maxScore) * 100f;
1285 }
1286
1287 return determinedScaledScore;
1288 }
1289
1290 private Extensions AppendStandardContextExtension(Extensions currentContextExtensions)
1291 {
1292 return AppendStandardContextExtension(new Extension(currentContextExtensions.ToJObject()));
1293 }
1294
1295 private Extensions AppendStandardContextExtension(Extension currentContextExtension)
1296 {
1297 Extension contextExtension;
1298 if (currentContextExtension != null)
1299 {
1300 contextExtension = currentContextExtension;
1302 else
1303 {
1304 contextExtension = new Extension();
1305 }
1306
1307 contextExtension.Add(ApexExtensionStrings.MODULE_ID, moduleID.ToString());
1308 contextExtension.AddSimple("device_id", deviceID);
1309 contextExtension.AddSimple("device_model", deviceModel);
1310 contextExtension.AddSimple("sdk_version", "unity-" + ApexUtils.SDKVersion);
1311
1312 if (string.IsNullOrEmpty(deviceSerialNumber))
1313 {
1314 contextExtension.AddSimple("device_serial", deviceSerialNumber.ToString());
1315 }
1316
1317 return new Extensions(contextExtension.ToJObject());
1319
1320 protected void OnAPIResponse(ResponseType response, HttpResponseMessage message, object responseData)
1321 {
1322 Debug.unityLogger.Log(LogType.Log, TAG, "On API Response");
1323 bool success = message.IsSuccessStatusCode;
1324 if (responseData is FailureResponse)
1325 {
1326 success = success && (responseData is IFailure) && (!(responseData as FailureResponse).HasErrored());
1327 }
1328
1329 switch (response)
1330 {
1331 case ResponseType.RT_PING:
1332 {
1333 if (success)
1334 {
1335 Debug.unityLogger.Log(LogType.Log, TAG, "Ping successful.");
1336 OnPingSuccess.Invoke(message);
1337 }
1338 else
1339 {
1340 Debug.unityLogger.Log(LogType.Log, TAG, "Ping failed.");
1341 OnPingFailed.Invoke(message);
1342 }
1343 break;
1344 }
1345 case ResponseType.RT_LOGIN:
1346 {
1347 Debug.unityLogger.Log(LogType.Log, TAG, "Calling to handle login.");
1348 HandleLogin(success, responseData);
1349 break;
1350 }
1351 case ResponseType.RT_GET_USER:
1352 {
1353 if (success)
1354 {
1355 OnGetUserSuccess.Invoke(responseData as GetUserResponseContent);
1356 }
1357 else
1358 {
1359 FailureResponse failureData = responseData as FailureResponse;
1360 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get user.\nError: {0}", failureData.Message));
1361 OnGetUserFailed.Invoke(responseData as FailureResponse);
1362 }
1363 break;
1364 }
1365 case ResponseType.RT_GET_USER_MODULES:
1366 {
1367 if (success)
1369 OnGetUserModulesSuccess.Invoke(responseData as GetUserModulesResponse);
1370 }
1371 else
1372 {
1373 FailureResponse failureData = responseData as FailureResponse;
1374 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get user.\nError: {0}", failureData.Message));
1375 OnGetUserFailed.Invoke(responseData as FailureResponse);
1376 }
1377 break;
1378 }
1379 case ResponseType.RT_SESSION_JOINED:
1380 {
1381 if (success)
1382 {
1383 JoinSessionResponse joinSessionResponse = responseData as JoinSessionResponse;
1384 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Session Id is {0}.", joinSessionResponse.SessionId));
1385 heartbeatSessionID = joinSessionResponse.SessionId;
1386 sessionInProgress = true;
1387 OnJoinSessionSuccess.Invoke(message);
1388 }
1389 else
1390 {
1391 FailureResponse failureData = responseData as FailureResponse;
1392 Debug.unityLogger.Log(LogType.Log, TAG,
1393 string.Format("Failed to join session.\nError: {0}", failureData.Message)
1394 );
1395 currentSessionID = Guid.Empty;
1396 sessionInProgress = false;
1397 OnJoinSessionFailed.Invoke(responseData as FailureResponse);
1398 }
1399 break;
1400 }
1401 case ResponseType.RT_SESSION_COMPLETE:
1402 {
1403 if (success)
1404 {
1405 sessionInProgress = false;
1406 currentSessionID = Guid.Empty;
1407 OnCompleteSessionSuccess.Invoke(message);
1408 }
1409 else
1410 {
1411 FailureResponse failureData = responseData as FailureResponse;
1412 Debug.unityLogger.Log(LogType.Log, TAG,
1413 string.Format("Failed to complete session.\nError: {0}", failureData.Message)
1414 );
1415 OnCompleteSessionFailed.Invoke(responseData as FailureResponse);
1416 }
1417 break;
1418 }
1419 case ResponseType.RT_SESSION_EVENT:
1420 {
1421 if (success)
1422 {
1423 Debug.unityLogger.Log(LogType.Log, TAG, "Session event sent.");
1424 OnSendEventSuccess.Invoke(message);
1425 }
1426 else
1427 {
1428 FailureResponse failureData = responseData as FailureResponse;
1429 Debug.unityLogger.Log(LogType.Log, TAG,
1430 string.Format("Failed to send session event.\nError: {0}", failureData.Message)
1431 );
1432 OnSendEventFailed.Invoke(responseData as FailureResponse);
1433 }
1434 break;
1435 }
1436 case ResponseType.RT_GET_USER_ACCESS:
1437 {
1438 if (success)
1439 {
1440 var userAccessResponseContent = responseData as UserAccessResponseContent;
1441 if (userAccessResponseContent.Access)
1442 {
1443 if (userAccessResponseContent.PassingScore.HasValue)
1444 {
1445 currentActiveLogin.MinimumPassingScore = userAccessResponseContent.PassingScore.Value;
1446 }
1447
1448 userAccessVerified = true;
1450 }
1451 else
1452 {
1453 currentActiveLogin = null;
1454 userAccessVerified = false;
1455 OnModuleAccessFailed.Invoke(
1456 new FailureResponse()
1457 {
1458 Error = "True",
1459 HttpCode = "401",
1460 Message = "User does not have access to module",
1461 }
1462 );
1463 }
1464 }
1465 else
1466 {
1467 FailureResponse failureData = responseData as FailureResponse;
1468 Debug.unityLogger.Log(LogType.Log, TAG,
1469 string.Format(
1470 "Failed to get users module access data.\nError: {0}",
1471 failureData.Message
1472 )
1473 );
1474
1475 OnModuleAccessFailed.Invoke(responseData as FailureResponse);
1476 }
1477 break;
1478 }
1479 case ResponseType.RT_GET_MODULES_LIST:
1480 {
1481 if (success)
1482 {
1483 OnGetOrganizationModulesSuccess.Invoke(responseData as List<OrgModule>);
1484 }
1485 else
1486 {
1487 FailureResponse failureData = responseData as FailureResponse;
1488 Debug.unityLogger.Log(LogType.Log, TAG,
1489 string.Format("Failed to get org modules.\nError: {0}", failureData.Message)
1490 );
1491
1492 OnGetOrganizationModulesFailed.Invoke(responseData as FailureResponse);
1493 }
1494
1495 break;
1496 }
1497 case ResponseType.RT_QUICK_ID_AUTH_GET_USERS:
1498 {
1499 if (success)
1500 {
1502 }
1503 else
1504 {
1505 FailureResponse failureData = responseData as FailureResponse;
1506 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get Quick ID Authentication users.\nError: {0}", failureData.Message));
1507 OnGetQuickIDAuthGetUsersFailed.Invoke(responseData as FailureResponse);
1508 }
1509 break;
1510 }
1511
1512 case ResponseType.RT_QUICK_ID_AUTH_LOGIN:
1513 {
1514 HandleLogin(success, responseData);
1515 if (success)
1516 {
1517 OnQuickIDAuthLoginSuccess.Invoke(responseData as LoginResponseContent);
1518 }
1519 else
1520 {
1521 FailureResponse failureData = responseData as FailureResponse;
1522 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to authenticate with Quick ID Authentication.\nError: {0}", failureData.Message));
1523 OnQuickIDAuthLoginFailed.Invoke(responseData as FailureResponse);
1524 }
1525 break;
1526 }
1527 case ResponseType.RT_GET_USER_METRICS_FOR_ORG:
1528 {
1529 if (success)
1530 {
1531 OnGetUserMetricsForOrgSuccess.Invoke(responseData as UserMetricsResponse);
1532 }
1533 else
1534 {
1535 FailureResponse failureData = responseData as FailureResponse;
1536 Debug.Log(
1537 string.Format("[ApexSystem] Failed to get user metrics for org.\nError: {0}", failureData.Message)
1538 );
1539 OnGetUserMetricsForOrgFailed.Invoke(responseData as FailureResponse);
1540 }
1541 break;
1542 }
1543 default:
1544 {
1545 break;
1546 }
1547 }
1548
1549 if (OnPlatformResponse != null)
1550 {
1551 OnPlatformResponse.Invoke(response, success, responseData);
1552 }
1553 }
1554
1555 protected void HandleLogin(bool successful, object responseData)
1556 {
1557 Debug.unityLogger.Log(LogType.Log, TAG, "Handling Login");
1558 userAccessVerified = false;
1559
1560 if (successful)
1561 {
1562 currentActiveLogin = responseData as LoginResponseContent;
1563
1564 OnLoginSuccess.Invoke();
1565
1567 {
1569 }
1570 }
1571 else
1572 {
1573 FailureResponse failureData = responseData as FailureResponse;
1574 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to log in.\nError: {0}", failureData.Message));
1575 OnLoginFailed.Invoke(responseData as FailureResponse);
1576 }
1577 }
1578
1580 {
1581 if (!webSocket.IsConnected())
1582 {
1584 }
1586 }
1587
1588 public static bool GenerateOneTimeLoginForCurrentUser(Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1589 {
1590 return Instance._GenerateOneTimeLoginForCurrentUser(success, failure);
1591 }
1592
1593 public static bool GenerateOneTimeLoginForUser(int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1594 {
1595 return Instance._GenerateOneTimeLoginForUser(userId, success, failure);
1596 }
1597
1598 public static bool GetUserMetricsForCurrentUsersOrg(int page)
1599 {
1600 if ( Instance.currentActiveLogin == null )
1601 return false;
1602 return Instance._GetUserMetricsForCurrentUsersOrg(page);
1604
1605 bool _GenerateOneTimeLoginForUser(int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1606 {
1607 if (currentActiveLogin == null)
1608 {
1609 Debug.unityLogger.Log(LogType.Error, TAG, "No current user logged in.");
1610 return false;
1611 }
1612
1613 if(userId < 0)
1614 {
1615 Debug.unityLogger.Log(LogType.Error, TAG, "User id is invalid.");
1616 return false;
1617 }
1618
1620 return true;
1621 }
1622
1623 bool _GenerateOneTimeLoginForCurrentUser(Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1624 {
1625 if (currentActiveLogin == null)
1626 {
1627 Debug.unityLogger.Log(LogType.Error, TAG, "No user logged in to generate code.");
1628 return false;
1629 }
1630
1632 return true;
1633 }
1634
1637 if (currentActiveLogin == null)
1638 {
1639 Debug.LogError("[ApexSystem] No user logged in to retrieve users.");
1640 return false;
1645 }
1647}
async void SendHeartbeat(string authToken, int sessionId)
async void GetUserModules(string authToken, int userId)
async void QuickIDLogin(QuickIDLoginData login)
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)
async void Login(LoginData login)
async void SendSessionEvent(string authToken, SessionEventData sessionEvent)
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 GetModuleAccess(int moduleId, int userId, string serialNumber)
async void GetModuleList(string authToken, string platform)
const string PIXOVR_SESSION_COMPLETE
const string PIXOVR_SESSION_EVENT
const string PIXOVR_SESSION_JOINED
static readonly string MODULE_ID
bool InitializeInstance(T targetInstance)
bool _GenerateOneTimeLoginForUser(int userId, Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
ApexWebsocket webSocket
OnHttpResponseEvent OnPingSuccess
Extensions AppendStandardContextExtension(Extensions currentContextExtensions)
OnGeneratedAssistedLoginSuccessEvent OnGeneratedAssistedLoginSuccess
bool runSetupOnAwake
[SerializeField]
static string CurrentExitTarget
static string PassedLoginToken
Definition ApexSystem.cs:88
static bool LoginCheckModuleAccess
Definition ApexSystem.cs:76
static bool QuickIDLogin(string serialNumber, string username)
static bool GetCurrentUser()
static bool GenerateOneTimeLoginForCurrentUser(Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
static bool RunSetupOnAwake
Definition ApexSystem.cs:70
static bool GetUserMetricsForCurrentUsersOrg(int page)
FailureResponse GenerateFailureResponse(string message)
OnApexFailureEvent OnJoinSessionFailed
string GetPlatformEndpointFromPlatformTarget(PlatformServer target)
void _ChangePlatformServer(PlatformServer newServer)
int moduleID
[SerializeField]
static bool Login(string username, string password)
bool _GenerateOneTimeLoginForCurrentUser(Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
OnApexFailureEvent OnGeneratedAssistedLoginFailed
static string ModuleName
Definition ApexSystem.cs:46
OnHttpResponseEvent OnPingFailed
static bool SendSessionEvent(Statement eventStatement)
OnGetQuickIDAuthUsersSuccessEvent OnGetQuickIDAuthGetUsersSuccess
string GetWebEndpointFromPlatformTarget(PlatformServer target)
void OnAPIResponse(ResponseType response, HttpResponseMessage message, object responseData)
static void ExitApplication(string nextExitTarget="")
OnHttpResponseEvent OnJoinSessionSuccess
OnApexFailureEvent OnGetUserFailed
OnAuthCodeReceived OnAuthorizationCodeReceived
OnGetOrgModulesSuccessEvent OnGetOrganizationModulesSuccess
bool _JoinSession(string newScenarioID=null, Extension contextExtension=null)
bool _Login(LoginData login)
static bool RequestAuthorizationCode()
bool _CompleteSession(SessionData currentSessionData, Extension contextExtension, Extension resultExtension)
void SetupPlatformConfiguration()
PlatformResponse OnPlatformResponse
static bool GetUser(int userId=-1)
OnHttpResponseEvent OnCompleteSessionSuccess
static bool GetQuickIDAuthUsers(string serialNumber)
string moduleVersion
[SerializeField]
string GetEndpointFromTarget(PlatformServer target)
bool _SendSimpleSessionEvent(string verbName, string targetObject, Extension contextExtension)
OnApexFailureEvent OnCompleteSessionFailed
OnLoginSuccessEvent OnLoginSuccess
void OnWebSocketConnectFailed(string reason)
static bool CheckModuleAccess(int targetModuleID=-1)
OnApexFailureEvent OnSendEventFailed
OnQuickIDAuthLoginSuccessEvent OnQuickIDAuthLoginSuccess
void OnWebSocketReceive(string data)
void HandleLogin(bool successful, object responseData)
static bool GetUserModules(int userId=-1)
static LoginResponseContent CurrentActiveLogin
Definition ApexSystem.cs:64
bool _GetQuickIDAuthUsers(string serialNumber)
string currentExitTargetParameter
static bool SendSimpleSessionEvent(string action, string targetObject, Extension contextExtension)
OnGetUserMetricsForOrgSuccessEvent OnGetUserMetricsForOrgSuccess
static string ServerIP
Definition ApexSystem.cs:34
static string TargetType
float DetermineScaledScore(float scaledScore, float score, float maxScore)
APIHandler apexAPIHandler
static bool GetCurrentUserModules()
static bool GetModulesList(string platformName)
Task< bool > socketConnectTask
OnApexFailureEvent OnGetQuickIDAuthGetUsersFailed
static void ChangePlatformServer(PlatformServer newServer)
static string ModuleVersion
Definition ApexSystem.cs:52
static bool LoginWithToken()
bool _Login(string username, string password)
static bool JoinSession(string scenarioID=null, Extension contextExtension=null)
bool loginCheckModuleAccess
[SerializeField]
OnApexFailureEvent OnGetUserModulesFailed
bool _SendSessionEvent(Statement eventStatement)
OnApexFailureEvent OnLoginFailed
static bool Login(LoginData login)
static string ScenarioID
Definition ApexSystem.cs:58
void _ParsePassedData(Dictionary< string, string > arguments)
static string DeviceSerialNumber
Definition ApexSystem.cs:82
LoginResponseContent currentActiveLogin
bool _LoginWithToken(string token)
static readonly Regex VersionValidator
OnApexFailureEvent OnGetOrganizationModulesFailed
float heartbeatTime
[SerializeField]
OnApexFailureEvent OnModuleAccessFailed
static bool GenerateOneTimeLoginForUser(int userId, Action< HttpResponseMessage, object > success, Action< HttpResponseMessage, FailureResponse > failure)
OnApexFailureEvent OnQuickIDAuthLoginFailed
static string OptionalData
string scenarioID
[SerializeField]
static readonly string TAG
Definition ApexSystem.cs:25
OnModuleAccessSuccessEvent OnModuleAccessSuccess
void _ExitApplication(string nextExitApplication)
bool _GetUser(int userId=-1)
OnGetUserSuccessEvent OnGetUserSuccess
OnHttpResponseEvent OnSendEventSuccess
bool _QuickIDLogin(string serialNumber, string username)
bool _CheckModuleAccess(int targetModuleID=-1)
static bool CompleteSession(SessionData currentSessionData, Extension contextExtension=null, Extension resultExtension=null)
bool IsModuleVersionOnlyNumerical()
bool _GetUserMetricsForCurrentUsersOrg(int page)
OnApexFailureEvent OnGetUserMetricsForOrgFailed
string serverIP
[SerializeField]
void OnWebSocketClosed(System.Net.WebSockets.WebSocketCloseStatus reason)
bool _GetModuleList(string platformName)
static bool LoginWithToken(string token)
PlatformServer PlatformTargetServer
OnGetUserModulesSuccessEvent OnGetUserModulesSuccess
Extensions AppendStandardContextExtension(Extension currentContextExtension)
string moduleName
[SerializeField]
bool IsModuleNonMajorVersionPartValid(string modulePart)
bool _GetUserModules(int userId=-1)
bool IsModuleMajorVersionPartValid(string modulePart)
void OnDeepLinkActivated(string url)
static readonly Uri JOINED_SESSION
static readonly Uri COMPLETED_SESSION
async Task< bool > Connect(Uri endpoint, int attemptTries=3)
OnWebSocketReceive OnReceive
OnWebSocketConnectFailed OnConnectFailed
OnWebSocketClosed OnClosed
OnWebSocketConnectSuccessful OnConnectSuccess
[Serializable]
Definition ApexTypes.cs:165
static bool DoesFileExistInSharedLocation(string fileName)
static string ReadFileFromSharedStorage(string fileName)
static bool OpenApplication(string applicationPath, string[] argumentKeys, string[] argumentValues)
static Dictionary< string, string > ParseURLArguments(string url)
static Dictionary< string, string > ParseApplicationArguments()
static string GetMacAddress()
Definition ApexUtils.cs:21
void Add(Uri key, string value)
void AddSimple(string key, string value)
override JObject ToJObject(TCAPIVersion version)
delegate void PlatformResponse(ResponseType type, bool wasSuccessful, object responseData)