コード例 #1
0
    public static void LoginAsGuestInBackground(Action <BacktoryResponse <LoginResponse> > callback)
    {
        // Simplifying this by removing "BacktoryUser" type parameter leads to error though compiler suggests, but why?!
        Backtory.RestClient.ExecuteAsync <BacktoryUser>(GuestRegisterRequest(), response =>
        {
            // **this part will be called on background thread! (Since we're using restsharp async method)**

            // if guest register failed don't proceed to login
            if (!response.IsSuccessful())
            {
                Backtory.Dispatch(() => BacktoryResponse <LoginResponse> .Unknown(response.ErrorMessage));
                return;
            }

            var guest         = response.Data;
            var loginResponse = Backtory.Execute <LoginResponse>(LoginRequest(guest.Username, guest.Password));

            if (loginResponse.Successful)
            {
                DispatchSaveCurrentUser(guest);
                DispatchSaveGuestPassword(guest.Password);
                DispatchSaveLoginInfo(loginResponse.Body);
            }

            Backtory.Dispatch(() => callback(loginResponse));
        });
    }
        private static IRestRequest GuestRegisterRequest()
        {
            var request = Backtory.RestRequest("auth/guest-users", Method.POST);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            return(request);
        }
 // Message Processing Part ---------------------------------------------------------------------
 internal void ProcessMessage(string message)
 {
     if ((message != null) && (message.Length != 0))
     {
         try {
             JSONNode jsonNode = JSONNode.Parse(message);
             string   clazz    = (string)jsonNode ["_type"];
             if (clazz != null)
             {
                 string clientRequestId = (string)jsonNode ["clientRequestId"];
                 if (clientRequestId != null)
                 {
                     sendResponseToMainThread(message, clazz, clientRequestId);
                 }
                 else
                 {
                     Debug.Log("************");
                     Backtory.Dispatch(() => backtoryApi.NotifyMessageReceived(message, clazz));
                 }
             }
             else
             {
                 Debug.Log(TAG + "_type field not found in message");
             }
         } catch (Exception e) {
             Debug.Log(TAG + e.Data);
         }
     }
     else
     {
         // TODO
     }
 }
コード例 #4
0
        public void OnMatchEndedMessage(MatchEndedMessage endedMessage)
        {
            writeLine("-+-match ended. Winners json: " + Backtory.ToJson((endedMessage.Winners), true));
            int previousLevel = PlayerPrefs.GetInt("MainLevel");

            Application.LoadLevel(previousLevel);
        }
        // Alireza: inja type ro as string misze ke hatman ye child az BacktoryMatchMessage e.
        override internal void NotifyMessageReceived(string jsonMessage, string _type)
        {
            if (_type != null)
            {
                Type clazz = BacktoryRealtimeMessageFactory.GetType(_type);
                // TODO uncomment, if it is important???????
//				JsonElement mJson =  new JsonParser().parse(jsonMessage.toJSONstring());
//				if (mJson == null) {
//					// TODO: 7/18/16 AD What to do?
//				}
                var message = (BacktoryMatchMessage)Backtory.FromJson(jsonMessage, clazz);                  //(new Gson()).fromJson(mJson, clazz);
                // TODO: 7/18/16 AD Use better mechanism for checking requestId:
                if (connectorClient.CheckRequestId(jsonMessage, _type))
                {
                    // TODO IMPORTANT : move this action on main thread
                    if (BacktoryRealtimeMessageFactory.GetTypeCategory(_type).Equals(BacktoryRealtimeMessageFactory.TypeCategory.Challenge) && MatchListener != null)
                    {
                        message.OnMessageReceived(MatchListener);
                    }
                    else if (BacktoryRealtimeMessageFactory.GetTypeCategory(_type).Equals(BacktoryRealtimeMessageFactory.TypeCategory.General) && connectorClient.sdkListener != null)
                    {
                        message.OnMessageReceived(connectorClient.sdkListener);
                    }
                    else
                    {
                        // TODO: 7/20/16 AD What to do?
                    }
                }
            }
            else
            {
                // TODO: 7/23/16 AD What to do?
//				connectorClient.sdkListener.OnMessage (jsonMessage);
            }
        }
コード例 #6
0
 public static void LoginInBackground(string username, string password,
                                      Action <BacktoryResponse <LoginResponse> > callback)
 {
     Backtory.ExecuteAsync <LoginResponse>(LoginRequest(username, password), loginResopnse =>
     {
         // this will be called in main thread since we're using backtory API
         if (loginResopnse.Successful)
         {
             Backtory.ExecuteAsync <BacktoryUser>(UserByUsernameRequest(username, loginResopnse.Body.AccessToken), userResponse =>
             {
                 // also on main thread
                 if (userResponse.Successful)
                 {
                     //DispatchSaveCurrentUser(userResponse.Body);
                     //DispatchSaveLoginInfo(loginResopnse.Body);
                     SaveAsCurrentUserInMemoryAndStorage(userResponse.Body);
                     SaveLoginInfo(loginResopnse.Body);
                     callback(loginResopnse);
                 }
                 else
                 {
                     callback(BacktoryResponse <LoginResponse> .Unknown(userResponse.Message));
                 }
             });
         }
         else
         {
             callback(loginResopnse);
         }
     });
 }
コード例 #7
0
    private static LoginResponse GetStoredLoginResponse()
    {
        string loginResponseString = Backtory.Storage.Get(KeyLoginInfo);

        /*if (loginResponseString == null)
         * throw new IllegalStateException("no auth token exists");*/
        return(Backtory.FromJson <LoginResponse>(loginResponseString));
    }
コード例 #8
0
        private IRestRequest PlayerRankRequest()
        {
            var request = Backtory.RestRequest("game/leaderboards/{leader_board_id}", Method.GET);

            request = AddDefaultHeaders(request);
            request.AddParameter("leader_board_id", LeaderboardId, ParameterType.UrlSegment);
            return(request);
        }
        private static IRestRequest RegisterRequest(BacktoryUser registrationParams)
        {
            var request = Backtory.RestRequest("auth/users", Method.POST);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddJsonBody(registrationParams);
            return(request);
        }
コード例 #10
0
 public BacktoryResponse <object> ChangePassword(string oldPassword, string newPassword)
 {
     if (Guest)
     {
         throw new InvalidOperationException("guest user con not change it's password");
     }
     return(Backtory.Execute <object>(ChangePassRequest(oldPassword, newPassword)));
 }
コード例 #11
0
 public void ChangePasswordInBackground(string oldPassword, string newPassword, Action <BacktoryResponse <object> > callback)
 {
     if (Guest)
     {
         throw new InvalidOperationException("guest user con not change it's password");
     }
     Backtory.ExecuteAsync(ChangePassRequest(oldPassword, newPassword), callback);
 }
        private static IRestRequest LogoutRequest(string refreshToken)
        {
            var request = Backtory.RestRequest("auth/logout", Method.DELETE);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddParameter("refresh-token", refreshToken, ParameterType.QueryString);
            request.OnBeforeDeserialization = response => { response.ContentType = "text/plain"; };
            return(request);
        }
コード例 #13
0
        private IRestRequest AroundMeRequest(int count)
        {
            var request = Backtory.RestRequest("game/leaderboards/around-me/{leader_board_id}", Method.GET);

            request = AddDefaultHeaders(request);
            request.AddParameter("leader_board_id", LeaderboardId, ParameterType.UrlSegment);
            request.AddQueryParameter("count", count.ToString());
            return(request);
        }
        private IRestRequest CompleteRegRequest(GuestCompletionParam guestRegistrationParam)
        {
            var request = Backtory.RestRequest("auth/guest-users/complete-registration", Method.POST);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddHeader(KeyAuthorization, AuthorizationHeader());
            request.AddJsonBody(guestRegistrationParam);
            return(request);
        }
コード例 #15
0
    public BacktoryResponse <BacktoryUser> UpdateUser()
    {
        var updateResponse = Backtory.Execute <BacktoryUser>(UpdateUserRequest(this));

        if (updateResponse.Successful)
        {
            DispatchSaveCurrentUser(updateResponse.Body);
        }
        return(updateResponse);
    }
        private IRestRequest UpdateUserRequest(BacktoryUser toBeUpdateUser)
        {
            var request = Backtory.RestRequest("auth/users/{user_id}", Method.PUT);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddHeader(KeyAuthorization, AuthorizationHeader());
            request.AddParameter("user_id", toBeUpdateUser.UserId, ParameterType.UrlSegment);
            request.AddJsonBody(toBeUpdateUser);
            return(request);
        }
        internal static IRestRequest UserByUsernameRequest(string username, string accessToken = null)
        {
            var request = Backtory.RestRequest("auth/users/by-username/{username}", Method.GET);

            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddHeader(KeyAuthorization, accessToken != null ? "Bearer " + accessToken : AuthorizationHeader());
            request.AddParameter("username", username, ParameterType.UrlSegment);

            return(request);
        }
コード例 #18
0
    public BacktoryResponse <BacktoryUser> CompleteRegistration(GuestCompletionParam guestRegistrationParam)
    {
        var completeRegResponse = Backtory.Execute <BacktoryUser>(CompleteRegRequest(guestRegistrationParam));

        if (completeRegResponse.Successful)
        {
            DispatchSaveCurrentUser(completeRegResponse.Body);
        }
        return(completeRegResponse);
    }
コード例 #19
0
 public void UpdateUserInBackground(Action <BacktoryResponse <BacktoryUser> > callback)
 {
     Backtory.ExecuteAsync <BacktoryUser>(UpdateUserRequest(this), updateResponse => {
         if (updateResponse.Successful)
         {
             SaveAsCurrentUserInMemoryAndStorage(updateResponse.Body);
         }
         callback(updateResponse);
     });
 }
コード例 #20
0
 public void CompleteRegistrationInBackgrond(GuestCompletionParam guestRegistrationParam, Action <BacktoryResponse <BacktoryUser> > callback)
 {
     Backtory.ExecuteAsync <BacktoryUser>(CompleteRegRequest(guestRegistrationParam), completeRegResponse =>
     {
         if (completeRegResponse.Successful)
         {
             SaveAsCurrentUserInMemoryAndStorage(completeRegResponse.Body);
         }
         callback(completeRegResponse);
     });
 }
        internal static IRestRequest NewAccessTokenRequest()
        {
            var request = Backtory.RestRequest("auth/login", Method.POST);

            request.AlwaysMultipartFormData = true;
            request.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            request.AddHeader(Backtory.AuthClientKeyString, BacktoryConfig.BacktoryAuthClientKey);
            request.AddHeader("X-Backtory-Authentication-Refresh", "1");
            request.AddParameter("refresh_token", BacktoryUser.GetRefreshToken(), ParameterType.GetOrPost);
            return(request);
        }
        private IRestRequest SendEventRequest(BacktoryGameEvent backtoryGameEvent)
        {
            var request = Backtory.RestRequest("game/events", Method.POST);

            request.AddHeader(Backtory.GameInstanceIdString, BacktoryConfig.BacktoryGameInstanceId);
            request.AddHeader(BacktoryUser.KeyAuthorization, BacktoryUser.AuthorizationHeader());
            request.AddHeader("Accept", Backtory.ApplicationJson);
            request.AddJsonBody(backtoryGameEvent);

            return(request);
        }
 internal void OnDisconnect()
 {
     if (connectorStateEngine.getConnectionState() == ConnectorStateEngine.ConnectorState.DISCONNECTING /*&& disconnectLatch.getCount() == 1*/)
     {
         disconnectLatch.Signal();
     }
     else
     {
         Backtory.Dispatch(() => sdkListener.OnDisconnect());
     }
     connectorStateEngine.ChangeState(ConnectorStateEngine.StateChangeEvent.CONNECTED);
 }
        // restsharp normally doesn't support multipart request without file
        // by setting AlwaysMultipart we force it to do so
        private static IRestRequest LoginRequest(string username, string password)
        {
            var loginRequest = Backtory.RestRequest("auth/login", Method.POST);

            loginRequest.AlwaysMultipartFormData = true;
            loginRequest.AddHeader(Backtory.AuthInstanceIdString, BacktoryConfig.BacktoryAuthInstanceId);
            loginRequest.AddHeader("X-Backtory-Authentication-Key", BacktoryConfig.BacktoryAuthClientKey);
            loginRequest.AddParameter("username", username, ParameterType.GetOrPost);
            loginRequest.AddParameter("password", password, ParameterType.GetOrPost);

            return(loginRequest);
        }
コード例 #25
0
 internal static readonly ISerializer jsonSerializer = new NewtonsoftJsonSerializer();/*new MyJsonSerializer();*/
 internal Action <BacktoryResponse <T> > PrintCallBack <T>() where T : class
 {
     return((backtoryResponse) =>
     {
         if (backtoryResponse.Successful)
         {
             ResultText.text = Backtory.ToJson(backtoryResponse.Body, true); /*JsonHelper.FormatJson(jsonSerializer.Serialize(backtoryResponse.Body));*/
         }
         else
         {
             ResultText.text = backtoryResponse.Message;
         }
     });
 }
コード例 #26
0
        public static GroupChatHistoryResponse Get(string responseJson)
        {
            A a = Backtory.FromJson <A> (responseJson);

            GroupChatHistoryResponse response    = new GroupChatHistoryResponse();
            List <ChatMessage>       messageList = new List <ChatMessage>();

            for (int i = 0; i < a.MessageList.Count; i++)
            {
                ComprehensiveChatMessage cCM = a.MessageList [i];
                string cCMJson = Backtory.ToJson(cCM);
                if (cCM._type == ".SimpleChatMessage")
                {
                    SimpleChatMessage sCM = Backtory.FromJson <SimpleChatMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else if (cCM._type == ".ChatGroupUserAddedMessage")
                {
                    UserAddedMessage sCM = Backtory.FromJson <UserAddedMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else if (cCM._type == ".ChatGroupUserJoinedMessage")
                {
                    UserJoinedMessage sCM = Backtory.FromJson <UserJoinedMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else if (cCM._type == ".ChatGroupUserLeftMessage")
                {
                    UserLeftMessage sCM = Backtory.FromJson <UserLeftMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else if (cCM._type == ".ChatGroupUserRemovedMessage")
                {
                    UserRemovedMessage sCM = Backtory.FromJson <UserRemovedMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else if (cCM._type == ".ChatGroupInvitationMessage")
                {
                    ChatInvitationMessage sCM = Backtory.FromJson <ChatInvitationMessage> (cCMJson);
                    messageList.Add(sCM);
                }
                else
                {
                    // ERROR
                }
            }
            response.ChatMessageList = messageList;
            return(response);
        }
        public Dictionary <string, object> sendNoWait(string destination, Dictionary <string, object> jsonData, Dictionary <string, string> extraHeader)
        {
            if (!isConnected())
            {
                throw new Exception("WS is not connected");
            }

            string jsonstring = Backtory.ToJson(jsonData);

            webSocket.Send(destination, jsonstring, extraHeader);
            Dictionary <string, object> result = new Dictionary <string, object> ();

            result.Add("success", "message sent");
            return(result);
        }
コード例 #28
0
        internal void NotifyMessageReceived(string jsonMessage, string _type)
        {
            Debug.Log("==::::=> ");
            if (_type != null)
            {
                Type clazz = BacktoryConnectivityMessageFactory.GetType(_type);
                BacktoryConnectivityMessage message = (BacktoryConnectivityMessage)Backtory.FromJson(jsonMessage, clazz);
                if (connectorClient.CheckRequestId(jsonMessage, _type))
                {
                    // TODO IMPORTANT : move this action on main thread
                    if (BacktoryConnectivityMessageFactory.GetTypeCategory(_type).Equals(BacktoryConnectivityMessageFactory.TypeCategory.Matchmaking) && matchmakingListener != null)
                    {
                        if (_type.Equals(BacktoryConnectivityMessage.MATCH_FOUND_MESSAGE))
                        {
                            GenerateRealtimeMatch((MatchFoundMessage)message);
                        }
                        message.OnMessageReceived(matchmakingListener);
                    }
                    else if (BacktoryConnectivityMessageFactory.GetTypeCategory(_type).Equals(BacktoryConnectivityMessageFactory.TypeCategory.Challenge) && challengeListener != null)
                    {
                        if (_type.Equals(BacktoryConnectivityMessage.CHALLENGE_READY_MESSAGE))
                        {
                            GenerateRealtimeMatch((ChallengeReadyMessage)message);
                        }
                        message.OnMessageReceived(challengeListener);
                    }
                    else if (BacktoryConnectivityMessageFactory.GetTypeCategory(_type).Equals(BacktoryConnectivityMessageFactory.TypeCategory.Chat) && chatListener != null)
                    {
                        message.OnMessageReceived(chatListener);
                        JSONNode jsonNode = JSON.Parse(jsonMessage);
                        SendDelivery((string)jsonNode ["deliveryId"]);
                    }
                    else if (BacktoryConnectivityMessageFactory.GetTypeCategory(_type).Equals(BacktoryConnectivityMessageFactory.TypeCategory.General) && connectorClient.sdkListener != null)
                    {
                        message.OnMessageReceived(connectorClient.sdkListener);
                    }
                    else
                    {
                        // TODO: 7/20/16 AD What to do?
                    }
                }
            }
            else
            {
                // TODO: 7/23/16 AD What to do?
//				connectorClient.sdkListener.OnMessage (jsonMessage);
            }
        }
コード例 #29
0
        private BacktoryResponse <T> GenerateBacktoryResponse <T> (string responseJson, Type clazz) where T : class
        {
            Debug.Log("jsonnode: " + responseJson);
            if (responseJson == null)
            {
                return(BacktoryResponse <T> .Error((int)BacktoryHttpStatusCode.RequestTimeout, null));
            }
            JSONNode jsonNode = JSONNode.Parse(responseJson);
            string   _type    = jsonNode ["_type"];

            if (_type.Equals(".ExceptionResponse"))
            {
                ExceptionResponse exceptionResponse = Backtory.FromJson <ExceptionResponse> (responseJson);
                string            message           = exceptionResponse.Exception.Message;
                int errorCode = (int)exceptionResponse.Exception.Code;
                return(BacktoryResponse <T> .Error(errorCode, message));
            }
            else if (typeof(T).Equals(typeof(GroupChatHistoryResponse)))
            {
                T body = GroupChatHistoryResponse.Get(responseJson) as T;
                return(BacktoryResponse <T> .Success(200, body));
            }
            else if (typeof(T).Equals(typeof(UserChatHistoryResponse)))
            {
                T body = UserChatHistoryResponse.Get(responseJson) as T;
                return(BacktoryResponse <T> .Success(200, body));
            }
            else if (typeof(T).Equals(typeof(OfflineMessageResponse)))
            {
                T body = OfflineMessageResponse.Get(responseJson) as T;
                return(BacktoryResponse <T> .Success(200, body));
            }
            else
            {
                T body;
                if (clazz != typeof(BacktoryVoid))
                {
                    body = Backtory.FromJson(responseJson, clazz) as T;
                }
                else
                {
                    body = default(BacktoryVoid) as T;
                }
                return(BacktoryResponse <T> .Success(200, body));
            }
        }
コード例 #30
0
    public static BacktoryUser GetCurrentUser()
    {
        // from memory
        if (currentUser != null)
        {
            return(currentUser);
        }
        // from storage (mostly disk)
        string userJson = Backtory.Storage.Get(KeyCurrentUser);

        if (!userJson.IsEmpty())
        {
            return(Backtory.FromJson <BacktoryUser>(userJson));
        }
        // indicating a login is required because a user info must be exist in all conditions if user
        // access token is present in storage
        return(null);
    }