Example #1
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));
        }
Example #2
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
}

Example #3
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 string SerializeObject(object obj)
 {
     return(JsonWrapper.SerializeObject(obj, PlayFabUtil.ApiSerializerStrategy));
 }
 public static string SerializeObject(object obj, IJsonSerializerStrategy strategy)
 {
     return(JsonWrapper.SerializeObject(obj, strategy));
 }
Example #6
0
        public void MakeApiCall(CallRequestContainer reqContainer)
        {
            reqContainer.RequestHeaders["Content-Type"] = "application/json";
            if (PlayFabSettings.CompressApiData)
            {
                reqContainer.RequestHeaders["Content-Encoding"] = "GZIP";
                reqContainer.RequestHeaders["Accept-Encoding"]  = "GZIP";
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression))
                    {
                        gzipStream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length);
                    }
                    reqContainer.Payload = memoryStream.ToArray();
                }
            }
            WWW             www = new WWW(reqContainer.FullUrl, reqContainer.Payload, reqContainer.RequestHeaders);
            Action <string> wwwSuccessCallback = delegate(string response)
            {
                try
                {
                    HttpResponseObject httpResponseObject = JsonWrapper.DeserializeObject <HttpResponseObject>(response);
                    if (httpResponseObject.code == 200)
                    {
                        reqContainer.JsonResponse = JsonWrapper.SerializeObject(httpResponseObject.data);
                        reqContainer.DeserializeResultJson();
                        reqContainer.ApiResult.Request    = reqContainer.ApiRequest;
                        reqContainer.ApiResult.CustomData = reqContainer.CustomData;
                        SingletonMonoBehaviour <PlayFabHttp> .instance.OnPlayFabApiResult(reqContainer.ApiResult);

                        PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult);
                        try
                        {
                            PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                        }
                        catch (Exception ex)
                        {
                        }
                        try
                        {
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception ex2)
                        {
                        }
                    }
                    else if (reqContainer.ErrorCallback != null)
                    {
                        reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, response, reqContainer.CustomData);
                        PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                        reqContainer.ErrorCallback(reqContainer.Error);
                    }
                }
                catch (Exception ex3)
                {
                }
            };
            Action <string> wwwErrorCallback = delegate(string errorCb)
            {
                reqContainer.JsonResponse = errorCb;
                if (reqContainer.ErrorCallback != null)
                {
                    reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData);
                    PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                    reqContainer.ErrorCallback(reqContainer.Error);
                }
            };

            SingletonMonoBehaviour <PlayFabHttp> .instance.StartCoroutine(this.PostPlayFabApiCall(www, wwwSuccessCallback, wwwErrorCallback));
        }
Example #7
0
        private static void ProcessJsonResponse(CallRequestContainer reqContainer)
        {
            try
            {
                var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(reqContainer.JsonResponse,
                                                                                    PlayFabUtil.ApiSerializerStrategy);

#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)
                {
                    reqContainer.Error     = PlayFabHttp.GeneratePlayFabErrorGeneric(reqContainer.JsonResponse, null, reqContainer.CustomData);
                    reqContainer.HttpState = HttpRequestState.Error;
                    lock (ResultQueue)
                    {
                        //Queue The result callbacks to run on the main thread.
                        ResultQueue.Enqueue(() =>
                        {
                            PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                            if (reqContainer.ErrorCallback != null)
                            {
                                reqContainer.ErrorCallback(reqContainer.Error);
                            }
                        });
                    }
                    return;
                }

                if (httpResult.code != 200)
                {
                    reqContainer.Error     = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData);
                    reqContainer.HttpState = HttpRequestState.Error;
                    lock (ResultQueue)
                    {
                        //Queue The result callbacks to run on the main thread.
                        ResultQueue.Enqueue(() =>
                        {
                            PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                            if (reqContainer.ErrorCallback != null)
                            {
                                reqContainer.ErrorCallback(reqContainer.Error);
                            }
                        });
                    }
                    return;
                }

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

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

                if (userSettings != null && _authKey != null && userSettings.NeedsAttribution)
                {
                    lock (ResultQueue)
                    {
                        ResultQueue.Enqueue(PlayFabIdfa.OnPlayFabLogin);
                    }
                }

                var cloudScriptUrl = reqContainer.ApiResult as GetCloudScriptUrlResult;
                if (cloudScriptUrl != null)
                {
                    PlayFabSettings.LogicServerUrl = cloudScriptUrl.Url;
                }
#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.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post);
                            reqContainer.InvokeSuccessCallback();
                        }
                        catch (Exception e)
                        {
                            Debug.LogException(e);
                        }
                    });
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                reqContainer.HttpState = HttpRequestState.Error;
            }
        }
Example #8
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()));
            }
        }
Example #9
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);
        }
Example #10
0
        static private void OnGetSomeShip(ExecuteCloudScriptResult result)
        {
            string ship = JsonWrapper.SerializeObject(result.FunctionResult);

            Debug.Log(ship);
        }
Example #11
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);
        }
        private static void SaveToEditorPrefs(object obj, string key)
        {
            var json = JsonWrapper.SerializeObject(obj);

            EditorPrefs.SetString(KeyPrefix + key, json);
        }
Example #13
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);
            }
        }
 void OnPushReceived(PlayFabNotificationPackage package)
 {
     _lastMessageReceived = JsonWrapper.SerializeObject(package);
 }
Example #15
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);
            }
        }
Example #16
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);
        }
Example #17
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"));
        }
Example #18
0
 void OnCloudGameOverRewards(ExecuteCloudScriptResult result)
 {
     Debug.Log(JsonWrapper.SerializeObject(result.FunctionResult));
 }
Example #19
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;

                        PlayFabHttp.instance.OnPlayFabApiResult(reqContainer.ApiResult);
#if !DISABLE_PLAYFABCLIENT_API
                        PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult);
#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(reqContainer.ApiEndpoint, 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.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData);
                    PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error);
                    reqContainer.ErrorCallback(reqContainer.Error);
                }
            };

            PlayFabHttp.instance.StartCoroutine(PostPlayFabApiCall(www, wwwSuccessCallback, wwwErrorCallback));
        }
Example #20
0
    public void FindOpponentReplay(int trackIndex, int playerLevel, int handiCap, Action <string> callback)
    {
        if (!Singleton <PlayFabManager> .Instance.Initialized)
        {
            return;
        }
        ExecuteCloudScriptRequest request = new ExecuteCloudScriptRequest
        {
            FunctionName      = "fetchOpponentReplay",
            FunctionParameter = new
            {
                trackIndex  = trackIndex,
                playerLevel = playerLevel,
                handicap    = handiCap
            }
        };

        PlayFabClientAPI.ExecuteCloudScript(request, delegate(ExecuteCloudScriptResult result)
        {
            if (result.Logs != null)
            {
                foreach (LogStatement logStatement in result.Logs)
                {
                    StringBuilder stringBuilder = new StringBuilder();
                    if (logStatement.Data != null)
                    {
                        stringBuilder.AppendFormat("Data: '{0}'\n", logStatement.Data);
                    }
                    if (!string.IsNullOrEmpty(logStatement.Level))
                    {
                        stringBuilder.AppendFormat("Level: '{0}'\n", logStatement.Level);
                    }
                    if (!string.IsNullOrEmpty(logStatement.Message))
                    {
                        stringBuilder.AppendFormat("Message: '{0}'\n", logStatement.Message);
                    }
                }
            }
            string key = "replay";
            string obj = string.Empty;
            UnityEngine.Debug.Log("[PlayFabManager] result.FunctionResult: " + JsonWrapper.SerializeObject(result.FunctionResult));
            JsonObject jsonObject = (JsonObject)result.FunctionResult;
            if (jsonObject != null)
            {
                if (jsonObject.ContainsKey(key) && jsonObject[key] is JsonObject && ((JsonObject)jsonObject[key]).ContainsKey("Value"))
                {
                    obj = ((JsonObject)jsonObject[key])["Value"].ToString();
                }
                else
                {
                    CakeRaceMenu.UseDefaultReplay = true;
                }
            }
            if (callback != null)
            {
                callback(obj);
            }
        }, delegate(PlayFabError error)
        {
            CakeRaceMenu.UseDefaultReplay = true;
            if (callback != null)
            {
                callback(string.Empty);
            }
        }, null, null);
    }