using Newtonsoft.Json; using System.Collections; using Octopus.Simulator.Networks; using System.Collections.Generic; using System.IO; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; using System; using System.Text; using Octopus.Simulator; using Octopus.Simulator.UI.Popup; #pragma warning disable CS8632 namespace UVC.Networks { //API를 통해 서버와 통신하기 위한 함수들이 내장되어 있습니다. //Post, Get. Put을 사용하며, Post의 경우엔 Class를 입력으로 받아 Json형식으로 변환하여 업로드합니다. //비동기로 실행하기 위해 Coroutine으로 제작되었으며, callback의 bool값을 통해 서버로부터 //정상적으로 API가 입력, 결과가 출력되었는지를 확인할 수 있습니다. public enum RequestType { //"GET", "POST", "PUT", "PATCH", "DELETE" GET, POST, PUT, PATCH, DELETE, } public class WebManager : MonoBehaviour { static WebManager webManager; public static WebManager Instance { get { if (webManager == null) { GameObject go = new GameObject("[WebManager]"); webManager = go.AddComponent(); DontDestroyOnLoad(go); } return webManager; } } [SerializeField] private string _webConfigResourcePath= "WebConfig"; [SerializeField] private string _apiConfigResourcePath= "APIEndPointsConfig"; private WebConfigLoader _webConfigLoader = new WebConfigLoader(); private ApiConfigLoader _apiConfigLoader = new ApiConfigLoader(); public APIEndPointsConfig apiConfig; public string ProjectTitle = ""; void Awake() { if (webManager != null && webManager != this) { Destroy(gameObject); return; } webManager = this; //DontDestroyOnLoad(gameObject); #if UNITY_EDITOR _webConfigLoader.LoadFromResources(_webConfigResourcePath); #else Debug.Log("onwebgl"); WebReceiver receiver = FindAnyObjectByType(); receiver.onWebConfigReceived += HandleWebConfigFromReceiver; #endif apiConfig = _apiConfigLoader.LoadFromResources(_apiConfigResourcePath); } private void HandleWebConfigFromReceiver(string json) { _webConfigLoader.LoadFromJsonString(json); Debug.Log("handle"); } //별도의 Data Content 가 없을 경우 reqeustURL 과 callback 등 만을 parameter로 넘기면 됨 public void Reqeust(string requestURL, RequestType type , Action callback, object json = null) { string data = ""; if ( json != null) { try { data = JsonConvert.SerializeObject(json); } catch (Exception e) { AlertManager.I.ShowConfirm("Error",e.Message).Forget(); } } RequestAsync(requestURL, type, data) .ContinueWith(result => callback?.Invoke(result)) .Forget(); } private async UniTask RequestAsync(string requestURL, RequestType type, string json) { string fullUrl = _webConfigLoader.BaseUrl + requestURL; Debug.Log(fullUrl); using (UnityWebRequest request = new UnityWebRequest(fullUrl, type.ToString())) { byte[] body = Encoding.UTF8.GetBytes(json); request.uploadHandler = new UploadHandlerRaw(body); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); request.SetRequestHeader("Authorization", "Bearer " + _webConfigLoader.Token); await request.SendWebRequest(); if (IsSuccess(request.result)) { Debug.Log(requestURL); string responseJson = request.downloadHandler.text; Debug.Log($"data:{responseJson}"); Base result = JsonConvert.DeserializeObject>(responseJson); return result.data; } else { Debug.LogError($"Request failed, API Name {fullUrl}, Result : {request.error}"); throw new Exception($"HTTP Request Failed: {request.error}"); } } } private bool IsSuccess(UnityWebRequest.Result result) { switch(result) { case UnityWebRequest.Result.Success: return true; case UnityWebRequest.Result.ConnectionError: return false; case UnityWebRequest.Result.ProtocolError: return false; default: return false; } } } }