static void DeleteResponseWorker <O, I>(UnityWebRequest unityWebRequest, IWorker <O, I> worker) where O : class where I : class { if (unityWebRequest.isNetworkError || !string.IsNullOrEmpty(unityWebRequest.error)) { if (unityWebRequest.responseCode != 400) { worker.ErrorProcessing(unityWebRequest.responseCode, unityWebRequest.error); } else { string error = ""; if (unityWebRequest?.downloadHandler?.text != null) { error += unityWebRequest.downloadHandler.text; } worker.ErrorProcessing(unityWebRequest.responseCode, error); } } else { try { O response; string downloadedText; if (MocksResource == MocksResource.NONE) { downloadedText = unityWebRequest.downloadHandler.text; } else { var key = worker.GetType().ToString(); if (!mocks.ContainsKey(key)) { key = $"DELETE:{unityWebRequest.url.Replace($"{url}/", "")}"; } if (mocks.ContainsKey(key)) { downloadedText = mocks[key]; ToolsDebug.Log($"Use mock with key: {key}"); } else { ToolsDebug.Log($"Mocks for key {unityWebRequest.url.Replace($"{url}/", "")} or {worker.GetType().ToString()} not found. Try real request."); downloadedText = unityWebRequest.downloadHandler.text; } } ToolsDebug.Log($"Response: {downloadedText?.Substring(0, Mathf.Min(downloadedText.Length, Instance.logLimit))}"); response = worker.Deserialize <O>(downloadedText); if (response != null) { worker.Execute(response); } else { worker.ErrorProcessing(unityWebRequest.responseCode, "Unknown Error"); } } catch (ArgumentException) { ToolsDebug.Log(unityWebRequest.downloadHandler.text); } } }
static bool DeleteRequestInit <O, W>(string endpoint, out UnityWebRequest uwr, out IWorker <O, Dictionary <string, string> > worker, Dictionary <string, string> query = null, IWorker <O, Dictionary <string, string> > workerDefault = null, string token = null) where W : IWorker <O, Dictionary <string, string> >, new() where O : class { bool useMock = false; url = Instance.urlParam; TokenPrefix = Instance.tokenPrefix; string requestUrl = $"{url}/{ endpoint}"; if (endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { requestUrl = endpoint; } byte[] queryUrlString = null; if (query != null) { queryUrlString = UnityWebRequest.SerializeSimpleForm(query); requestUrl = $"{requestUrl}?{Encoding.UTF8.GetString(queryUrlString)}"; } uwr = new UnityWebRequest($"{requestUrl}", UnityWebRequest.kHttpVerbDELETE); uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); if (MocksResource != MocksResource.NONE) { var key = typeof(W).ToString(); if (!mocks.ContainsKey(key)) { key = $"DELETE:{endpoint}"; } if (mocks.ContainsKey(key)) { ToolsDebug.Log($"Use mock for Key:{key} Value:{mocks[key]?.Substring(0, Mathf.Min(mocks[key].Length, Instance.logLimit))}"); useMock = true; } else { ToolsDebug.Log($"Mocks for key {endpoint} or {typeof(W).ToString()} not found. Try real request."); } } if (!string.IsNullOrEmpty(token)) { uwr.SetRequestHeader("Authorization", $"{TokenPrefix} {token}"); } ToolsDebug.Log($"{UnityWebRequest.kHttpVerbDELETE}: {requestUrl} {uwr.GetRequestHeader("Authorization")}"); if (workerDefault == null) { worker = new W(); } else { worker = workerDefault; } worker.Request = query; worker.Start(); return(useMock); }
static bool PutRequestInit <O, I, W>(string endpoint, out UnityWebRequest uwr, out IWorker <O, I> worker, I param, IWorker <O, I> workerDefault = null, string token = null, params IMultipartFormSection[] parts) where W : IWorker <O, I>, new() where O : class where I : class { bool useMock = false; url = Instance.urlParam; TokenPrefix = Instance.tokenPrefix; string requestUrl = $"{url}/{endpoint}"; if (endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { requestUrl = endpoint; } string json = null; byte[] jsonToSend = new byte[1]; if (workerDefault == null) { worker = new W(); } else { worker = workerDefault; } uwr = new UnityWebRequest($"{requestUrl}", "PUT"); if (MocksResource != MocksResource.NONE) { var key = typeof(W).ToString(); if (!mocks.ContainsKey(key)) { key = $"PUT:{endpoint}"; } if (mocks.ContainsKey(key)) { ToolsDebug.Log($"Use mock for Key:{key} Value:{mocks[key]?.Substring(0, Mathf.Min(mocks[key].Length, Instance.logLimit))}"); useMock = true; } else { ToolsDebug.Log($"Mocks for key {endpoint} or {typeof(W).ToString()} not found. Try real request."); } } if (typeof(I) == typeof(Texture2D)) { Texture2D sendTexture = param as Texture2D; json = "Texture2D"; jsonToSend = ImageConversion.EncodeToPNG(sendTexture); uwr.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); uwr.SetRequestHeader("Content-Type", "image/png"); } else { if (param != null) { json = worker.Serialize(param); jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); } if (parts != null && parts.Length != 0) { //TODO: //Finish it Debug.Log("WTF"); List <IMultipartFormSection> formData = new List <IMultipartFormSection>(); formData.Add(new MultipartFormDataSection("JSON Body", json, "application/json")); formData.AddRange(parts); var boundary = UnityWebRequest.GenerateBoundary(); byte[] formSections = UnityWebRequest.SerializeFormSections(formData, boundary); uwr = UnityWebRequest.Put($"{requestUrl}", formSections); uwr.SetRequestHeader("Content-Type", "multipart/form-data; boundary=" + System.Text.Encoding.UTF8.GetString(boundary)); uwr.uploadHandler.contentType = "multipart/form-data; boundary=" + System.Text.Encoding.UTF8.GetString(boundary); } else { uwr.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); uwr.uploadHandler.contentType = "application/json"; } } uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); if (!string.IsNullOrEmpty(token)) { uwr.SetRequestHeader("Authorization", $"{TokenPrefix} {token}"); } ToolsDebug.Log($"{UnityWebRequest.kHttpVerbPUT}: {requestUrl} {uwr.GetRequestHeader("Authorization")} JSONBody:{json?.Substring(0, Mathf.Min(json.Length, Instance.logLimit))}"); worker.Request = param; worker.Start(); return(useMock); }
static void UpdateMocks() { switch (MocksResource) { case MocksResource.MEMORY: if (mocks == null) { mocks = new Dictionary <string, string>(); } break; case MocksResource.FILE: string filePath = Instance.mocksFilePath; if (!File.Exists(filePath)) { filePath = Path.Combine(Application.persistentDataPath, Instance.mocksFilePath); if (!File.Exists(filePath)) { filePath = Path.Combine(Application.streamingAssetsPath, Instance.mocksFilePath); if (!File.Exists(filePath)) { UnityWebRequest copyFile = new UnityWebRequest(filePath, "GET"); copyFile.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); copyFile.SendWebRequest(); while (!copyFile.isDone) { } if (!copyFile.isHttpError && !copyFile.isNetworkError) { if (!string.IsNullOrEmpty(copyFile.downloadHandler.text)) { File.WriteAllText(Path.Combine(Application.persistentDataPath, Instance.mocksFilePath), copyFile.downloadHandler.text); filePath = Path.Combine(Application.persistentDataPath, Instance.mocksFilePath); } } } } } if (File.Exists(filePath)) { ListKeyValueMocks mocksList = JsonUtility.FromJson <ListKeyValueMocks>(File.ReadAllText(filePath)); if (mocks == null) { mocks = new Dictionary <string, string>(); } foreach (var p in mocksList.mocks.ToDictionary((pair) => pair.Key, (pair) => pair.Value)) { if (!p.Value.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { string filePathRequest = p.Value; if (!File.Exists(filePathRequest)) { filePathRequest = Path.Combine(Application.persistentDataPath, p.Value); if (!File.Exists(filePathRequest)) { filePathRequest = Path.Combine(Application.streamingAssetsPath, p.Value); if (!File.Exists(filePathRequest)) { UnityWebRequest copyFile = new UnityWebRequest(filePathRequest, "GET"); copyFile.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); copyFile.SendWebRequest(); while (!copyFile.isDone) { } if (!copyFile.isHttpError && !copyFile.isNetworkError) { File.WriteAllText(Path.Combine(Application.persistentDataPath, p.Value), copyFile.downloadHandler.text); filePathRequest = Path.Combine(Application.persistentDataPath, p.Value); } } } } mocks[p.Key] = File.ReadAllText(filePathRequest); } } } else { ToolsDebug.Log($"Can't read mock data file from: {Instance.mocksFilePath}"); MocksResource = MocksResource.NONE; } break; case MocksResource.REMOTE_FILE: UnityWebRequest unityWebRequest = new UnityWebRequest(Instance.mocksFilePath, UnityWebRequest.kHttpVerbGET, new DownloadHandlerBuffer(), null); unityWebRequest.SendWebRequest().completed += (dh) => { if (!unityWebRequest.isNetworkError && !unityWebRequest.isHttpError && !string.IsNullOrEmpty(unityWebRequest.downloadHandler?.text)) { ListKeyValueMocks mocksList = JsonUtility.FromJson <ListKeyValueMocks>(unityWebRequest.downloadHandler?.text); mocks = mocksList.mocks.ToDictionary((pair) => pair.Key, (pair) => pair.Value); foreach (var p in mocks) { if (p.Value.EndsWith("json", StringComparison.OrdinalIgnoreCase)) { UnityWebRequest uwr = new UnityWebRequest(p.Value, UnityWebRequest.kHttpVerbGET, new DownloadHandlerBuffer(), null); uwr.SendWebRequest().completed += (dhh) => { if (!uwr.isNetworkError && !uwr.isHttpError && !string.IsNullOrEmpty(uwr.downloadHandler?.text)) { mocks[p.Key] = uwr.downloadHandler?.text; } }; } } } else { ToolsDebug.Log($"Can't read mock data remote file from: {Instance.mocksFilePath}"); MocksResource = MocksResource.NONE; } }; break; default: mocks = null; break; } }
static void GetResponseWorker <O, I>(UnityWebRequest unityWebRequest, IWorker <O, I> worker) where O : class where I : class { if (unityWebRequest.isNetworkError || !string.IsNullOrEmpty(unityWebRequest.error)) { if (unityWebRequest.responseCode != 400) { worker.ErrorProcessing(unityWebRequest.responseCode, unityWebRequest.error); } else { string error = ""; if (unityWebRequest?.downloadHandler?.text != null) { error += unityWebRequest.downloadHandler.text; } worker.ErrorProcessing(unityWebRequest.responseCode, error); } } else { try { O response; if (typeof(O) == typeof(Texture2D)) { Texture2D image = new Texture2D(2, 2, TextureFormat.ARGB32, false); image = DownloadHandlerTexture.GetContent(unityWebRequest); if (image == null) { response = default(O); } else { response = image as O; } } else { string downloadedText; if (MocksResource == MocksResource.NONE) { downloadedText = unityWebRequest.downloadHandler.text; } else { var key = worker.GetType().ToString(); if (!mocks.ContainsKey(key)) { key = $"GET:{unityWebRequest.url.Replace($"{url}/", "")}"; } if (mocks.ContainsKey(key)) { downloadedText = mocks[key]; ToolsDebug.Log($"Use mock with key: {key}"); } else { ToolsDebug.Log($"Mocks for key {unityWebRequest.url.Replace($"{url}/", "")} or {worker.GetType().ToString()} not found. Try real request."); downloadedText = unityWebRequest.downloadHandler.text; } } ToolsDebug.Log($"Response: {downloadedText?.Substring(0, Mathf.Min(downloadedText.Length, Instance.logLimit))}"); try { response = worker.Deserialize <O>(downloadedText); } catch (Exception e) { worker.ErrorProcessing(400, "Can't deserialize answer."); return; } } if (response != null) { worker.Execute(response); } else { worker.ErrorProcessing(unityWebRequest.responseCode, "Unknown Error"); } } catch (ArgumentException) { ToolsDebug.Log(unityWebRequest.downloadHandler.text); } } }
static bool GetWithBodyRequestInit <O, I, W>(string endpoint, out UnityWebRequest uwr, out IWorker <O, HTTPGetWithBodyParameter <I> > worker, HTTPGetWithBodyParameter <I> query = null, IWorker <O, HTTPGetWithBodyParameter <I> > workerDefault = null, string token = null) where W : IWorker <O, HTTPGetWithBodyParameter <I> >, new() where O : class where I : class { bool useMock = false; url = Instance.urlParam; TokenPrefix = Instance.tokenPrefix; string requestUrl = $"{url}/{ endpoint}"; if (endpoint.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { requestUrl = endpoint; } byte[] queryUrlString = null; if (query.query != null) { queryUrlString = UnityWebRequest.SerializeSimpleForm(query.query); requestUrl = $"{requestUrl}?{Encoding.UTF8.GetString(queryUrlString)}"; } if (typeof(O) == typeof(Texture2D)) { if (MocksResource == MocksResource.NONE) { uwr = UnityWebRequestTexture.GetTexture($"{requestUrl}"); } else { var key = typeof(W).ToString(); if (!mocks.ContainsKey(key)) { key = $"GET:{endpoint}"; } if (mocks.ContainsKey(key)) { uwr = UnityWebRequestTexture.GetTexture($"{mocks[key]}"); ToolsDebug.Log($"Use mock for texture. Key:{key} Value:{mocks[key]?.Substring(0, Mathf.Min(mocks[key].Length, Instance.logLimit))}"); useMock = true; } else { ToolsDebug.Log($"Mocks for key {key} or {key} not found. Try real request."); uwr = UnityWebRequestTexture.GetTexture($"{requestUrl}"); } } } else { uwr = new UnityWebRequest($"{requestUrl}"); uwr.method = "GET"; uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); if (MocksResource != MocksResource.NONE) { var key = typeof(W).ToString(); if (!mocks.ContainsKey(key)) { key = $"GET:{endpoint}"; } if (mocks.ContainsKey(key)) { ToolsDebug.Log($"Use mock for Key:{key} Value:{mocks[key]?.Substring(0, Mathf.Min(mocks[key].Length, Instance.logLimit))}"); useMock = true; } else { ToolsDebug.Log($"Mocks for key {key} or {key} not found. Try real request."); } } } if (!string.IsNullOrEmpty(token)) { uwr.SetRequestHeader("Authorization", $"{TokenPrefix} {token}"); } ToolsDebug.Log($"{UnityWebRequest.kHttpVerbGET}: {requestUrl} {uwr.GetRequestHeader("Authorization")}"); if (workerDefault == null) { worker = new W(); } else { worker = workerDefault; } string json = null; byte[] jsonToSend = new byte[1]; if (query.param != null) { json = worker.Serialize <I>(query.param); jsonToSend = new System.Text.UTF8Encoding().GetBytes(json); } uwr.uploadHandler = (UploadHandler) new UploadHandlerRaw(jsonToSend); uwr.uploadHandler.contentType = "application/json"; worker.Request = query; worker.Start(); return(useMock); }