Ejemplo n.º 1
0
        public bool Evaluate(out IJsonValue value, IJSONDocument document)
        {
            //ReturnOperation consideration.

            if (_operation == ArithmeticOperation.None && _rhs == null)
            {
                return(_lhs.Evaluate(out value, document));
            }

            IComparable opValue;

            value = null;
            switch (_operation)
            {
            case ArithmeticOperation.Addition:
                opValue = _lhs.Add(_rhs, document);

                if (opValue == null)
                {
                    return(false);
                }

                value = JsonWrapper.Wrap(opValue);
                break;

            case ArithmeticOperation.Subtraction:

                opValue = _lhs.Subtract(_rhs, document);

                if (opValue == null)
                {
                    return(false);
                }
                value = JsonWrapper.Wrap(opValue);
                break;

            case ArithmeticOperation.Multiplication:

                opValue = _lhs.Multiply(_rhs, document);

                if (opValue == null)
                {
                    return(false);
                }

                value = JsonWrapper.Wrap(opValue);
                break;

            case ArithmeticOperation.Division:

                opValue = _lhs.Divide(_rhs, document);

                if (opValue == null)
                {
                    return(false);
                }

                value = JsonWrapper.Wrap(opValue);
                break;

            case ArithmeticOperation.Modulus:

                opValue = _lhs.Modulate(_rhs, document);

                if (opValue == null)
                {
                    return(false);
                }

                value = JsonWrapper.Wrap(opValue);
                break;
            }
            return(true);
        }
Ejemplo n.º 2
0
        public void MakeApiCall(CallRequestContainer reqContainer)
        {
            //Set headers
            var headers = new Dictionary <string, string> {
                { "Content-Type", "application/json" }
            };

            if (reqContainer.AuthKey == AuthType.DevSecretKey)
            {
                headers.Add("X-SecretKey", DevKey);
            }
            else if (reqContainer.AuthKey == AuthType.LoginSession)
            {
                headers.Add("X-Authorization", AuthKey);
            }

            headers.Add("X-ReportErrorAsSuccess", "true");
            headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString);

#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
            if (PlayFabSettings.CompressApiData)
            {
                headers.Add("Content-Encoding", "GZIP");
                headers.Add("Accept-Encoding", "GZIP");

                using (var stream = new MemoryStream())
                {
                    using (GZipStream zipstream = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression))
                    {
                        zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
                    }
                    reqContainer.Payload = stream.ToArray();
                }
            }
#endif

            //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url);
            var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, headers);

#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif

            // Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
            Action <string> wwwSuccessCallback = (response) =>
            {
                try
                {
#if PLAYFAB_REQUEST_TIMING
                    var startTime = DateTime.UtcNow;
#endif
                    var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(response, PlayFabUtil.ApiSerializerStrategy);

                    if (httpResult.code == 200)
                    {
                        // We have a good response from the server
                        reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data, PlayFabUtil.ApiSerializerStrategy);
                        reqContainer.DeserializeResultJson();
                        reqContainer.ApiResult.Request    = reqContainer.ApiRequest;
                        reqContainer.ApiResult.CustomData = reqContainer.CustomData;

#if !DISABLE_PLAYFABCLIENT_API
                        ClientModels.UserSettings userSettings = null;
                        var res    = reqContainer.ApiResult as ClientModels.LoginResult;
                        var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
                        if (res != null)
                        {
                            userSettings = res.SettingsForUser;
                            AuthKey      = res.SessionTicket;
                        }
                        else if (regRes != null)
                        {
                            userSettings = regRes.SettingsForUser;
                            AuthKey      = regRes.SessionTicket;
                        }

                        if (userSettings != null && AuthKey != null && userSettings.NeedsAttribution)
                        {
                            PlayFabIdfa.OnPlayFabLogin();
                        }

                        var cloudScriptUrl = reqContainer.ApiResult as ClientModels.GetCloudScriptUrlResult;
                        if (cloudScriptUrl != null)
                        {
                            PlayFabSettings.LogicServerUrl = cloudScriptUrl.Url;
                        }
#endif
                        try
                        {
                            PlayFabHttp.SendEvent(reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }

#if PLAYFAB_REQUEST_TIMING
                        stopwatch.Stop();
                        var timing = new PlayFabHttp.RequestTiming {
                            StartTimeUtc        = startTime,
                            ApiEndpoint         = reqContainer.ApiEndpoint,
                            WorkerRequestMs     = (int)stopwatch.ElapsedMilliseconds,
                            MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
                        };
                        PlayFabHttp.SendRequestTiming(timing);
#endif
                        try
                        {
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                    else
                    {
                        if (reqContainer.ErrorCallback != null)
                        {
                            reqContainer.Error = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData);
                            PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                            reqContainer.ErrorCallback(reqContainer.Error);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            };

            Action <string> wwwErrorCallback = (errorCb) =>
            {
                if (reqContainer.ErrorCallback != null)
                {
                    reqContainer.Error = PlayFabHttp.GeneratePlayFabErrorGeneric(errorCb, null, reqContainer.CustomData);
                    PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                    reqContainer.ErrorCallback(reqContainer.Error);
                }
            };

            PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Internal method for Make API Calls
        /// </summary>
        protected internal static void MakeApiCall <TResult>(string apiEndpoint,
                                                             PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback,
                                                             Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false)
            where TResult : PlayFabResultCommon
        {
            InitializeHttp();
            SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);

            var reqContainer = new CallRequestContainer
            {
                ApiEndpoint    = apiEndpoint,
                FullUrl        = PlayFabSettings.GetFullUrl(apiEndpoint),
                CustomData     = customData,
                Payload        = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)),
                ApiRequest     = request,
                ErrorCallback  = errorCallback,
                RequestHeaders = extraHeaders ?? new Dictionary <string, string>() // Use any headers provided by the customer
            };

#if PLAYFAB_REQUEST_TIMING
            reqContainer.Timing.StartTimeUtc = DateTime.UtcNow;
            reqContainer.Timing.ApiEndpoint  = apiEndpoint;
#endif

            // Add PlayFab Headers
            reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true";                        // Makes processing PlayFab errors a little easier
            reqContainer.RequestHeaders["X-PlayFabSDK"]           = PlayFabSettings.VersionString; // Tell PlayFab which SDK this is
            switch (authType)
            {
#if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API
            case AuthType.DevSecretKey: reqContainer.RequestHeaders["X-SecretKey"] = PlayFabSettings.DeveloperSecretKey; break;
#endif
            case AuthType.LoginSession: reqContainer.RequestHeaders["X-Authorization"] = _internalHttp.AuthKey; break;
            }

            // These closures preserve the TResult generic information in a way that's safe for all the devices
            reqContainer.DeserializeResultJson = () =>
            {
                reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse);
            };
            reqContainer.InvokeSuccessCallback = () =>
            {
                if (resultCallback != null)
                {
                    resultCallback((TResult)reqContainer.ApiResult);
                }
            };

            if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted)
            {
                for (var i = _apiCallQueue.Count - 1; i >= 0; i--)
                {
                    if (_apiCallQueue[i].ApiEndpoint == apiEndpoint)
                    {
                        _apiCallQueue.RemoveAt(i);
                    }
                }
                _apiCallQueue.Add(reqContainer);
            }
            else
            {
                _internalHttp.MakeApiCall(reqContainer);
            }
        }
Ejemplo n.º 4
0
using System.Collections.Generic;
using Photon.Pun;
using PlayFab;
using PlayFab.ClientModels;
using PlayFab.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayFabController : MonoBehaviour
{
    public static PlayFabController PFC;

    private string userEmail;
    private string userPassword;
    private string username;
    public GameObject loginPanel;
    public GameObject addLoginPanel;
    public GameObject recoverButton;
    public SceneManager SM;

    private void OnEnable() {
        if (PlayFabController.PFC == null) {
            PlayFabController.PFC = this;
        }
        else { 
            if (PlayFabController.PFC != this) {
                Destroy(this.gameObject);
            }
        }
        DontDestroyOnLoad(this.gameObject);
    }

    public void Start()
    {
        //Used currently to counteract the autologin setting
        PlayerPrefs.DeleteAll();

        //Note: Setting title Id here can be skipped if you have set the value in Editor Extensions already.
        if (string.IsNullOrEmpty(PlayFabSettings.TitleId))
        {
            PlayFabSettings.TitleId = "E5D9";
        }
        //var request = new LoginWithCustomIDRequest { CustomId = "GettingStartedGuide", CreateAccount = true };
        //PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);


        if (PlayerPrefs.HasKey("EMAIL"))
        {
            userEmail = PlayerPrefs.GetString("EMAIL");
            userPassword = PlayerPrefs.GetString("PASSWORD");
            var request = new LoginWithEmailAddressRequest { Email = userEmail, Password = userPassword };
            PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFailure);
        }
        else {
#if UNITY_ANDROID
            var requestAndroid = new LoginWithAndroidDeviceIDRequest { AndroidDeviceId = returnMobileID(), CreateAccount = true };
            PlayFabClientAPI.LoginWithAndroidDeviceID(requestAndroid, OnLoginMobileSuccess, OnLoginMobileFailure);
#endif
#if UNITY_IOS
            var requestIOS = new LoginWithIOSDeviceIDRequest { DeviceId = returnMobileID(), CreateAccount = true };
            PlayFabClientAPI.LoginWithIOSDeviceID(requestIOS, OnLoginMobileSuccess, OnLoginMobileFailure);
#endif
        }
              
    }

    #region Login
    private void OnLoginSuccess(LoginResult result)
    {
        Debug.Log("Login Success!");
        PlayerPrefs.SetString("EMAIL", userEmail);
        PlayerPrefs.SetString("PASSWORD", userPassword);
        loginPanel.SetActive(false);
        getStats();

        //Move the camera to reveal database and launch options
        var moveScript = GameObject.Find("Main Camera").GetComponent<CameraMove>();
        moveScript.MoveBack();
    }

    private void OnLoginMobileSuccess(LoginResult result)
    {
        Debug.Log("Mobile Login Success!");
        getStats();
        loginPanel.SetActive(false);

        //Move the camera to reveal the new input options
        var moveScript = GameObject.Find("Main Camera").GetComponent<CameraMove>();
        moveScript.MoveBack();
    }

    private void onRegisterSuccess(RegisterPlayFabUserResult result) {
        Debug.Log("Registration Success!");
        PlayerPrefs.SetString("EMAIL", userEmail);
        PlayerPrefs.SetString("PASSWORD", userPassword);

        PlayFabClientAPI.UpdateUserTitleDisplayName(new UpdateUserTitleDisplayNameRequest { DisplayName = username }, OnDisplayName, OnLoginMobileFailure);
        getStats();
        loginPanel.SetActive(false);

        //Move the camera to reveal the new input options
        var moveScript = GameObject.Find("Main Camera").GetComponent<CameraMove>();
        moveScript.MoveBack();
    }

    void OnDisplayName(UpdateUserTitleDisplayNameResult result) {
        Debug.Log(result.DisplayName + " is your new display name");
    }

    private void OnLoginFailure(PlayFabError error)
    {
        var registerRequest = new RegisterPlayFabUserRequest { Email = userEmail, Password = userPassword, Username = username};
        PlayFabClientAPI.RegisterPlayFabUser(registerRequest, onRegisterSuccess, onRegisterFailure);
    }

    private void OnLoginMobileFailure(PlayFabError error)
    {
        Debug.Log(error.GenerateErrorReport());
    }

    private void onRegisterFailure(PlayFabError error) {
        Debug.LogError(error.GenerateErrorReport());
    }

    public void GetUserEmail(string emailIn) {
        userEmail = emailIn;
    }

    public void getUserPassword(string passwordIn) {
        userPassword = passwordIn;
    }

    public void getUsername(string usernameIn) {
        username = usernameIn;
    }

    public void onClickLogin() {
        var request = new LoginWithEmailAddressRequest { Email = userEmail, Password = userPassword };
        PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFailure);
    }

    public static string returnMobileID() {
        string deviceID = SystemInfo.deviceUniqueIdentifier;
        return deviceID;
    }

    public void openAddLogin() {
        addLoginPanel.SetActive(true);

        //Move the camera to reveal the new input options
        var moveScript = GameObject.Find("Main Camera").GetComponent<CameraMove>();
        moveScript.MoveForward();
    }

    public void onClickAddLogin() {
        addLoginPanel.SetActive(false);

        var request = new LoginWithEmailAddressRequest { Email = userEmail, Password = userPassword };
        PlayFabClientAPI.LoginWithEmailAddress(request, OnLoginSuccess, OnLoginFailure);
    }

    private void onAddLoginSuccess(AddUsernamePasswordResult result)
    {
        Debug.Log("Login Success!");
        PlayerPrefs.SetString("EMAIL", userEmail);
        PlayerPrefs.SetString("PASSWORD", userPassword);
        getStats();
        addLoginPanel.SetActive(false);

        //Move the camera to reveal the new input options
        var moveScript = GameObject.Find("Main Camera").GetComponent<CameraMove>();
        moveScript.MoveBack();
    }
    #endregion Login

    #region PlayerStats

    public int playerKillCount;

    public void setStats() { 
        PlayFabClientAPI.UpdatePlayerStatistics( new UpdatePlayerStatisticsRequest {
            // request.Statistics is a list, so multiple StatisticUpdate objects can be defined if required.
            Statistics = new List<StatisticUpdate> {
            new StatisticUpdate { StatisticName = "PlayerKillCount", Value = playerKillCount }
            }
        },
        result => { Debug.Log("User statistics updated"); },
        error => { Debug.LogError(error.GenerateErrorReport()); });
    }

    void getStats() {
        PlayFabClientAPI.GetPlayerStatistics(
            new GetPlayerStatisticsRequest(),
            OnGetStatistics,
            error => Debug.LogError(error.GenerateErrorReport())
        );
    }

    void OnGetStatistics(GetPlayerStatisticsResult result)
    {
        Debug.Log("Received the following Statistics:");
        foreach (var eachStat in result.Statistics)
        {
            Debug.Log("Statistic (" + eachStat.StatisticName + "): " + eachStat.Value);
            switch(eachStat.StatisticName) {
                case "PlayerKillCount":
                    playerKillCount = eachStat.Value;
                    break;
            }
        }
    }

    // Build the request object and access the API
    public void StartCloudUpdatePlayerStats()
    {
        PlayFabClientAPI.ExecuteCloudScript(new ExecuteCloudScriptRequest()
        {
            FunctionName = "UpdatePlayerStats", // Arbitrary function name (must exist in your uploaded cloud.js file)
            FunctionParameter = new { pKillCount = playerKillCount}, // The parameter provided to your function
            GeneratePlayStreamEvent = true, // Optional - Shows this event in PlayStream
        }, OnCloudUpdateStats, OnErrorShared);
    }


    private static void OnCloudUpdateStats(ExecuteCloudScriptResult result)
    {
        // Cloud Script returns arbitrary results, so you have to evaluate them one step and one parameter at a time
        Debug.Log(JsonWrapper.SerializeObject(result.FunctionResult));
        JsonObject jsonResult = (JsonObject)result.FunctionResult;
        object messageValue;
        jsonResult.TryGetValue("messageValue", out messageValue); // note how "messageValue" directly corresponds to the JSON values set in Cloud Script
        Debug.Log((string)messageValue);
    }

    private static void OnErrorShared(PlayFabError error)
    {
        Debug.Log(error.GenerateErrorReport());
    }

    #endregion PlayerStats


    public GameObject leaderboardPanel;
    public GameObject listingPrefab;
    public Transform listingContainer;

    #region Leaderboard
    public void GetLeaderboard() {
        var requestLeaderboard = new GetLeaderboardRequest { StartPosition = 0, StatisticName = "PlayerKillCount", MaxResultsCount = 20 };
        PlayFabClientAPI.GetLeaderboard(requestLeaderboard, onGetLeaderboard, onErrorLeaderboard);
    }

    void onGetLeaderboard(GetLeaderboardResult result) {
        leaderboardPanel.SetActive(true);
        //Debug.Log(result.Leaderboard[0].StatValue);
        foreach(PlayerLeaderboardEntry player in result.Leaderboard) {
            GameObject tempListing = Instantiate(listingPrefab, listingContainer);
            LeaderboardListing LL = tempListing.GetComponent<LeaderboardListing>();
            LL.playerNameText.text = player.DisplayName;
            LL.playerScoreText.text = player.StatValue.ToString();
            Debug.Log(player.DisplayName + ": " + player.StatValue);
        }
    }

    public void closeLeaderboardPanel() {
        leaderboardPanel.SetActive(false);
        for(int i = listingContainer.childCount - 1; i >= 0; i--) {
            Destroy(listingContainer.GetChild(i).gameObject);
        }
    }

    void onErrorLeaderboard(PlayFabError error) {
        Debug.LogError(error.GenerateErrorReport());
    }

    #endregion Leaderboard



    #region Friends

    string friendUsername;

    enum FriendIdType { PlayFabId, Username, Email, DisplayName };

    void AddFriend(FriendIdType idType, string friendId)
    {
        var request = new AddFriendRequest();
        switch (idType)
        {
            case FriendIdType.PlayFabId:
                request.FriendPlayFabId = friendId;
                break;
            case FriendIdType.Username:
                request.FriendUsername = friendId;
                break;
            case FriendIdType.Email:
                request.FriendEmail = friendId;
                break;
            case FriendIdType.DisplayName:
                request.FriendTitleDisplayName = friendId;
                break;
        }
        // Execute request and update friends when we are done
        PlayFabClientAPI.AddFriend(request, result => {
            Debug.Log("Friend added successfully!");
        }, DisplayPlayFabError);
    }

    List<FriendInfo> _friends = null;

    void GetFriends()
    {
        PlayFabClientAPI.GetFriendsList(new GetFriendsListRequest
        {
            IncludeSteamFriends = false,
            IncludeFacebookFriends = false
        }, result => {
            _friends = result.Friends;
            DisplayFriends(_friends); // triggers your UI
        }, DisplayPlayFabError);
    }

    void DisplayFriends(List<FriendInfo> friendsCache) { friendsCache.ForEach(f => Debug.Log(f.Username)); }
    void DisplayPlayFabError(PlayFabError error) { Debug.Log(error.GenerateErrorReport()); }
    void DisplayError(string error) { Debug.LogError(error); }

    public void OnClickAddFriend() {
        AddFriend(FriendIdType.Username, friendUsername);
    }

    public void setFriendUsername(string value) {
        friendUsername = value;
    }

    #endregion Friends
}

Ejemplo n.º 5
0
        private static void ProcessJsonResponse(CallRequestContainer reqContainer)
        {
            try
            {
                var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(reqContainer.JsonResponse);

#if PLAYFAB_REQUEST_TIMING
                reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
#endif

                //This would happen if playfab returned a 500 internal server error or a bad json response.
                if (httpResult == null || httpResult.code != 200)
                {
                    QueueRequestError(reqContainer);
                    return;
                }

                reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data);
                reqContainer.DeserializeResultJson(); // Assigns Result with a properly typed object
                reqContainer.ApiResult.Request    = reqContainer.ApiRequest;
                reqContainer.ApiResult.CustomData = reqContainer.CustomData;

#if !DISABLE_PLAYFABCLIENT_API
                var res    = reqContainer.ApiResult as ClientModels.LoginResult;
                var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
                if (res != null)
                {
                    _authKey = res.SessionTicket;
                }
                else if (regRes != null)
                {
                    _authKey = regRes.SessionTicket;
                }

                lock (ResultQueue)
                {
                    ResultQueue.Enqueue(() => { PlayFabDeviceUtil.OnPlayFabLogin(res, regRes); });
                }
#endif
                lock (ResultQueue)
                {
                    //Queue The result callbacks to run on the main thread.
                    ResultQueue.Enqueue(() =>
                    {
#if PLAYFAB_REQUEST_TIMING
                        reqContainer.Stopwatch.Stop();
                        reqContainer.Timing.MainThreadRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds;
                        PlayFabHttp.SendRequestTiming(reqContainer.Timing);
#endif
                        try
                        {
                            PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e); // Log the user's callback exception back to them without halting PlayFabHttp
                        }
                    });
                }
            }
            catch (Exception e)
            {
                var msg = "Unhandled exception in ProcessJsonResponse : " + reqContainer.FullUrl;
                reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg;
                var enhancedError = new Exception(msg, e);
                Debug.LogException(enhancedError);
                QueueRequestError(reqContainer);
            }
        }
 public static T DeserializeObject <T>(string json)
 {
     return(JsonWrapper.DeserializeObject <T>(json, PlayFabUtil.ApiSerializerStrategy));
 }
 public static object DeserializeObject(string json)
 {
     return(JsonWrapper.DeserializeObject(json));
 }
Ejemplo n.º 8
0
        public int Execute(Dictionary <string, string> argsLc, Dictionary <string, string> argsCased)
        {
            string destFile, workspacePath, varsWithSpaces;

            JenkinsConsoleUtility.TryGetArgVar(out destFile, argsLc, "destFile");
            JenkinsConsoleUtility.TryGetArgVar(out workspacePath, argsLc, "workspacePath");
            // Jenkins wants a file with spaces around the "=", but Bash wants a file without. This controls which format nuance to use
            JenkinsConsoleUtility.TryGetArgVar(out varsWithSpaces, argsLc, "varsWithSpaces");
            var sdkName   = JenkinsConsoleUtility.GetArgVar(argsLc, "sdkName");
            var sdkGenKey = GetSdkGenKey(sdkName);

            if (argsLc.ContainsKey("apispecpath"))
            {
                _apiSpecPath = JenkinsConsoleUtility.GetArgVar(argsLc, "apiSpecPath");
            }
            else if (argsLc.ContainsKey("apispecgiturl"))
            {
                _apiSpecGitUrl = JenkinsConsoleUtility.GetArgVar(argsLc, "apiSpecGitUrl");
            }
            else if (argsLc.ContainsKey("apispecpfurl"))
            {
                _apiSpecPfUrl = JenkinsConsoleUtility.GetArgVar(argsLc, "apiSpecPfUrl");
            }
            else
            {
                JcuUtil.FancyWriteToConsole("Api-Spec input not defined.  Please input one of: apiSpecPath, apiSpecGitUrl, apiSpecPfUrl");
                return(1);
            }

            var versionJson = GetApiJson("SdkManualNotes.json");
            var sdkNotes    = JsonWrapper.DeserializeObject <SdkManualNotes>(versionJson);

            if (!sdkNotes.sdkVersion.TryGetValue(sdkGenKey, out sdkVersionString))
            {
                JcuUtil.FancyWriteToConsole("SdkManualNotes.json does not contain: " + sdkGenKey);
                JcuUtil.FancyWriteToConsole("SdkManualNotes.json:\n" + versionJson);
                return(1);
            }

            var sdkPieces = sdkVersionString.Split('.');

            major = sdkPieces[0]; minor = sdkPieces[1]; date = sdkPieces[sdkPieces.Length - 1];
            set   = true;

            // Write this to a Jenkins environment variable file, if defined
            var space = " ";

            if (!string.IsNullOrEmpty(varsWithSpaces) && varsWithSpaces.ToLower() == "false")
            {
                space = "";
            }
            if (!string.IsNullOrEmpty(destFile))
            {
                using (var outputFile = new StreamWriter(Path.Combine(workspacePath, destFile)))
                {
                    outputFile.WriteLine("sdkVersion" + space + "=" + space + sdkVersionString);
                    outputFile.WriteLine("sdkDate" + space + "=" + space + date);
                }
            }
            else
            {
                JcuUtil.FancyWriteToConsole(System.ConsoleColor.Yellow, "WARNING: Output file not defined.");
            }
            JcuUtil.FancyWriteToConsole("sdkVersion" + space + "=" + space + sdkVersionString);
            JcuUtil.FancyWriteToConsole("sdkDate" + space + "=" + space + date);
            return(0);
        }
Ejemplo n.º 9
0
        internal static void MakeApiCall <TRequestType, TResultType>(string api, string apiEndpoint, TRequestType request, Action <TResultType> resultCallback, Action <EditorModels.PlayFabError> errorCallback)
        {
            var url = apiEndpoint + api;
            var req = JsonWrapper.SerializeObject(request, PlayFabEditorUtil.ApiSerializerStrategy);
            //Set headers
            var headers = new Dictionary <string, string>
            {
                { "Content-Type", "application/json" },
                { "X-ReportErrorAsSuccess", "true" },
                { "X-PlayFabSDK", string.Format("{0}_{1}", PlayFabEditorHelper.EDEX_NAME, PlayFabEditorHelper.EDEX_VERSION) }
            };


            if (api.Contains("/Server/") || api.Contains("/Admin/"))
            {
                if (PlayFabEditorDataService.activeTitle == null || string.IsNullOrEmpty(PlayFabEditorDataService.activeTitle.SecretKey))
                {
                    PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "Must have PlayFabSettings.DeveloperSecretKey set to call this method");
                    return;
                }

                headers.Add("X-SecretKey", PlayFabEditorDataService.activeTitle.SecretKey);
            }



            //Encode Payload
            var payload = System.Text.Encoding.UTF8.GetBytes(req.Trim());

            var www = new WWW(url, payload, headers);

            PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnHttpReq, api, PlayFabEditorHelper.MSG_SPIN_BLOCK);

            EditorCoroutine.start(Post(www, (response) =>
            {
                var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(response,
                                                                                    PlayFabEditorUtil.ApiSerializerStrategy);

                if (httpResult.code == 200)
                {
                    try
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnHttpRes, api);

                        var dataJson = JsonWrapper.SerializeObject(httpResult.data,
                                                                   PlayFabEditorUtil.ApiSerializerStrategy);
                        var result = JsonWrapper.DeserializeObject <TResultType>(dataJson,
                                                                                 PlayFabEditorUtil.ApiSerializerStrategy);

                        if (resultCallback != null)
                        {
                            resultCallback(result);
                        }
                    }
                    catch (Exception e)
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, e.Message);
                    }
                }
                else
                {
                    if (errorCallback != null)
                    {
                        PlayFab.Editor.EditorModels.PlayFabError playFabError = PlayFabEditorHelper.GeneratePlayFabError(response);
                        errorCallback(playFabError);
                    }
                    else
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, string.Format("ErrorCode:{0} -- {1}", httpResult.code, httpResult.status));
                    }
                }
            }, (error) =>
            {
                if (errorCallback != null)
                {
                    var playFabError = PlayFabEditorHelper.GeneratePlayFabError(error);
                    errorCallback(playFabError);
                }
                else
                {
                    PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error);
                }
            }), www);
        }
Ejemplo n.º 10
0
            /// @param data
            ///     The json data
            ///
            public static void DeserializeString(this ISerializable serializable, string data)
            {
                var jsonData = JsonWrapper.Deserialize(data);

                serializable.Deserialize(jsonData);
            }
Ejemplo n.º 11
0
        static private void OnGetSomeShip(ExecuteCloudScriptResult result)
        {
            string ship = JsonWrapper.SerializeObject(result.FunctionResult);

            Debug.Log(ship);
        }
Ejemplo n.º 12
0
        public async Task SavelinksAsync([Summary("The message link to quote")] string link, [Summary("The qauntities of link to save")] int quantity)
        {
            // Initializes the control boolean
            bool success = false;

            // Remove the message base part and splits all the IDs into an array
            string[] stringIDs = link.Replace(MessageBaseLink, "").Split('/');

            // Creates a new array to hold the IDs
            ulong[] ids = new ulong[3];

            // Parses all the IDs from strings to unsigned longs and saves the result into the array, also it stores the successes or failures into the boolean
            for (int i = 0; i < 3; i++)
            {
                success = UInt64.TryParse(stringIDs[i], out ids[i]);
            }

            // If the parse fails, delete the original user command message
            if (!success)
            {
                await Context.Message.DeleteAsync();

                await Ageha.Log(LogSeverity.Error, "Could not parse some ID");

                return;
            }

            // Free up memory
            stringIDs = null;

            // Tries to get the guild from the ID
            SocketGuild sourceGuild = Context.Client.GetGuild(ids[0]);

            // If the guild is null, reply to the user
            if (sourceGuild == null)
            {
                await ReplyAsync("I'm not in the linked server");

                return;
            }

            // Tries to get the channel from the ID
            SocketTextChannel sourceChannel = sourceGuild?.GetTextChannel(ids[1]);

            // If the channel is null, reply to the user
            if (sourceChannel == null)
            {
                await ReplyAsync("I can't view the linked channel");

                return;
            }

            // Tries to get the message from the ID
            IMessage linkedMessage = sourceChannel?.GetMessageAsync(ids[2]).Result;

            // If the message is null, reply to the user
            if (linkedMessage == null)
            {
                await ReplyAsync("The linked message doesn't exist");

                return;
            }

            // Free up some memory
            ids = null;

            // Gets the cached messages
            var cachedMessages = await sourceChannel.GetMessagesAsync(linkedMessage, Direction.Before, quantity).FlattenAsync();

            // Puts the linked message in the list
            cachedMessages.Append(linkedMessage);

            // Reverses the list to be in chronological order
            cachedMessages.Reverse();

            // Sends the quantity of found messages in the channel
            await ReplyAsync($"Found {cachedMessages.Count()} links.");

            // Creates an empty dictionary and a counter
            Dictionary <int, string> links = new Dictionary <int, string>();
            int counter = 0;

            // Only proceeds if any messages are found
            if (cachedMessages != null || cachedMessages.Count() > 0)
            {
                // Creates a valid file name to save the links
                string fileName = $"{MakeValidFileName(sourceGuild.Name)}_{MakeValidFileName(sourceChannel.Name)}_{linkedMessage.Id}.json";

                // Iterates over all messages found
                foreach (IMessage message in cachedMessages)
                {
                    // Only tries to pick emotes if the message isn't empty
                    if (!String.IsNullOrWhiteSpace(message.Content))
                    {
                        // Iterates over all tags
                        foreach (ITag tag in message.Tags)
                        {
                            // Only procceeds on emote tags
                            if (tag.Type == TagType.Emoji)
                            {
                                // Adds the emote link and updates the counter
                                links.Add(counter++, Emote.Parse($"<:{(tag.Value as Emote).Name}:{tag.Key.ToString()}>").Url);
                            }
                        }
                    }

                    // Checks to seed if there are any embeds
                    if (message.Embeds.Count > 0)
                    {
                        GetEmbeds(message.Embeds, ref links, ref counter);
                    }

                    // Checks to seed if there are any attachments
                    if (message.Attachments.Count > 0)
                    {
                        GetAttachments(message.Attachments, ref links, ref counter);
                    }
                }

                // Writes the json on a file
                JsonWrapper.WriteJSON <int, string>(fileName, links);

                // Sends the json back in the channel
                await Context.Channel.SendFileAsync(fileName, $"Here is the json containing {cachedMessages.Count()} links from before the message : {linkedMessage.GetJumpUrl()}");

                // Deletes the original file
                File.Delete(fileName);
            }
        }
Ejemplo n.º 13
0
        private static bool UploadEconomyData()
        {
            ////MUST upload these in this order so that the economy data is properly imported: VC -> Catalogs -> DropTables -> Catalogs part 2 -> Stores
            if (!UploadVc())
            {
                return(false);
            }

            if (string.IsNullOrEmpty(catalogPath))
            {
                return(false);
            }

            LogToFile("Uploading CatalogItems...");

            // now go through the catalog; split into two parts.
            var reUploadList = new List <CatalogItem>();
            var parsedFile   = ParseFile(catalogPath);

            var catalogWrapper = JsonWrapper.DeserializeObject <CatalogWrapper>(parsedFile);

            if (catalogWrapper == null)
            {
                LogToFile("\tAn error occurred deserializing the Catalog.json file.", ConsoleColor.Red);
                return(false);
            }
            for (var z = 0; z < catalogWrapper.Catalog.Count; z++)
            {
                if (catalogWrapper.Catalog[z].Bundle != null || catalogWrapper.Catalog[z].Container != null)
                {
                    var original      = catalogWrapper.Catalog[z];
                    var strippedClone = CloneCatalogItemAndStripTables(original);

                    reUploadList.Add(original);
                    catalogWrapper.Catalog.Remove(original);
                    catalogWrapper.Catalog.Add(strippedClone);
                }
            }

            if (!UpdateCatalog(catalogWrapper.Catalog, defaultCatalog, true))
            {
                return(false);
            }

            if (!UploadDropTables())
            {
                return(false);
            }

            if (!UploadStores(storesPath, defaultCatalog))
            {
                return(false);
            }

            // workaround for the DropTable conflict
            if (reUploadList.Count > 0)
            {
                LogToFile("Re-uploading [" + reUploadList.Count + "] CatalogItems due to DropTable conflicts...");
                if (!UpdateCatalog(reUploadList, defaultCatalog, true))
                {
                    return(false);
                }
            }
            return(true);
        }
        private static void SaveToEditorPrefs(object obj, string key)
        {
            var json = JsonWrapper.SerializeObject(obj);

            EditorPrefs.SetString(KeyPrefix + key, json);
        }
 public static string SerializeObject(object obj)
 {
     return(JsonWrapper.SerializeObject(obj, PlayFabUtil.ApiSerializerStrategy));
 }
Ejemplo n.º 16
0
        private void SaveAtlasResult()
        {
            string json = JsonWrapper.ToJson(SpriteDatabase, false);

            EditorPrefs.SetString(ATLAS_AUDITOR_STORAGE_KEY, json);
        }
 public static string SerializeObject(object obj, IJsonSerializerStrategy strategy)
 {
     return(JsonWrapper.SerializeObject(obj, strategy));
 }
Ejemplo n.º 18
0
        public void NullableJson(UUnitTestContext testContext)
        {
            var testObjNull = new NullableTestClass();
            var testObjInt  = new NullableTestClass {
                IntField = 42, IntProperty = 42
            };
            var testObjTime = new NullableTestClass {
                TimeField = DateTime.UtcNow, TimeProperty = DateTime.UtcNow
            };
            var testObjEnum = new NullableTestClass {
                EnumField = Region.Japan, EnumProperty = Region.Japan
            };
            var testObjBool = new NullableTestClass {
                BoolField = true, BoolProperty = true
            };
            var testObjs = new[] { testObjNull, testObjEnum, testObjBool, testObjInt, testObjTime };

            List <string> failures = new List <string>();

            foreach (var testObj in testObjs)
            {
                NullableTestClass actualObj = null;
                var actualJson = JsonWrapper.SerializeObject(testObj);
                try
                {
                    actualObj = JsonWrapper.DeserializeObject <NullableTestClass>(actualJson);
                }
                catch (Exception)
                {
                    failures.Add(actualJson + " Cannot be deserialized as NullableTestClass");
                    continue;
                }

                if (testObj.BoolField != actualObj.BoolField)
                {
                    failures.Add("Nullable bool field does not serialize properly: " + testObj.BoolField + ", from " + actualJson);
                }
                if (testObj.BoolProperty != actualObj.BoolProperty)
                {
                    failures.Add("Nullable bool property does not serialize properly: " + testObj.BoolProperty + ", from " + actualJson);
                }
                if (testObj.IntField != actualObj.IntField)
                {
                    failures.Add("Nullable integer field does not serialize properly: " + testObj.IntField + ", from " + actualJson);
                }
                if (testObj.IntProperty != actualObj.IntProperty)
                {
                    failures.Add("Nullable integer property does not serialize properly: " + testObj.IntProperty + ", from " + actualJson);
                }
                if (testObj.EnumField != actualObj.EnumField)
                {
                    failures.Add("Nullable enum field does not serialize properly: " + testObj.EnumField + ", from " + actualJson);
                }
                if (testObj.EnumProperty != actualObj.EnumProperty)
                {
                    failures.Add("Nullable enum property does not serialize properly: " + testObj.EnumProperty + ", from " + actualJson);
                }

                if (testObj.TimeField.HasValue != actualObj.TimeField.HasValue)
                {
                    failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
                }
                if (testObj.TimeField.HasValue && Math.Abs((testObj.TimeField - actualObj.TimeField).Value.TotalSeconds) > 1)
                {
                    failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeField + ", from " + actualJson);
                }

                if (testObj.TimeProperty.HasValue != actualObj.TimeProperty.HasValue)
                {
                    failures.Add("Nullable struct field does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
                }
                if (testObj.TimeProperty.HasValue && Math.Abs((testObj.TimeProperty - actualObj.TimeProperty).Value.TotalSeconds) > 1)
                {
                    failures.Add("Nullable struct property does not serialize properly: " + testObj.TimeProperty + ", from " + actualJson);
                }
            }

            if (failures.Count == 0)
            {
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            else
            {
                testContext.EndTest(UUnitFinishState.FAILED, string.Join("\n", failures.ToArray()));
            }
        }
 public static T DeserializeObject <T>(string json, IJsonSerializerStrategy strategy)
 {
     return(JsonWrapper.DeserializeObject <T>(json, strategy));
 }
Ejemplo n.º 20
0
    void LoadData(int _leveltype)
    {
        TextAsset file = Resources.Load("Animal/AnimalDataBase") as TextAsset;

        try
        {
            if (file != null)
            {
                //Get Json File.
                string contents = file.ToString();
                Debug.Log(contents);

                JsonWrapper wrapper = JsonUtility.FromJson <JsonWrapper>(contents);
                theWords = wrapper.WordData;

                //Get data.
                Debug.Log(theWords.date + "\n" + theWords.time);

                switch (_leveltype)
                {
                case 1:
                    for (int i = 0; i < theWords.Animal1.Count; i++)
                    {
                        saveList.Add(theWords.Animal1[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 2:
                    for (int i = 0; i < theWords.Animal2.Count; i++)
                    {
                        saveList.Add(theWords.Animal2[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 3:
                    for (int i = 0; i < theWords.Animal3.Count; i++)
                    {
                        saveList.Add(theWords.Animal3[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 4:
                    for (int i = 0; i < theWords.Cuisime1.Count; i++)
                    {
                        saveList.Add(theWords.Cuisime1[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 5:
                    for (int i = 0; i < theWords.Cuisime2.Count; i++)
                    {
                        saveList.Add(theWords.Cuisime2[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 6:
                    for (int i = 0; i < theWords.Fruit1.Count; i++)
                    {
                        saveList.Add(theWords.Fruit1[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;

                case 7:
                    for (int i = 0; i < theWords.Fruit2.Count; i++)
                    {
                        saveList.Add(theWords.Fruit2[i]);
                        //Debug.Log(getJsonList.Count);
                        //Debug.Log(saveList[i].chinese);
                    }
                    break;
                }
            }
            else
            {
                Debug.Log("Unable to read the save data, file does not exist.");
            }
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
Ejemplo n.º 21
0
        // Ideally this wouldn't live here, but for now, whatever.
        internal void CallService(string serviceName, string argsJson, System.IntPtr reportResultPtr)
        {
            Native.ReportResultFunction reportResult = null;
            if (CacheReportResult)
            {
                if (cachedReportResult == null)
                {
                    cachedReportResult   = Marshal.GetDelegateForFunctionPointer <Native.ReportResultFunction>(reportResultPtr);
                    firstReportResultPtr = reportResultPtr;
                }

                reportResult = cachedReportResult;
                Debug.Assert(firstReportResultPtr == reportResultPtr, $"Different reportResultPtr was given!");
            }
            else
            {
                reportResult = Marshal.GetDelegateForFunctionPointer <Native.ReportResultFunction>(reportResultPtr);
            }

            try
            {
                switch (serviceName)
                {
                case "BeginProfileSample":
                {
                    InGameProfiler.BeginSection(argsJson);
                    reportResult("0");
                    break;
                }

                case "EndProfileSample":
                {
                    InGameProfiler.EndSection();
                    reportResult("0");
                    break;
                }

                case "OverlapSphere":
                    using (Util.Profile(serviceName))
                    {
                        var args    = JsonUtility.FromJson <OverlapSphereArgs>(argsJson);
                        int numHits = Physics.OverlapSphereNonAlloc(args.center, args.radius, SharedColliderBuffer, VoosActor.LayerMaskValue, QueryTriggerInteraction.Collide);
                        if (numHits == SharedColliderBuffer.Length)
                        {
                            Util.LogError($"The OverlapSphere call exceeded the maximum number of allowed results ({SharedColliderBuffer.Length}). You are probably not getting what you want. Please try to adjust the parameters so you get less hits, like reducing the radius.");
                        }
                        using (Util.Profile("report actors"))
                        {
                            var jsoner = SharedStringBuilder;
                            jsoner.Clear();
                            jsoner.Append("[");
                            bool gotOneActor = false;
                            for (int i = 0; i < numHits; i++)
                            {
                                Collider  obj   = SharedColliderBuffer[i];
                                VoosActor actor = obj.GetComponentInParent <VoosActor>();
                                if (actor == null)
                                {
                                    continue;
                                }
                                if (!args.tag.IsNullOrEmpty())
                                {
                                    if (!actor.HasTag(args.tag))
                                    {
                                        continue;
                                    }
                                }

                                if (gotOneActor)
                                {
                                    jsoner.Append(",");
                                }
                                jsoner.Append("\"");
                                jsoner.Append(actor.GetName());
                                jsoner.Append("\"");
                                gotOneActor = true;
                            }
                            jsoner.Append("]");
                            reportResult(jsoner.ToString());
                        }
                        break;
                    }

                case "CheckBox":
                    using (Util.Profile(serviceName))
                    {
                        var  args        = JsonUtility.FromJson <CheckBoxArgs>(argsJson);
                        bool hitAnything = Physics.CheckBox(args.box.center, args.box.dimensions * 0.5f, args.box.rotation,
                                                            -1,                            // We're probably looking for clearance, so return true if the box hits actors OR just static terrain.
                                                            QueryTriggerInteraction.Ignore // Ignore triggers for checks. We are probably looking for clearance, in which case triggers don't matter.
                                                            );
                        reportResult(hitAnything ? "true" : "false");
                        break;
                    }

                case "Cast":
                    using (Util.Profile(serviceName))
                    {
                        PhysicsCastRequest req = JsonUtility.FromJson <PhysicsCastRequest>(argsJson);

                        int layerMask = (req.includeActors ? VoosActor.LayerMaskValue : 0) |
                                        (req.includeTerrain ? LayerMask.GetMask("Default") : 0);
                        int numHits = req.radius < 0.01 ?
                                      Physics.RaycastNonAlloc(req.origin, req.dir, SharedRaycastHitBuffer, req.maxDist, layerMask, QueryTriggerInteraction.Collide) :
                                      Physics.SphereCastNonAlloc(req.origin, req.radius, req.dir, SharedRaycastHitBuffer, req.maxDist, layerMask, QueryTriggerInteraction.Collide);

                        // These variables things are somewhat redundant, but for performance we keep all three and
                        // only use the appropriate ones per req.castMode, to avoid unnecessary allocations.
                        // List of results. Only allocate if we have to.
                        List <PhysicsCastHit> results = null;
                        // Did we have any hit?
                        bool anyHit = false;
                        // The closest hit we got. Only valid if anyHit == true.
                        PhysicsCastHit closestHit = new PhysicsCastHit();

                        if (req.mode == CastMode.ALL_SORTED || req.mode == CastMode.ALL_UNSORTED)
                        {
                            // We will need to return a list, so allocate it.
                            results = new List <PhysicsCastHit>();
                        }

                        for (int i = 0; i < numHits; i++)
                        {
                            RaycastHit     hit = SharedRaycastHitBuffer[i];
                            PhysicsCastHit thisHit;
                            if (hit.collider != null && hit.collider.gameObject != null &&
                                hit.collider.gameObject.GetComponent <IgnoreRaycastFromScript>() != null)
                            {
                                continue;
                            }
                            if (req.includeActors && IsScriptReadyActor(hit.collider) && GetActorName(hit.collider) != req.excludeActor)
                            {
                                // Hit an actor.
                                // (PhysicsCastHit is a struct, not allocating on heap)
                                thisHit = new PhysicsCastHit
                                {
                                    actor    = GetActorName(hit.collider),
                                    distance = hit.distance,
                                    point    = hit.point
                                };
                            }
                            else if (req.includeTerrain && hit.collider.tag == "Ground")
                            {
                                // Hit terrain.
                                // (PhysicsCastHit is a struct, not allocating on heap)
                                thisHit = new PhysicsCastHit
                                {
                                    actor    = null,
                                    distance = hit.distance,
                                    point    = hit.point
                                };
                            }
                            else
                            {
                                continue;
                            }
                            closestHit = (!anyHit || thisHit.distance < closestHit.distance) ? thisHit : closestHit;
                            anyHit     = true;
                            results?.Add(thisHit);
                            if (req.mode == CastMode.BOOLEAN)
                            {
                                // If we're just returning true/false, that's all we need.
                                break;
                            }
                        }

                        // Sort results by distance, if requested.
                        if (req.mode == CastMode.ALL_SORTED)
                        {
                            results.Sort((a, b) => a.distance.CompareTo(b.distance));
                        }

                        // Report results as requested.
                        if (req.mode == CastMode.ALL_SORTED || req.mode == CastMode.ALL_UNSORTED)
                        {
                            PhysicsCastResult result = new PhysicsCastResult {
                                hits = results.ToArray()
                            };
                            reportResult(JsonUtility.ToJson(result));
                        }
                        else if (req.mode == CastMode.CLOSEST)
                        {
                            reportResult(anyHit ? JsonUtility.ToJson(closestHit) : "null");
                        }
                        else
                        {
                            reportResult(anyHit ? "true" : "false");
                        }
                        break;
                    }

                case "GetPlayerActors":
                    using (Util.Profile(serviceName))
                    {
                        var jsoner = SharedStringBuilder;
                        jsoner.Clear();
                        jsoner.Append("[");
                        bool gotOneActor = false;

                        foreach (VoosActor actor in engine.EnumerateActors())
                        {
                            if (actor.GetIsPlayerControllable())
                            {
                                if (gotOneActor)
                                {
                                    jsoner.Append(",");
                                }
                                jsoner.Append("\"");
                                jsoner.Append(actor.GetName());
                                jsoner.Append("\"");
                                gotOneActor = true;
                            }
                        }
                        jsoner.Append("]");
                        reportResult(jsoner.ToString());
                        break;
                    }

                case "SetTerrainCell":
                {
                    var args = JsonUtility.FromJson <TerrainManager.SetCellRpcJsonable>(argsJson);
                    terrainSystem.SetCellValue(args.cell, args.value);
                    reportResult("true");
                    break;
                }

                case "GetTerrainCell":
                {
                    Vector3 coords = JsonUtility.FromJson <Vector3>(argsJson);
                    TerrainManager.CellValue cellValue = terrainSystem.GetCellValue(
                        new TerrainManager.Cell((int)coords.x, (int)coords.y, (int)coords.z));
                    GetTerrainCellResult result = new GetTerrainCellResult
                    {
                        shape = (int)cellValue.blockType,
                        dir   = (int)cellValue.direction,
                        style = (int)cellValue.style
                    };
                    reportResult(JsonUtility.ToJson(result));
                    break;
                }

                case "IsMultiplayer":
                {
                    reportResult(GameBuilderApplication.CurrentGameOptions.playOptions.isMultiplayer ? "true" : "false");
                    break;
                }

                case "TransferPlayerControl":
                {
                    VoosEngine.TransferPlayerControlRequest request =
                        JsonUtility.FromJson <VoosEngine.TransferPlayerControlRequest>(argsJson);
                    // Engine will handle this asynchronously because the actor might not be immediately
                    // available (maybe it was a clone that was just created, for instance).
                    GetEngine().RequestTransferPlayerControl(request);
                    reportResult("true");
                    break;
                }

                case "GetPlayerControlledActor":
                {
                    VoosActor actor = GetUserMain().GetPlayerActor();
                    reportResult(actor == null ? "null" : "\"" + actor.GetName() + "\"");
                    break;
                }

                case "IsMasterClient":
                {
                    reportResult(PhotonNetwork.isMasterClient ? "true" : "false");
                    break;
                }

                case "GetPlayersInfo":
                {
                    Dictionary <int, string> nicknames = new Dictionary <int, string>();
                    int i;
                    for (i = 0; i < PhotonNetwork.playerList.Length; i++)
                    {
                        int    id   = PhotonNetwork.playerList[i].ID;
                        string nick = PhotonNetwork.playerList[i].NickName;
                        nicknames[id] = nick;
                    }

                    VirtualPlayersResult result = new VirtualPlayersResult();
                    result.allPlayers = new VirtualPlayerResultEntry[virtualPlayerManager.GetVirtualPlayerCount()];

                    i = 0;
                    foreach (VirtualPlayerManager.VirtualPlayerInfo virtualPlayer in virtualPlayerManager.EnumerateVirtualPlayers())
                    {
                        Debug.Assert(i < result.allPlayers.Length);
                        result.allPlayers[i].id         = virtualPlayer.virtualId;
                        result.allPlayers[i].slotNumber = virtualPlayer.slotNumber;
                        result.allPlayers[i].nickName   = virtualPlayer.nickName;
                        ++i;
                    }
                    Debug.Assert(i == result.allPlayers.Length);

                    result.localPlayerId = playerControlsManager.GetVirtualPlayerId();
                    reportResult(JsonUtility.ToJson(result));
                    break;
                }

                case "RequestUi":
                {
                    using (Util.Profile("RequestUi"))
                    {
                        GameUiMain.UiCommandList list = JsonUtility.FromJson <GameUiMain.UiCommandList>(argsJson);
                        gameUiMain.SetUiCommands(list);
                        reportResult("true");
                    }
                    break;
                }

                case "GetActorColorField":
                {
                    GetActorFieldArgs args = JsonUtility.FromJson <GetActorFieldArgs>(argsJson);
                    reportResult(JsonUtility.ToJson(engine.GetActorColor(args.actorId, args.fieldId)));
                    break;
                }

                case "SetActorColorField":
                {
                    SetActorColorFieldArgs args = JsonUtility.FromJson <SetActorColorFieldArgs>(argsJson);
                    engine.SetActorColor(args.actorId, args.fieldId, args.newValue);
                    reportResult("true");
                    break;
                }

                case "CloneActor":
                    using (Util.Profile(serviceName))
                    {
                        VoosEngine.CloneActorRequest  args     = JsonUtility.FromJson <VoosEngine.CloneActorRequest>(argsJson);
                        VoosEngine.CloneActorResponse response = GetEngine().CloneActorForScript(args);
                        reportResult(JsonUtility.ToJson(response));
                        break;
                    }

                case "InstantiatePrefab":
                    using (Util.Profile(serviceName))
                    {
                        VoosEngine.InstantiatePrefab.Request  args     = JsonUtility.FromJson <VoosEngine.InstantiatePrefab.Request>(argsJson);
                        VoosEngine.InstantiatePrefab.Response response = GetEngine().InstantiatePrefabForScript(args);
                        reportResult(JsonUtility.ToJson(response));
                        break;
                    }

                case "DestroyActors":
                    using (Util.Profile(serviceName))
                    {
                        VoosEngine.DestroyActorsRequest args = JsonUtility.FromJson <VoosEngine.DestroyActorsRequest>(argsJson);
                        GetEngine().DestroyActorsForScript(args);
                        reportResult("true");
                        break;
                    }

                case "PlaySound":
                    using (Util.Profile(serviceName))
                    {
                        PlaySoundRequest args = JsonUtility.FromJson <PlaySoundRequest>(argsJson);
                        SoundEffect      sfx  = soundEffectSystem.GetSoundEffect(args.soundId);
                        if (sfx != null)
                        {
                            if (string.IsNullOrEmpty(args.actorName))
                            {
                                soundEffectSystem.PlaySoundEffect(sfx, null, args.position);
                            }
                            else
                            {
                                VoosActor actor = engine.GetActor(args.actorName);
                                if (actor == null)
                                {
                                    Debug.LogError("Could not play sound on actor. Actor not found: " + args.actorName);
                                    reportResult("false");
                                }
                                soundEffectSystem.PlaySoundEffect(sfx, actor, Vector3.zero);
                            }
                            reportResult("true");
                        }
                        else
                        {
                            Debug.LogWarning("No SFX with ID: " + args.soundId);
                            reportResult("false");
                        }
                        break;
                    }

                case "SpawnParticleEffect":
                    using (Util.Profile(serviceName))
                    {
                        ParticleEffectRequest args = JsonUtility.FromJson <ParticleEffectRequest>(argsJson);
                        ParticleEffect        pfx  = particleEffectSystem.GetParticleEffect(args.pfxId);
                        if (pfx != null)
                        {
                            particleEffectSystem.SpawnParticleEffect(
                                pfx, args.position, args.rotation * Mathf.Rad2Deg, args.scale);
                            reportResult("true");
                        }
                        else
                        {
                            Debug.LogWarning("No particle effect with ID: " + args.pfxId);
                            reportResult("false");
                        }
                        break;
                    }

                case "PlayOneShotAnimation":
                {
                    OneShotAnimationRequest req = JsonUtility.FromJson <OneShotAnimationRequest>(argsJson);
                    VoosActor actor             = engine.GetActorByTempId(req.actorTempId);
                    if (actor != null)
                    {
                        actor.PlayOneShotAnimation(req.animationName);
                    }
                    else
                    {
                        Util.LogError($"PlayOneShotAnimation: Could not find actor for temp ID {req.actorTempId}. Ignoring.");
                    }
                    reportResult("true");
                    break;
                }

                case "ProjectPoint":
                {
                    Camera  cam         = GetUserMain().GetCamera();
                    Vector3 point       = JsonUtility.FromJson <Vector3>(argsJson);
                    Vector3 screenPoint = cam.WorldToScreenPoint(point);
                    if (screenPoint.z > 0)
                    {
                        Vector2 gameUiPoint = gameUiMain.UnityScreenPointToGameUiPoint(screenPoint);
                        reportResult(JsonUtility.ToJson(gameUiPoint));
                    }
                    else
                    {
                        reportResult("null");
                    }
                    break;
                }

                case "ProjectSphere":
                {
                    Camera    cam          = GetUserMain().GetCamera();
                    SphereArg inSphere     = JsonUtility.FromJson <SphereArg>(argsJson);
                    Vector3   screenCenter = cam.WorldToScreenPoint(inSphere.center);
                    if (screenCenter.z > 0)
                    {
                        Vector3   centerGameUi     = gameUiMain.UnityScreenPointToGameUiPoint(screenCenter);
                        Vector3   rightPoint       = cam.WorldToScreenPoint(inSphere.center + cam.transform.right * inSphere.radius);
                        Vector3   rightPointGameUi = gameUiMain.UnityScreenPointToGameUiPoint(rightPoint);
                        SphereArg outSphere        = new SphereArg
                        {
                            center = centerGameUi,
                            radius = Mathf.Abs(rightPointGameUi.x - centerGameUi.x)
                        };
                        reportResult(JsonUtility.ToJson(outSphere));
                    }
                    else
                    {
                        reportResult("null");
                    }
                    break;
                }

                case "GetActorScreenRect":
                {
                    string    actorName   = JsonUtility.FromJson <GetActorScreenRectRequest>(argsJson).actor;
                    VoosActor actor       = engine.GetActor(actorName);
                    Bounds    worldBounds = new Bounds(actor.GetWorldRenderBoundsCenter(), actor.GetWorldRenderBoundsSize());

                    // Depending on the orientation, any of the 8 corners of the world-space bounding box
                    // can contribute to the screen-space bounding box, so we have to go through them all.
                    Bounds screenBounds = new Bounds();
                    bool   success      = true;
                    for (int i = 0; i < 8; i++)
                    {
                        Vector3 worldPoint = new Vector3(
                            (i & 1) > 0 ? worldBounds.min.x : worldBounds.max.x,
                            (i & 2) > 0 ? worldBounds.min.y : worldBounds.max.y,
                            (i & 4) > 0 ? worldBounds.min.z : worldBounds.max.z);
                        Vector3 screenPoint = GetUserMain().GetCamera().WorldToScreenPoint(worldPoint);
                        if (screenPoint.z < 0)
                        {
                            // Off-screen (behind camera).
                            success = false;
                            break;
                        }
                        Vector2 gameUiPoint = gameUiMain.UnityScreenPointToGameUiPoint(screenPoint);
                        if (i == 0)
                        {
                            // Note: due to the Bounds() constructor assuming Vector3.zero as the center
                            // (known Unity bug), we have to reinitialize it here:
                            screenBounds = new Bounds(gameUiPoint, Vector3.zero);
                        }
                        else
                        {
                            screenBounds.Encapsulate(gameUiPoint);
                        }
                    }
                    reportResult(success ? JsonUtility.ToJson(new GetActorScreenRectResponse
                        {
                            x = screenBounds.min.x,
                            y = screenBounds.min.y,
                            w = screenBounds.size.x,
                            h = screenBounds.size.y
                        }) : "null");
                    break;
                }

                case "GetCameraInfo":
                {
                    Transform  cameraTransform = GetUserMain().GetCamera().transform;
                    CameraInfo info            = new CameraInfo
                    {
                        pos = cameraTransform.position,
                        rot = cameraTransform.rotation
                    };
                    reportResult(JsonUtility.ToJson(info));
                    break;
                }

                case "ReportBehaviorException":
                {
                    Util.LogError($"ReportBehaviorException {argsJson}");
                    VoosEngine.BehaviorLogItem e = JsonUtility.FromJson <VoosEngine.BehaviorLogItem>(argsJson);
                    engine.HandleBehaviorException(e);
                    reportResult("true");
                    break;
                }

                case "LogBehaviorMessage":
                {
                    Util.Log($"LogBehaviorMessage {argsJson}");
                    VoosEngine.BehaviorLogItem msg = JsonUtility.FromJson <VoosEngine.BehaviorLogItem>(argsJson);
                    engine.HandleBehaviorLogMessage(msg);
                    reportResult("true");
                    break;
                }

                case "GetCameraActor":
                {
                    string cameraActorName = GetUserMain().GetCameraActor()?.GetName();
                    reportResult(cameraActorName == null ? "null" : ("\"" + cameraActorName + "\""));
                    break;
                }

                case "RequestTempCameraOffset":
                {
                    TempCameraOffsetRequest request = JsonUtility.FromJson <TempCameraOffsetRequest>(argsJson);
                    if (request.actor == GetUserMain().GetPlayerActor()?.GetName())
                    {
                        GetUserMain().GetNavigationControls().RequestTemporaryCameraOffset(request.offset);
                    }
                    reportResult("true");
                    break;
                }

                case "GetScreenInfo":
                {
                    reportResult(JsonUtility.ToJson(gameUiMain.GetScreenInfoForScript()));
                    break;
                }

                case "SetSkyType":
                {
                    JsonWrapper <string>     request = JsonUtility.FromJson <JsonWrapper <string> >(argsJson);
                    GameBuilderStage.SkyType skyType;
                    if (Util.TryParseEnum(request.value ?? "", out skyType, true))
                    {
                        gbStage.SetSkyType(skyType);
                        reportResult("true");
                    }
                    else
                    {
                        Debug.LogError("Invalid sky type requested: " + request.value);
                        reportResult("false");
                    }
                    break;
                }

                case "GetSkyType":
                {
                    reportResult(JsonUtility.ToJson(JsonWrapper <string> .Wrap(gbStage.GetSkyType().ToString())));
                    break;
                }

                case "SetSkyColor":
                {
                    JsonWrapper <Color> request = JsonUtility.FromJson <JsonWrapper <Color> >(argsJson);
                    gbStage.SetSkyColor(request.value);
                    reportResult("true");
                    break;
                }

                case "GetSkyColor":
                {
                    reportResult(JsonUtility.ToJson(JsonWrapper <Color> .Wrap(gbStage.GetSkyColor())));
                    break;
                }

                case "SetSceneLighting":
                {
                    JsonWrapper <string> request = JsonUtility.FromJson <JsonWrapper <string> >(argsJson);
                    GameBuilderStage.SceneLightingMode sceneLightingMode;
                    if (Util.TryParseEnum <GameBuilderStage.SceneLightingMode>(request.value, out sceneLightingMode, ignoreCase: true))
                    {
                        gbStage.SetSceneLightingMode(sceneLightingMode);
                        reportResult("true");
                    }
                    else
                    {
                        Debug.LogError("Invalid scene lighting mode: " + request.value);
                        reportResult("false");
                    }
                    break;
                }

                case "GetSceneLighting":
                {
                    reportResult(JsonUtility.ToJson(JsonWrapper <string> .Wrap(gbStage.GetSceneLightingMode().ToString().ToUpperInvariant())));
                    break;
                }

                default:
                    Util.LogError($"VOOS script tried to call unknown service {serviceName}.");
                    break;
                }
            }
            catch (System.Exception e)
            {
                // We cannot let exceptions escape. It will tend to crash the process.
                Util.LogError($"Exception during CallService({serviceName}):\n{e}");
                reportResult("false");
            }
        }
Ejemplo n.º 22
0
        public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders)
        {
            var    fullUrl = PlayFabSettings.GetFullUrl(urlPath);
            string bodyString;

            if (request == null)
            {
                bodyString = "{}";
            }
            else
            {
                bodyString = JsonWrapper.SerializeObject(request);
            }

            var client = new HttpClient();
            HttpResponseMessage httpResponse;
            string httpResponseString;

            using (var postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString)))
            {
                postBody.Headers.Add("Content-Type", "application/json");
                if (authType != null)
                {
                    postBody.Headers.Add(authType, authKey);
                }
                postBody.Headers.Add("X-PlayFabSDK", PlayFabSettings.SdkVersionString);
                if (extraHeaders != null)
                {
                    foreach (var headerPair in extraHeaders)
                    {
                        postBody.Headers.Add(headerPair.Key, headerPair.Value);
                    }
                }

                try
                {
                    httpResponse = await client.PostAsync(fullUrl, postBody);

                    httpResponseString = await httpResponse.Content.ReadAsStringAsync();
                }
                catch (HttpRequestException e)
                {
                    return(new PlayFabError
                    {
                        Error = PlayFabErrorCode.ConnectionError,
                        ErrorMessage = e.InnerException.Message
                    });
                }
                catch (Exception e)
                {
                    return(new PlayFabError
                    {
                        Error = PlayFabErrorCode.ConnectionError,
                        ErrorMessage = e.Message
                    });
                }
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                var error = new PlayFabError();

                if (string.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();
                    return(error);
                }

                PlayFabJsonError errorResult;
                try
                {
                    errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(httpResponseString);
                }
                catch (Exception e)
                {
                    error.HttpCode     = (int)httpResponse.StatusCode;
                    error.HttpStatus   = httpResponse.StatusCode.ToString();
                    error.Error        = PlayFabErrorCode.JsonParseError;
                    error.ErrorMessage = e.Message;
                    return(error);
                }

                error.HttpCode     = errorResult.code;
                error.HttpStatus   = errorResult.status;
                error.Error        = (PlayFabErrorCode)errorResult.errorCode;
                error.ErrorMessage = errorResult.errorMessage;
                error.ErrorDetails = errorResult.errorDetails;
                return(error);
            }

            if (string.IsNullOrEmpty(httpResponseString))
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.Unknown,
                    ErrorMessage = "Internal server error"
                });
            }

            return(httpResponseString);
        }
Ejemplo n.º 23
0
        private static bool UploadStatisticDefinitions()
        {
            if (string.IsNullOrEmpty(statsDefPath))
            {
                return(false);
            }

            LogToFile("Updating Player Statistics Definitions ...");
            var parsedFile = ParseFile(statsDefPath);

            var statisticDefinitions = JsonWrapper.DeserializeObject <List <PlayerStatisticDefinition> >(parsedFile);

            foreach (var item in statisticDefinitions)
            {
                LogToFile(string.Format("\tUploading: {0}", item.StatisticName));

                var request = new CreatePlayerStatisticDefinitionRequest()
                {
                    StatisticName         = item.StatisticName,
                    VersionChangeInterval = item.VersionChangeInterval,
                    AggregationMethod     = item.AggregationMethod
                };

                var createStatTask = PlayFabAdminAPI.CreatePlayerStatisticDefinitionAsync(request);
                createStatTask.Wait();

                if (createStatTask.Result.Error != null)
                {
                    if (createStatTask.Result.Error.Error == PlayFabErrorCode.StatisticNameConflict)
                    {
                        LogToFile(string.Format("\tStatistic Already Exists, Updating values: {0}", item.StatisticName), ConsoleColor.DarkYellow);
                        var updateRequest = new UpdatePlayerStatisticDefinitionRequest()
                        {
                            StatisticName         = item.StatisticName,
                            VersionChangeInterval = item.VersionChangeInterval,
                            AggregationMethod     = item.AggregationMethod
                        };

                        var updateStatTask = PlayFabAdminAPI.UpdatePlayerStatisticDefinitionAsync(updateRequest);
                        updateStatTask.Wait();
                        if (updateStatTask.Result.Error != null)
                        {
                            OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName, updateStatTask.Result.Error);
                        }
                        else
                        {
                            LogToFile(string.Format("\t\tStatistics Definition: {0} Updated ", item.StatisticName), ConsoleColor.Green);
                        }
                    }
                    else
                    {
                        OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName, createStatTask.Result.Error);
                    }
                }
                else
                {
                    LogToFile(string.Format("\t\tStatistics Definition: {0} Created ", item.StatisticName), ConsoleColor.Green);
                }
            }
            return(true);
        }
Ejemplo n.º 24
0
        public bool Evaluate(out IJsonValue value, IJSONDocument document)
        {
            value = null;
            if (document == null)
            {
                return(false);
            }

            if (!document.Contains(_name))
            {
                return(false);
            }

            IJsonValue outValue;

            outValue = value = JsonWrapper.Wrap(document[_name]);

            if (_childAttribute == null && _indecies == null && value.DataType != FieldDataType.Array)
            {
                return(true);
            }

            if (outValue.DataType != FieldDataType.Array &&
                outValue.DataType != FieldDataType.Object)
            {
                value = null;
                return(false);
            }

            if (_indecies != null)
            {
                foreach (int index in _indecies)
                {
                    if (outValue.DataType != FieldDataType.Array)
                    {
                        value = null;
                        return(false);
                    }

                    var values = ((IJsonValue[])((ArrayJsonValue)outValue).WrapedValue);

                    if (values.Length - 1 < index)
                    {
                        return(false);
                    }

                    outValue = value = values[index];
                }
            }

            if (_childAttribute == null && value.DataType != FieldDataType.Array)
            {
                return(true);
            }

            if (outValue.DataType == FieldDataType.Object)
            {
                return(_childAttribute.Evaluate(out value, (IJSONDocument)outValue.Value));
            }

            EmbeddedList embededValues = new EmbeddedList();

            var arrayValues = ((IJsonValue[])((ArrayJsonValue)outValue).WrapedValue);

            foreach (var arrayValue in arrayValues)
            {
                IJsonValue embededValue;

                if (arrayValue.DataType == FieldDataType.Object)
                {
                    if (_childAttribute == null)
                    {
                        if (value.DataType == FieldDataType.Array)
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    //else
                    //{
                    //    return false;
                    //}

                    if (_childAttribute.Evaluate(out embededValue, (IJSONDocument)arrayValue.Value))
                    {
                        if (outValue is EmbeddedList)
                        {
                            embededValues.AddRange(embededValue as EmbeddedList);
                        }
                        else
                        {
                            embededValues.Add(embededValue);
                        }
                    }
                }
                //else if(arrayValue.DataType != FieldDataType.Array)
                else
                {
                    embededValues.Add(arrayValue);
                }
            }

            value = embededValues;
            return(true);
        }
Ejemplo n.º 25
0
        public void MakeApiCall(CallRequestContainer reqContainer)
        {
            reqContainer.RequestHeaders["Content-Type"] = "application/json";

#if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL
            if (PlayFabSettings.CompressApiData)
            {
                reqContainer.RequestHeaders["Content-Encoding"] = "GZIP";
                reqContainer.RequestHeaders["Accept-Encoding"]  = "GZIP";

                using (var stream = new MemoryStream())
                {
                    using (var zipstream = new GZipStream(stream, CompressionMode.Compress, CompressionLevel.BestCompression))
                    {
                        zipstream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
                    }
                    reqContainer.Payload = stream.ToArray();
                }
            }
#endif

            //Debug.LogFormat("Posting {0} to Url: {1}", req.Trim(), url);
            var www = new WWW(reqContainer.FullUrl, reqContainer.Payload, reqContainer.RequestHeaders);

#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
#endif

            // Start the www corouting to Post, and get a response or error which is then passed to the callbacks.
            Action <string> wwwSuccessCallback = (response) =>
            {
                try
                {
#if PLAYFAB_REQUEST_TIMING
                    var startTime = DateTime.UtcNow;
#endif
                    var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(response);

                    if (httpResult.code == 200)
                    {
                        // We have a good response from the server
                        reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResult.data);
                        reqContainer.DeserializeResultJson();
                        reqContainer.ApiResult.Request    = reqContainer.ApiRequest;
                        reqContainer.ApiResult.CustomData = reqContainer.CustomData;

#if !DISABLE_PLAYFABCLIENT_API
                        var res    = reqContainer.ApiResult as ClientModels.LoginResult;
                        var regRes = reqContainer.ApiResult as ClientModels.RegisterPlayFabUserResult;
                        if (res != null)
                        {
                            AuthKey = res.SessionTicket;
                        }
                        else if (regRes != null)
                        {
                            AuthKey = regRes.SessionTicket;
                        }

                        Debug.Log("WWW Success Callback: " + reqContainer.ApiEndpoint + " " + (res == null) + " " + (regRes == null));
                        if (res != null || regRes != null)
                        {
                            PlayFabDeviceUtil.OnPlayFabLogin(res, regRes);
                        }
#endif
                        try
                        {
                            PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }

#if PLAYFAB_REQUEST_TIMING
                        stopwatch.Stop();
                        var timing = new PlayFabHttp.RequestTiming {
                            StartTimeUtc        = startTime,
                            ApiEndpoint         = reqContainer.ApiEndpoint,
                            WorkerRequestMs     = (int)stopwatch.ElapsedMilliseconds,
                            MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
                        };
                        PlayFabHttp.SendRequestTiming(timing);
#endif
                        try
                        {
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    }
                    else
                    {
                        if (reqContainer.ErrorCallback != null)
                        {
                            reqContainer.Error = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData);
                            PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                            reqContainer.ErrorCallback(reqContainer.Error);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            };

            Action <string> wwwErrorCallback = (errorCb) =>
            {
                reqContainer.JsonResponse = errorCb;
                if (reqContainer.ErrorCallback != null)
                {
                    reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData);
                    PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                    reqContainer.ErrorCallback(reqContainer.Error);
                }
            };

            PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback));
        }
Ejemplo n.º 26
0
        public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders)
        {
            var    fullUrl = PlayFabSettings.GetFullUrl(urlPath);
            string bodyString;

            if (request == null)
            {
                bodyString = "{}";
            }
            else
            {
                bodyString = JsonWrapper.SerializeObject(request);
            }

            var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(fullUrl));

            requestMessage.Content = new HttpStringContent(bodyString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            if (authType != null)
            {
                requestMessage.Headers.Add(new KeyValuePair <string, string>(authType, authKey));
            }
            requestMessage.Headers.Add(new KeyValuePair <string, string>("X-PlayFabSDK", PlayFabSettings.SdkVersionString));
            if (extraHeaders != null)
            {
                foreach (var headerPair in extraHeaders)
                {
                    requestMessage.Headers.Add(headerPair);
                }
            }

            HttpResponseMessage httpResponse;
            string httpResponseString;

            try
            {
                httpResponse = await _client.SendRequestAsync(requestMessage);

                httpResponseString = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.ConnectionError,
                    ErrorMessage = e.Message
                });
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                var error = new PlayFabError();

                if (string.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();
                    return(error);
                }

                PlayFabJsonError errorResult;
                try
                {
                    errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(httpResponseString);
                }
                catch (Exception e)
                {
                    error.HttpCode     = (int)httpResponse.StatusCode;
                    error.HttpStatus   = httpResponse.StatusCode.ToString();
                    error.Error        = PlayFabErrorCode.JsonParseError;
                    error.ErrorMessage = e.Message;
                    return(error);
                }

                error.HttpCode     = errorResult.code;
                error.HttpStatus   = errorResult.status;
                error.Error        = (PlayFabErrorCode)errorResult.errorCode;
                error.ErrorMessage = errorResult.errorMessage;
                error.ErrorDetails = errorResult.errorDetails;
                return(error);
            }

            if (string.IsNullOrEmpty(httpResponseString))
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.Unknown,
                    ErrorMessage = "Internal server error"
                });
            }

            return(httpResponseString);
        }
Ejemplo n.º 27
0
        public async Task <bool> UploadStatisticDefinitions()
        {
            if (string.IsNullOrEmpty(statsDefPath))
            {
                LogToFile("Player Statistics Definitions File Path is Null ");
                return(true);
            }


            LogToFile("Updating Player Statistics Definitions ...");
            var parsedFile = ParseFile(statsDefPath);

            var statisticDefinitions = JsonWrapper.DeserializeObject <List <PlayerStatisticDefinition> >(parsedFile);

            foreach (var item in statisticDefinitions)
            {
                LogToFile("\tUploading: " + item.StatisticName);

                var request = new CreatePlayerStatisticDefinitionRequest()
                {
                    StatisticName         = item.StatisticName,
                    VersionChangeInterval = item.VersionChangeInterval,
                    AggregationMethod     = item.AggregationMethod
                };

                if (token.IsCancellationRequested)
                {
                    return(true);
                }

                var createStatTask = await PlayFabAdminAPI.CreatePlayerStatisticDefinitionAsync(request);

                if (createStatTask.Error != null)
                {
                    if (createStatTask.Error.Error == PlayFabErrorCode.StatisticNameConflict)
                    {
                        LogToFile("\tStatistic Already Exists, Updating values: " + item.StatisticName,
                                  ConsoleColor.DarkYellow);
                        var updateRequest = new UpdatePlayerStatisticDefinitionRequest()
                        {
                            StatisticName         = item.StatisticName,
                            VersionChangeInterval = item.VersionChangeInterval,
                            AggregationMethod     = item.AggregationMethod
                        };

                        if (token.IsCancellationRequested)
                        {
                            return(true);
                        }

                        var updateStatTask = await PlayFabAdminAPI.UpdatePlayerStatisticDefinitionAsync(updateRequest);

                        //updateStatTask.Wait();
                        if (updateStatTask.Error != null)
                        {
                            OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName,
                                               updateStatTask.Error);
                        }
                        else
                        {
                            LogToFile("\t\tStatistics Definition:" + item.StatisticName + " Updated",
                                      ConsoleColor.Green);
                        }
                    }
                    else
                    {
                        OutputPlayFabError("\t\tStatistics Definition Error: " + item.StatisticName,
                                           createStatTask.Error);
                    }
                }
                else
                {
                    LogToFile("\t\tStatistics Definition: " + item.StatisticName + " Created", ConsoleColor.Green);
                }
            }

            return(true);
        }
Ejemplo n.º 28
0
 void OnCloudGameOverRewards(ExecuteCloudScriptResult result)
 {
     Debug.Log(JsonWrapper.SerializeObject(result.FunctionResult));
 }
Ejemplo n.º 29
0
        public static bool ExecuteCloudScript <TIn, TOut>(string functionName, TIn functionParameter, Dictionary <string, string> extraHeaders, out TOut result, out string errorReport)
        {
            // Perform the request
            var request = new ExecuteCloudScriptRequest
            {
                FunctionName            = functionName,
                FunctionParameter       = functionParameter,
                GeneratePlayStreamEvent = true
            };
            var task = PlayFabClientAPI.ExecuteCloudScriptAsync(request, null, extraHeaders);

            task.Wait();
            errorReport = PlayFabUtil.GetCloudScriptErrorReport(task.Result);

            if (task.Result.Error != null)
            {
                Console.WriteLine("Execute Cloudscript failure: " + functionName + ":\n" + JsonWrapper.SerializeObject(functionParameter));
                Console.WriteLine(errorReport);
                result = default(TOut);
                return(false);
            }

            // Re-serialize as the target type
            var json = JsonWrapper.SerializeObject(task.Result.Result.FunctionResult);

            if (verbose)
            {
                Console.WriteLine("===== Verbose ExecuteCloudScript Json: =====");
                Console.WriteLine(json);
                Console.WriteLine("===== End =====");
            }
            try
            {
                result = JsonWrapper.DeserializeObject <TOut>(json);
            }
            catch (Exception)
            {
                Console.WriteLine("Could not serialize text: \"" + json + "\" as " + typeof(TOut).Name);
                result = default(TOut);
                return(false);
            }
            return(task.Result.Error == null && task.Result.Result.Error == null && (result != null || json == "null"));
        }
Ejemplo n.º 30
0
        protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false) where TResult : PlayFabResultCommon
        {
            PlayFabHttp.InitializeHttp();
            PlayFabHttp.SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);
            CallRequestContainer reqContainer = new CallRequestContainer
            {
                ApiEndpoint    = apiEndpoint,
                FullUrl        = PlayFabSettings.GetFullUrl(apiEndpoint),
                CustomData     = customData,
                Payload        = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)),
                ApiRequest     = request,
                ErrorCallback  = errorCallback,
                RequestHeaders = (extraHeaders ?? new Dictionary <string, string>())
            };

            foreach (KeyValuePair <string, string> keyValuePair in PlayFabHttp.GlobalHeaderInjection)
            {
                if (!reqContainer.RequestHeaders.ContainsKey(keyValuePair.Key))
                {
                    reqContainer.RequestHeaders[keyValuePair.Key] = keyValuePair.Value;
                }
            }
            reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true";
            reqContainer.RequestHeaders["X-PlayFabSDK"]           = "UnitySDK-2.39.180409";
            if (authType != AuthType.LoginSession)
            {
                if (authType == AuthType.EntityToken)
                {
                    reqContainer.RequestHeaders["X-EntityToken"] = PlayFabHttp._internalHttp.EntityToken;
                }
            }
            else
            {
                reqContainer.RequestHeaders["X-Authorization"] = PlayFabHttp._internalHttp.AuthKey;
            }
            reqContainer.DeserializeResultJson = delegate()
            {
                reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse);
            };
            reqContainer.InvokeSuccessCallback = delegate()
            {
                if (resultCallback != null)
                {
                    resultCallback((TResult)((object)reqContainer.ApiResult));
                }
            };
            if (allowQueueing && PlayFabHttp._apiCallQueue != null && !PlayFabHttp._internalHttp.SessionStarted)
            {
                for (int i = PlayFabHttp._apiCallQueue.Count - 1; i >= 0; i--)
                {
                    if (PlayFabHttp._apiCallQueue[i].ApiEndpoint == apiEndpoint)
                    {
                        PlayFabHttp._apiCallQueue.RemoveAt(i);
                    }
                }
                PlayFabHttp._apiCallQueue.Add(reqContainer);
            }
            else
            {
                PlayFabHttp._internalHttp.MakeApiCall(reqContainer);
            }
        }