Beispiel #1
0
    public void StartNewRTSession(string host, int port, string accessToken, Action <bool> onResponse)
    {
        if (_isStartingSession)
        {
            if (onResponse != null)
            {
                onResponse(false);
            }
            return;
        }
        _isStartingSession = true;
        _onResponse        = onResponse;
        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", (double)port)
                                       .AddString("host", host)
                                       .AddString("accessToken", accessToken);
        FindMatchResponse response = new FindMatchResponse(mockedResponse);

        _RT.Configure(response,
                      (peerId) => { OnPlayerConnectedToGame(peerId); },
                      (peerId) => { OnPlayerDisconnectedFromGame(peerId); },
                      (ready) => { OnRTReady(ready); },
                      (packet) => { OnPacketReceived(packet); });
        _RT.Connect();
        _sentCommands.Clear();
        _lastReceivedMessageIds.Clear();
    }
    public void SendDragPosition(List <DrawQueueItem> queue, Vector3 center, Action <LogChallengeEventResponse> response)
    {
        if (_currentChallengeId == null)
        {
            _currentChallengeId = GameSparksManager.Instance.GetCurrentChallengeId();
        }

        List <GSData> _pos             = new List <GSData>();
        Dictionary <string, object> _d = new Dictionary <string, object>();

        foreach (DrawQueueItem _p in queue)
        {
            _d.Add("item", _p.ToJson());

            GSData _data = new GSData(_d);

            _pos.Add(_data);
            _d.Clear();
        }

        GSRequestData data = new GSRequestData();

        data.AddObjectList("positions", _pos);
        data.AddNumber("center_x", center.x);
        data.AddNumber("center_y", center.y);
        data.AddNumber("center_z", center.z);

        new LogChallengeEventRequest()
        .SetChallengeInstanceId(_currentChallengeId)
        .SetEventKey("WordDrag")
        .SetEventAttribute("data", data)
        .Send(response);
    }
    public void SyncProgress()
    {
        if (!IsUserLoggedIn())
        {
            return;
        }

        DateTime now = UnbiasedTime.Instance.Now();

        // when implement void SaveState(), add it here to save state before sync
        CustomFreePrizeManager.Instance.SaveState();
        LevelController.Instance.SaveState();

        PreferencesFactory.SetString("LastProgressSyncDate", now.ToString(CultureInfo.InvariantCulture), false);
        PreferencesFactory.Save();

        string json = JSONPrefs.String();

        GSRequestData parsedJson = new GSRequestData(json);

        new LogEventRequest()
        .SetEventKey("PlayerProgress")
        .SetEventAttribute("data", parsedJson)
        .Send(((response) => {
            if (!response.HasErrors)
            {
                PlayerPrefs.SetString("LastProgressSyncDate", now.ToString(CultureInfo.InvariantCulture));
                PlayerPrefs.Save();
            }
        }));
    }
Beispiel #4
0
        public void StartNewRTSession(RTSessionInfo _info)
        {
            Debug.Log("GSM| Creating New RT Session Instance...");
            sessionInfo       = _info;
            gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); // Adds the RT script to the game
                                                                                    // In order to create a new RT game we need a 'FindMatchResponse' //
                                                                                    // This would usually come from the server directly after a successful MatchmakingRequest //
                                                                                    // However, in our case, we want the game to be created only when the first player decides using a button //
                                                                                    // therefore, the details from the response is passed in from the gameInfo and a mock-up of a FindMatchResponse //
                                                                                    // is passed in. //
            GSRequestData mockedResponse = new GSRequestData()
                                           .AddNumber("port", (double)_info.GetPortID())
                                           .AddString("host", _info.GetHostURL())
                                           .AddString("accessToken", _info.GetAccessToken()); // construct a dataset from the game-details

            FindMatchResponse response = new FindMatchResponse(mockedResponse);               // create a match-response from that data and pass it into the game-config

            // So in the game-config method we pass in the response which gives the instance its connection settings //
            // In this example, I use a lambda expression to pass in actions for
            // OnPlayerConnect, OnPlayerDisconnect, OnReady and OnPacket actions //
            // These methods are self-explanatory, but the important one is the OnPacket Method //
            // this gets called when a packet is received //

            gameSparksRTUnity.Configure(response,
                                        (peerId) => { OnPlayerConnectedToGame(peerId); },
                                        (peerId) => { OnPlayerDisconnected(peerId); },
                                        (ready) => { OnRTReady(ready); },
                                        (packet) => { OnPacketReceived(packet); });
            gameSparksRTUnity.Connect(); // when the config is set, connect the game
        }
Beispiel #5
0
        public void StartNewRtSession(RTSessionInfo rtSessionInfo)
        {
            Debug.Log("Creating New RT Session Instance");
            RtSessionInfo     = rtSessionInfo;
            GameSparksRtUnity = gameObject.AddComponent <GameSparksRTUnity>();


            GSRequestData requestData = new GSRequestData()
                                        .AddNumber("port", (double)rtSessionInfo.PortId)
                                        .AddString("host", rtSessionInfo.HostUrl)
                                        .AddString("accessToken", rtSessionInfo.AccessToken);

            Debug.Log((double)rtSessionInfo.PortId);
            Debug.Log(rtSessionInfo.HostUrl);
            Debug.Log(rtSessionInfo.AccessToken);

            FindMatchResponse findMatchResponse = new FindMatchResponse(requestData);

            GameSparksRtUnity.Configure(findMatchResponse,
                                        (peerId) => { OnPlayerConnected(peerId); },
                                        (peerId) => { OnPlayerDisconnected(peerId); },
                                        (ready) => { OnRtReady(ready); },
                                        (packet) => { OnPacketReceived(packet); });
            GameSparksRtUnity.Connect();
        }
    void MatchFound(MatchFoundMessage message)
    {
        session_info = new RTSessionInfo(message);
        ManagersController.Message(Message.Create(this, MessageData.EVENT_SET_ONLINE_PLAYERS, session_info.players));

        #region Create Session

        session = this.gameObject.GetComponent <GameSparksRTUnity> ();

        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", session_info.PortID)
                                       .AddString("host", session_info.HostURL)
                                       .AddString("accessToken", session_info.AccessToken);
        FindMatchResponse response = new FindMatchResponse(mockedResponse);

        session.Configure(
            response,
            peerID => OnPlayerConnected(peerID),
            peerID => OnPlayerDisconnected(peerID),
            ready => OnRTReady(ready),
            packet => OnPacketRecieved(packet)
            );

        session.Connect();

        #endregion
    }
        //Starts the game session
        public void StartNewRTSession(RTSessionInfo _info)
        {
            //if the settings arent null
            if (gameSparksRTUnity == null)
            {
                Debug.Log("GSM| Creating New RT Session Instance...");
                sessionInfo       = _info;                                              //player/session information
                gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); //add the RT script to the manager
                GSRequestData mockedResponse = new GSRequestData();                     //create a new request
                mockedResponse.AddNumber("port", (double)_info.GetPortID());            //gets the port id
                mockedResponse.AddString("host", _info.GetHostURL());                   //gets host server
                mockedResponse.AddString("accessToken", _info.GetAccessToken());        // construct a dataset from the game-details
                FindMatchResponse response = new FindMatchResponse(mockedResponse);     //create a mock response for match

                //configures the game
                gameSparksRTUnity.Configure(response,
                                            (peerId) => { OnPlayerConnectedToGame(peerId); },
                                            (peerId) => { OnPlayerDisconnected(peerId); },
                                            (ready) => { OnRTReady(ready); },
                                            (packet) => { OnPacketReceived(packet); });
                gameSparksRTUnity.Connect(); // when the config is set, connect the game
            }
            else
            {
                Debug.LogError("Session Already Started");
            }
        }
        /// <summary>
        /// Initializes and starts a new real time session for users
        /// </summary>
        /// <param name="_info">The session information for this game</param>
        public void StartNewRTSession(RTSessionInfo _info)
        {
            Debug.Log("GSM| Creating new RT Session instance...");
            m_SessionInfo       = _info;
            m_GameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>(); //Adds the RT script to the game
            //In order to create a new RT game we need a 'FindMatchResponse'
            //This would usually come from the server directly after a successful MatchmakingRequest
            //However, in our case, we want the game to be create only when all the players ready up
            //Therefore, the details from the response is passed in from the gameInfo and a mock-up of a FindMatchReponse is passed in
            GSRequestData mockedReponse = new GSRequestData()
                                          .AddNumber("port", (double)_info.GetPortID())
                                          .AddString("host", _info.GetHostURL())
                                          .AddString("accessToken", _info.GetAccessToken()); //Construct a dataset from the game-details

            FindMatchResponse response = new FindMatchResponse(mockedReponse);               //Create a match-response from that data and pass it into the game-configuration

            //So in the game-configuration method we pass in the response which gives the Instance its connection settings
            //In this example, a lambda expression is used to pass in actions for
            //OnPlayerConnect, OnPlayerDisconnect, OnReady, and OnPacket
            //The methods do exactly what they are named. For example, OnPacket gets called when a packet is received

            m_GameSparksRTUnity.Configure(response,
                                          (peerId) => { OnPlayerConnectedToGame(peerId); },
                                          (peerId) => { OnPlayerDisconnected(peerId); },
                                          (ready) => { OnRTReady(ready); },
                                          (packet) => { OnPacketReceived(packet); });
            m_GameSparksRTUnity.Connect(); //When the configuration is set, connect the game
        }
Beispiel #9
0
    void SaveLog()
    {
        if (stringBuilder.Length == 0)
        {
            return;
        }

        GSRequestData logData = new GSRequestData();

        logData.AddString("key", "InAppPurchase");
        logData.AddString("message", "User purchase in-app");

        GSData _d = new GSData(new Dictionary <string, object>()
        {
            { "purchase", stringBuilder },
        });

        logData.AddObject("data", _d);

        GameSparksManager.Instance.Log(logData);

        string purchaseLog = PreferencesFactory.GetString("PurchaseLog", "");

        purchaseLog = string.Format("{0}\n-----------\n{1}", purchaseLog, stringBuilder);

        PreferencesFactory.SetString("PurchaseLog", purchaseLog);

        stringBuilder.Length = 0;
    }
    public bool PasswordRecoveryRequest(string email)
    {
        var request = new GSRequestData()
                      .AddString("action", "passwordRecoveryRequest")
                      .AddString("email", email);

        return(Authentication("", "", request));
    }
    public bool PasswordReset(string newPassword, string token)
    {
        var request = new GSRequestData()
                      .AddString("action", "resetPassword")
                      .AddString("password", newPassword)
                      .AddString("token", token);

        return(Authentication("", "", request));
    }
Beispiel #12
0
    private void UploadAudio(string filename, Byte[] data)
    {
        GSRequestData gsdata = new GSRequestData().AddString("Quote", recordObject.name);

        new GetUploadUrlRequest().SetUploadData(gsdata).Send((response) =>
        {
            //Start coroutine and pass in the upload url
            StartCoroutine(UploadAFile(response.Url, filename, data));
        });
    }
Beispiel #13
0
    public void ForgotPassAction(GameObject GO, Action callback)
    {
        var mainTransform = GO.transform;
        var email         = mainTransform.Find("EmailField").GetComponent <InputField> ();

        var emailString = email.text;

        if (string.IsNullOrEmpty(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailEmptyError"), "CLOSE");
            return;
        }
        if (!IsMailValid(emailString))
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.EmailNotValidError"), "CLOSE");
            return;
        }

        if (!Reachability.Instance.IsReachable())
        {
            ShowInfoDialogWithText(LocaliseText.Get("Account.NoConnection"), "CLOSE");
            return;
        }

        if (!GS.Available)
        {
            GS.Reconnect();
        }

        GSRequestData d = new GSRequestData();

        d.Add("email", emailString);
        d.Add("action", "passwordRecoveryRequest");

        Loading.Instance.Show();

        new AuthenticationRequest()
        .SetUserName("")
        .SetPassword("")
        .SetScriptData(d)
        .Send(((response) => {
            Loading.Instance.Hide();

            if (response.HasErrors)
            {
                ShowInfoDialogWithText(LocaliseText.Get("Account.ForgotPassEmailSuccess"), "CLOSE");

                if (callback != null)
                {
                    callback();
                }
            }
        }));
    }
Beispiel #14
0
        /// <summary> Create a new match making request, hosting a match based upon the dropdown menu option </summary>
        private void HostRoom()
        {
            m_hosting = true;
            QuickConnect.m_StaticQuickStart = true; //Not technically true, but prevents QuickConnect from firing upon scene load
            //Gather data for hosting the match
            string matchShortCode = m_MatchShortCodes[m_HostSelectionDropDown.GetComponent <Dropdown>().value];

            m_cleanRoomName = m_RoomNameInputField.GetComponentsInChildren <Text>()[1].text;
            GSRequestData matchData = new GSRequestData();

            matchData.AddString("m_cleanRoomName", m_cleanRoomName);

            //Get max player count
            new LogEventRequest()
            .SetEventKey("GetFoundMatchInfo")
            .SetEventAttribute("MatchShortCode", matchShortCode)
            .Send((_nameResponse) =>
            {
                //Since these calls are asynchronous, call host from inside here
                var matchInfo         = JsonUtility.FromJson <JSONFoundMatchInfoConverter>(_nameResponse.ScriptData.JSON);
                string maxPlayerCount = matchInfo.m_MaxPlayerCount.ToString();
                matchData.AddString("maxPlayerCount", maxPlayerCount);

                //Start hosting the match
                new MatchmakingRequest()
                .SetMatchShortCode(matchShortCode)
                .SetSkill(0)
                .SetMatchData(matchData)
                .Send((_matchMakingResponse) =>
                {
                    if (_matchMakingResponse.HasErrors)
                    {
                        Debug.LogError("GSM| Matchmaking Error\n" + _matchMakingResponse.Errors.JSON);
                        m_HostErrorText.SetActive(true);
                        m_HostErrorText.GetComponent <Text>().text = "Error attempting to host match: \"" + _matchMakingResponse.Errors.JSON + "\"";
                        DisplayPanel(PanelSelection.HostMenu);
                    }
                    else         //Host was successful - update lobby screen
                    {
                        //Add player count and match name to lobby screen
                        m_PlayerCountText.GetComponent <Text>().text = "1/" + matchInfo.m_MaxPlayerCount.ToString();
                        m_MatchNameText.GetComponent <Text>().text   = matchShortCode + ": " + m_cleanRoomName;

                        //Add player name to the player list in the lobby screen
                        m_PlayerListText.GetComponent <Text>().text = m_UsernameInput.GetComponentsInChildren <Text>()[1].text; //Display the users in the room
                        m_ChosenMatch.shortCode = matchShortCode;                                                               //Update matchShortCode in case "host" disconnects
                        GameSparksManager.Instance().SetMatchShortCode(m_ChosenMatch.shortCode);
                    }
                });
            });
        }
Beispiel #15
0
    public static void RegisterPlayerBttn(string displayName, string password,
                                          string email, string fname, string lname, int age,
                                          string gender, string school, string major, string schoolYear, Text textError,
                                          Text emailError, GameObject panel, GameObject start,
                                          GameObject goBack, Text succefullReg)
    {
        GSRequestData sd = new GSRequestData().
                           AddString("displayName", displayName).
                           AddString("email", email).
                           AddString("userName", displayName);

        new GameSparks.Api.Requests.RegistrationRequest()
        .SetDisplayName(displayName)
        .SetUserName(displayName)
        .SetPassword(password)
        .SetScriptData(sd)
        .Send((response) => {
            if (!response.HasErrors)
            {
                Debug.Log("Player Registered \n User Name: " + response.DisplayName);

                SavePlayerData.SaveData(email, fname, lname, age, gender,
                                        school, major, schoolYear);

                stopMusic = true;

                /* after all is checked a ConfirmationRegistration form is displayed*/
                RegistrationConfirmation.Confirmation(panel, start, goBack, succefullReg);
                textError.text = " ";

                SaveLevel.saveLevel();
            }
            else
            {
                /**it handles when username is not unique**/

                if (response.Errors.JSON.Contains("Email"))
                {
                    emailError.text  = "Email has been taken";
                    emailError.color = Color.red;
                }
                else
                {
                    textError.text  = "Username has been taken";
                    textError.color = Color.red;
                }
            }
        });
    }
Beispiel #16
0
    private void ResetPasswordCanvasContinueBtn()
    {
        if (Register.isSoundPlaying)
        {
            audioSource.Play();
        }
        string token       = resetPasswordCanvas_token.text;
        string newPassword = resetPasswordCanvas_newPassword.text;

        if (token == "")
        {
            ShowToast.MyShowToastMethod("Please Enter Token!");
            return;
        }
        if (newPassword == "")
        {
            ShowToast.MyShowToastMethod("Please Enter New Password!");
            return;
        }
        GSRequestData gSRequestData = new GSRequestData();

        gSRequestData.AddString("action", "resetPassword");
        gSRequestData.AddString("token", token);
        gSRequestData.AddString("password", newPassword);
        new GameSparks.Api.Requests.AuthenticationRequest().SetUserName("").SetPassword("").SetScriptData(gSRequestData).Send((response) =>
        {
            Register.userId = response.UserId;

            if (response.Errors.GetString("action") == "complete")
            {
                ShowToast.MyShowToastMethod("Password Changed Successfully");
                Debug.Log("Password Changed Successfully");
                forgetPassword_canvas.enabled = false;
                resetPassword_canvas.enabled  = false;
                createOne_btn.enabled         = true;
                login_btn.interactable        = true;
                playAsGuest_btn.interactable  = true;
            }
            else
            {
                ShowToast.MyShowToastMethod("Error Resetting Password!");
                Debug.Log(response.Errors.GetString("action"));
                forgetPassword_canvas.enabled = false;
                login_btn.interactable        = true;
                createOne_btn.interactable    = true;
                playAsGuest_btn.interactable  = true;
            }
        });
    }
Beispiel #17
0
    public static void CreateMatchByName(string[] playersIDs)
    {
        GSRequestData data = new GSRequestData();

        data.Add("PlayersIDs", playersIDs);

        new LogEventRequest()
        .SetEventKey("CREATE_MATCH")
        .SetEventAttribute("Players", data)
        .Send((response) =>
        {
            if (response.HasErrors)
            {
                Debug.LogError("Error to create match: " + response.Errors);
            }
        });
    }
    public void SendFoundWord(string word, float time, Action <LogChallengeEventResponse> response)
    {
        if (_currentChallengeId == null)
        {
            _currentChallengeId = GameSparksManager.Instance.GetCurrentChallengeId();
        }

        GSRequestData data = new GSRequestData();

        data.AddString("word", word);
        data.AddNumber("time", time);

        new LogChallengeEventRequest()
        .SetChallengeInstanceId(_currentChallengeId)
        .SetEventKey("WordFound")
        .SetEventAttribute("data", data)
        .Send(response);
    }
Beispiel #19
0
        /// <summary>
        /// Connects a user to a game using GameSparks auto-matchmaking ability based upon the room name that the programmer specified in the Unity Editor
        /// for the <see cref="QuickConnect"/> script if they are using <see cref="QuickConnect"/>. Otherwise is moves onto the next step of manually connecting players
        /// </summary>
        private void Connect()
        {
            if (m_QuickConnect && !m_SwitchedToManualMatchMaking)
            {
                GSRequestData matchData = new GSRequestData();
                m_cleanRoomName = Regex.Replace(m_RoomName, @"\s+", "");
                matchData.AddString("m_cleanRoomName", m_cleanRoomName);
                new MatchmakingRequest()
                .SetMatchShortCode("QS") //Quick Start short code
                .SetSkill(1)
                .SetMatchData(matchData)
                .SetMatchGroup(m_cleanRoomName)
                .Send((_matchMakingResponse) =>
                {
                    if (_matchMakingResponse.HasErrors)
                    {
                        Debug.LogError("GSM| Matchmaking Error\n" + _matchMakingResponse.Errors.JSON);
                        m_HostErrorText.SetActive(true);
                        m_HostErrorText.GetComponent <Text>().text = "Error attempting to host match: \"" + _matchMakingResponse.Errors.JSON + "\"";
                        DisplayPanel(PanelSelection.HostMenu);
                    }
                    else //Host was successful - update lobby screen
                    {
                        DisplayPanel(PanelSelection.LobbyScreen);

                        //Add player count and match name to lobby screen
                        m_PlayerCountText.GetComponent <Text>().text = "1/20";
                        m_MatchNameText.GetComponent <Text>().text   = "QS" + ": " + m_RoomName;

                        //Add player name to the player list in the lobby screen
                        m_PlayerListText.GetComponent <Text>().text = m_UsernameInput.GetComponentsInChildren <Text>()[1].text; //Display the users in the room
                        m_ChosenMatch.shortCode = "QS";                                                                         //Update matchShortCode in case "host" disconnects
                        GameSparksManager.Instance().SetMatchShortCode(m_ChosenMatch.shortCode);
                    }
                });
            }
            else
            {
                //Switch to the connection menu
                DisplayPanel(PanelSelection.ConnectionMenu);
                GetMatchShortCodes();
            }
        }
Beispiel #20
0
    private void ForgetPasswordContinueBtn()
    {
        if (Register.isSoundPlaying)
        {
            audioSource.Play();
        }

        string userName = forgetPasswordUserName.text;
        string email    = forgetPasswordEmail.text;

        if (userName == "")
        {
            ShowToast.MyShowToastMethod("Please Enter User Name!");
            return;
        }
        if (email == "")
        {
            ShowToast.MyShowToastMethod("Please Enter Email Address!");
            return;
        }
        GSRequestData gSRequestData = new GSRequestData();

        gSRequestData.AddString("action", "passwordRecoveryRequest");
        gSRequestData.AddString("email", email);
        new GameSparks.Api.Requests.AuthenticationRequest().SetUserName(userName).SetPassword("").SetScriptData(gSRequestData).Send((response) =>
        {
            Register.userId = response.UserId;

            if (response.Errors.GetString("action") == "complete")
            {
                ShowToast.MyShowToastMethod("Request Sent! Check You Email");
                Debug.Log("Request Sent! Check You Email");
                forgetPassword.enabled       = false;
                resetPassword_canvas.enabled = true;
            }
            else
            {
                ShowToast.MyShowToastMethod("Error Sending Requset!");
                Debug.Log("Error Sending Requset! " + response.Errors.GetString("action"));
            }
        });
    }
Beispiel #21
0
    public void retrievePassword()
    {
        GSRequestData scriptData = new GSRequestData().
                                   AddString("action", "passwordRecoveryRequest").
                                   AddString("email", ForgetPasswordController.emailstring);



        new GameSparks.Api.Requests.AuthenticationRequest().
        SetUserName("").
        SetPassword("").
        SetScriptData(scriptData).
        Send((response) => {
            if (response.Errors.JSON.Contains("complete"))
            {
                Debug.Log("Password retrieval request sent");

                //SHOW NEXT PANEL
                panel.SetActive(true);
                Innerpanel.SetActive(true);
                enterToken.text  = "Please enter token received:";
                enterToken.color = Color.white;
                token.SetActive(true);
                enterConfpass.text  = "Confirm new password:"******" ";
            }
            else
            {
                AudioTrack.PlayOneShot(clip, 1.9F);
                print("Effect no.2 done well ");
                emailWarning.text  = "Email is invalid. Please try again";
                emailWarning.color = Color.red;

                Debug.Log("Password Reset Error" + response.Errors.JSON.ToString());
            }
        });
    }
    public void SyncLevels()
    {
        if (!IsUserLoggedIn())
        {
            return;
        }

        JSONArray levels   = new JSONArray();
        int       maxLevel = 1;

        foreach (Level level in GameManager.Instance.Levels.Items)
        {
            if (level.IsUnlocked && level.TimeBest > 0.0f)
            {
                JSONObject l = new JSONObject();
                l.Add("level", new JSONValue(level.Number));
                l.Add("time", new JSONValue(level.TimeBest));

                levels.Add(l);

                maxLevel = level.Number;
            }
        }

        JSONObject d = new JSONObject();

        d.Add("levels", levels);
        d.Add("max", maxLevel);

        string json = d.ToString();

        GSRequestData parsedJson = new GSRequestData(json);

        new LogEventRequest()
        .SetEventKey("UserPlayedLevels")
        .SetEventAttribute("levels", parsedJson)
        .Send(((response) => {
            if (!response.HasErrors)
            {
            }
        }));
    }
    public void Log(GSRequestData json)
    {
        if (!GameSparksManager.IsTokenAvailable())
        {
            GameSparksManager.Instance.AnonymousLogin();
        }

        json.AddString("userId", UserID());
        json.AddDate("user_date", UnbiasedTime.Instance.Now());
        json.AddDate("utc_date", UnbiasedTime.Instance.UTCNow());

        new LogEventRequest()
        .SetEventKey("AppLog")
        .SetEventAttribute("data", json)
        .Send(((response) => {
            if (!response.HasErrors)
            {
            }
        }));
    }
Beispiel #24
0
    public void StartNewRTSession(RTSessionInfo _info)
    {
        Debug.Log("GSM| Creating New RT Session Instance...");
        sessionInfo       = _info;
        gameSparksRTUnity = this.gameObject.AddComponent <GameSparksRTUnity>();

        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", (double)_info.GetPortID())
                                       .AddString("host", _info.GetHostURL())
                                       .AddString("accessToken", _info.GetAccessToken());

        FindMatchResponse response = new FindMatchResponse(mockedResponse);

        gameSparksRTUnity.Configure(response,
                                    (peerId) => { OnPlayerConnectedToGame(peerId); },
                                    (peerId) => { OnPlayerDisconnected(peerId); },
                                    (ready) => { OnRTReady(ready); },
                                    (packet) => { OnPacketReceived(packet); });
        gameSparksRTUnity.Connect();
    }
Beispiel #25
0
    public void StartNewRealTimeSession(RTSessionInfo sessionInfo)
    {
        m_rtSessionInfo   = sessionInfo;
        gameSparksRTUnity = gameObject.AddComponent <GameSparksRTUnity>();

        GSRequestData mockedResponse = new GSRequestData()
                                       .AddNumber("port", (double)sessionInfo.GetPortId())
                                       .AddString("host", sessionInfo.GetHostUrl())
                                       .AddString("accessToken", sessionInfo.GetAccessToken());

        FindMatchResponse response = new FindMatchResponse(mockedResponse);


        gameSparksRTUnity.Configure(response,
                                    OnPlayerConnect,
                                    OnPlayerDisconnect,
                                    OnReady,
                                    OnPacket);

        gameSparksRTUnity.Connect();
    }
Beispiel #26
0
    public void resetPassword()
    {
        GSRequestData scriptData = new GSRequestData().
                                   AddString("action", "resetPassword").
                                   AddString("token", stringToken).
                                   AddString("password", stringPassword);



        new GameSparks.Api.Requests.AuthenticationRequest().
        SetUserName("").
        SetPassword("").
        SetScriptData(scriptData).
        Send((response) => {
            if (response.Errors.JSON.Contains("complete"))
            {
                Debug.Log("Password reset request sent");

                //SHOW NEXT PANEL
                notificationPanel.SetActive(true);
                notification.text  = "Password has been successfully reset";
                notification.color = Color.white;
                goBackToLogin.SetActive(true);
            }
            else
            {
                print("Invalid credentials");

                AudioTrack.PlayOneShot(clip, 1.9F);
                print("Effect no.2 done well ");

                //error message shown
                errorMessage.text  = "WRONG INFORMATION ENTERED";
                errorMessage.color = Color.red;

                Debug.Log("Password Reset Error" + response.Errors.JSON.ToString());
            }
        });
    }
    public void retrievePassword()
    {
        GSRequestData sd = new GSRequestData().
                           AddString("action", "passwordRecoveryRequest").
                           AddString("email", "*****@*****.**");


        new GameSparks.Api.Requests.AuthenticationRequest().
        SetUserName("").
        SetPassword("").
        SetScriptData(sd).
        Send((response) => {
            if (!response.HasErrors)
            {
                Debug.Log("Password retrieval request sent");
            }
            else
            {
                Debug.Log("Password Reset Error" + response.Errors.JSON.ToString());
            }
        });
    }
Beispiel #28
0
    //void PlayfabLoginCallback(LoginResult result)
    //{
    //    Debug.Log("YESSSSSS");
    //}
    //void PlayfabLoginCallbackError(PlayFabError error)
    //{
    //    Debug.LogError(error.GenerateErrorReport());
    //}

    public void onRegisterClick()
    {
        if ((usernameInputreg.text != ""))
        {
            Setting.waitingPanel.Show("در حال ثبت نام");

            GSRequestData sd = new GSRequestData().AddNumber(Setting.sexKey, sexDropDown.value).AddNumber(Setting.ageKey, ageDropDown.value);
            new RegistrationRequest().SetUserName(SystemInfo.deviceUniqueIdentifier + testPre).SetPassword(SystemInfo.deviceUniqueIdentifier).SetDisplayName(usernameInputreg.text).SetScriptData(sd).Send((RegistrationResponse response) =>
            {
                Setting.waitingPanel.Hide();

                if (response.HasErrors)
                {
                    try
                    {
                        if (response.Errors.BaseData["USERNAME"].ToString() == "TAKEN")
                        {
                            DoAfterRegister();
                        }
                        else
                        {
                            Setting.MessegeBox.SetMessege("خطا در ایجاد پروفایل کاربری");
                            Debug.LogError(response.Errors.BaseData["DETAILS"].ToString());
                        }
                    }
                    catch { }
                }
                else
                {
                    DoAfterRegister();
                }
            });
        }
        else if ((usernameInputreg.text == ""))
        {
            Setting.MessegeBox.SetMessege("لطفا نام کاربری خود را وارد کنید.");
        }
    }
    public void CreateChallengeWithUser(string userId, bool isRematch)
    {
        _isRematch = isRematch;
        var usersToChallenge = new List <string> {
            userId
        };

        var data = new GSRequestData();

        new CreateChallengeRequest()
        .SetChallengeShortCode(Constants.ChallengeShortCode)
        .SetMaxPlayers(2)
        .SetScriptData(data)
        .SetExpiryTime(DateTime.UtcNow.AddMinutes(10))
        .SetEndTime(DateTime.UtcNow.AddHours(24))
        .SetUsersToChallenge(usersToChallenge)
        .Send((response) =>
        {
            if (!response.HasErrors)
            {
            }
        });
    }
Beispiel #30
0
    public void FindPlayers()
    {
        if (!GS.Authenticated)
        {
            print("Not logged in!");
            return;
        }
        Debug.Log("GSM| Attempting Matchmaking...");
        ObliusGameManager.instance.matchFailed = false;
        GSRequestData data = new GSRequestData();

        data.Add("server", PhotonNetwork.CloudRegion.ToString());
        new GameSparks.Api.Requests.MatchmakingRequest()
        .SetMatchShortCode("normal")
        .SetSkill(0)
        .Send((response) =>
        {
            if (response.HasErrors)
            {
                Debug.LogError("GSM| MatchMaking Error \n" + response.Errors.JSON);
            }
        });
    }