Ejemplo n.º 1
0
        private void BuildEventRegistrationRequest(string eventID)
        {
            string playerId   = TTPlayerPrefs.GetValue(_keyPlayerId, "0");
            string playerName = WWW.EscapeURL(socialStateModel.GetPlayerName());

            _requestUrl = String.Format("{0}{1}/{2}/{3}/{4}{5}={6}", _url, "events", eventID, "players", playerId, "?playerName", playerName);
        }
Ejemplo n.º 2
0
        private void HandleLoginResponse(ConnectionHandler.RequestResult result, string response)
        {
            if (_timedOut)
            {
                logger.LogWarning(Tag, "HandleGetdataResponse - ModelSyncCompleted timed out");
                return;
            }

            logger.Log(Tag, "HandleLoginResponse (result=" + result + ")\nresponse=" + response.SSubstring(300));
            if (result != ConnectionHandler.RequestResult.Ok)
            {
                HandleErrorResponse(result, response);
                return;
            }

            JsonData responseJsonObject = JsonMapper.ToObject(response);

            string playerId = ((long)responseJsonObject [keyPlayerId]).ToString();

            logger.Log(Tag, "Got playerId:" + playerId);

            bool isNewPlayer = TTPlayerPrefs.GetValue(keyPlayerId, "0") == "0";

            TTPlayerPrefs.SetValue(keyPlayerId, playerId);

            //_gameDB.SaveSyncInfo (keyPlayerId, ((long)responseJsonObject [keyPlayerId]).ToString ());
            logger.Log(Tag, "Got token:" + (string)responseJsonObject [keyToken]);
            _gameDB.SaveSyncInfo(keyToken, (string)responseJsonObject [keyToken]);

            _syncState = SyncLoopState.GettingSync;
        }
Ejemplo n.º 3
0
        /*
         * public Promise<TeamData> AddTeam(string name, List<AssetData> assets, List<GenericPropertyData> properties)
         * {
         *      TeamInfo teamInfo = new TeamInfo()
         *
         *      var promise = new Promise<TeamStateData>();
         *
         *
         *      Action<ConnectionHandler.RequestResult, string> HandleAddTeam = (result,response) => {
         *
         *              logger.Log(Tag,"HandleAddTeamResponse (result=" + result + ")\nresponse=" + response);
         *
         *              if (result != ConnectionHandler.RequestResult.Ok)
         *              {
         *                      promise.Reject(new Exception(response));
         *                      return;
         *              }
         *
         *              TeamStateData teamData = JsonMapper.ToObject<TeamStateData>(response);
         *
         *              teamStateModel.SetState(teamData);
         *
         *              promise.Resolve(teamData);
         *      };
         *
         *      routineRunner.StartCoroutine(connectionHandler.SendRequest(TeamSyncConnectionHandler.TeamRequestType.AddTeam, HandleAddTeam, 0, teamInfo));
         *
         *      return promise;
         * }
         */

        public Promise <TeamData> GetTeamData(string teamId)
        {
            TeamData teamData = new TeamData();

            teamData.id = teamId;

            var promise = new Promise <TeamData>();
            Action <ConnectionHandler.RequestResult, string> HandleGetTeam = (result, response) => {
                logger.Log(Tag, "HandleGetTeamDataResponse (result=" + result + ")\nresponse=" + response);

                if (result != ConnectionHandler.RequestResult.Ok)
                {
                    string persistedScore = TTPlayerPrefs.GetValue("TeamScore", 0).ToString();
                    promise.Reject(new Exception(persistedScore));
                    return;
                }

                TeamData responseTeamData = JsonMapper.ToObject <TeamData>(response);

                NotifyTeamScoreIsUpdated(responseTeamData.score);

                promise.Resolve(responseTeamData);
            };

            routineRunner.StartCoroutine(notificationConnectionHandler.SendRequest(TeamSyncConnectionHandler.TeamRequestType.GetTeam, HandleGetTeam, 0, teamData));

            return(promise);
        }
Ejemplo n.º 4
0
        private void BuildGetRelationshipsScoresRequest(string levelConfigId)
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");

            _requestUrl = String.Format("{0}{1}{2}/{3}{4}",
                                        _url, _getPlayerRequest, playerId, _relationshipsScoresRequest, levelConfigId);
        }
Ejemplo n.º 5
0
 private bool FirstTimeRun()
 {
     if (TTPlayerPrefs.HasKey("firstTimer"))
     {
         return(false);
     }
     else
     {
         TTPlayerPrefs.SetValue("firstTimer", true);
         return(true);
     }
 }
Ejemplo n.º 6
0
        private void BuildSyncStateRequest()
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");
            //string playerId = _gameDB.LoadSyncInfo(_keyPlayerId);
            string lastStateUpdate  = _gameDB.LoadSyncInfo(_keyLastStateUpdate);
            string lastSharedUpdate = _gameDB.LoadSyncInfo(_keyLastSharedUpdate);
            string maxProgress      = _gameDB.LoadSyncInfo(_keyMaxProgress);

            _requestUrl = String.Format("{0}{1}{2}?{3}={4}&{5}={6}&{7}={8}",
                                        _url, _savePlayerRequest, playerId,
                                        _keyLastStateUpdate, lastStateUpdate, _keyLastSharedUpdate, lastSharedUpdate,
                                        _keyMaxProgress, maxProgress);
        }
Ejemplo n.º 7
0
        private void BuildLoginRequest()
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");
            //string playerId = _gameDB.LoadSyncInfo(_keyPlayerId);
            string platform = "Other";

#if UNITY_ANDROID
            platform = "Android";
#elif UNITY_IOS
            platform = "iOS";
#endif
            _requestUrl = String.Format("{0}{1}?{2}={3}&{4}={5}",
                                        _url, _loginRequest, _keyPlayerId, playerId, _keyPlatform, platform);
        }
Ejemplo n.º 8
0
        private void OnGamePausedOrQuit()
        {
            int timeDiff = (int)_timeDiff.TotalSeconds;

#if UNITY_2017_1_OR_NEWER
            Debug.unityLogger.Log(Tag, "OnGamePaused - Saving Server Time " + _serverTime.ToString() + " ,time difference: " + timeDiff);
#else
            Debug.logger.Log(Tag, "OnGamePaused - Saving Server Time " + _serverTime.ToString() + " ,time difference: " + timeDiff);
#endif

            TTPlayerPrefs.SetValue(Tag, _serverTime.ToString());
            TTPlayerPrefs.SetValue(TimeDiff, timeDiff);
            TTPlayerPrefs.Save();
        }
Ejemplo n.º 9
0
        private void BuildConnectToNetworkRequest(SocialConnectData socialConnectData)
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");

            //string playerId = _gameDB.LoadSyncInfo(_keyPlayerId);

            _requestUrl = String.Format("{0}{1}{2}{3}?{4}={5}&{6}={7}&{8}={9}&{10}={11}&{12}={13}&{14}={15}",
                                        _url, _connectSocialNetworkRequestPrefix, playerId, _connectSocialNetworkRequestSuffix,
                                        _keySocialNetworkType, socialConnectData.network, _keySocialNetworkUserId, socialConnectData.userId,
                                        _keySocialNetworkToken, socialConnectData.userToken,
                                        _keySocialNetworkPlayerName, WWW.EscapeURL(socialConnectData.userName),
                                        _keySocialNetworkPlayerEmail, WWW.EscapeURL(socialConnectData.email),
                                        _keySocialNetworkPlayerImage, WWW.EscapeURL(socialConnectData.photoUrl));
        }
Ejemplo n.º 10
0
        public override void Execute()
        {
            logger.Log("ShowSessionStartCommand: Attempting to show start if available");

            // According to new guidelines - by default we won't show session start when no ads is bought
            bool disableSessionStartOnNoAds = generalParamtersConfigModel.GetBool("DisableSessionStartOnNoAds", true);
            bool noAdsBought = !settingsStateModel.ShowingAds();

            bool skipShowingSessionStart = disableSessionStartOnNoAds && noAdsBought;

            if (skipShowingSessionStart)
            {
                logger.Log("ShowSessionStartCommand: No ads bought - skip showing session start");
                return;
            }
            else
            {
                logger.Log(Tag, "No ads bought - skip showing session start");
            }

            bool showSessionStartOnFirstSession = generalParamtersConfigModel.GetBool("ShowSessionStartOnFirstSession", true);

            logger.Log(Tag, "ShowSessionStartOnFirstSession :" + showSessionStartOnFirstSession);

            int launchCount = TTPlayerPrefs.GetValue("TimesLaunched", 1);

            logger.Log(Tag, "App Launch count : " + launchCount);

            if (!showSessionStartOnFirstSession && launchCount <= 1)
            {
                logger.Log("ShowSessionStartCommand: skipping show in first game session");
                return;
            }

            if (Application.isEditor && !GsdkSettingsData.Instance.IsShowingSessionStartInEditor)
            {
                logger.Log("ShowSessionStartCommand: skipping show in Unity Editor");
                return;
            }

            Retain();

            popupHandle = locationManager.Get(ApplicationLocation.AppLoaded);

            popupHandle.Closed.AddListener(OnLocationClosed);
            float sessionStartTimeOut = generalParamtersConfigModel.GetFloat(SessionStartTimeOut, 10.0f);

            popupHandle.Open(OnLocationResult, sessionStartTimeOut);
        }
Ejemplo n.º 11
0
        public void Init()
        {
            _serverTime = DateTime.Parse(TTPlayerPrefs.GetValue(Tag, _serverTime.ToString()));
            _timeDiff   = TimeSpan.FromSeconds(TTPlayerPrefs.GetValue(TimeDiff, 0));

#if UNITY_2017_1_OR_NEWER
            Debug.unityLogger.Log(Tag, "Init - Set server time to: " + _serverTime + " Set time diff to: " + _timeDiff.TotalSeconds);
#else
            Debug.logger.Log(Tag, "Init - Set server time to: " + _serverTime + " Set time diff to: " + _timeDiff.TotalSeconds);
#endif

            ReCalculateTimeDiffFromServer();

            gamePausedSignal.AddListener(OnGamePausedOrQuit);
            gameQuitSignal.AddListener(OnGamePausedOrQuit);
        }
Ejemplo n.º 12
0
        public void SwitchUserAndRestartFlow(string newPlayerId)
        {
            _syncState = SyncLoopState.LoggingIn;
            _gameDB.SaveSyncInfo(keyToken, "");

            TTPlayerPrefs.SetValue("SwitchPlayerInProgress", true);
            TTPlayerPrefs.SetValue(keyPlayerId, newPlayerId);
            //_gameDB.SaveSyncInfo(keyPlayerId, newPlayerId);
            _gameDB.SaveSyncInfo(keyLastStateUpdate, "2015-01-01T12:00:00Z");
            _gameDB.SaveSyncInfo(keyLastSharedStateUpdate, "2015-01-01T12:00:00Z");
            _timedOut = false;

            if (modelSyncStartSignal != null)
            {
                modelSyncStartSignal.Dispatch();
            }

            _coroutineFactory.StartCoroutine(() => StartOnDemandMode(true));
        }
Ejemplo n.º 13
0
 public DateTime GetPersistedServerTime()
 {
     return(new DateTime().AddSeconds(TTPlayerPrefs.GetValue(Tag, 0)));
 }
Ejemplo n.º 14
0
 private void NotifyTeamScoreIsUpdated(int teamScore)
 {
     TTPlayerPrefs.SetValue("TeamScore", teamScore);
     teamScoreUpdatedSignal.Dispatch(teamScore);
 }
Ejemplo n.º 15
0
        public void HandleErrorResponse(ConnectionHandler.RequestResult result, string response)
        {
            logger.Log(Tag.Italics(), "ModelSync.HandleErrorResponse (result=" + result + ")\nresponse: " + response.SSubstring(200));

            string title      = "";
            string message    = "";
            string button     = "";
            bool   showDialog = false;
            bool   recoverUnidentifiedUSer = false;

            switch (result)
            {
            case (ConnectionHandler.RequestResult.NoInternet):
                _flowDisconnectReason = FlowDisconnectReason.NoInternet;
                title   = "Connection Error";
                message = "Unable to connect with server. Check you internet connection and try again";
                button  = "Try Again";
                break;

            case (ConnectionHandler.RequestResult.CantReachServer):
                title   = "Connection Error";
                message = "Unable to connect with server. Please try again";
                button  = "Try Again";
                _flowDisconnectReason = FlowDisconnectReason.CantReachServer;
                break;

            case (ConnectionHandler.RequestResult.InternalServerError):
                _flowDisconnectReason = FlowDisconnectReason.ServerInternalError;
                break;

            case (ConnectionHandler.RequestResult.UnAuthorized):
                title   = "Progress Detected";
                message = "You have been playing on another device. Please reload game to load your progress";
                button  = "Reload";
                _flowDisconnectReason = FlowDisconnectReason.ExpiredToken;
                break;

            case (ConnectionHandler.RequestResult.OkWithErrorInside):
                JsonData        responseErrorJsonOnject = JsonMapper.ToObject(response);
                JsonData        errorObject             = (JsonData)responseErrorJsonOnject [keyError];
                ServerErrorData error = JsonMapper.ToObject <ServerErrorData> (errorObject.ToJson());
                logger.Log(Tag, "Handling server error message: " + error.ToString());
                if (error.code == (int)ConnectionHandler.RequestResult.UnAuthorized)
                {
                    _flowDisconnectReason = FlowDisconnectReason.ExpiredToken;
                    title   = "Progress Detected";
                    message = "You have been playing on another device. Please reload game to load your progress";
                    button  = "Reload";
                    break;
                }
                if (error.code == (int)ConnectionHandler.RequestResult.ClientUpdateRequired)
                {
                    _flowDisconnectReason = FlowDisconnectReason.ClientUpdateStarted;
                    title   = error.title;
                    message = "You must update your game - update initiated (url=" + error.message + ").";
                    button  = "";
                    break;
                }

                if (error.code == (int)ConnectionHandler.RequestResult.InternalServerError &&
                    error.message == "User not foundPlayer not found")
                {
                    logger.Log(Tag, "ModelSync.HandleErrorResponse() - PlayerId not found on server => staring new game");

                    recoverUnidentifiedUSer = true;
                    //_gameDB.SaveSyncInfo(keyPlayerId, "0");
                    TTPlayerPrefs.SetValue(keyPlayerId, "0");
                    _gameDB.SaveSyncInfo(keyLastStateUpdate, "");
                    RestartFlowAfterUserSwitch();
                }

                title   = "Unidentified Server Error";
                message = "error " + error.ToString();
                button  = "reload";
                break;
            }

            if (!recoverUnidentifiedUSer)
            {
                _syncState = SyncLoopState.DisconnectedOnHold;
            }

            if (connectionDisconnectedSignal != null)
            {
                connectionDisconnectedSignal.Dispatch(_flowDisconnectReason);
            }

            if (showDialog)
            {
                ShowErrorDialog(title, message, button);
            }
        }
Ejemplo n.º 16
0
        private void BuildRefreshRelationshipsRequest()
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");

            _requestUrl = String.Format("{0}{1}/{2}{3}", _url, "players", playerId, _refreshRelationshipsSuffix);
        }
Ejemplo n.º 17
0
 private static void ResetPlayerId()
 {
     Debug.Log("ResetPlayer: Setting playerId to 0");
     TTPlayerPrefs.SetValue(keyPlayerId, "0");
 }
Ejemplo n.º 18
0
 public static void ResetAllPlayerPrefs()
 {
     Debug.Log("Resetting all player preferences & In app purchases");
     TTPlayerPrefs.DeleteAll();
 }
Ejemplo n.º 19
0
        private void HandleConnectToNetworkResponse(ConnectionHandler.RequestResult result, string response)
        {
            logger.Log(Tag, "HandleConnectToNetworkResponse (result=" + result + ")\nresponse=" + response);

            if (result != ConnectionHandler.RequestResult.Ok)
            {
                modelSyncService.HandleErrorResponse(result, response);
                return;
            }

            JsonData responseJsonObject = JsonMapper.ToObject(response);

            _lastRecievedPlayerId = (string)responseJsonObject[keyPlayerId];
            NewSocialPlayerData playerData = new NewSocialPlayerData();

            playerData.id = _lastRecievedPlayerId;

            // Response body contains SocialStateData:
            if (responseJsonObject.Keys.Contains(keySocialStateData))
            {
                logger.Log(Tag, "Got social update");
                JsonData jsonData = (JsonData)responseJsonObject[keySocialStateData];
                string   data     = jsonData.ToJson();

                if (data.CompareTo("{}") != 0)
                {
                    gameDB.SyncState(keySocialStateData, data);
                    syncStatesSignal.Dispatch(new List <string> {
                        keySocialStateData
                    });
                }
            }

            //playerData.socialType = SocialStateData.GetNetworkFromString((string)responseJsonObject[keySocialType]);

            string currentPlayerId = TTPlayerPrefs.GetValue(keyPlayerId, "0");

            //string currentPlayerId = gameDB.LoadSyncInfo(keyPlayerId);

            if (_lastRecievedPlayerId.CompareTo("0") == 0)
            {
                logger.Log(Tag, "HandleConnectToNetworkResponse - got \"0\", no action required");
                //Logger.LogDebug ("SocialSync.HandleConnectToNetworkResponse - got \"0\", after changing network user => asking player to choose start new game or keep playing without being connected to this network.");
                //_socialConnectionStatus[playerData.socialType] = false;
                //connectionAllowUserToStartNewGameSignal.Dispatch(playerData);

                socialSyncCompletedSignal.Dispatch();
            }
            else if (currentPlayerId.CompareTo(_lastRecievedPlayerId) != 0)
            {
                logger.Log(Tag, "HandleConnectToNetworkResponse - got new user id from server: " + _lastRecievedPlayerId + ", switching to it from "
                           + currentPlayerId);
                //Logger.LogDebug ("SocialSync.HandleConnectToNetworkResponse - got new user id from server, allowing player to replace the game playerId.\nOld="
                //           + currentPlayerId + " new=" + _lastRecievedPlayerId);
                //_socialConnectionStatus[playerData.socialType] = false;
                //connectionAllowUserToSwitchUserSignal.Dispatch(playerData);
                SwitchUser(playerData.id);
            }
            else
            {
                logger.Log(Tag, "HandleConnectToNetworkResponse - got same user id, first time connected to this network => saving new network user id in state.");
                socialStateModel.SetNetworkUserId(playerData.socialType, _socialUserId[playerData.socialType]);
                //_socialConnectionStatus[playerData.socialType] = true;

                socialSyncCompletedSignal.Dispatch();
            }
        }
Ejemplo n.º 20
0
        private void BuildGetPushNotifURLRequest(string token)
        {
            string playerId = TTPlayerPrefs.GetValue(_keyPlayerId, "0");

            _requestUrl = String.Format("{0}{1}{2}{3}={4}", _url, "players", playerId, "pushToken?registerToken", token);
        }