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