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 public static string APIEndpoint
140 {
141 get { return ((APIPlatformServer)Instance.PlatformTargetServer).ToUrlString(); }
142 }
143
144 [SerializeField, EndpointDisplay]
146
147 [SerializeField]
148 protected string serverIP = "";
149
150 [SerializeField]
151 protected int moduleID = 0;
152
153 [SerializeField]
154 protected string moduleName = "Generic";
155
156 [SerializeField]
157 protected string moduleVersion = "0.00.00";
158
159 [SerializeField]
160 protected string scenarioID = "Generic";
161
162 [SerializeField]
163 public bool runSetupOnAwake = true;
164
165 [SerializeField]
166 public bool loginCheckModuleAccess = true;
167
168 [SerializeField]
169 protected float heartbeatTime = 5.0f;
170
171 protected string webSocketUrl;
172 protected string deviceID;
173 protected string deviceModel;
174 protected string platform;
175 protected string clientIP;
176 protected Guid currentSessionID;
177 protected int heartbeatSessionID;
178 protected float heartbeatTimer;
179 protected bool sessionInProgress;
180 protected bool userAccessVerified = false;
181 protected string deviceSerialNumber = "";
182 protected bool hasParsedArguments = false;
183
184 protected string loginToken = "";
185 protected string optionalParameter = "";
186 protected string currentExitTargetParameter = "";
187 protected string targetTypeParameter = "";
188
191 protected ApexWebsocket webSocket;
192 protected Task<bool> socketConnectTask;
193 protected Task socketDisconnectTask;
194
197
200
203
206
209
212
215
218
222 public PlatformResponse OnPlatformResponse = null;
231
244 void Awake()
245 {
246 Debug.unityLogger.Log(LogType.Log, TAG, $"ApexSystem found on {gameObject.name}");
248 {
249 Debug.unityLogger.Log(LogType.Log, TAG, "Instance already initialized.");
251
254#if UNITY_IOS || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
256#endif
257 if (runSetupOnAwake)
259 Debug.unityLogger.Log(LogType.Log, TAG, "Running on awake!");
260 SetupAPI();
263 DontDestroyOnLoad(gameObject);
264#if MANAGE_XR && !UNITY_EDITOR
265 Debug.unityLogger.Log(LogType.Log, TAG, "Using ManageXR");
266 InitMXRSDK();
267#endif
269
270#if MANAGE_XR
271 async void InitMXRSDK()
273 Debug.unityLogger.Log(LogType.Log, TAG, "Initializing the ManageXR SDK");
274 await MXRManager.InitAsync();
275 MXRManager.System.OnDeviceStatusChange += OnDeviceStatusChanged;
276 deviceSerialNumber = MXRManager.System.DeviceStatus.serial;
277 Debug.unityLogger.Log(LogType.Log, TAG, $"Device serial set to {deviceSerialNumber}");
279
280 void OnDeviceStatusChanged(DeviceStatus newDeviceStatus)
282 deviceSerialNumber = newDeviceStatus.serial;
283 Debug.unityLogger.Log(LogType.Log, TAG, $"Device serial number changed to {deviceSerialNumber}");
285#endif
288 {
289 Application.deepLinkActivated += OnDeepLinkActivated;
290 if (!string.IsNullOrEmpty(Application.absoluteURL))
291 {
292 // Cold start and Application.absoluteURL not null so process Deep Link.
293 OnDeepLinkActivated(Application.absoluteURL);
294 }
295 }
296
297 void OnDeepLinkActivated(string url)
298 {
299 // Update DeepLink Manager global variable, so URL can be accessed from anywhere.
300 var urlArguments = PixoPlatformUtilities.ParseURLArguments(url);
301 _ParsePassedData(urlArguments);
302 }
303
305 {
306 Debug.unityLogger.Log(LogType.Log, TAG, "SetupPlatformConfiguration");
307
308#if UNITY_ANDROID
310 {
311 Debug.unityLogger.Log(LogType.Log, TAG, "Found pixoconfig.cnf");
312
313 string configContent = PixoAndroidUtils.ReadFileFromSharedStorage("pixoconfig.cnf");
314
315 if (configContent.Length > 0)
316 {
317 Debug.unityLogger.Log(LogType.Log, TAG, "Configuration is not empty.");
318 ConfigurationTypes configData = JsonConvert.DeserializeObject<ConfigurationTypes>(configContent);
319 if (configData == null)
320 {
321 Debug.unityLogger.Log(LogType.Log, TAG, "Failed to deserialize the config.");
322 return;
323 }
324
325 // Parse out the platform target to utilize the unity built in config values
326 if (configData.Platform.Contains("NA", StringComparison.CurrentCultureIgnoreCase))
327 {
328 if (configData.Platform.Contains("Production", StringComparison.CurrentCultureIgnoreCase))
329 {
330 Debug.unityLogger.Log(LogType.Log, TAG, "NA Production platform target.");
331 PlatformTargetServer = PlatformServer.NA_PRODUCTION;
332 }
333
334 if (configData.Platform.Contains("Dev", StringComparison.CurrentCultureIgnoreCase))
336 Debug.unityLogger.Log(LogType.Log, TAG, "NA Dev platform target.");
338 }
339
340 if (configData.Platform.Contains("Stage", StringComparison.CurrentCultureIgnoreCase))
341 {
342 Debug.unityLogger.Log(LogType.Log, TAG, "NA Stage platform target.");
344 }
346 else if (configData.Platform.Contains("SA", StringComparison.CurrentCultureIgnoreCase))
347 {
348 Debug.unityLogger.Log(LogType.Log, TAG, "SA Production platform target.");
349 PlatformTargetServer = PlatformServer.SA_PRODUCTION;
350 }
351
352 // TODO (MGruber): Add a custom value, but this requires multiple configuration values to be saved.
353 // Need to save the normal headset api endpoint, web api endpoint and platform api endpoint. 3 VALUES! D:
354 }
355 }
356#endif
357 }
358
359 void SetupAPI()
360 {
361 Debug.unityLogger.Log(LogType.Log, TAG, "Mac Address: " + ApexUtils.GetMacAddress());
362 if (serverIP.Length == 0)
363 {
365 }
366
368
369 if (apexAPIHandler != null)
370 {
371 Debug.unityLogger.Log(LogType.Log, TAG, "Apex API Handler is not null!");
372 }
373
374 // TODO: Move to new plugin
376 apexAPIHandler.OnAPIResponse += OnAPIResponse;
377
378 if (webSocket != null)
379 {
381 {
383 }
384 }
385
386 webSocket = new ApexWebsocket();
388 webSocket.OnConnectFailed.AddListener((reason) => OnWebSocketConnectFailed(reason));
389 webSocket.OnReceive.AddListener((data) => OnWebSocketReceive(data));
390 webSocket.OnClosed.AddListener((reason) => OnWebSocketClosed(reason));
391
393
395 {
396 var applicationArugments = PixoPlatformUtilities.ParseApplicationArguments();
397 _ParsePassedData(applicationArugments);
398 Debug.unityLogger.Log(LogType.Log, TAG, $"Login Token: {(string.IsNullOrEmpty(PassedLoginToken) ? "<Null>" : PassedLoginToken)}");
399 hasParsedArguments = true;
400 }
401 }
402
403 void _ExitApplication(string nextExitApplication)
404 {
405 Debug.unityLogger.Log(LogType.Log, TAG, "ApexSystem::_ExitApplication");
406 if (nextExitApplication == null)
408 nextExitApplication = "";
409 }
410
411 string returnTargetType = "app";
412
413 if (nextExitApplication.Contains("://"))
414 {
415 returnTargetType = "url";
416 }
417
418 Debug.unityLogger.Log(LogType.Log, TAG, "" + nextExitApplication + " " + returnTargetType);
419
420 string parameters = "";
421
422 Debug.unityLogger.Log(LogType.Log, TAG, "Building parameters for url.");
423
424 if (CurrentActiveLogin != null)
425 {
426 parameters += "pixotoken=" + CurrentActiveLogin.Token;
427 }
428 else if (!string.IsNullOrEmpty(PassedLoginToken))
429 {
430 parameters += "pixotoken=" + PassedLoginToken;
431 }
432
433 if (optionalParameter != null)
434 {
435 if (optionalParameter.Length > 0)
436 {
437 if (parameters.Length > 0)
438 parameters += "&";
439 parameters += "optional=" + optionalParameter;
440 }
441 }
442
443 if (nextExitApplication.Length > 0)
444 {
445 if (parameters.Length > 0)
446 parameters += "&";
447 parameters += "returntarget=" + nextExitApplication;
448 }
449
450 if (returnTargetType.Length > 0)
452 if (parameters.Length > 0)
453 parameters += "&";
454 parameters += "targettype=" + returnTargetType;
455 }
456
457 Debug.unityLogger.Log(LogType.Log, TAG, "Checking the return target parameter.");
458
459 if (!string.IsNullOrEmpty(CurrentExitTarget))
460 {
461 Debug.unityLogger.Log(LogType.Log, TAG, "Had a valid return target parameter.");
462 if (targetTypeParameter.Equals("url", StringComparison.OrdinalIgnoreCase))
463 {
464 Debug.unityLogger.Log(LogType.Log, TAG, "Return Target is a URL.");
465
466 string returnURL = CurrentExitTarget;
467 if (!string.IsNullOrEmpty(parameters))
468 {
469 if (!returnURL.Contains('?'))
470 returnURL += "?";
471 else
472 returnURL += "&";
473
474 returnURL += parameters;
475 }
476 Debug.unityLogger.Log(LogType.Log, TAG, "Custom Target: " + returnURL);
478 return;
479 }
480 else
481 {
482 Debug.unityLogger.Log(LogType.Log, TAG, $"Return Target is a package name. {CurrentExitTarget}");
483
484 List<string> keys = new List<string>(),
485 values = new List<string>();
486
487 Debug.unityLogger.Log(LogType.Log, TAG, "Adding pixo token.");
488
489 if (CurrentActiveLogin != null)
490 {
491 keys.Add("pixotoken");
492 values.Add(CurrentActiveLogin.Token);
493 }
494 else if (!string.IsNullOrEmpty(PassedLoginToken))
495 {
496 keys.Add("pixotoken");
497 values.Add(PassedLoginToken);
498 }
499
500 Debug.unityLogger.Log(LogType.Log, TAG, "Adding optional.");
501
502 if (!string.IsNullOrEmpty(optionalParameter))
503 {
504 keys.Add("optional");
505 values.Add(optionalParameter);
506 }
507
508 Debug.unityLogger.Log(LogType.Log, TAG, "Adding return target.");
509
510 if (!string.IsNullOrEmpty(nextExitApplication))
511 {
512 keys.Add("returntarget");
513 values.Add(nextExitApplication);
514 }
515
516 Debug.unityLogger.Log(LogType.Log, TAG, "Adding return target type.");
517
518 if (!string.IsNullOrEmpty(returnTargetType))
519 {
520 keys.Add("targettype");
521 values.Add(returnTargetType);
522 }
523
524 PixoPlatformUtilities.OpenApplication(CurrentExitTarget, keys.ToArray(), values.ToArray());
525 return;
526 }
527 }
528
530 }
531
532 string GetEndpointFromTarget(PlatformServer target)
533 {
534 return target.ToUrlString();
535 }
536
537 string GetWebEndpointFromPlatformTarget(PlatformServer target)
538 {
539 int targetValue = (int)target;
540 WebPlatformServer webTarget = (WebPlatformServer)targetValue;
541
542 return webTarget.ToUrlString();
543 }
544
545 string GetPlatformEndpointFromPlatformTarget(PlatformServer target)
546 {
547 int targetValue = (int)target;
548 APIPlatformServer apiTarget = (APIPlatformServer)targetValue;
549
550 return apiTarget.ToUrlString();
551 }
552
554 {
556
557 if (webSocketUrl.Contains("://"))
558 {
559 webSocketUrl = webSocketUrl.Split(new string[] { "://" }, 2, StringSplitOptions.RemoveEmptyEntries)[1];
560 }
561
562 if (webSocketUrl.Contains("/"))
563 {
564 webSocketUrl = webSocketUrl.Split(new string[] { "/" }, 2, StringSplitOptions.RemoveEmptyEntries)[0];
565 }
566
567 webSocketUrl = "wss://" + webSocketUrl + "/ws";
568 }
569
570 void Start()
571 {
573 {
574 Debug.unityLogger.Log(LogType.Warning, TAG, $"{moduleVersion} is an invalid module version.");
575 }
576 deviceID = SystemInfo.deviceUniqueIdentifier;
577 deviceModel = SystemInfo.deviceModel;
578 platform =
579 XRSettings.loadedDeviceName.Length > 0 ? XRSettings.loadedDeviceName : Application.platform.ToString();
580 clientIP = Utils.ApexUtils.GetLocalIP();
581 }
582
583 private void FixedUpdate()
584 {
585 if (webSocket != null)
586 {
588 }
589
591 {
592 heartbeatTimer -= Time.fixedDeltaTime;
594 if (heartbeatTimer <= 0.0f)
595 {
598 }
599 }
600 }
602 void ConnectWebsocket()
603 {
604 socketConnectTask = Task.Run(() => webSocket.Connect(new Uri(webSocketUrl)));
605 }
606
608 {
609 socketDisconnectTask = Task.Run(() => webSocket.CloseSocket());
610 }
611
613 {
614 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket connected successfully.");
615 }
616
617 void OnWebSocketConnectFailed(string reason)
619 Debug.unityLogger.Log(LogType.Error, TAG, "Websocket failed to connect with error: " + reason);
620 }
621
622 void OnWebSocketReceive(string data)
623 {
624 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket received: " + data);
625 try
626 {
627 if (data.Contains("auth_code"))
628 {
629 var authCode = JsonConvert.DeserializeObject<AuthorizationCode>(data);
630 OnAuthorizationCodeReceived.Invoke(authCode.Code);
632
633 if (data.Contains("Token", StringComparison.OrdinalIgnoreCase))
634 {
635 object loginResponse = JsonConvert.DeserializeObject<LoginResponseContent>(data);
636 HandleLogin(true, loginResponse);
637 }
638 }
639 catch (Exception ex)
640 {
641 Debug.unityLogger.Log(LogType.Log, TAG, ex.Message);
642 }
643 }
644
645 void OnWebSocketClosed(System.Net.WebSockets.WebSocketCloseStatus reason)
646 {
647 Debug.unityLogger.Log(LogType.Log, TAG, "Websocket closed with reason: " + reason);
648 }
649
651 {
652 if (IsModuleVersionOnlyNumerical() == false)
653 return false;
654
655 string[] moduleVersionParts = moduleVersion.Split('.');
656
657 if (moduleVersionParts.Length != 3)
658 return false;
659
660 if (!IsModuleMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Major]))
661 return false;
662
663 if (!IsModuleNonMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Minor]))
664 return false;
666 if (!IsModuleNonMajorVersionPartValid(moduleVersionParts[(int)VersionParts.Patch]))
667 return false;
668
669 return true;
671
672 static readonly Regex VersionValidator = new Regex(@"^[0123456789.]+$");
673
675 {
676 return VersionValidator.IsMatch(moduleVersion);
677 }
678
679 bool IsModuleNonMajorVersionPartValid(string modulePart)
680 {
681 if (modulePart.Length <= 0)
682 return false;
683
684 if (modulePart.Length > 2)
685 return false;
686
687 return true;
688 }
689
690 bool IsModuleMajorVersionPartValid(string modulePart)
691 {
692 if (modulePart.Length <= 0)
693 return false;
694
695 if (modulePart.StartsWith("0"))
696 return false;
697
698 return true;
699 }
700
701 public static void ExitApplication(string nextExitTarget = "")
702 {
703 Instance._ExitApplication(nextExitTarget);
704 }
705
706 public static bool RequestAuthorizationCode()
707 {
708 return Instance._RequestAuthorizationCode();
709 }
710
711 public static void ChangePlatformServer(PlatformServer newServer)
712 {
713 Instance._ChangePlatformServer(newServer);
714 }
715
716 public static void Ping()
717 {
718 Instance._Ping();
719 }
721 public static bool LoginWithToken()
723 Debug.unityLogger.Log(LogType.Log, TAG, $"Login with token of token {(string.IsNullOrEmpty(PassedLoginToken) ? "<none>" : PassedLoginToken)}");
725 }
726
727 public static bool LoginWithToken(string token)
728 {
729 return Instance._LoginWithToken(token);
730 }
731
732 public static bool Login(LoginData login)
733 {
734 return Instance._Login(login);
735 }
736
737 public static bool Login(string username, string password)
739 return Instance._Login(username, password);
740 }
741
742 public static bool CheckModuleAccess(int targetModuleID = -1)
743 {
744 return Instance._CheckModuleAccess(targetModuleID);
745 }
746
747 public static bool JoinSession(string scenarioID = null, Extension contextExtension = null)
748 {
749 return Instance._JoinSession(scenarioID, contextExtension);
750 }
751
752 public static bool CompleteSession(
753 SessionData currentSessionData,
754 Extension contextExtension = null,
755 Extension resultExtension = null
756 )
757 {
758 return Instance._CompleteSession(currentSessionData, contextExtension, resultExtension);
760
761 public static bool SendSimpleSessionEvent(string action, string targetObject, Extension contextExtension)
762 {
763 return Instance._SendSimpleSessionEvent(action, targetObject, contextExtension);
765
766 public static bool SendSessionEvent(Statement eventStatement)
767 {
768 return Instance._SendSessionEvent(eventStatement);
770
771 public static bool GetCurrentUser()
772 {
773 return GetUser();
774 }
776 public static bool GetUser(int userId = -1)
777 {
778 return Instance._GetUser(userId);
779 }
781 public static bool GetCurrentUserModules()
782 {
783 return GetUserModules();
784 }
786 public static bool GetUserModules(int userId = -1)
787 {
788 return Instance._GetUserModules(userId);
789 }
791 public static bool GetModulesList(string platformName)
792 {
793 return Instance._GetModuleList(platformName);
794 }
796 public static bool GetQuickIDAuthUsers(string serialNumber)
797 {
798 return Instance._GetQuickIDAuthUsers(serialNumber);
799 }
801 public static bool QuickIDLogin(string serialNumber, string username)
802 {
803 return Instance._QuickIDLogin(serialNumber, username);
804 }
805
806 protected void _ChangePlatformServer(PlatformServer newServer)
807 {
808 PlatformTargetServer = newServer;
810 SetupAPI();
811 }
812
813 protected void _Ping()
816 }
817
818 protected bool _LoginWithToken(string token)
820 Debug.unityLogger.Log(LogType.Log, TAG, $"Calling LoginWithToken ({token})");
821 if (token.Length <= 0)
822 {
823 return false;
825
826 Debug.unityLogger.Log(LogType.Log, TAG, $"Logging in with token: {token}");
828
829 return true;
830 }
831
832 protected bool _Login(LoginData login)
833 {
834 Debug.unityLogger.Log(LogType.Log, TAG, "_Login called.");
835 if (apexAPIHandler == null)
836 {
837 Debug.unityLogger.Log(LogType.Log, TAG, "API Handler is null.");
838 OnLoginFailed.Invoke(
840 "There was an error reaching the platform, please contact your administrator."
841 )
842 );
843 return false;
845
846 if (login.Login.Length <= 0)
847 {
848 Debug.unityLogger.Log(LogType.Log, TAG, "[Login] No user name.");
849 OnLoginFailed.Invoke(GenerateFailureResponse("No username or email entered."));
850 return false;
851 }
852
853 if (login.Password.Length <= 0)
855 Debug.unityLogger.Log(LogType.Log, TAG, "[Login] No password.");
856 login.Password = "<empty>";
857 }
858
859 apexAPIHandler.Login(login);
860
861 Debug.unityLogger.Log(LogType.Log, TAG, "Login called.");
862
863 return true;
864 }
865
866 protected bool _Login(string username, string password)
867 {
868 return _Login(new LoginData(username, password));
869 }
870
871 protected FailureResponse GenerateFailureResponse(string message)
872 {
873 FailureResponse failureResponse = new FailureResponse();
874 failureResponse.Error = "true";
875 failureResponse.HttpCode = "400";
876 failureResponse.Message = message;
877
878 return failureResponse;
879 }
881 protected void _ParsePassedData(Dictionary<string, string> arguments)
882 {
883 Debug.unityLogger.Log(LogType.Log, TAG, "Parsing passed data.");
884 if (arguments == null)
885 {
886 Debug.unityLogger.Log(LogType.Log, TAG, "No arguments found for the application.");
887 return;
888 }
889
890 if (arguments.ContainsKey("optional"))
891 optionalParameter = arguments["optional"];
892
893 if (arguments.ContainsKey("returntarget"))
894 CurrentExitTarget = arguments["returntarget"];
895
896 if (arguments.ContainsKey("targettype"))
897 TargetType = arguments["targettype"];
898
899 Debug.unityLogger.Log(LogType.Log, TAG, "Is the token already set?");
900 if (string.IsNullOrEmpty(PassedLoginToken))
901 {
902 Debug.unityLogger.Log(LogType.Log, TAG, "Token is not set, but does the arguments contain a token?");
903 if (arguments.ContainsKey("pixotoken"))
904 {
905 Debug.unityLogger.Log(LogType.Log, TAG, "Token was found in the arguments.");
906 string token = arguments["pixotoken"];
907 Debug.unityLogger.Log(LogType.Log, TAG, $"Found pixotoken {token}.");
908 if (!string.IsNullOrEmpty(token))
909 {
910 PassedLoginToken = string.Copy(token);
911 }
912 }
913 }
915
916 protected bool _CheckModuleAccess(int targetModuleID = -1)
917 {
918 Debug.unityLogger.Log(LogType.Log, TAG, "_CheckModuleAccess called.");
920 if (currentActiveLogin == null)
921 {
922 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot check user's module access with no active login.");
923 return false;
924 }
925
926 if (targetModuleID <= -1)
927 {
928 targetModuleID = moduleID;
930
931 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)}");
933
934 return true;
935 }
936
937 protected bool _JoinSession(string newScenarioID = null, Extension contextExtension = null)
938 {
939 if (currentActiveLogin == null)
940 {
941 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot join session with no active login.");
942 return false;
943 }
944
945 if (userAccessVerified == false)
946 {
947 return false;
948 }
949
950 if (newScenarioID != null)
951 {
952 scenarioID = newScenarioID;
953 }
954
955 if (sessionInProgress == true)
956 {
957 Debug.unityLogger.Log(LogType.Error, TAG,
958 "Session is already in progress."
959 + " The previous session didn't complete or a new session was started during an active session."
960 );
961 }
962
963 currentSessionID = Guid.NewGuid();
965 Statement sessionStatement = new Statement();
966 Agent sessionActor = new Agent();
967 sessionActor.mbox = currentActiveLogin.Email;
968
969 Verb sessionVerb = new Verb();
970 sessionVerb.id = ApexVerbs.JOINED_SESSION;
971 sessionVerb.display = new LanguageMap();
972 sessionVerb.display.Add("en", "Joined Session");
973
974 Activity sessionActivity = new Activity();
975 sessionActivity.id = string.Format("https://pixovr.com/xapi/objects/{0}/{1}", moduleID, scenarioID);
976
977 Context sessionContext = new Context();
978 sessionContext.registration = currentSessionID;
979 sessionContext.revision = moduleVersion;
980 sessionContext.platform = platform;
981
982 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
983
984 sessionStatement.actor = sessionActor;
985 sessionStatement.verb = sessionVerb;
986 sessionStatement.target = sessionActivity;
987 sessionStatement.context = sessionContext;
988
989 JoinSessionData sessionData = new JoinSessionData();
990 sessionData.DeviceId = deviceID;
991 sessionData.IpAddress = clientIP;
992 sessionData.ModuleId = moduleID;
993 sessionData.Uuid = currentSessionID.ToString();
994 sessionData.EventType = ApexEventTypes.PIXOVR_SESSION_JOINED;
995 sessionData.JsonData = sessionStatement;
996
998
999 return true;
1000 }
1001
1002 protected bool _SendSimpleSessionEvent(string verbName, string targetObject, Extension contextExtension)
1003 {
1004 if (userAccessVerified == false)
1005 return false;
1006
1007 if (verbName == null)
1008 return false;
1009
1010 if (verbName.Length == 0)
1011 return false;
1012
1013 Statement sessionStatement = new Statement();
1014 Agent sessionActor = new Agent();
1015 sessionActor.mbox = currentActiveLogin.Email;
1016
1017 Verb sessionVerb = new Verb();
1018 sessionVerb.id = new Uri("https://pixovr.com/xapi/verbs/" + verbName.Replace(' ', '_').ToLower());
1019 sessionVerb.display = new LanguageMap();
1020 sessionVerb.display.Add("en", verbName);
1021
1022 Activity sessionActivity = new Activity();
1023 sessionActivity.id = string.Format(
1024 "https://pixovr.com/xapi/objects/{0}/{1}/{2}",
1025 moduleID,
1026 scenarioID,
1027 targetObject.Replace(' ', '_').ToLower()
1028 );
1029
1030 Context sessionContext = new Context();
1031 sessionContext.registration = currentSessionID;
1032 sessionContext.revision = moduleVersion;
1033 sessionContext.platform = platform;
1034
1035 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
1036
1037 sessionStatement.actor = sessionActor;
1038 sessionStatement.verb = sessionVerb;
1039 sessionStatement.target = sessionActivity;
1040 sessionStatement.context = sessionContext;
1041
1042 SessionEventData sessionEvent = new SessionEventData();
1043 sessionEvent.DeviceId = deviceID;
1044 sessionEvent.ModuleId = ModuleID;
1045 sessionEvent.Uuid = currentSessionID.ToString();
1046 sessionEvent.EventType = ApexEventTypes.PIXOVR_SESSION_EVENT;
1047 sessionEvent.JsonData = sessionStatement;
1048
1051 return true;
1052 }
1053
1054 protected bool _SendSessionEvent(Statement eventStatement)
1055 {
1056 if (userAccessVerified == false)
1057 {
1058 return false;
1059 }
1060
1061 if (currentActiveLogin == null)
1062 {
1063 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot send a session event with no active login.");
1064 return false;
1065 }
1066
1067 if (sessionInProgress == false)
1068 {
1069 Debug.unityLogger.Log(LogType.Error, TAG, "No session in progress to send event for.");
1070 return false;
1071 }
1072
1073 if (eventStatement == null)
1074 {
1075 Debug.unityLogger.Log(LogType.Error, TAG, "No event data to send.");
1076 return false;
1077 }
1078
1079 if (eventStatement.actor != null)
1080 {
1081 Debug.unityLogger.Log(LogType.Warning, TAG, "Actor data should not be filled out.");
1082 }
1083
1084 if (eventStatement.verb == null)
1085 {
1086 Debug.unityLogger.Log(LogType.Error, TAG, "Verb missing from eventStatement.");
1087 return false;
1088 }
1089
1090 if (eventStatement.verb.id == null)
1091 {
1092 Debug.unityLogger.Log(LogType.Error, TAG, "verb.id missing from eventStatement.");
1093 return false;
1094 }
1095
1096 if (eventStatement.target == null)
1097 {
1098 Debug.unityLogger.Log(LogType.Error, TAG, "Object (target) missing from eventStatement.");
1099 return false;
1100 }
1101
1102 eventStatement.actor = new Agent();
1103 eventStatement.actor.mbox = currentActiveLogin.Email;
1104
1105 if (eventStatement.context == null)
1106 {
1107 eventStatement.context = new Context();
1108 }
1109
1110 eventStatement.context.registration = currentSessionID;
1111 eventStatement.context.revision = ModuleVersion;
1112 eventStatement.context.platform = platform;
1113
1114 eventStatement.context.extensions = AppendStandardContextExtension(eventStatement.context.extensions);
1115
1116 SessionEventData sessionEvent = new SessionEventData();
1117 sessionEvent.DeviceId = deviceID;
1118 sessionEvent.ModuleId = ModuleID;
1119 sessionEvent.Uuid = currentSessionID.ToString();
1120 sessionEvent.EventType = ApexEventTypes.PIXOVR_SESSION_EVENT;
1121 sessionEvent.JsonData = eventStatement;
1122
1124
1125 return true;
1126 }
1127
1128 protected bool _CompleteSession(
1129 SessionData currentSessionData,
1130 Extension contextExtension,
1131 Extension resultExtension
1132 )
1133 {
1134 if (userAccessVerified == false)
1135 {
1136 return false;
1137 }
1138
1139 if (currentActiveLogin == null)
1140 {
1141 Debug.unityLogger.Log(LogType.Error, TAG, "Cannot complete session with no active login.");
1142 return false;
1143 }
1144
1145 if (sessionInProgress == false)
1146 {
1147 Debug.unityLogger.Log(LogType.Error, TAG, "No session in progress to complete.");
1148 return false;
1149 }
1150
1151 // Create our actor
1152 Agent sessionActor = new Agent();
1153 sessionActor.mbox = currentActiveLogin.Email;
1154
1155 // Create our verb
1156 Verb sessionVerb = new Verb();
1157 sessionVerb.id = ApexVerbs.COMPLETED_SESSION;
1158 sessionVerb.display = new LanguageMap();
1159 sessionVerb.display.Add("en", "Completed Session");
1160
1161 // Create the session activity
1162 Activity sessionActivity = new Activity();
1163 sessionActivity.id = string.Format("https://pixovr.com/xapi/objects/{0}/{1}", moduleID, scenarioID);
1164
1165 // Create our context
1166 Context sessionContext = new Context();
1167 sessionContext.registration = currentSessionID;
1168 sessionContext.revision = moduleVersion;
1169 sessionContext.platform = platform;
1170
1171 sessionContext.extensions = AppendStandardContextExtension(contextExtension);
1172
1173 // Create our results
1174 Result sessionResult = new Result();
1175 sessionResult.completion = currentSessionData.Complete;
1176 sessionResult.success = currentSessionData.Success;
1177 // Add score to the results
1178 sessionResult.score = new Score();
1179 sessionResult.score.min = currentSessionData.MinimumScore;
1180 sessionResult.score.max = currentSessionData.MaximumScore;
1181 sessionResult.score.raw = currentSessionData.Score;
1182 sessionResult.score.scaled = DetermineScaledScore(
1183 currentSessionData.ScaledScore,
1184 currentSessionData.Score,
1185 currentSessionData.MaximumScore
1186 );
1187 sessionResult.duration = TimeSpan.FromSeconds(currentSessionData.Duration);
1188 if (resultExtension != null)
1189 {
1190 sessionResult.extensions = new Extensions(resultExtension.ToJObject());
1191 }
1192
1193 // Create our statement and add the pieces
1194 Statement sessionStatement = new Statement();
1195 sessionStatement.actor = sessionActor;
1196 sessionStatement.verb = sessionVerb;
1197 sessionStatement.target = sessionActivity;
1198 sessionStatement.context = sessionContext;
1199 sessionStatement.result = sessionResult;
1200
1201 CompleteSessionData sessionData = new CompleteSessionData();
1202 sessionData.DeviceId = deviceID;
1203 sessionData.ModuleId = moduleID;
1204 sessionData.Uuid = currentSessionID.ToString();
1205 sessionData.EventType = ApexEventTypes.PIXOVR_SESSION_COMPLETE;
1206 sessionData.JsonData = sessionStatement;
1207 sessionData.SessionDuration = currentSessionData.Duration;
1208 sessionData.Score = currentSessionData.Score;
1209 sessionData.ScoreMin = currentSessionData.MinimumScore;
1210 sessionData.ScoreMax = currentSessionData.MaximumScore;
1211 sessionData.ScoreScaled = DetermineScaledScore(
1212 currentSessionData.ScaledScore,
1213 currentSessionData.Score,
1214 currentSessionData.MaximumScore
1215 );
1216
1218
1219 return true;
1220 }
1221
1222 protected bool _SendHeartbeat()
1223 {
1224 Debug.unityLogger.Log(LogType.Log, TAG, "Sending heartbeat...");
1225 if (!sessionInProgress)
1226 return false;
1227
1228 if (currentActiveLogin == null)
1229 return false;
1230
1232
1233 return true;
1234 }
1235
1236 protected bool _GetUser(int userId = -1)
1237 {
1238 if (currentActiveLogin == null)
1239 return false;
1240
1241 if (userId < 0)
1242 {
1243 userId = currentActiveLogin.ID;
1244 }
1245
1247 return true;
1248 }
1249
1250 protected bool _GetUserModules(int userId = -1)
1251 {
1252 if (currentActiveLogin == null)
1253 return false;
1254
1255 if (userId < 0)
1256 {
1257 userId = currentActiveLogin.ID;
1258 }
1259
1261 return true;
1262 }
1263
1264 protected bool _GetModuleList(string platformName)
1265 {
1266 if (currentActiveLogin == null)
1267 return false;
1268
1270 return true;
1271 }
1272
1273 protected bool _GetQuickIDAuthUsers(string serialNumber)
1274 {
1275 if (String.IsNullOrEmpty(serialNumber)) return false;
1277 return true;
1278 }
1279
1280
1281 protected bool _QuickIDLogin(string serialNumber, string username)
1282 {
1283 if (String.IsNullOrEmpty(serialNumber) || string.IsNullOrEmpty(username)) return false;
1284 var loginData = new QuickIDLoginData(serialNumber, username);
1285 apexAPIHandler.QuickIDLogin(loginData);
1286 return true;
1287 }
1288
1289 private float DetermineScaledScore(float scaledScore, float score, float maxScore)
1290 {
1291 float determinedScaledScore = scaledScore;
1292
1293 if (scaledScore < Mathf.Epsilon && score >= Mathf.Epsilon)
1294 {
1295 determinedScaledScore = (score / maxScore) * 100f;
1296 }
1297
1298 return determinedScaledScore;
1299 }
1300
1301 private Extensions AppendStandardContextExtension(Extensions currentContextExtensions)
1302 {
1303 return AppendStandardContextExtension(new Extension(currentContextExtensions.ToJObject()));
1304 }
1305
1306 private Extensions AppendStandardContextExtension(Extension currentContextExtension)
1307 {
1308 Extension contextExtension;
1309 if (currentContextExtension != null)
1310 {
1311 contextExtension = currentContextExtension;
1313 else
1314 {
1315 contextExtension = new Extension();
1316 }
1317
1318 contextExtension.Add(ApexExtensionStrings.MODULE_ID, moduleID.ToString());
1319 contextExtension.AddSimple("device_id", deviceID);
1320 contextExtension.AddSimple("device_model", deviceModel);
1321 contextExtension.AddSimple("sdk_version", "unity-" + ApexUtils.SDKVersion);
1322
1323 if (string.IsNullOrEmpty(deviceSerialNumber))
1324 {
1325 contextExtension.AddSimple("device_serial", deviceSerialNumber.ToString());
1326 }
1327
1328 return new Extensions(contextExtension.ToJObject());
1330
1331 protected void OnAPIResponse(ResponseType response, HttpResponseMessage message, object responseData)
1332 {
1333 Debug.unityLogger.Log(LogType.Log, TAG, "On API Response");
1334 bool success = message.IsSuccessStatusCode;
1335 if (responseData is FailureResponse)
1336 {
1337 success = success && (responseData is IFailure) && (!(responseData as FailureResponse).HasErrored());
1338 }
1339
1340 switch (response)
1341 {
1342 case ResponseType.RT_PING:
1343 {
1344 if (success)
1345 {
1346 Debug.unityLogger.Log(LogType.Log, TAG, "Ping successful.");
1347 OnPingSuccess.Invoke(message);
1348 }
1349 else
1350 {
1351 Debug.unityLogger.Log(LogType.Log, TAG, "Ping failed.");
1352 OnPingFailed.Invoke(message);
1353 }
1354 break;
1355 }
1356 case ResponseType.RT_LOGIN:
1357 {
1358 Debug.unityLogger.Log(LogType.Log, TAG, "Calling to handle login.");
1359 HandleLogin(success, responseData);
1360 break;
1361 }
1362 case ResponseType.RT_GET_USER:
1363 {
1364 if (success)
1365 {
1366 OnGetUserSuccess.Invoke(responseData as GetUserResponseContent);
1367 }
1368 else
1369 {
1370 FailureResponse failureData = responseData as FailureResponse;
1371 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get user.\nError: {0}", failureData.Message));
1372 OnGetUserFailed.Invoke(responseData as FailureResponse);
1373 }
1374 break;
1375 }
1376 case ResponseType.RT_GET_USER_MODULES:
1377 {
1378 if (success)
1380 OnGetUserModulesSuccess.Invoke(responseData as GetUserModulesResponse);
1381 }
1382 else
1383 {
1384 FailureResponse failureData = responseData as FailureResponse;
1385 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get user.\nError: {0}", failureData.Message));
1386 OnGetUserFailed.Invoke(responseData as FailureResponse);
1387 }
1388 break;
1389 }
1390 case ResponseType.RT_SESSION_JOINED:
1391 {
1392 if (success)
1393 {
1394 JoinSessionResponse joinSessionResponse = responseData as JoinSessionResponse;
1395 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Session Id is {0}.", joinSessionResponse.SessionId));
1396 heartbeatSessionID = joinSessionResponse.SessionId;
1397 sessionInProgress = true;
1398 OnJoinSessionSuccess.Invoke(message);
1399 }
1400 else
1401 {
1402 FailureResponse failureData = responseData as FailureResponse;
1403 Debug.unityLogger.Log(LogType.Log, TAG,
1404 string.Format("Failed to join session.\nError: {0}", failureData.Message)
1405 );
1406 currentSessionID = Guid.Empty;
1407 sessionInProgress = false;
1408 OnJoinSessionFailed.Invoke(responseData as FailureResponse);
1409 }
1410 break;
1411 }
1412 case ResponseType.RT_SESSION_COMPLETE:
1413 {
1414 if (success)
1415 {
1416 sessionInProgress = false;
1417 currentSessionID = Guid.Empty;
1418 OnCompleteSessionSuccess.Invoke(message);
1419 }
1420 else
1421 {
1422 FailureResponse failureData = responseData as FailureResponse;
1423 Debug.unityLogger.Log(LogType.Log, TAG,
1424 string.Format("Failed to complete session.\nError: {0}", failureData.Message)
1425 );
1426 OnCompleteSessionFailed.Invoke(responseData as FailureResponse);
1427 }
1428 break;
1429 }
1430 case ResponseType.RT_SESSION_EVENT:
1431 {
1432 if (success)
1433 {
1434 Debug.unityLogger.Log(LogType.Log, TAG, "Session event sent.");
1435 OnSendEventSuccess.Invoke(message);
1436 }
1437 else
1438 {
1439 FailureResponse failureData = responseData as FailureResponse;
1440 Debug.unityLogger.Log(LogType.Log, TAG,
1441 string.Format("Failed to send session event.\nError: {0}", failureData.Message)
1442 );
1443 OnSendEventFailed.Invoke(responseData as FailureResponse);
1444 }
1445 break;
1446 }
1447 case ResponseType.RT_GET_USER_ACCESS:
1448 {
1449 if (success)
1450 {
1451 var userAccessResponseContent = responseData as UserAccessResponseContent;
1452 if (userAccessResponseContent.Access)
1453 {
1454 if (userAccessResponseContent.PassingScore.HasValue)
1455 {
1456 currentActiveLogin.MinimumPassingScore = userAccessResponseContent.PassingScore.Value;
1457 }
1458
1459 userAccessVerified = true;
1461 }
1462 else
1463 {
1464 currentActiveLogin = null;
1465 userAccessVerified = false;
1466 OnModuleAccessFailed.Invoke(
1467 new FailureResponse()
1468 {
1469 Error = "True",
1470 HttpCode = "401",
1471 Message = "User does not have access to module",
1472 }
1473 );
1474 }
1475 }
1476 else
1477 {
1478 FailureResponse failureData = responseData as FailureResponse;
1479 Debug.unityLogger.Log(LogType.Log, TAG,
1480 string.Format(
1481 "Failed to get users module access data.\nError: {0}",
1482 failureData.Message
1483 )
1484 );
1485
1486 OnModuleAccessFailed.Invoke(responseData as FailureResponse);
1487 }
1488 break;
1489 }
1490 case ResponseType.RT_GET_MODULES_LIST:
1491 {
1492 if (success)
1493 {
1494 OnGetOrganizationModulesSuccess.Invoke(responseData as List<OrgModule>);
1495 }
1496 else
1497 {
1498 FailureResponse failureData = responseData as FailureResponse;
1499 Debug.unityLogger.Log(LogType.Log, TAG,
1500 string.Format("Failed to get org modules.\nError: {0}", failureData.Message)
1501 );
1502
1503 OnGetOrganizationModulesFailed.Invoke(responseData as FailureResponse);
1504 }
1505
1506 break;
1507 }
1508 case ResponseType.RT_QUICK_ID_AUTH_GET_USERS:
1509 {
1510 if (success)
1511 {
1513 }
1514 else
1515 {
1516 FailureResponse failureData = responseData as FailureResponse;
1517 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to get Quick ID Authentication users.\nError: {0}", failureData.Message));
1518 OnGetQuickIDAuthGetUsersFailed.Invoke(responseData as FailureResponse);
1519 }
1520 break;
1521 }
1522
1523 case ResponseType.RT_QUICK_ID_AUTH_LOGIN:
1524 {
1525 HandleLogin(success, responseData);
1526 if (success)
1527 {
1528 OnQuickIDAuthLoginSuccess.Invoke(responseData as LoginResponseContent);
1529 }
1530 else
1531 {
1532 FailureResponse failureData = responseData as FailureResponse;
1533 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to authenticate with Quick ID Authentication.\nError: {0}", failureData.Message));
1534 OnQuickIDAuthLoginFailed.Invoke(responseData as FailureResponse);
1535 }
1536 break;
1537 }
1538 case ResponseType.RT_GET_USER_METRICS_FOR_ORG:
1539 {
1540 if (success)
1541 {
1542 OnGetUserMetricsForOrgSuccess.Invoke(responseData as UserMetricsResponse);
1543 }
1544 else
1545 {
1546 FailureResponse failureData = responseData as FailureResponse;
1547 Debug.Log(
1548 string.Format("[ApexSystem] Failed to get user metrics for org.\nError: {0}", failureData.Message)
1549 );
1550 OnGetUserMetricsForOrgFailed.Invoke(responseData as FailureResponse);
1551 }
1552 break;
1553 }
1554 case ResponseType.RT_GET_DEVICES_FOR_ORG:
1555 {
1556 if (success)
1557 {
1558 OnGetDevicesForOrgSuccess.Invoke(responseData as OrgDevicesResponse);
1559 }
1560 else
1561 {
1562 FailureResponse failureData = responseData as FailureResponse;
1563 Debug.Log(
1564 string.Format("[ApexSystem] Failed to get devices for org.\nError: {0}", failureData.Message)
1565 );
1566 OnGetDevicesForOrgFailed.Invoke(responseData as FailureResponse);
1567 }
1568 break;
1569 }
1570 case ResponseType.RT_GET_SESSION_HISTORY:
1571 {
1572 if (success)
1573 {
1574 OnGetSessionHistorySuccess.Invoke(responseData as SessionHistoryResponse);
1575 }
1576 else
1577 {
1578 FailureResponse failureData = responseData as FailureResponse;
1579 Debug.Log(
1580 string.Format("[ApexSystem] Failed to get session history.\nError: {0}", failureData.Message)
1581 );
1582 OnGetSessionHistoryFailed.Invoke(responseData as FailureResponse);
1583 }
1584 break;
1585 }
1586 default:
1587 {
1588 break;
1589 }
1590 }
1591
1592 if (OnPlatformResponse != null)
1593 {
1594 OnPlatformResponse.Invoke(response, success, responseData);
1595 }
1596 }
1597
1598 protected void HandleLogin(bool successful, object responseData)
1599 {
1600 Debug.unityLogger.Log(LogType.Log, TAG, "Handling Login");
1601 userAccessVerified = false;
1602
1603 if (successful)
1604 {
1605 currentActiveLogin = responseData as LoginResponseContent;
1606
1607 OnLoginSuccess.Invoke();
1608
1610 {
1612 }
1613 }
1614 else
1615 {
1616 FailureResponse failureData = responseData as FailureResponse;
1617 Debug.unityLogger.Log(LogType.Log, TAG, string.Format("Failed to log in.\nError: {0}", failureData.Message));
1618 OnLoginFailed.Invoke(responseData as FailureResponse);
1619 }
1620 }
1621
1623 {
1624 if (!webSocket.IsConnected())
1625 {
1627 }
1629 }
1630
1631 public static bool GenerateOneTimeLoginForCurrentUser(Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1632 {
1633 return Instance._GenerateOneTimeLoginForCurrentUser(success, failure);
1634 }
1635
1636 public static bool GenerateOneTimeLoginForUser(int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1637 {
1638 return Instance._GenerateOneTimeLoginForUser(userId, success, failure);
1639 }
1640
1641 public static bool GetUserMetricsForCurrentUsersOrg(int page, FilterParams filterParams)
1642 {
1643 if (Instance.currentActiveLogin == null)
1644 return false;
1645 return Instance._GetUserMetricsForCurrentUsersOrg(page, filterParams);
1647
1648 public static bool GetDevicesForOrg(int page, FilterParams filterParams)
1649 {
1650 if (Instance.currentActiveLogin == null)
1651 return false;
1652 return Instance._GetDevicesForOrg(page, filterParams);
1653 }
1654
1655 public static bool GetSesssionHistory(int page, SessionFilters sessionFilters, FilterParams filterParams)
1656 {
1657 if (Instance.currentActiveLogin == null)
1658 return false;
1659 return Instance._GetSessionHistory(page, sessionFilters, filterParams);
1660 }
1661 bool _GenerateOneTimeLoginForUser(int userId, Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1662 {
1663 if (currentActiveLogin == null)
1664 {
1665 Debug.unityLogger.Log(LogType.Error, TAG, "No current user logged in.");
1666 return false;
1667 }
1668
1669 if (userId < 0)
1671 Debug.unityLogger.Log(LogType.Error, TAG, "User id is invalid.");
1672 return false;
1673 }
1674
1676 return true;
1677 }
1678
1679 bool _GenerateOneTimeLoginForCurrentUser(Action<HttpResponseMessage, object> success, Action<HttpResponseMessage, FailureResponse> failure)
1680 {
1681 if (currentActiveLogin == null)
1682 {
1683 Debug.unityLogger.Log(LogType.Error, TAG, "No user logged in to generate code.");
1684 return false;
1685 }
1686
1688 return true;
1690
1691 bool _GetUserMetricsForCurrentUsersOrg(int page, FilterParams filterParams)
1692 {
1693 if (currentActiveLogin == null)
1694 {
1695 Debug.LogError("[ApexSystem] No user logged in to retrieve users.");
1696 return false;
1697 }
1698
1700 return true;
1701 }
1702
1703 bool _GetDevicesForOrg(int page, FilterParams filterParams)
1704 {
1705 if (currentActiveLogin == null)
1706 {
1707 Debug.LogError("[ApexSystem] No user logged in to retrieve org devices.");
1708 return false;
1710
1712 return true;
1713 }
1714
1715 bool _GetSessionHistory(int page, SessionFilters sessionFilters, FilterParams filterParams)
1716 {
1717 if (currentActiveLogin == null)
1718 {
1719 Debug.LogError("[ApexSystem] No user logged in to retrieve session history.");
1720 return false;
1721 }
1722
1723 apexAPIHandler.GetSessionHistory(currentActiveLogin.Token, page, sessionFilters, filterParams);
1724 return true;
1725 }
1726 }
async void SendHeartbeat(string authToken, int sessionId)
async void GetUserMetricsForOrg(string authToken, int orgID, int page, FilterParams filterParams)
async void GetUserModules(string authToken, int userId)
async void QuickIDLogin(QuickIDLoginData login)
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)
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 GetDevicesForOrg(string authToken, int orgID, int page, FilterParams filterParams)
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
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
OnGetSessionHistorySuccessEvent OnGetSessionHistorySuccess
static string APIEndpoint
static string ModuleName
Definition ApexSystem.cs:46
static bool GetDevicesForOrg(int page, FilterParams filterParams)
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
OnGetDevicesForOrgSuccessEvent OnGetDevicesForOrgSuccess
bool _GetSessionHistory(int page, SessionFilters sessionFilters, FilterParams filterParams)
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 OnGetSessionHistoryFailed
OnApexFailureEvent OnSendEventFailed
static bool GetUserMetricsForCurrentUsersOrg(int page, FilterParams filterParams)
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]
static bool GetSesssionHistory(int page, SessionFilters sessionFilters, FilterParams filterParams)
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 OnGetDevicesForOrgFailed
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
bool _GetDevicesForOrg(int page, FilterParams filterParams)
void _ExitApplication(string nextExitApplication)
bool _GetUser(int userId=-1)
OnGetUserSuccessEvent OnGetUserSuccess
OnHttpResponseEvent OnSendEventSuccess
bool _QuickIDLogin(string serialNumber, string username)
bool _GetUserMetricsForCurrentUsersOrg(int page, FilterParams filterParams)
bool _CheckModuleAccess(int targetModuleID=-1)
static bool CompleteSession(SessionData currentSessionData, Extension contextExtension=null, Extension resultExtension=null)
bool IsModuleVersionOnlyNumerical()
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:164
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:20
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)