Last active
October 12, 2024 16:40
-
-
Save caglarenes/dee5cc41f8ae695928494b0e05d76e9d to your computer and use it in GitHub Desktop.
BestHTTP/2 with PlayFab SDK - Example transport plug-in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// EXAMPLE TRANSPORT PLUG-IN FOR USAGE OF BESTHTTP/2 WITH PLAYFAB SDK | |
// YOU MUST SET THIS TRANSPORT PLUG-IN BEFORE ANY PLAYFAB CALL | |
// PluginManager.SetPlugin(new PlayFabBestHttp(), PluginContract.PlayFab_Transport); | |
#if UNITY_2017_2_OR_NEWER | |
using PlayFab.SharedModels; | |
using System; | |
using UnityEngine; | |
using BestHTTP; | |
namespace PlayFab.Internal | |
{ | |
public class PlayFabBestHttp : ITransportPlugin | |
{ | |
private bool _isInitialized = false; | |
private readonly int _pendingWwwMessages = 0; | |
public bool IsInitialized { get { return _isInitialized; } } | |
public void Initialize() { _isInitialized = true; } | |
public void Update() { } | |
public void OnDestroy() { } | |
public void SimpleGetCall(string fullUrl, Action<byte[]> successCallback, Action<string> errorCallback) | |
{ | |
SimpleCallCoroutine("get", fullUrl, null, successCallback, errorCallback); | |
} | |
public void SimplePutCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) | |
{ | |
SimpleCallCoroutine("put", fullUrl, payload, successCallback, errorCallback); | |
} | |
public void SimplePostCall(string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) | |
{ | |
SimpleCallCoroutine("post", fullUrl, payload, successCallback, errorCallback); | |
} | |
private static void SimpleCallCoroutine(string method, string fullUrl, byte[] payload, Action<byte[]> successCallback, Action<string> errorCallback) | |
{ | |
if (payload == null) | |
{ | |
HTTPRequest requestGet = new(new Uri(fullUrl), (HTTPRequest originalRequest, HTTPResponse response) => { OnRequestFinished(originalRequest, response, successCallback, errorCallback); }); | |
requestGet.Send(); | |
} | |
else | |
{ | |
if (method == "put") | |
{ | |
HTTPRequest requestPut = new(new Uri(fullUrl), HTTPMethods.Put, (HTTPRequest originalRequest, HTTPResponse response) => { OnRequestFinished(originalRequest, response, successCallback, errorCallback); }) | |
{ | |
RawData = payload | |
}; | |
requestPut.Send(); | |
} | |
else | |
{ | |
HTTPRequest requestPost = new(new Uri(fullUrl), HTTPMethods.Post, (HTTPRequest originalRequest, HTTPResponse response) => { OnRequestFinished(originalRequest, response, successCallback, errorCallback); }) | |
{ | |
RawData = payload | |
}; | |
requestPost.AddHeader("Content-Type", "application/json"); | |
requestPost.Send(); | |
} | |
} | |
} | |
public void MakeApiCall(object reqContainerObj) | |
{ | |
CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj; | |
HTTPRequest requestApiCall = new(new Uri(reqContainer.FullUrl), HTTPMethods.Post, (HTTPRequest originalRequest, HTTPResponse response) => { OnPostRequestFinished(originalRequest, response, reqContainer); }) | |
{ | |
RawData = reqContainer.Payload | |
}; | |
requestApiCall.AddHeader("Content-Type", "application/json"); | |
foreach (var headerPair in reqContainer.RequestHeaders) | |
{ | |
if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value)) | |
{ | |
requestApiCall.AddHeader(headerPair.Key, headerPair.Value); | |
} | |
else | |
{ | |
Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value); | |
} | |
} | |
requestApiCall.Send(); | |
} | |
public static void OnRequestFinished(HTTPRequest originalRequest, HTTPResponse response, Action<byte[]> OnSuccess, Action<string> OnError) | |
{ | |
switch (originalRequest.State) | |
{ | |
// The request finished without any problem. | |
case HTTPRequestStates.Finished: | |
if (response.IsSuccess) | |
{ | |
OnSuccess.Invoke(response.Data); | |
} | |
else | |
{ | |
Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", response.StatusCode, response.Message, response.DataAsText)); | |
OnError.Invoke(response.DataAsText); | |
} | |
break; | |
// The request finished with an unexpected error. The request's Exception property may contain more info about the error. | |
case HTTPRequestStates.Error: | |
Debug.LogError("Request Finished with Error! " + (originalRequest.Exception != null ? (originalRequest.Exception.Message + "\n" + originalRequest.Exception.StackTrace) : "No Exception")); | |
OnError.Invoke("Request Finished with Error!"); | |
break; | |
// The request aborted, initiated by the user. | |
case HTTPRequestStates.Aborted: | |
Debug.LogWarning("Request Aborted!"); | |
OnError.Invoke("Request Aborted!"); | |
break; | |
// Connecting to the server is timed out. | |
case HTTPRequestStates.ConnectionTimedOut: | |
Debug.LogError("Connection Timed Out!"); | |
OnError.Invoke("Connection Timed Out!"); | |
break; | |
// The request didn't finished in the given time. | |
case HTTPRequestStates.TimedOut: | |
Debug.LogError("Processing the request Timed Out!"); | |
OnError.Invoke("Processing the request Timed Out!"); | |
break; | |
} | |
} | |
public void OnPostRequestFinished(HTTPRequest originalRequest, HTTPResponse response, CallRequestContainer reqContainer) | |
{ | |
switch (originalRequest.State) | |
{ | |
// The request finished without any problem. | |
case HTTPRequestStates.Finished: | |
if (response.IsSuccess) | |
{ | |
OnResponse(response.DataAsText, reqContainer); | |
} | |
else | |
{ | |
Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}", response.StatusCode, response.Message, response.DataAsText)); | |
OnError(response.DataAsText, reqContainer); | |
} | |
break; | |
// The request finished with an unexpected error. The request's Exception property may contain more info about the error. | |
case HTTPRequestStates.Error: | |
Debug.LogError("Request Finished with Error! " + (originalRequest.Exception != null ? (originalRequest.Exception.Message + "\n" + originalRequest.Exception.StackTrace) : "No Exception")); | |
OnError("Request Finished with Error!", reqContainer); | |
break; | |
// The request aborted, initiated by the user. | |
case HTTPRequestStates.Aborted: | |
Debug.LogWarning("Request Aborted!"); | |
OnError("Request Aborted!", reqContainer); | |
break; | |
// Connecting to the server is timed out. | |
case HTTPRequestStates.ConnectionTimedOut: | |
Debug.LogError("Connection Timed Out!"); | |
OnError("Connection Timed Out!", reqContainer); | |
break; | |
// The request didn't finished in the given time. | |
case HTTPRequestStates.TimedOut: | |
Debug.LogError("Processing the request Timed Out!"); | |
OnError("Processing the request Timed Out!", reqContainer); | |
break; | |
} | |
} | |
public int GetPendingMessages() | |
{ | |
return _pendingWwwMessages; | |
} | |
public void OnResponse(string response, CallRequestContainer reqContainer) | |
{ | |
try | |
{ | |
#if PLAYFAB_REQUEST_TIMING | |
var startTime = DateTime.UtcNow; | |
#endif | |
var serializer = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); | |
var httpResult = serializer.DeserializeObject<HttpResponseObject>(response); | |
if (httpResult.code == 200) | |
{ | |
// We have a good response from the server | |
reqContainer.JsonResponse = serializer.SerializeObject(httpResult.data); | |
reqContainer.DeserializeResultJson(); | |
reqContainer.ApiResult.Request = reqContainer.ApiRequest; | |
reqContainer.ApiResult.CustomData = reqContainer.CustomData; | |
PlayFabHttp.instance.OnPlayFabApiResult(reqContainer); | |
#if !DISABLE_PLAYFABCLIENT_API | |
PlayFabDeviceUtil.OnPlayFabLogin(reqContainer.ApiResult, reqContainer.settings, reqContainer.instanceApi); | |
#endif | |
try | |
{ | |
PlayFabHttp.SendEvent(reqContainer.ApiEndpoint, reqContainer.ApiRequest, reqContainer.ApiResult, ApiProcessingEventType.Post); | |
} | |
catch (Exception e) | |
{ | |
Debug.LogException(e); | |
} | |
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); | |
} | |
} | |
public void OnError(string error, CallRequestContainer reqContainer) | |
{ | |
reqContainer.JsonResponse = error; | |
if (reqContainer.ErrorCallback != null) | |
{ | |
reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.ApiEndpoint, reqContainer.JsonResponse, reqContainer.CustomData); | |
PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, reqContainer.Error); | |
reqContainer.ErrorCallback(reqContainer.Error); | |
} | |
} | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment