public void Connect(String matchId)
        {
//			URI uri;
//			try {
//				uri = new URI(url);
//			} catch (URISyntaxException e) {
//				e.printStackTrace();
//				// TODO: 7/13/16 AD What to do?
//				return;
//			}
            Dictionary <String, String> extraHeaders = new Dictionary <String, String>();

            // TODO: uncomment
//			extraHeaders.Add("user-agent", System.getProperty("http.agent"));
            // TODO: 7/13/16 AD WebSocket should gather token in true manner
            //        extraHeaders.put("Authorization", "Bearer " + BacktoryAuth.getAccessToken());
            extraHeaders.Add("Authorization-Bearer", BacktoryUser.GetAccessToken());
            extraHeaders.Add("X-Backtory-Connectivity-Id", X_BACKTORY_CONNECTIVITY_ID);
            if (matchId != null)
            {
                extraHeaders.Add("X-Backtory-Realtime-Challenge-Id", matchId);
            }

            InnerStompWebSocketEventHandler innerEventHandler = new InnerStompWebSocketEventHandler(this);

            webSocketClient = new InnerBacktoryStompWebSocket(this, url, extraHeaders, innerEventHandler);

            webSocketClient.Connect();
        }
Example #2
0
        //private static BacktoryResponse<T> RawResponseToBacktoryResponse<T>(IRestResponse<T> response) where T : class, new()
        //{
        //    BacktoryResponse<T> result;
        //    if (response.ErrorException != null || !response.IsSuccessful())
        //    {
        //        if ((int)response.StatusCode == (int)BacktoryHttpStatusCode.Unauthorized)
        //            response = Handle401StatusCode(response);
        //        result = BacktoryResponse<T>.Error((int)response.StatusCode, response.ErrorMessage);
        //    }
        //    else
        //        result = BacktoryResponse<T>.Success((int)response.StatusCode, response.Data);
        //    Debug.Log("Receiving response of: " + typeof(T).Name + " with code: " + result.Code + "\ncause: " + response.ErrorMessage);
        //    Debug.Log(response.ResponseUri);
        //    return result;
        //}

        /// <summary>
        /// A 401 error mostly indicates access-token is expired. (Only exception is login which 401 shows incorrect username/password)
        /// We must refresh the access-token using refresh-token and retry the original request with new access-token
        /// If on refreshing access-token we get another 401, it indicates refresh-token is expired, too
        /// On that case, if current user is guest we must login with stored username-pass and if not we must force the user to login
        /// </summary>
        /// <typeparam name="T">type of response body</typeparam>
        /// <param name="response">raw response containing error 401</param>
        /// <returns></returns>
        private static IRestResponse Handle401StatusCode(IRestResponse response)
        {
            // in response of login request (no access token yet!) return the original response
            if (response.Request.Resource.Contains("login"))
            {
                return(response);
            }

            // In some request like cloudcode's run, 401 might indicate to absence of access-token not the expiration.
            // We detect this by checking access-token nullity and simply just return the response.
            if (BacktoryUser.GetAccessToken() == null)
            {
                return(response);
            }
            // getting new access-token
            var tokenResponse = RestClient.Execute <BacktoryUser.LoginResponse>(BacktoryUser.NewAccessTokenRequest());

            if (tokenResponse.ErrorException != null || !response.IsSuccessful())
            {
                // failed to get new token
                if ((int)tokenResponse.StatusCode == (int)BacktoryHttpStatusCode.Unauthorized)                 // 401
                {
                    // refresh token itself is expired
                    if (BacktoryUser.GetCurrentUser().Guest)
                    {
                        // if guest, first login with stored username/pass and the retry the request
                        // new token is stored and after this we can simply call original request again which uses new token
                        BacktoryUser.Login(BacktoryUser.GetCurrentUser().Username, BacktoryUser.GetGuestPassword());
                    }

                    // normal user must login again
                    // TODO: clean way for forcing user to login. How to keep his/her progress? How to retry original request?
                    else
                    {
                        BacktoryUser.ClearBacktoryStoredData();

                        // On this case return value is not important
                        // TODO: may be changing the response error message
                        BacktoryManager.Instance.GlobalEventListener.OnEvent(BacktorySDKEvent.LogoutEvent());
                    }
                }

                // successfully gotten new token
            }
            return(RestClient.Execute(response.Request));
        }
        private void addClickListeners()
        {
            btnLogin.onClick.AddListener(() => {
                string username = ifUsername.text;
                string password = ifPassword.text;
                BacktoryUser.LoginInBackground(username, password, loginResponse =>
                {
                    if (loginResponse.Successful)
                    {
                        writeLine("logged in!");
                    }
                    else
                    {
                        writeLine("Unable to login=> " + loginResponse.Code + ":" + loginResponse.Message);
                    }
                });
            });

            btnConnect.onClick.AddListener(() => {
                Debug.Log("AccessToken: " + BacktoryUser.GetAccessToken());
                if (BacktoryUser.GetAccessToken() == null)
                {
                    writeLine("login first");
                    return;
                }
                connect();
            });

            btnDisconnect.onClick.AddListener(() => {
                BacktoryResponse <BacktoryVoid> response = backtoryApi.Disconnect();
                if (response.Successful)
                {
                    writeLine("---disconnect successful");
                }
                else
                {
                    writeLine("---disconnect failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnMatchmaking.onClick.AddListener(() => {
                BacktoryResponse <MatchmakingResponse> response = backtoryApi.RequestMatchmaking(matchmakingName, 55, "sample meta data");
                if (response.Successful)
                {
                    lastMatchmakingRequestId = response.Body.RequestId;
                    writeLine("---matchmaking successful. id: " + lastMatchmakingRequestId);
                }
                else
                {
                    writeLine("---matchmaking failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnCancelMM.onClick.AddListener(() => {
                BacktoryResponse <BacktoryVoid> response = backtoryApi.CancelMatchmaking(matchmakingName, lastMatchmakingRequestId);
                if (response.Successful)
                {
                    writeLine("---matchmaking cancelled successful.");
                }
                else
                {
                    writeLine("---matchmaking cancellation failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnChallenge.onClick.AddListener(() => {
                List <String> users = new List <String> ();
                users.Add("5720b016e4b0bf11f90cdee6");  // ali
                users.Add("5720b01be4b0bf11f90cdee7");  // mamad
                users.Add("5720b01ee4b0bf11f90cdee8");  // farib
                BacktoryResponse <ChallengeResponse> response = backtoryApi.RequestChallenge(users, 15, 2);
                if (response.Successful)
                {
                    writeLine("---challenge request successful. challenge id: " + response.Body.ChallengeId);
                }
                else
                {
                    writeLine("---challenge request failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnChallengeList.onClick.AddListener(() => {
                BacktoryResponse <ActiveChallengesListResponse> response = backtoryApi.RequestListOfActiveChallenges();
                if (response.Successful)
                {
                    writeLine("---active challenges list json: " + Backtory.ToJson((response.Body), true));
                }
                else
                {
                    writeLine("---active challenges list failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnAccept.onClick.AddListener(() => {
                BacktoryResponse <BacktoryVoid> response = backtoryApi.AcceptChallenge(lastChallengeInvitationId);
                if (response.Successful)
                {
                    writeLine("---challenge accepted successful.");
                }
                else
                {
                    writeLine("---accepting challenge failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnDecline.onClick.AddListener(() => {
                BacktoryResponse <BacktoryVoid> response = backtoryApi.DeclineChallenge(lastChallengeInvitationId);
                if (response.Successful)
                {
                    writeLine("---challenge declined successful.");
                }
                else
                {
                    writeLine("---declining challenge failed with code: " + response.Code + " and message " + response.Message);
                }
            });

            btnChat.onClick.AddListener(() => SceneManager.LoadScene("ChatScene"));
        }