public void MakeApiCall(CallRequestContainer reqContainer) { reqContainer.HttpState = HttpRequestState.Idle; lock (ActiveRequests) { ActiveRequests.Insert(0, reqContainer); } ActivateThreadWorker(); }
private static void Post(CallRequestContainer reqContainer) { try { reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl); reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _unityVersion; reqContainer.HttpRequest.SendChunked = false; reqContainer.HttpRequest.Proxy = null; // Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's. reqContainer.HttpRequest.Headers.Add("X-ReportErrorAsSuccess", "true"); // Without this, we have to catch WebException instead, and manually decode the result reqContainer.HttpRequest.Headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString); switch (reqContainer.AuthKey) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API case AuthType.DevSecretKey: reqContainer.HttpRequest.Headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey); break; #endif case AuthType.LoginSession: reqContainer.HttpRequest.Headers.Add("X-Authorization", _authKey); break; } reqContainer.HttpRequest.ContentType = "application/json"; reqContainer.HttpRequest.Method = "POST"; reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive; reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout; reqContainer.HttpRequest.AllowWriteStreamBuffering = false; reqContainer.HttpRequest.Proxy = null; reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength; reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout; //Debug.Log("Get Stream"); // Get Request Stream and send data in the body. using (var stream = reqContainer.HttpRequest.GetRequestStream()) { //Debug.Log("Post Stream"); stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); //Debug.Log("After Post stream"); } reqContainer.HttpState = HttpRequestState.Sent; } catch (WebException e) { reqContainer.JsonResponse = ResponseToString(e.Response) ?? e.Status + ": WebException making http request to: " + reqContainer.FullUrl; var enhancedError = new WebException(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } catch (Exception e) { reqContainer.JsonResponse = "Unhandled exception in Post : " + reqContainer.FullUrl; var enhancedError = new Exception(reqContainer.JsonResponse, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } }
/// <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 }; // Append any additional headers foreach (var pair in GlobalHeaderInjection) { if (!reqContainer.RequestHeaders.ContainsKey(pair.Key)) { reqContainer.RequestHeaders[pair.Key] = pair.Value; } } #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; case AuthType.EntityToken: reqContainer.RequestHeaders["X-EntityToken"] = _internalHttp.EntityToken; 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); } }
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)); }
private IEnumerator Post(CallRequestContainer reqContainer) { #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif var www = new UnityWebRequest(reqContainer.FullUrl) { uploadHandler = new UploadHandlerRaw(reqContainer.Payload), downloadHandler = new DownloadHandlerBuffer(), method = "POST" }; foreach (var headerPair in reqContainer.RequestHeaders) { www.SetRequestHeader(headerPair.Key, headerPair.Value); } yield return(www.Send()); #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 if (!string.IsNullOrEmpty(www.error)) { OnError(www.error, reqContainer); } else { try { #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL string encoding; if (www.GetResponseHeaders().TryGetValue("Content-Encoding", out encoding) && encoding.ToLower() == "gzip") { var stream = new MemoryStream(www.downloadHandler.data); using (var gZipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress, false)) { var buffer = new byte[4096]; using (var output = new MemoryStream()) { int read; while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } output.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(output); var jsonResponse = streamReader.ReadToEnd(); //Debug.Log(jsonResponse); OnResponse(jsonResponse, reqContainer); } } } else #endif { OnResponse(www.downloadHandler.text, reqContainer); } } catch (Exception e) { OnError("Unhandled error in PlayFabWWW: " + e, reqContainer); } } }
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 = 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) { var playFabError = PlayFabHttp.GeneratePlayFabError(response, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, playFabError); reqContainer.ErrorCallback(playFabError); } } } catch (Exception e) { Debug.LogException(e); } }; Action <string> wwwErrorCallback = (errorCb) => { if (reqContainer.ErrorCallback != null) { var playFabError = PlayFabHttp.GeneratePlayFabErrorGeneric(errorCb, null, reqContainer.CustomData); PlayFabHttp.SendErrorEvent(reqContainer.ApiRequest, playFabError); reqContainer.ErrorCallback(playFabError); } }; PlayFabHttp.instance.StartCoroutine(Post(www, wwwSuccessCallback, wwwErrorCallback)); }
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; } }
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 || httpResult.code != 200) { QueueRequestError(reqContainer); 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 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) { lock (ResultQueue) { ResultQueue.Enqueue(PlayFabIdfa.OnPlayFabLogin); } } var cloudScriptUrl = reqContainer.ApiResult as ClientModels.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); // 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 void MakeApiCall(CallRequestContainer reqContainer) { //Set headers var headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }; if (reqContainer.AuthKey == AuthType.DevSecretKey) { #if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API headers.Add("X-SecretKey", PlayFabSettings.DeveloperSecretKey); #endif } 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) => { 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)); }
/// <summary> /// Internal method for Make API Calls /// </summary> private static void _MakeApiCall <TResult>(string apiEndpoint, string fullUrl, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData, Dictionary <string, string> extraHeaders, bool allowQueueing, PlayFabAuthenticationContext authenticationContext, PlayFabApiSettings apiSettings, IPlayFabInstanceApi instanceApi) where TResult : PlayFabResultCommon { InitializeHttp(); SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre); var serializer = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer); var reqContainer = new CallRequestContainer { ApiEndpoint = apiEndpoint, FullUrl = fullUrl, settings = apiSettings, context = authenticationContext, CustomData = customData, Payload = Encoding.UTF8.GetBytes(serializer.SerializeObject(request)), ApiRequest = request, ErrorCallback = errorCallback, RequestHeaders = extraHeaders ?? new Dictionary <string, string>(), // Use any headers provided by the customer instanceApi = instanceApi }; // Append any additional headers foreach (var pair in GlobalHeaderInjection) { if (!reqContainer.RequestHeaders.ContainsKey(pair.Key)) { reqContainer.RequestHeaders[pair.Key] = pair.Value; } } #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.StartTimeUtc = DateTime.UtcNow; reqContainer.Timing.ApiEndpoint = apiEndpoint; #endif // Add PlayFab Headers var transport = PluginManager.GetPlugin <ITransportPlugin>(PluginContract.PlayFab_Transport); 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 || UNITY_EDITOR case AuthType.DevSecretKey: if (apiSettings.DeveloperSecretKey == null) { throw new PlayFabException(PlayFabExceptionCode.DeveloperKeyNotSet, "DeveloperSecretKey is not found in Request, Server Instance or PlayFabSettings"); } reqContainer.RequestHeaders["X-SecretKey"] = apiSettings.DeveloperSecretKey; break; #endif #if !DISABLE_PLAYFABCLIENT_API case AuthType.LoginSession: if (authenticationContext != null) { reqContainer.RequestHeaders["X-Authorization"] = authenticationContext.ClientSessionTicket; } break; #endif #if !DISABLE_PLAYFABENTITY_API case AuthType.EntityToken: if (authenticationContext != null) { reqContainer.RequestHeaders["X-EntityToken"] = authenticationContext.EntityToken; } break; #endif } // These closures preserve the TResult generic information in a way that's safe for all the devices reqContainer.DeserializeResultJson = () => { reqContainer.ApiResult = serializer.DeserializeObject <TResult>(reqContainer.JsonResponse); }; reqContainer.InvokeSuccessCallback = () => { if (resultCallback != null) { resultCallback((TResult)reqContainer.ApiResult); } }; if (allowQueueing && _apiCallQueue != null) { for (var i = _apiCallQueue.Count - 1; i >= 0; i--) { if (_apiCallQueue[i].ApiEndpoint == apiEndpoint) { _apiCallQueue.RemoveAt(i); } } _apiCallQueue.Add(reqContainer); } else { transport.MakeApiCall(reqContainer); } }
private IEnumerator Post(CallRequestContainer reqContainer) { #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); var startTime = DateTime.UtcNow; #endif var www = new UnityWebRequest(reqContainer.FullUrl) { uploadHandler = new UploadHandlerRaw(reqContainer.Payload), downloadHandler = new DownloadHandlerBuffer(), method = "POST" }; foreach (var headerPair in reqContainer.RequestHeaders) { if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value)) { www.SetRequestHeader(headerPair.Key, headerPair.Value); } else { Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value); } } #if UNITY_2017_2_OR_NEWER yield return(www.SendWebRequest()); #else yield return(www.Send()); #endif #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 if (!string.IsNullOrEmpty(www.error)) { OnError(www.error, reqContainer); } else { try { byte[] responseBytes = www.downloadHandler.data; bool isGzipCompressed = responseBytes != null && responseBytes[0] == 31 && responseBytes[1] == 139; string responseText = "Unexpected error: cannot decompress GZIP stream."; if (!isGzipCompressed && responseBytes != null) { responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); } #if !UNITY_WSA && !UNITY_WP8 && !UNITY_WEBGL if (isGzipCompressed) { var stream = new MemoryStream(responseBytes); using (var gZipStream = new Ionic.Zlib.GZipStream(stream, Ionic.Zlib.CompressionMode.Decompress, false)) { var buffer = new byte[4096]; using (var output = new MemoryStream()) { int read; while ((read = gZipStream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } output.Seek(0, SeekOrigin.Begin); var streamReader = new StreamReader(output); var jsonResponse = streamReader.ReadToEnd(); //Debug.Log(jsonResponse); OnResponse(jsonResponse, reqContainer); //Debug.Log("Successful UnityHttp decompress for: " + www.url); } } } else #endif { OnResponse(responseText, reqContainer); } } catch (Exception e) { OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer); } } www.Dispose(); }
public static void AddHttpDelegate(CallRequestContainer requestContainer) { Init(); HttpHandlers.Add(requestContainer.CallId, requestContainer); }
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); } }
public void MakeApiCall(object reqContainerObj) { CallRequestContainer reqContainer = (CallRequestContainer)reqContainerObj; reqContainer.RequestHeaders["Content-Type"] = "application/json"; //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 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); } #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)); }
public static void AddHttpDelegate(CallRequestContainer requestContainer) { Init(); HttpHandlers.Add(requestContainer.CallId, requestContainer); }
private static void ProcessHttpResponse(CallRequestContainer reqContainer) { try { #if PLAYFAB_REQUEST_TIMING reqContainer.Timing.WorkerRequestMs = (int)reqContainer.Stopwatch.ElapsedMilliseconds; #endif // Get and check the response var httpResponse = (HttpWebResponse)reqContainer.HttpRequest.GetResponse(); if (httpResponse.StatusCode == HttpStatusCode.OK) { reqContainer.JsonResponse = ResponseToString(httpResponse); } if (httpResponse.StatusCode != HttpStatusCode.OK || string.IsNullOrEmpty(reqContainer.JsonResponse)) { reqContainer.JsonResponse = reqContainer.JsonResponse ?? "No response from server"; QueueRequestError(reqContainer); return; } else { // Response Recieved Successfully, now process. } reqContainer.HttpState = HttpRequestState.Received; } catch (Exception e) { var msg = "Unhandled exception in ProcessHttpResponse : " + reqContainer.FullUrl; reqContainer.JsonResponse = reqContainer.JsonResponse ?? msg; var enhancedError = new Exception(msg, e); Debug.LogException(enhancedError); QueueRequestError(reqContainer); } }
/// <summary> /// Set the reqContainer into an error state, and queue it to invoke the ErrorCallback for that request /// </summary> private static void QueueRequestError(CallRequestContainer reqContainer) { reqContainer.Error = PlayFabHttp.GeneratePlayFabError(reqContainer.JsonResponse, reqContainer.CustomData); // Decode the server-json error 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); }); } }
private IEnumerator Post(CallRequestContainer reqContainer) { #if PLAYFAB_REQUEST_TIMING var stopwatch = System.Diagnostics.Stopwatch.StartNew(); var startTime = DateTime.UtcNow; #endif var www = new UnityWebRequest(reqContainer.FullUrl) { uploadHandler = new UploadHandlerRaw(reqContainer.Payload), downloadHandler = new DownloadHandlerBuffer(), method = "POST" }; foreach (var headerPair in reqContainer.RequestHeaders) { if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value)) { www.SetRequestHeader(headerPair.Key, headerPair.Value); } else { Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value); } } #if UNITY_2017_2_OR_NEWER yield return(www.SendWebRequest()); #else yield return(www.Send()); #endif #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 if (!string.IsNullOrEmpty(www.error)) { OnError(www.error, reqContainer); } else { try { byte[] responseBytes = www.downloadHandler.data; string responseText = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length); OnResponse(responseText, reqContainer); } catch (Exception e) { OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer); } } www.Dispose(); }
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); } }
private static void Post(CallRequestContainer reqContainer) { try { reqContainer.HttpRequest = (HttpWebRequest)WebRequest.Create(reqContainer.FullUrl); reqContainer.HttpRequest.UserAgent = "UnityEngine-Unity; Version: " + _UnityVersion; reqContainer.HttpRequest.SendChunked = false; reqContainer.HttpRequest.Proxy = null; // Prevents hitting a proxy if no proxy is available. TODO: Add support for proxy's. reqContainer.HttpRequest.Headers.Add("X-ReportErrorAsSuccess", "true"); // Without this, we have to catch WebException instead, and manually decode the result reqContainer.HttpRequest.Headers.Add("X-PlayFabSDK", PlayFabSettings.VersionString); if (reqContainer.AuthKey == AuthType.DevSecretKey) { reqContainer.HttpRequest.Headers.Add("X-SecretKey", _devKey); } else if (reqContainer.AuthKey == AuthType.LoginSession) { reqContainer.HttpRequest.Headers.Add("X-Authorization", _authKey); } reqContainer.HttpRequest.ContentType = "application/json"; reqContainer.HttpRequest.Method = "POST"; reqContainer.HttpRequest.KeepAlive = PlayFabSettings.RequestKeepAlive; reqContainer.HttpRequest.Timeout = PlayFabSettings.RequestTimeout; reqContainer.HttpRequest.AllowWriteStreamBuffering = false; reqContainer.HttpRequest.Proxy = null; reqContainer.HttpRequest.ContentLength = reqContainer.Payload.LongLength; reqContainer.HttpRequest.ReadWriteTimeout = PlayFabSettings.RequestTimeout; //Debug.Log("Get Stream"); // Get Request Stream and send data in the body. using (Stream stream = reqContainer.HttpRequest.GetRequestStream()) { //Debug.Log("Post Stream"); stream.Write(reqContainer.Payload, 0, reqContainer.Payload.Length); //Debug.Log("After Post stream"); } reqContainer.HttpState = HttpRequestState.Sent; } catch (WebException e) { if (reqContainer.RetryTimeoutCounter == 0 && e.Status == WebExceptionStatus.Timeout) { reqContainer.RetryTimeoutCounter++; } else { var enhancedError = new WebException("Exception making http request to :" + reqContainer.FullUrl, e); Debug.LogException(enhancedError); reqContainer.RetryTimeoutCounter = 0; reqContainer.HttpState = HttpRequestState.Error; } } catch (Exception e) { Debug.LogException(e); reqContainer.HttpState = HttpRequestState.Error; } }