/// <summary>
 /// Enqueues a request to be processed by the UnityMainThreadDispatcher.
 /// Unity 
 /// </summary>
 /// <param name="request">An instance of UnityWebRequest.</param>
 public void EnqueueRequest(UnityWebRequest request)
 {
     lock (_requestsLock)
     {
         _requests.Enqueue(request);
     }            
 }
Пример #2
0
        /// <summary>
        /// 加载资源(异步)
        /// </summary>
        /// <typeparam name="T">资源类型</typeparam>
        /// <param name="info">资源信息标记</param>
        /// <param name="loadingAction">加载中事件</param>
        /// <param name="loadDoneAction">加载完成事件</param>
        /// <param name="isPrefab">是否是加载预制体</param>
        /// <param name="parent">预制体加载完成后的父级</param>
        /// <param name="isUI">是否是加载UI</param>
        /// <returns>加载协程迭代器</returns>
        public IEnumerator LoadAssetAsync <T>(ResourceInfoBase info, HTFAction <float> loadingAction, HTFAction <T> loadDoneAction, bool isPrefab, Transform parent, bool isUI) where T : UnityEngine.Object
        {
            DateTime beginTime = DateTime.Now;

            if (_isLoading)
            {
                yield return(_loadWait);
            }

            _isLoading = true;

            yield return(Main.Current.StartCoroutine(LoadDependenciesAssetBundleAsync(info.AssetBundleName)));

            DateTime waitTime = DateTime.Now;

            UnityEngine.Object asset = null;

            if (LoadMode == ResourceLoadMode.Resource)
            {
                ResourceRequest request = Resources.LoadAsync <T>(info.ResourcePath);
                while (!request.isDone)
                {
                    loadingAction?.Invoke(request.progress);
                    yield return(null);
                }
                asset = request.asset;
                if (asset)
                {
                    if (isPrefab)
                    {
                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                    }
                }
                else
                {
                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:Resources文件夹中不存在资源 " + info.ResourcePath + "!");
                }
            }
            else
            {
#if UNITY_EDITOR
                if (IsEditorMode)
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetDatabase.LoadAssetAtPath <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:路径中不存在资源 " + info.AssetPath + "!");
                    }
                }
                else
                {
                    if (AssetBundles.ContainsKey(info.AssetBundleName))
                    {
                        loadingAction?.Invoke(1);
                        yield return(null);

                        asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                        if (asset)
                        {
                            if (isPrefab)
                            {
                                asset = ClonePrefab(asset as GameObject, parent, isUI);
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                        }
                    }
                    else
                    {
                        using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                        {
                            request.SendWebRequest();
                            while (!request.isDone)
                            {
                                loadingAction?.Invoke(request.downloadProgress);
                                yield return(null);
                            }
                            if (!request.isNetworkError && !request.isHttpError)
                            {
                                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                                if (bundle)
                                {
                                    asset = bundle.LoadAsset <T>(info.AssetPath);
                                    if (asset)
                                    {
                                        if (isPrefab)
                                        {
                                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                                        }
                                    }
                                    else
                                    {
                                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                    }

                                    if (IsCacheAssetBundle)
                                    {
                                        if (!AssetBundles.ContainsKey(info.AssetBundleName))
                                        {
                                            AssetBundles.Add(info.AssetBundleName, bundle);
                                        }
                                    }
                                    else
                                    {
                                        bundle.Unload(false);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                            }
                        }
                    }
                }
#else
                if (AssetBundles.ContainsKey(info.AssetBundleName))
                {
                    loadingAction?.Invoke(1);
                    yield return(null);

                    asset = AssetBundles[info.AssetBundleName].LoadAsset <T>(info.AssetPath);
                    if (asset)
                    {
                        if (isPrefab)
                        {
                            asset = ClonePrefab(asset as GameObject, parent, isUI);
                        }
                    }
                    else
                    {
                        throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                    }
                }
                else
                {
                    using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(AssetBundleRootPath + info.AssetBundleName, GetAssetBundleHash(info.AssetBundleName)))
                    {
                        request.SendWebRequest();
                        while (!request.isDone)
                        {
                            loadingAction?.Invoke(request.downloadProgress);
                            yield return(null);
                        }
                        if (!request.isNetworkError && !request.isHttpError)
                        {
                            AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(request);
                            if (bundle)
                            {
                                asset = bundle.LoadAsset <T>(info.AssetPath);
                                if (asset)
                                {
                                    if (isPrefab)
                                    {
                                        asset = ClonePrefab(asset as GameObject, parent, isUI);
                                    }
                                }
                                else
                                {
                                    throw new HTFrameworkException(HTFrameworkModule.Resource, "加载资源失败:AB包 " + info.AssetBundleName + " 中不存在资源 " + info.AssetPath + " !");
                                }

                                if (IsCacheAssetBundle)
                                {
                                    if (!AssetBundles.ContainsKey(info.AssetBundleName))
                                    {
                                        AssetBundles.Add(info.AssetBundleName, bundle);
                                    }
                                }
                                else
                                {
                                    bundle.Unload(false);
                                }
                            }
                            else
                            {
                                throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 未下载到AB包!");
                            }
                        }
                        else
                        {
                            throw new HTFrameworkException(HTFrameworkModule.Resource, "请求:" + request.url + " 遇到网络错误:" + request.error + "!");
                        }
                    }
                }
#endif
            }

            DateTime endTime = DateTime.Now;

            Log.Info(string.Format("异步加载资源{0}[{1}模式]:\r\n{2}\r\n等待耗时:{3}秒  加载耗时:{4}秒"
                                   , asset ? "成功" : "失败"
                                   , LoadMode.ToString()
                                   , LoadMode == ResourceLoadMode.Resource ? info.GetResourceFullPath() : info.GetAssetBundleFullPath(AssetBundleRootPath)
                                   , (waitTime - beginTime).TotalSeconds
                                   , (endTime - waitTime).TotalSeconds));

            if (asset)
            {
                DataSetInfo dataSet = info as DataSetInfo;
                if (dataSet != null && dataSet.Data != null)
                {
                    asset.Cast <DataSetBase>().Fill(dataSet.Data);
                }

                loadDoneAction?.Invoke(asset as T);
            }
            asset = null;

            _isLoading = false;
        }
Пример #3
0
            /// <summary>
            /// Returns more info about the connected user.
            /// </summary>
            /// <remarks>
            /// <para>
            /// Form more information please see <see href="https://docs-staging.venly.io/pages/reference.html#_user_profile_arkane_api">https://docs-staging.venly.io/pages/reference.html#_user_profile_arkane_api</see>
            /// </para>
            /// <para>
            /// The <see cref="UserProfileResult.result"/> is a <see cref="UserProfile"/> object containing details about the local user.
            /// This method assumes you have already authenticated via one of the available login methods such as <see cref="Login_Facebook(string, Action{AuthenticationResult})"/>
            /// </para>
            /// </remarks>
            /// <param name="callback"></param>
            /// <returns>The Unity routine enumerator</returns>
            /// <example>
            /// <para>
            /// How to call:
            /// </para>
            /// <code>
            /// StartCoroutine(HeathenEngineering.BGSDK.API.User.GetProfile(Identity, HandleProfileResult));
            /// </code>
            /// </example>
            public static IEnumerator GetProfile(Action <UserProfileResult> callback)
            {
                if (BGSDKSettings.current == null)
                {
                    callback(new UserProfileResult()
                    {
                        hasError = true, message = "Attempted to call BGSDK.User.GetProfile with no BGSDK.Settings object applied."
                    });
                    yield return(null);
                }
                else
                {
                    if (BGSDKSettings.user == null)
                    {
                        callback(new UserProfileResult()
                        {
                            hasError = true, message = "BGSDKIdentity required, null identity provided.\nPlease initalize Settings.user before calling GetProfile", result = null
                        });
                        yield return(null);
                    }
                    else
                    {
                        UnityWebRequest www = UnityWebRequest.Get(BGSDKSettings.current.api[BGSDKSettings.current.UseStaging] + "/api/profile");
                        www.SetRequestHeader("Authorization", BGSDKSettings.user.authentication.token_type + " " + BGSDKSettings.user.authentication.access_token);

                        var co = www.SendWebRequest();
                        while (!co.isDone)
                        {
                            yield return(null);
                        }

                        if (!www.isNetworkError && !www.isHttpError)
                        {
                            var results = new UserProfileResult();
                            try
                            {
                                string resultContent = www.downloadHandler.text;
                                results.result   = JsonUtility.FromJson <UserProfile>(resultContent);
                                results.message  = "Wallet refresh complete.";
                                results.httpCode = www.responseCode;
                            }
                            catch (Exception ex)
                            {
                                results           = null;
                                results.message   = "An error occured while processing JSON results, see exception for more details.";
                                results.exception = ex;
                                results.httpCode  = www.responseCode;
                            }
                            finally
                            {
                                callback(results);
                            }
                        }
                        else
                        {
                            callback(new UserProfileResult()
                            {
                                hasError = true, message = "Error:" + (www.isNetworkError ? " a network error occured while requesting the user's wallets." : " a HTTP error occured while requesting the user's wallets."), result = null, httpCode = www.responseCode
                            });
                        }
                    }
                }
            }
Пример #4
0
    IEnumerator UploadNewHighscore(string username, int score)
    {
        UnityWebRequest request = new UnityWebRequest(webURL + privateCode + "/add/" + UnityWebRequest.EscapeURL(username) + "/" + score);

        yield return(request.SendWebRequest());

        if (request.isHttpError || request.isNetworkError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Debug.Log("Successfully added");
            DownloadHighscores();
        }
    }
Пример #5
0
 private void PrepareHeaders(UnityWebRequest r, string apiVersion = "3.4")
 {
     r.chunkedTransfer = false;
     r.SetRequestHeader("Authorization", "bearer " + token);
     r.SetRequestHeader("Accept", "application/vnd.vimeo.*+json;version=" + apiVersion);
 }
Пример #6
0
 public bool IsHttpError(UnityWebRequest request)
 {
     return(request.isHttpError);
 }
Пример #7
0
 public bool IsNetworkError(UnityWebRequest request)
 {
     return(request.isNetworkError);
 }
Пример #8
0
    IEnumerator Start()
    {
        AppsFlyer.initSDK(devkey, appID);
        AppsFlyer.startSDK();

        string tempSettingsPath = Application.persistentDataPath + "/AFUID.dat";

        if (!System.IO.File.Exists(tempSettingsPath))
        {
            appsFlyerData[0] = AppsFlyer.getAppsFlyerId();
            System.IO.File.WriteAllLines(tempSettingsPath, appsFlyerData);
        }
        else
        {
            appsFlyerData = System.IO.File.ReadAllLines(tempSettingsPath);
        }

        Url += appsFlyerData[0];

        //  webView Init
        webViewObject = (new GameObject("WebViewObject")).AddComponent <WebViewObject>();

        webViewObject.Init(
            // Callback
            cb: (msg) =>
        {
            Debug.Log(string.Format("CallFromJS[{0}]", msg));
            mUrl = msg;
        },
            // On error
            err: (msg) =>
        {
            Debug.Log(string.Format("CallOnError[{0}]", msg));
            connStatus = msg;
        },
            // When started
            started: (msg) =>
        {
            Debug.Log(string.Format("CallOnStarted[{0}]", msg));
        },
            hooked: (msg) =>
        {
            Debug.Log(string.Format("CallOnHooked[{0}]", msg));
        },
            // When loaded
            ld: (msg) =>
        {
            Debug.Log(string.Format("CallOnLoaded[{0}]", msg));

#if UNITY_EDITOR_OSX || (!UNITY_ANDROID && !UNITY_WEBPLAYER && !UNITY_WEBGL)
#if true
            webViewObject.EvaluateJS(@"
				  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
					window.Unity = {
					  call: function(msg) {
						window.webkit.messageHandlers.unityControl.postMessage(msg);
					  }
					}
				  } else {
					window.Unity = {
					  call: function(msg) {
						window.location = 'unity:' + msg;
					  }
					}
				  }
				"                );
#else
            webViewObject.EvaluateJS(@"
				  if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
					window.Unity = {
					  call: function(msg) {
						window.webkit.messageHandlers.unityControl.postMessage(msg);
					  }
					}
				  } else {
					window.Unity = {
					  call: function(msg) {
						var iframe = document.createElement('IFRAME');
						iframe.setAttribute('src', 'unity:' + msg);
						document.documentElement.appendChild(iframe);
						iframe.parentNode.removeChild(iframe);
						iframe = null;
					  }
					}
				  }
				"                );
#endif
#elif UNITY_WEBPLAYER || UNITY_WEBGL
            webViewObject.EvaluateJS(
                "window.Unity = {" +
                "   call:function(msg) {" +
                "       parent.unityWebView.sendMessage('WebViewObject', msg)" +
                "   }" +
                "};");
#endif
        },
#if UNITY_EDITOR
            separated: false,
#endif
            enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
        webViewObject.bitmapRefreshCycle = 1;
#endif

        if (dev)
        {
            webViewObject.SetMargins(0, 120, 0, 0);             //WebView size
        }
        else
        {
            webViewObject.SetMargins(0, 0, 0, 0);             //WebView size
        }
        webViewObject.SetVisibility(true);

#if !UNITY_WEBPLAYER && !UNITY_WEBGL
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            var exts = new string[] {
                ".jpg",
                ".js",
                ".html"
            };
            foreach (var ext in exts)
            {
                var    url    = Url.Replace(".html", ext);
                var    src    = System.IO.Path.Combine(Application.streamingAssetsPath, url);
                var    dst    = System.IO.Path.Combine(Application.persistentDataPath, url);
                byte[] result = null;
                if (src.Contains("://"))
                {
#if UNITY_2018_4_OR_NEWER
                    var unityWebRequest = UnityWebRequest.Get(src);
                    yield return(unityWebRequest.SendWebRequest());

                    result = unityWebRequest.downloadHandler.data;
#else
                    var www = new WWW(src);
                    yield return(www);

                    result = www.bytes;
#endif
                }
                else
                {
                    result = System.IO.File.ReadAllBytes(src);
                }
                System.IO.File.WriteAllBytes(dst, result);
                if (ext == ".html")
                {
                    webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
                    break;
                }
            }
        }

        webViewObject.EvaluateJS(
            "window.Unity = {" +
            "   call:function(msg) {" +
            "       parent.unityWebView.sendMessage('WebViewObject', msg)" +
            "   }" +
            "};");
#else
        if (Url.StartsWith("http"))
        {
            webViewObject.LoadURL(Url.Replace(" ", "%20"));
        }
        else
        {
            webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
        }
#endif
        yield break;
    }
        public static IEnumerator SendRequest(AdGateServerRequest request, System.Action <AdGateDefaultResponse> OnServerResponse = null)
        {
            //Always wait 1 frame before starting any request to the server to make sure the requesters code has exited the main thread.
            yield return(null);

            //Build the URL that we will hit based on the specified endpoint, query params, etc
            string url = request.url;


#if UNITY_EDITOR
            AdGateManager.DebugMessage("ServerRequest URL: " + url);
#endif

            using (UnityWebRequest webRequest = request.CreateWebRequest())
            {
                webRequest.downloadHandler = new DownloadHandlerBuffer();

                float startTime  = Time.time;
                float maxTimeOut = 5f;

                yield return(webRequest.SendWebRequest());

                while (!webRequest.isDone)
                {
                    yield return(null);

                    if (Time.time - startTime >= maxTimeOut)
                    {
                        AdGateManager.DebugMessage("ERROR: Exceeded maxTimeOut waiting for a response from " + request.httpMethod.ToString() + " " + url);
                        yield break;
                    }
                }

                if (!webRequest.isDone)
                {
                    OnServerResponse?.Invoke(new AdGateDefaultResponse()
                    {
                        statusCode = 408, Error = "{\"error\": \"" + request.url + " Timed out.\"}"
                    });
                    yield break;
                }

                try
                {
#if UNITY_EDITOR
                    AdGateManager.DebugMessage("Server Response: " + request.httpMethod + " " + request.url + " completed in " + (Time.time - startTime).ToString("n4") + " secs.\nResponse: " + webRequest.downloadHandler.text);
#endif
                }
                catch
                {
                    AdGateManager.DebugMessage(request.httpMethod.ToString(), true);
                    AdGateManager.DebugMessage(request.url, true);
                    AdGateManager.DebugMessage(webRequest.downloadHandler.text, true);
                }

                AdGateDefaultResponse response = new AdGateDefaultResponse();
                response.statusCode = (int)webRequest.responseCode;
                if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError || !string.IsNullOrEmpty(webRequest.error))
                {
                    switch (webRequest.responseCode)
                    {
                    case 200:
                        response.Error = "";
                        break;

                    case 400:
                        response.Error = "Bad Request -- Your request has an error";
                        break;

                    case 402:
                        response.Error = "Payment Required -- Payment failed. Insufficient funds, etc.";
                        break;

                    case 401:
                        response.Error = "Unauthroized -- Your session_token is invalid";
                        break;

                    case 403:
                        response.Error = "Forbidden -- You do not have access";
                        break;

                    case 404:
                        response.Error = "Not Found";
                        break;

                    case 405:
                        response.Error = "Method Not Allowed";
                        break;

                    case 406:
                        response.Error = "Not Acceptable -- Purchasing is disabled";
                        break;

                    case 409:
                        response.Error = "Conflict -- Your state is most likely not aligned with the servers.";
                        break;

                    case 429:
                        response.Error = "Too Many Requests -- You're being limited for sending too many requests too quickly.";
                        break;

                    case 500:
                        response.Error = "Internal Server Error -- We had a problem with our server. Try again later.";
                        break;

                    case 503:
                        response.Error = "Service Unavailable -- We're either offline for maintenance, or an error that should be solvable by calling again later was triggered.";
                        break;
                    }
#if UNITY_EDITOR
                    AdGateManager.DebugMessage("Response code: " + webRequest.responseCode);
#endif
                    response.Error  += " " + webRequest.downloadHandler.text;
                    response.text    = webRequest.downloadHandler.text;
                    response.success = false;
                    response.text    = webRequest.downloadHandler.text;
                    OnServerResponse?.Invoke(response);
                }
                else
                {
                    response.success = true;
                    response.text    = webRequest.downloadHandler.text;
                    OnServerResponse?.Invoke(response);
                }
            }
        }
Пример #10
0
    IEnumerator _Refresh()
    {
        string url = "https://maps.googleapis.com/maps/api/staticmap";
        string qs  = "";

        if (!autoLocateCenter)
        {
            if (centerLocation.address != "")
            {
                qs += "center=" + UnityWebRequest.UnEscapeURL(centerLocation.address);
            }
            else
            {
                qs += "center=" + UnityWebRequest.UnEscapeURL(string.Format("{0},{1}", centerLocation.latitude, centerLocation.longitude));
            }

            qs += "&zoom=" + zoom.ToString();
        }
        qs += "&size=" + UnityWebRequest.UnEscapeURL(string.Format("{0}x{0}", size));
        qs += "&scale=" + (doubleResolution ? "2" : "1");
        qs += "&maptype=" + mapType.ToString().ToLower();
        var usingSensor = false;

#if UNITY_IPHONE
        usingSensor = Input.location.isEnabledByUser && Input.location.status == LocationServiceStatus.Running;
#endif

        qs += "&sensor=" + (usingSensor ? "true" : "false");

        foreach (var i in markers)
        {
            qs += "&markers=" + string.Format("size:{0}|color:{1}|label:{2}", i.size.ToString().ToLower(), i.color, i.label);

            foreach (var loc in i.locations)
            {
                if (loc.address != "")
                {
                    qs += "|" + UnityWebRequest.UnEscapeURL(loc.address);
                }
                else
                {
                    qs += "|" + UnityWebRequest.UnEscapeURL(string.Format("{0},{1}", loc.latitude, loc.longitude));
                }
            }
        }

        foreach (var i in paths)
        {
            qs += "&path=" + string.Format("weight:{0}|color:{1}", i.weight, i.color);

            if (i.fill)
            {
                qs += "|fillcolor:" + i.fillColor;
            }

            foreach (var loc in i.locations)
            {
                if (loc.address != "")
                {
                    qs += "|" + UnityWebRequest.UnEscapeURL(loc.address);
                }
                else
                {
                    qs += "|" + UnityWebRequest.UnEscapeURL(string.Format("{0},{1}", loc.latitude, loc.longitude));
                }
            }
        }

        qs += "&key=" + UnityWebRequest.UnEscapeURL(GoogleApiKey);
        string          requestUrl = url + "?" + qs;
        UnityWebRequest request    = UnityWebRequestTexture.GetTexture(requestUrl);
        Debug.Log(requestUrl);

        yield return(request.SendWebRequest());

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            Texture2D texture = DownloadHandlerTexture.GetContent(request);
            //Set the renderer to display newly downloaded texture
            SpriteRenderer spriteRenderer = GetComponent <SpriteRenderer>();
            spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.width), new Vector2(0.5f, 0.5f));
            spriteRenderer.material.mainTexture = texture;
            spriteRenderer.material.shader      = Shader.Find("Sprites/Default");
            //Set the camera to fith width-wise with the texture
            Camera.main.orthographicSize = ((texture.width / ((float)spriteRenderer.sprite.pixelsPerUnit)) / 2) / (Screen.width / ((float)Screen.height));
        }
    }
 public UnityHttpErrorResponseException(string message, Exception innerException, UnityWebRequest request) :
     base(message,innerException)
 {
     this.Request = request;
     this.Response = request.Response;
 }
 public UnityHttpErrorResponseException(UnityWebRequest request)
 {
     this.Request = request;
     this.Response = request.Response;
 }
        /// <summary>
        /// Makes a single web request using the WWW API.
        /// </summary>
        /// <param name="request"></param>
        /// <returns>IEnumerator which indicated if the operation is pending.</returns>
        IEnumerator InvokeRequest(UnityWebRequest request)
        {

#if UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
            // Versions before Unity 4.3 use a WWW constructor
            // where the headers parameter is a HashTable.

            var headerTable = new Hashtable();
            foreach (string headerkey in request.Headers.Keys)
                headerTable.Add(headerkey, request.Headers[headerkey]);

            // Fire the request            
            request.WwwRequest = new WWW(request.RequestUri.AbsoluteUri,
                request.RequestContent, headerTable);
#else
            // Fire the request            
            request.WwwRequest = new WWW(request.RequestUri.AbsoluteUri,
                request.RequestContent, request.Headers);
#endif
            yield return request.WwwRequest;
            request.Response = new UnityWebResponseData(request.WwwRequest);

            if (request.IsSync)
            {
                // For synchronous calls, signal the wait handle 
                // so that the calling thread which waits on the wait handle
                // is unblocked.
                if (!request.Response.IsSuccessStatusCode)
                    request.Exception = new UnityHttpErrorResponseException(request);

                request.WaitHandle.Set();
            }
            else
            {
                if (!request.Response.IsSuccessStatusCode)
                {
                    request.Exception = new UnityHttpErrorResponseException(request);
                }
                // For asychronous calls invoke the callback method with the
                // state object that was originally passed in.

                // Invoke the callback method for the request on the thread pool
                // after the web request is executed. This callback triggers the 
                // post processing of the response from the server.
                ThreadPool.QueueUserWorkItem((state) =>
                {
                    try
                    {
                        request.Callback(request.AsyncResult);
                    }
                    catch (Exception exception)
                    {
                        // The callback method (HttpHandler.GetResponseCallback) and 
                        // subsequent calls to handler callbacks capture any exceptions
                        // thrown from the runtime pipeline during post processing.

                        // Log the exception, in case we get an unhandled exception 
                        // from the callback.
                        _logger.Error(exception,
                            "An exception was thrown from the callback method executed from" +
                            "UnityMainThreadDispatcher.InvokeRequest method.");

                    }
                });
            }
        }
Пример #14
0
        /// <summary>
        /// Post one or more MIME parts to a URI
        /// </summary>
        /// <param name="uri">The URI of the web service to receive the Http post message</param>
        /// <param name="retries">Number of times to retry post if there is an error</param>
        /// <param name="mimeParts">MIME encoded payload</param>
        /// <param name="callback">Method called on failure or success that is passed an AsyncResult whose Result property is set to HttpResult</param>
        /// <returns>WebRequest IAsyncResult object</returns>
        public IAsyncResult Post(Uri uri, int retries, List<MimePart> mimeParts, AsyncCallback callback)
        {
#if (SILVERLIGHT || WPF || TOOL)
            WebRequest webRequest = WebRequest.Create(uri);
#else
            WebRequest webRequest = new UnityWebRequest(uri);
#endif
            webRequest.Method = "POST";
            IAsyncResult asyncResult = webRequest.BeginGetRequestStream((asynchronousResult) =>
            {
                WebRequest request = (WebRequest)asynchronousResult.AsyncState;

                if (mimeParts.Count > 1)
                {
                    CreateMultiPartRequest(request, asynchronousResult, mimeParts);
                }
                else
                {
                    CreateSinglePartRequest(request, asynchronousResult, mimeParts[0]);
                }

                // Start the asynchronous operation to get the response
                request.BeginGetResponse((responseResult) =>
                {
                    bool retry = false;
                    HttpResult httpResult = null;
                    try
                    {
                        HttpWebResponse response = ((WebRequest)responseResult.AsyncState).EndGetResponse(responseResult) as HttpWebResponse;
                        // Response stream is released when HttpResult is released
                        httpResult = new HttpResult(response.GetResponseStream(), response.StatusCode, response.StatusDescription, response.ContentType);
                    }
                    catch (WebException we)
                    {
                        DebugLog.Error("WebException -> {0} '{1}' failed", webRequest.Method, uri.ToString());
                        DebugLog.Error(we.Message);
                        if (retries > 0 && we.Status != WebExceptionStatus.RequestCanceled)
                        {
                            DebugLog.Info("Retry {0} '{1}'", webRequest.Method, uri.ToString());
                            Post(uri, --retries, mimeParts, callback);
                            retry = true;
                        }
                        else
                        {
                            httpResult = new HttpResult(we);
                        }
                    }
                    catch (Exception e)
                    {
                        DebugLog.Error("HTTP {0} '{1}' failed: {2}", webRequest.Method, uri.ToString(), e.Message);
                        httpResult = new HttpResult(e);
                    }
                    finally
                    {
                        if (!retry && callback != null)
                        {
                            callback(new AsyncResult<HttpResult>(httpResult));
                        }
                    }
                },
                request);
            },
                webRequest);

            return asyncResult;
        }
Пример #15
0
    static async Task <UnityWebRequest> TcsAsync(string url)
    {
        var req = await UnityWebRequest.Get(url).SendWebRequest();

        return(req);
    }
Пример #16
0
    async UniTaskVoid Start()
    {
        var url = "http://google.com/404";
        var webRequestAsyncOperation = UnityWebRequest.Get(url).SendWebRequest();
        await webRequestAsyncOperation.ToUniTask();

        //PlayerLoopInfo.Inject();

        //_ = AsyncFixedUpdate();
        //StartCoroutine(CoroutineFixedUpdate());

        //StartCoroutine(TestCoroutine().ToCoroutine());

        // Application.logMessageReceived += Application_logMessageReceived;

        // var rp = new AsyncReactiveProperty<int>();


        // rp.AddTo(this.GetCancellationTokenOnDestroy());
        //var cts = new CancellationTokenSource();


        // UniTask.Post(

        // CancellationToken.

        //UniTask.Delay(TimeSpan.FromSeconds(3)).


        //okButton.onClick.AddListener(UniTask.UnityAction(async () =>
        //{
        //    _ = ExecuteAsync();

        //    await UniTask.Yield();

        //    //await DelayCheck();
        //    /*
        //    UnityEngine.Debug.Log("click:" + PlayerLoopInfo.CurrentLoopType);
        //    StartCoroutine(CoroutineRun());
        //    StartCoroutine(CoroutineRun2());
        //    _ = AsyncRun();
        //    _ = AsyncLastUpdate();
        //    _ = AsyncLastLast();
        //    */
        //    //await UniTask.Yield();
        //    //_ = Test2();
        //    // EarlyUpdate.ExecuteMainThreadJobs
        //    // _ = Test2();

        //    //var t = await Resources.LoadAsync<TextAsset>(Application.streamingAssetsPath + "test.txt");
        //    //Debug.Log("LoadEnd" + PlayerLoopInfo.CurrentLoopType + ", " + (t != null));
        //    //Debug.Log("LoadEnd" + PlayerLoopInfo.CurrentLoopType + ", " + ((TextAsset)t).text);


        //    //await UniTask.Yield(PlayerLoopTiming.LastUpdate);
        //    //UnityEngine.Debug.Log("after update:" + Time.frameCount);
        //    ////await UniTask.NextFrame();
        //    ////await UniTask.Yield();
        //    ////UnityEngine.Debug.Log("after update nextframe:" + Time.frameCount);

        //    //StartCoroutine(CoroutineRun2());
        //    ////StartCoroutine(CoroutineRun());
        //    //UnityEngine.Debug.Log("FOO?");

        //    //_ = DelayFrame3_Pre();
        //    //await UniTask.Yield();

        //}));

        //cancelButton.onClick.AddListener(UniTask.UnityAction(async () =>
        //{
        //    _ = DelayFrame3_Post();
        //    await UniTask.Yield();

        //    //await UniTask.Yield(PlayerLoopTiming.LastPreUpdate);
        //    //UnityEngine.Debug.Log("before update:" + Time.frameCount);
        //    //await UniTask.NextFrame();
        //    //await UniTask.Yield();
        //    //UnityEngine.Debug.Log("before update nextframe:" + Time.frameCount);

        //    //StartCoroutine(CoroutineRun());

        //    //UnityEngine.Debug.Log("click:" + PlayerLoopInfo.CurrentLoopType);
        //    //_ = Yieldding();

        //    //var cts = new CancellationTokenSource();

        //    //UnityEngine.Debug.Log("click:" + PlayerLoopInfo.CurrentLoopType + ":" + Time.frameCount);
        //    //var la = SceneManager.LoadSceneAsync("Scenes/ExceptionExamples").WithCancellation(cts.Token);
        //    ////cts.Cancel();
        //    //await la;
        //    //UnityEngine.Debug.Log("End LoadSceneAsync" + PlayerLoopInfo.CurrentLoopType + ":" + Time.frameCount);
        //}));

        //return;
        //await UniTask.SwitchToMainThread();

        //UniTaskAsyncEnumerable.EveryValueChanged(mcc, x => x.MyProperty)
        //    .Do(_ => { }, () => Debug.Log("COMPLETED"))
        //    .ForEachAsync(x =>
        //    {
        //        Debug.Log("VALUE_CHANGED:" + x);
        //    })
        //    .Forget();

        //_ = Test1();
        //Test2().Forget();
        //StartCoroutine(Test3("https://bing.com/"));



        //bool flip = false;
        //var rect = cancelButton.GetComponent<RectTransform>();
        //var cts = new CancellationTokenSource();
        //var ct = cts.Token;
        //okButton.onClick.AddListener(UniTask.UnityAction(async () =>
        //{
        //    await rect.DOMoveX(10f * (flip ? -1 : 1), 3).OnUpdate(() => { Debug.Log("UPDATE YEAH"); }).WithCancellation(ct);
        //    flip = !flip;
        //    // ok.
        //}));
        //cancelButton.onClick.AddListener(() =>
        //{
        //    cts.Cancel();
        //});


        // DG.Tweening.Core.TweenerCore<int>
        //Debug.Log("GO MOVEX");
        //await okButton.GetComponent<RectTransform>().DOMoveX(-10.2f, 3).WithCancellation(CancellationToken.None);
        //Debug.Log("END MOVEX");


        //Debug.Log("AGAIN MOVE");
        //await okButton.GetComponent<RectTransform>().DOMoveY(10.2f, 3).WithCancellation(CancellationToken.None);
        //Debug.Log("AGAIN END MOVE");

        //Debug.Log(Test().GetType().FullName);



        // check stacktrace
        // await UniTaskAsyncEnumerable.EveryUpdate().Where((x, i) => i % 2 == 0).Select(x => x).DistinctUntilChanged().ForEachAsync(x =>
        //{
        // Debug.Log("test");
        //});



        //// DOTween.To(

        //var cts = new CancellationTokenSource();

        ////var tween = okButton.GetComponent<RectTransform>().DOLocalMoveX(100, 5.0f);

        //cancelButton.OnClickAsAsyncEnumerable().ForEachAsync(_ =>
        //{
        //    cts.Cancel();
        //}).Forget();


        //// await tween.ToUniTask(TweenCancelBehaviour.KillAndCancelAwait, cts.Token);

        ////tween.SetRecyclable(true);

        //Debug.Log("END");

        //// tween.Play();

        //// DOTween.

        //// DOVirtual.Float(0, 1, 1, x => { }).ToUniTask();


        //await foreach (var _ in UniTaskAsyncEnumerable.EveryUpdate())
        //{
        //    Debug.Log("Update() " + Time.frameCount);
        //}



        //await okButton.OnClickAsAsyncEnumerable().Where((x, i) => i % 2 == 0).ForEachAsync(_ =>
        //{
        //});


        //okButton.OnClickAsAsyncEnumerable().ForEachAsync(_ =>
        //{


        //foreach (var (type, size) in TaskPool.GetCacheSizeInfo())
        //{
        //    Debug.Log(type + ":" + size);
        //}


        //}).Forget();

        //CloseAsync(this.GetCancellationTokenOnDestroy()).Forget();

        //okButton.onClick.AddListener(UniTask.UnityAction(async () => await UniTask.Yield()));



        //UpdateUniTask().Forget();

        //StartCoroutine(Coroutine());

        //await UniTask.Delay(TimeSpan.FromSeconds(1));


        // _ = ReturnToMainThreadTest();

        //GameObject.Destroy(this.gameObject);
    }
Пример #17
0
    public IEnumerator _PostToServer(string rFileName)
    {
        while (!IsFileSaveComplete(rFileName + ".log"))
        {
            yield return(0);
        }

        var     account  = Module_Login.instance?.account;
        WWWForm postForm = new WWWForm();

        var playerName = string.Empty;

        if (Module_Player.instance != null)
        {
            playerName = Module_Player.instance.roleInfo.roleId.ToString();
        }
        var path     = gameLogger.GetFullPath(rFileName);
        var contents = Util.LoadFile(path);

        if (contents != null && contents.Length > 0)
        {
            postForm.AddBinaryData("logFile", contents, $"{rFileName }_{playerName}.log");
        }

        var request = UnityWebRequest.Post(WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA), postForm);

        request.SetRequestHeader("Content-Type", postForm.headers["Content-Type"]);
        request.SetRequestHeader("Authorization", BasicAuth(account?.acc_name ?? "null", "123456"));
        request.SetRequestHeader("X-Game-Identity", $"kzwg/{rFileName}");

        request.timeout = 5;
        yield return(request.SendWebRequest());

        if (request.isNetworkError)
        {
            Logger.LogWarning($"日志文件上传失败:{request.url}");
            yield break;
        }
        Logger.LogWarning($"日志文件上传成功:{WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA)} 数据大小:{contents.Length}");
        request.Dispose();

        while (!IsFileSaveComplete(rFileName + ".gr"))
        {
            yield return(0);
        }

        postForm = new WWWForm();
        path     = GameRecorder.GetFullPath(rFileName);
        contents = Util.LoadFile(path);
        if (contents != null && contents.Length > 0)
        {
            postForm.AddBinaryData("grFile", contents, $"{rFileName }_{playerName}.gr");
        }

        request = UnityWebRequest.Post(WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA), postForm);
        request.SetRequestHeader("Content-Type", postForm.headers["Content-Type"]);
        request.SetRequestHeader("Authorization", BasicAuth(account?.acc_name ?? "null", "123456"));
        request.SetRequestHeader("X-Game-Identity", $"kzwg/{rFileName}");

        request.timeout = 5;
        yield return(request.SendWebRequest());

        if (request.isNetworkError)
        {
            Logger.LogWarning($"录像文件上传失败:{request.url}");
            yield break;
        }
        Logger.LogWarning($"录像文件上传成功:{WebAPI.FullApiUrl(WebAPI.RES_FIGHT_DATA)} 数据大小:{contents.Length}");
        request.Dispose();
    }
Пример #18
0
        /// <summary>
        /// Get response stream from a web service indicated by URI 
        /// </summary>
        /// <param name="uri">URI (path plus query string) to web service</param>
        /// <param name="retries">The number of times to retry get if it fails</param>
        /// <param name="callback">Method called on failure or success that is passed an AsyncResult whose Result property is set to HttpResult</param>
        /// <returns>WebRequest IAsyncResult object</returns>
        public IAsyncResult Get(Uri uri, int retries, AsyncCallback callback)
        {
#if (SILVERLIGHT || WPF || TOOL)
            WebRequest webRequest = WebRequest.Create(uri);
#else
            WebRequest webRequest = new UnityWebRequest(uri);
#endif
            webRequest.Method = "GET";
            IAsyncResult asyncResult = webRequest.BeginGetResponse((responseResult) =>
            {
                bool retry = false;
                HttpResult httpResult = null;
                try
                {
                    HttpWebResponse response = ((WebRequest)responseResult.AsyncState).EndGetResponse(responseResult) as HttpWebResponse;
                    // Response stream is released when HttpResult is released
                    httpResult = new HttpResult(response.GetResponseStream(), response.StatusCode, response.StatusDescription, response.ContentType);
                }
                catch (WebException we)
                {
                    DebugLog.Error("WebException -> Get '{0}' failed", uri.ToString());
                    DebugLog.Error(we.Message);
                    if (retries > 0 && we.Status != WebExceptionStatus.RequestCanceled)
                    {
                        DebugLog.Info("Retry Get '{0}'", uri.ToString());
                        Get(uri, --retries, callback);
                        retry = true;
                    }
                    else
                    {
                        httpResult = new HttpResult(we);
                    }
                }
                catch (Exception e)
                {
                    DebugLog.Error("HTTP GET '{0}' failed: {1}", uri.ToString(), e.Message);
                    httpResult = new HttpResult(e);
                }
                finally
                {
                    if (!retry && callback != null)
                    {
                        callback(new AsyncResult<HttpResult>(httpResult));
                    }
                }
            },
            webRequest);

            return asyncResult;
        }
Пример #19
0
        static void SendHeartbeat(bool fromSave = false)
        {
            if (_debug)
            {
                Debug.Log("<WakaTime> Sending heartbeat...");
            }

            var currentScene = EditorSceneManager.GetActiveScene().path;
            var file         = currentScene != string.Empty
        ? Path.Combine(Application.dataPath, currentScene.Substring("Assets/".Length))
        : string.Empty;

            var heartbeat = new Heartbeat(file, fromSave);

            if ((heartbeat.time - _lastHeartbeat.time < HEARTBEAT_COOLDOWN) && !fromSave &&
                (heartbeat.entity == _lastHeartbeat.entity))
            {
                if (_debug)
                {
                    Debug.Log("<WakaTime> Skip this heartbeat");
                }
                return;
            }

            var heartbeatJSON = JsonUtility.ToJson(heartbeat);

            var request = UnityWebRequest.Post(URL_PREFIX + "users/current/heartbeats?api_key=" + _apiKey, string.Empty);

            request.uploadHandler   = new UploadHandlerRaw(System.Text.Encoding.UTF8.GetBytes(heartbeatJSON));
            request.chunkedTransfer = false;
            request.SetRequestHeader("Content-Type", "application/json");

            request.SendWebRequest().completed +=
                operation => {
                if (request.downloadHandler.text == string.Empty)
                {
                    Debug.LogWarning(
                        "<WakaTime> Network is unreachable. Consider disabling completely if you're working offline");
                    return;
                }

                if (_debug)
                {
                    Debug.Log("<WakaTime> Got response\n" + request.downloadHandler.text);
                }
                var response =
                    JsonUtility.FromJson <Response <HeartbeatResponse> >(
                        request.downloadHandler.text);

                if (response.error != null)
                {
                    if (response.error == "Duplicate")
                    {
                        if (_debug)
                        {
                            Debug.LogWarning("<WakaTime> Duplicate heartbeat");
                        }
                    }
                    else
                    {
                        Debug.LogError(
                            "<WakaTime> Failed to send heartbeat to WakaTime!\n" +
                            response.error);
                    }
                }
                else
                {
                    if (_debug)
                    {
                        Debug.Log("<WakaTime> Sent heartbeat!");
                    }
                    _lastHeartbeat = response.data;
                }
            };
        }
Пример #20
0
 public bool IsHttpError(UnityWebRequest request)
 {
     return(request.responseCode >= 400);
 }
Пример #21
0
    private IEnumerator LoadSongCoroutine(string songName)
    {
        string path = (Application.platform == RuntimePlatform.Android) ? androidPath + songName : Application.persistentDataPath + "/" + songName;

        if (Application.platform == RuntimePlatform.Android)
        {
            using (UnityWebRequest song = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG))
            {
                song.url = song.url.Replace("http://localhost", "file://");
                yield return(song.SendWebRequest());

                if (song.isHttpError || song.isNetworkError)
                {
                    Debug.LogError(song.error);
                }
                else
                {
                    if (song.isDone && !_songObjectCreate)
                    {
                        GameObject songObject = new GameObject("Music");
                        songObject.AddComponent <AudioSource>();
                        songObject.GetComponent <AudioSource>().clip = DownloadHandlerAudioClip.GetContent(song);
                        songObject.GetComponent <AudioSource>().Play();
                        _soundPlayer = songObject;
                        System.TimeSpan time = System.TimeSpan.FromSeconds(songObject.GetComponent <AudioSource>().clip.length);
                        _songLength.text  = time.ToString("m':'ss");
                        _songObjectAddit  = true;
                        _songObjectCreate = true;
                    }
                }
            }
        }
        else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor)
        {
            using (UnityWebRequest song = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG))
            {
                yield return(song.SendWebRequest());

                if (song.isHttpError || song.isNetworkError)
                {
                    Debug.LogError(song.error);
                }
                else
                {
                    Debug.Log(song.url);
                    if (song.isDone && !_songObjectCreate)
                    {
                        GameObject songObject = new GameObject("Music");
                        songObject.AddComponent <AudioSource>();
                        songObject.GetComponent <AudioSource>().clip = DownloadHandlerAudioClip.GetContent(song);
                        songObject.GetComponent <AudioSource>().Play();
                        _soundPlayer = songObject;
                        System.TimeSpan time = System.TimeSpan.FromSeconds(songObject.GetComponent <AudioSource>().clip.length);
                        _songLength.text  = time.ToString("m':'ss");
                        _songObjectAddit  = true;
                        _songObjectCreate = true;
                    }
                }
            }
        }
    }
Пример #22
0
 private void PrepareTusHeaders(UnityWebRequest r, string apiVersion = "3.4")
 {
     r.method = "POST";
     r.SetRequestHeader("Content-Type", "application/json");
     PrepareHeaders(r, apiVersion);
 }
Пример #23
0
        public IEnumerator PostReview(float funFactor, float rhythm, float flow, float patternQuality, float readability, float levelQuality)
        {
            yield return(null);

            BeastSaberReview review = new BeastSaberReview(GetUserInfo.GetUserName(), funFactor, rhythm, flow, patternQuality, readability, levelQuality);

            _reviewViewController.SetSubmitButtonState(true, false);
            _reviewViewController.SetStatusText(false, "");

            UnityWebRequest voteWWW = new UnityWebRequest($"https://bsaber.com/wp-json/bsaber-api/songs/{songkey}/reviews");

            voteWWW.method          = "POST";
            voteWWW.uploadHandler   = new UploadHandlerRaw(Encoding.UTF8.GetBytes(JsonUtility.ToJson(review)));
            voteWWW.downloadHandler = new DownloadHandlerBuffer();
            voteWWW.SetRequestHeader("Content-Type", "application/json");
            voteWWW.timeout = 30;
            yield return(voteWWW.SendWebRequest());

            if (voteWWW.isNetworkError)
            {
                Misc.Logger.Error(voteWWW.error);
                _reviewViewController.SetSubmitButtonState(true, true);
                _reviewViewController.SetStatusText(false, "");
            }
            else
            {
                switch (voteWWW.responseCode)
                {
                case 200:
                {
                    JSONNode node = JSON.Parse(voteWWW.downloadHandler.text);

                    if (node["success"])
                    {
                        Misc.Logger.Log("Success!");

                        if (!PluginConfig.reviewedSongs.ContainsKey(levelId.Substring(0, 32)))
                        {
                            PluginConfig.reviewedSongs.Add(levelId.Substring(0, 32), new SongReview(songkey, funFactor, rhythm, flow, patternQuality, readability, levelQuality));
                            PluginConfig.SaveConfig();
                        }
                        else
                        {
                            PluginConfig.reviewedSongs[levelId.Substring(0, 32)] = new SongReview(songkey, funFactor, rhythm, flow, patternQuality, readability, levelQuality);
                            PluginConfig.SaveConfig();
                        }

                        _reviewViewController.SetSubmitButtonState(false, false);
                        _reviewViewController.SetStatusText(true, "<color=green>Success!");
                    }
                    else
                    {
                        Misc.Logger.Error("Something went wrong...\n Response: " + voteWWW.downloadHandler.text);
                        _reviewViewController.SetSubmitButtonState(true, true);
                        _reviewViewController.SetStatusText(false, "");
                    }
                }; break;

                default:
                {
                    Misc.Logger.Error("Error: " + voteWWW.responseCode + "\nResponse: " + voteWWW.downloadHandler.text);
                    _reviewViewController.SetSubmitButtonState(true, true);
                    _reviewViewController.SetStatusText(false, "");
                }; break;
                }
            }
        }
    public override void Init()
    {
        var data = string.Empty;

        if (Application.platform == RuntimePlatform.Android)
        {
            //LogUtils.Log("loading launch cfg at android... path =", CFG_PATH);

            var url = new System.Uri(CFG_PATH.DataPath());
            UnityWebRequest.ClearCookieCache();
            UnityWebRequest reader = UnityWebRequest.Get(url);
            reader.SendWebRequest();

            while (!reader.isDone)
            {
                //.Log("loading launch cfg...");
            }

            data = reader.downloadHandler.text;

            //LogUtils.Log("loading launch cfg at android... data =", data);

            //JsonData jsond = JsonMapper.ToObject(File.ReadAllText(API_PATH));
            //if(jsond.Count > 0 && jsond[0].Count > 0)
            //{
            //    Config.APPID = Convert.ToInt32(jsond[0]["appid"]);
            //    Debug.Log(Config.APPID);
            //}
        }
        else
        {
            var file = new FileInfo(CFG_PATH.DataPath());
            if (file.Exists)
            {
                var fs = file.OpenText();
                data = fs.ReadToEnd();
                fs.Close();
            }
        }

        if (!string.IsNullOrEmpty(data))
        {
            //LogUtils.Log(data);
            Config = JsonMapper.ToObject <LaunchConfig>(data);
        }
        else
        {
            //LogUtils.Log("load launch cfg failed...");
            Config = new LaunchConfig();
        }


        if (Application.platform == RuntimePlatform.Android)
        {
            //LogUtils.Log("loading launch cfg at android... path =", API_PATH);

            var url = new System.Uri(API_PATH.DataPath());
            UnityWebRequest.ClearCookieCache();
            UnityWebRequest reader = UnityWebRequest.Get(url);
            reader.SendWebRequest();

            while (!reader.isDone)
            {
                //LogUtils.Log("loading launch cfg...");
            }

            data = reader.downloadHandler.text;

            //LogUtils.Log("loading launch cfg at android... data =", data);
        }
        else
        {
            var file = new FileInfo(API_PATH.DataPath());
            if (file.Exists)
            {
                var fs = file.OpenText();
                data = fs.ReadToEnd();
                fs.Close();
            }
        }

        if (!string.IsNullOrEmpty(data))
        {
#if BRANCH_TAPTAP
            Config.APPID = 12;
            Debug.Log("Config.APPID = " + Config.APPID);
#else
            //LogUtils.Log(data);
            JsonData deJson = LitJson.JsonMapper.ToObject(data);
            if (deJson.Keys.Contains("appid"))
            {
                Config.APPID = int.Parse(deJson["appid"].ToString());
                //Debug.Log("Config.APPID = " + Config.APPID);
            }
            if (deJson.Keys.Contains("zoneid"))
            {
                Config.ZONEID = int.Parse(deJson["zoneid"].ToString());
                //Debug.Log("Config.APPID = " + Config.ZONEID);
            }
#endif
        }
        else
        {
            //LogUtils.Log("load launch appid failed...");
        }
    }
 public static bool IsUnityWebRequestReadyForJsonExtract(UnityWebRequest unityWebRequest)
 {
     return((unityWebRequest.result != UnityWebRequest.Result.ProtocolError) && !string.IsNullOrEmpty(unityWebRequest.downloadHandler.text));
 }
    //FixedUpdate()
    void FixedUpdate()
    {
        //
        if (!modScript.ModuleLoaded)
        {
            modScript.LoadModule(testReader);
            chartsLocation += modScript.ModuleFolder + "\\";
        }

        //Starting the song
        if (canLoadSong && Input.GetKeyDown(KeyCode.P))
        {
            canLoadSong = false;
            if (modScript.ReadChartFile(testChart))
            {
                string[] difficulties = modScript.GetChartDifficulties();
                if (modScript.ReadChartData(difficulties[1]))
                {
                    //Getting the audio file
                    string audioLoc  = modScript.GetAudioFile();
                    string toReplace = testChart.Substring(testChart.LastIndexOf("\\") + 1);
                    audioLoc = testChart.Replace(toReplace, audioLoc);

                    string    audioExtension = audioLoc.Substring(audioLoc.LastIndexOf(".") + 1);
                    AudioType ext;

                    switch (audioExtension)
                    {
                    case "mp3":
                        ext = AudioType.MPEG;
                        break;

                    case "mp2":
                        ext = AudioType.MPEG;
                        break;

                    case "ogg":
                        ext = AudioType.OGGVORBIS;
                        break;

                    case "wav":
                        ext = AudioType.WAV;
                        break;

                    default:
                        throw new Exception("AUDIO TYPE NOT SUPPORTED");
                    }

                    try
                    {
                        webAudio = UnityWebRequestMultimedia.GetAudioClip("file:///" + audioLoc, ext);
                        webAudio.SendWebRequest();
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }

                    List <float>[] chartNotes = modScript.CalculateNotes();
                    for (int num = 0; num < chartNotes.Length; num++)
                    {
                        laneScripts [num].SetNotes(chartNotes [num]);
                    }

                    loadSongTime = Time.realtimeSinceStartup;
                }
            }
        }

        //
        if (Time.realtimeSinceStartup > (4f + loadSongTime) && songStartTime == 0.0f)
        {
            //Changing the song audio
            song.clip = DownloadHandlerAudioClip.GetContent(webAudio);

            //Playing the song
            song.Play();

            //
            songStartTime = (float)AudioSettings.dspTime;
        }

        //Updating the measured song time
        if (songStartTime > 0.0)
        {
            measuredTime = (float)(AudioSettings.dspTime - songStartTime) * song.pitch;
            //Debug.Log("measuredTime: " + measuredTime);
        }

        //Defining the input list
        List <bool> inputs = new List <bool>();

        foreach (LaneScript lane in laneScripts)
        {
            inputs.Add(false);
        }


        if (Input.GetKeyDown(KeyCode.S))
        {
            debug = !debug;

            if (debug)
            {
                inputText.text = "Input: Keyboard\n('S' to change)";
            }
            else
            {
                inputText.text = "Input: Touch\n('S' to change)";
            }
        }

        if (debug)
        {
            if (Input.GetKey(KeyCode.D))
            {
                inputs[0] = true;
            }
            if (Input.GetKey(KeyCode.E))
            {
                inputs[1] = true;
            }
            if (Input.GetKey(KeyCode.W))
            {
                inputs[2] = true;
            }
            if (Input.GetKey(KeyCode.Q))
            {
                inputs[3] = true;
            }
            if (Input.GetKey(KeyCode.A))
            {
                inputs[4] = true;
            }
            if (Input.GetKey(KeyCode.Z))
            {
                inputs[5] = true;
            }
            if (Input.GetKey(KeyCode.X))
            {
                inputs[6] = true;
            }
            if (Input.GetKey(KeyCode.C))
            {
                inputs[7] = true;
            }
        }
        else
        {
            Vector3 screenPos = new Vector3(0, 0, 0);
            Vector3 worldPos  = new Vector3(0, 0, 0);
            float   rads      = 0.0f;
            foreach (Touch tch in Input.touches)
            {
                screenPos.x = tch.position.x;
                screenPos.y = tch.position.y;
                worldPos    = Camera.main.ScreenToWorldPoint(screenPos);

                rads = Mathf.Atan2(worldPos.y, worldPos.x) + (Mathf.PI / 8);        //Add π/8 to offset the angle for flooring
                rads = (rads + 2 * Mathf.PI) % (2 * Mathf.PI);
                int sector = Mathf.FloorToInt(rads * (4 / Mathf.PI));
                //Debug.Log("sector: " + sector);
                inputs[sector] = true;
            }
        }

        UpdateInput(inputs.ToArray(), measuredTime);
    }
    IEnumerator UploadJPG()
    {
        // We should only read the screen buffer after rendering is complete
        yield return(new WaitForEndOfFrame());

        // Create a texture the size of the screen, RGB24 format
        int       width  = Screen.width;
        int       height = Screen.height;
        Texture2D tex    = new Texture2D(width, height, TextureFormat.RGB24, true);

        // Read screen contents into the texture
        tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex.Apply();

        Texture2D tex2 = new Texture2D(tex.width / 2, tex.height / 2, TextureFormat.RGB24, true);

        // Read screen contents into the texture
        tex2.SetPixels(tex.GetPixels(1));

        tex2.Apply();

        Texture2D tex3 = new Texture2D(tex2.width / 2, tex2.height / 2, TextureFormat.RGB24, true);

        // Read screen contents into the texture
        tex3.SetPixels(tex2.GetPixels(1));

        tex3.Apply();

        // Encode texture into PNG
        byte[] bytes     = tex3.EncodeToPNG();
        string timeStamp = idLogin.text + "_" + namaPemain.text + "_" + LevelMain.text + "_checkout_" + tnya.ToString();

        // For testing purposes, also write to a file in the project folder
        //File.WriteAllBytes(Application.dataPath + "/../"+ timeStamp + ".jpeg", bytes);

        WWWForm form = new WWWForm();

        //===========================================================================================================//
        //EDIT AFIF ALLGAME

        form.AddField("token", btn_manager_Magnet.Control.token);
        form.AddField("id_event", btn_manager_Magnet.Control.id_event);
        form.AddField("id_peserta", btn_manager_Magnet.Control.id_peserta);
        form.AddField("id_game", btn_manager_Magnet.Control.id_game);
        form.AddField("nama_hirarki", "level_5");
        form.AddBinaryData("nama_file", bytes, timeStamp + ".jpeg");
        //===========================================================================================================//



        // Upload to a cgi script
        UnityWebRequest w = UnityWebRequest.Post(Config.Control.urlImage, form);

        yield return(w.SendWebRequest());

        if (w.isNetworkError || w.isHttpError)
        {
            Loading.SetActive(false);

            Debug.Log(w.error);
        }
        else
        {
            Loading.SetActive(false);

            if (btn_manager_Magnet.Control.sceneInt < btn_manager_Magnet.Control.scene.Count)
            {
                SceneManager.LoadScene(btn_manager_Magnet.Control.scene[btn_manager_Magnet.Control.sceneInt]);
                btn_manager_Magnet.Control.sceneInt++;
            }
            else
            {
                SceneManager.LoadScene("main_akhir_tanoto");
            }
        }
    }
Пример #28
0
        public static async Task <FetchResult> LoadTask(MonoBehaviour runner, Uri uri)
        {
            FetchResult result = new FetchResult()
            {
                Asset          = null,
                FailureMessage = null
            };

            runner.StartCoroutine(LoadCoroutine());

            while (!result.IsPopulated)
            {
                await Task.Delay(50);
            }

            return(result);

            IEnumerator LoadCoroutine()
            {
                DownloadHandler handler;

                if (typeof(T) == typeof(AudioClip))
                {
                    handler = new DownloadHandlerAudioClip(uri, AudioType.UNKNOWN);
                }
                else if (typeof(T) == typeof(Texture))
                {
                    handler = new DownloadHandlerTexture(false);
                }
                else
                {
                    result.FailureMessage = $"Unknown download type: {typeof(T)}";
                    yield break;
                }

                using (var www = new UnityWebRequest(uri, "GET", handler, null))
                {
                    yield return(www.SendWebRequest());

                    if (www.isNetworkError)
                    {
                        result.FailureMessage = www.error;
                    }
                    else if (www.isHttpError)
                    {
                        result.FailureMessage = $"[{www.responseCode}] {uri}";
                    }
                    else
                    {
                        if (typeof(T) == typeof(AudioClip))
                        {
                            result.Asset = ((DownloadHandlerAudioClip)handler).audioClip as T;
                        }
                        else if (typeof(T) == typeof(Texture))
                        {
                            result.Asset = ((DownloadHandlerTexture)handler).texture as T;
                        }
                    }
                }
            }
        }
Пример #29
0
            //public void TestWordCloudRestClient() {

            //}


            /// <summary>
            /// In this method, we actually invoke a request to the outside server
            /// </summary>
            public override IEnumerator AsyncRequest(string jsonPayload, string method, string url, string success, string error)
            {
                if (!url.StartsWith("http"))
                {
                    url = "http://" + url;
                }
                UnityWebRequest webRequest;

                Debug.Log("Payload is: " + jsonPayload);

                if (jsonPayload != "0")
                {
                    var form = new WWWForm();
                    form.AddField("message", jsonPayload); // IMPORTANT: Assumes there is a form with THIS PARICULAR NAME OF FIELD
                    webRequest = UnityWebRequest.Post(url, form);
                }
                else
                {
                    // Only really handles the initialization step, to see if the server is, in fact, real
                    webRequest = new UnityWebRequest(url + route, method); // route is specific page as directed by server
                    var payloadBytes = string.IsNullOrEmpty(jsonPayload)
                        ? Encoding.UTF8.GetBytes("{}")
                        : Encoding.UTF8.GetBytes(jsonPayload);

                    UploadHandler upload = new UploadHandlerRaw(payloadBytes);
                    webRequest.uploadHandler   = upload;
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                    webRequest.SetRequestHeader("Content-Type", "application/json");
                }

                webRequest.SendWebRequest();
                int count = 0;                                    // Try several times before failing

                while (count < 20)                                // 2 seconds max is good? Probably.
                {
                    yield return(new WaitForSeconds((float)0.1)); // Totally sufficient

                    if (webRequest.isNetworkError || webRequest.isHttpError)
                    {
                        Debug.LogWarning("Some sort of network error: " + webRequest.error + " from " + url);
                    }
                    else
                    {
                        // Show results as text
                        if (webRequest.downloadHandler.text != "")
                        {
                            last_read = webRequest.downloadHandler.text;
                            //BroadcastMessage("LookForNewParse"); // Tell something, in JointGestureDemo for instance, to grab the result
                            if (webRequest.downloadHandler.text != "connected")
                            {
                                // Really needs to change. SingleAgentInteraction isn't gonna be extensible in our package-based future
                                // And I didn't ever put together that LookForNewParse function either, this section is just a ghost :P
                                SingleAgentInteraction sai = GameObject.FindObjectOfType <SingleAgentInteraction>();
                                sai.SendMessage("LookForNewParse");
                            }
                            else
                            {
                                // Blatantly janky
                                WordCloudIOClient parent = GameObject.FindObjectOfType <WordCloudIOClient>();
                                parent.wordcloudrestclient = this; // Ew, disgusting
                            }

                            Debug.Log("Server took " + count * 0.1 + " seconds");
                            POST_okay(count * 0.1); // Parameter literally means nothing here.
                            break;
                        }
                    }
                    count++;
                }
                if (count >= 20)
                {
                    Debug.LogWarning("WordCloud Server took 2+ seconds ");
                    Debug.LogWarning(webRequest.uploadHandler.data);
                }
            }
Пример #30
0
    // Send a Raw and Custom POST request to the Arcade API
    IEnumerator Post(string endpoint, string json)
    {
        var uwr = new UnityWebRequest(EndpointMaster + endpoint, "POST");

        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler   = (UploadHandler) new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        uwr.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        // Send the request then wait here until it returns
        yield return(uwr.SendWebRequest());

        if (uwr.isNetworkError)
        {
            Debug.Log("Error sending to Arcade: " + uwr.error);
        }
        else
        {
            var data = JSON.Parse(uwr.downloadHandler.text);
            //Debug.Log("Processing Arcade Signal: " + uwr.downloadHandler.text);

            if (endpoint == "ping")
            {
                Status.text = "Arcade API is Active and a connection has been established.";
            }
            else if (endpoint == "account")
            {
                try
                {
                    Debug.Log(data);

                    //Debug.Log("User has " + data["content"]["balance"].Value + " ZNZ");



                    if (data["content"]["balance"].AsFloat > 0)
                    {
                        UserBalance      = data["content"]["balance"].AsFloat;
                        BalanceText.text = "ZNZ: " + UserBalance.ToString();
                    }

                    if (data["content"]["username"] != null)
                    {
                        UsernameText.text = data["content"]["username"].ToString();
                    }

                    if (data["content"]["email"] != null)
                    {
                        EmailText.text = data["content"]["email"].ToString();
                    }

                    if (data["content"]["id"] != null)
                    {
                        IDText.text = data["content"]["id"].ToString();
                    }

                    if (data["content"]["address"] != null)
                    {
                        AddressText.text = data["content"]["address"].ToString();
                    }


                    StartCoroutine(GetAvatar(data["content"]["avatar"].Value));



                    Status.text = "Data Retrieved Successfully";
                }
                catch (Exception e)
                {
                    Status.text = "Arcade Status: Invalid Key";
                    Status.text = "Arcade: Unable to parse user object, probably an incorrect API Key.";
                }
            }
        }
    }
Пример #31
0
 public override void OnSetDownloadHandler(UnityWebRequest request)
 {
 }
Пример #32
0
    static async UniTask <UnityWebRequest> UniAsync(string url, CancellationToken cancellationToken)
    {
        var req = await UnityWebRequest.Get(url).SendWebRequest().WithCancellation(cancellationToken);

        return(req);
    }
Пример #33
0
 private static RequestException CreateException(UnityWebRequest request)
 {
     return(new RequestException(request.error, request.isHttpError, request.isNetworkError, request.responseCode,
                                 !request.url.Contains("/levels/packages/") ? request.downloadHandler.text : "Response muted"));
 }
Пример #34
0
        private IEnumerator CheckPlugins()
        {
            Dictionary <string, PluginInfo> pluginInfos = Chainloader.PluginInfos;
            Dictionary <string, string>     ignores     = GetIgnores();

            foreach (KeyValuePair <string, PluginInfo> kvp in pluginInfos)
            {
                Version currentVersion = kvp.Value.Metadata.Version;
                string  pluginName     = kvp.Value.Metadata.Name;
                string  guid           = kvp.Value.Metadata.GUID;

                string cfgFile = Path.Combine(new string[] { Directory.GetParent(Path.GetDirectoryName(typeof(BepInProcess).Assembly.Location)).FullName, "config", $"{guid}.cfg" });
                //Dbgl($"{cfgFile}");
                if (!File.Exists(cfgFile))
                {
                    if (createEmptyConfigFiles.Value)
                    {
                        File.Create(cfgFile);
                    }
                    continue;
                }

                int      id       = -1;
                string[] cfgLines = File.ReadAllLines(cfgFile);
                foreach (string line in cfgLines)
                {
                    if (line.Trim().ToLower().StartsWith("nexusid"))
                    {
                        Match match = Regex.Match(line, @"[0-9]+");
                        if (match.Success)
                        {
                            id = int.Parse(match.Value);
                        }
                        break;
                    }
                }
                if (id == -1)
                {
                    continue;
                }

                Dbgl($"{pluginName} {id} current version: {currentVersion}");

                WWWForm form = new WWWForm();

                UnityWebRequest uwr = UnityWebRequest.Get($"https://www.nexusmods.com/valheim/mods/{id}");
                yield return(uwr.SendWebRequest());

                if (uwr.isNetworkError)
                {
                    Debug.Log("Error While Sending: " + uwr.error);
                }
                else
                {
                    //Dbgl($"entire text: {uwr.downloadHandler.text}.");

                    string[] lines = uwr.downloadHandler.text.Split(
                        new[] { "\r\n", "\r", "\n" },
                        StringSplitOptions.None
                        );
                    bool check = false;
                    foreach (string line in lines)
                    {
                        if (check && line.Contains("<div class=\"stat\">"))
                        {
                            Match match = Regex.Match(line, @"<[^>]+>[^0-9.]*([0-9.]+)[^0-9.]*<[^>]+>");
                            if (!match.Success)
                            {
                                break;
                            }

                            Version version = new Version(match.Groups[1].Value);
                            Dbgl($"remote version: {version}.");

                            if (ignores.ContainsKey("" + id))
                            {
                                if (ignores["" + id] == version.ToString())
                                {
                                    if (!showAllManagedMods.Value)
                                    {
                                        Dbgl($"ignoring {pluginName} {id} version: {version}");
                                        break;
                                    }
                                }
                                else
                                {
                                    Dbgl($"new version {version}, removing ignore {ignores[""+id]}");
                                    RemoveIgnore("" + id);
                                }
                            }


                            if (version > currentVersion)
                            {
                                Dbgl($"new remote version: {version}!");
                                nexusUpdatables.Add(new NexusUpdatable(pluginName, id, currentVersion, version));
                            }
                            else if (showAllManagedMods.Value)
                            {
                                nexusNonupdatables.Add(new NexusUpdatable(pluginName, id, currentVersion, version));
                            }
                            break;
                        }
                        if (line.Contains("<li class=\"stat-version\">"))
                        {
                            check = true;
                        }
                    }
                }
            }
            finishedChecking = true;
        }
        private IEnumerator ProcessRequestQueue()
        {
            // yield AFTER we increment the connection count, so the Send() function can return immediately
            _activeConnections += 1;
#if UNITY_EDITOR
            if (!UnityEditorInternal.InternalEditorUtility.inBatchMode)
            {
                yield return(null);
            }
#else
            yield return(null);
#endif

            while (_requests.Count > 0)
            {
                Request req = _requests.Dequeue();
                if (req.Cancel)
                {
                    continue;
                }
                string url = URL;
                if (!string.IsNullOrEmpty(req.Function))
                {
                    url += req.Function;
                }

                StringBuilder args = null;
                foreach (var kp in req.Parameters)
                {
                    var key   = kp.Key;
                    var value = kp.Value;

                    if (value is string)
                    {
                        value = UnityWebRequest.EscapeURL((string)value);
                    }
                    else if (value is byte[])
                    {
                        value = Convert.ToBase64String((byte[])value);
                    }
                    else if (value is Int32 || value is Int64 || value is UInt32 || value is UInt64 || value is float)
                    {
                        value = value.ToString();
                    }
                    else if (value is bool)
                    {
                        value = value.ToString().ToLower();
                    }
                    else if (value is DateTime?)
                    {
                        value = String.Format("{0:yyyy-MM-ddThh:mm:ssZ}", value);//yyyy-MM-ddthh:mm:ssz
                    }
                    else if (value != null)
                    {
                        Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported parameter value type {0}", value.GetType().Name);
                    }
                    else
                    {
                        Log.Error("RESTConnector.ProcessRequestQueue()", "Parameter {0} value is null", key);
                    }

                    if (args == null)
                    {
                        args = new StringBuilder();
                    }
                    else
                    {
                        args.Append("&");
                    }

                    args.Append(key + "=" + value);
                }

                if (args != null && args.Length > 0)
                {
                    url += "?" + args.ToString();
                }

                AddHeaders(req.Headers);

                Response resp = new Response();

                DateTime        startTime       = DateTime.Now;
                UnityWebRequest unityWebRequest = null;
                if (req.Forms != null || req.Send != null)
                {
                    //  POST and PUT with data
                    if (req.Forms != null)
                    {
                        if (req.Send != null)
                        {
                            Log.Warning("RESTConnector", "Do not use both Send & Form fields in a Request object.");
                        }

                        WWWForm form = new WWWForm();
                        try
                        {
                            foreach (var formData in req.Forms)
                            {
                                if (formData.Value.IsBinary)
                                {
                                    form.AddBinaryData(formData.Key, formData.Value.Contents, formData.Value.FileName, formData.Value.MimeType);
                                }
                                else if (formData.Value.BoxedObject is string)
                                {
                                    form.AddField(formData.Key, (string)formData.Value.BoxedObject);
                                }
                                else if (formData.Value.BoxedObject is int)
                                {
                                    form.AddField(formData.Key, (int)formData.Value.BoxedObject);
                                }
                                else if (formData.Value.BoxedObject != null)
                                {
                                    Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported form field type {0}", formData.Value.BoxedObject.GetType().ToString());
                                }
                            }
                            foreach (var headerData in form.headers)
                            {
                                req.Headers[headerData.Key] = headerData.Value;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Error("RESTConnector.ProcessRequestQueue()", "Exception when initializing WWWForm: {0}", e.ToString());
                        }
                        unityWebRequest = UnityWebRequest.Post(url, form);
                    }
                    else if (req.Send != null)
                    {
                        unityWebRequest = new UnityWebRequest(url, req.HttpMethod)
                        {
                            uploadHandler = (UploadHandler) new UploadHandlerRaw(req.Send)
                        };

                        unityWebRequest.SetRequestHeader("Content-Type", "application/json");
                    }
                }
                else
                {
                    //  GET, DELETE and POST without data
                    unityWebRequest = new UnityWebRequest
                    {
                        url    = url,
                        method = req.HttpMethod
                    };

                    if (req.HttpMethod == UnityWebRequest.kHttpVerbPOST)
                    {
                        unityWebRequest.SetRequestHeader("Content-Type", "application/json");
                    }
                }

                foreach (KeyValuePair <string, string> kvp in req.Headers)
                {
                    unityWebRequest.SetRequestHeader(kvp.Key, kvp.Value);
                }

                unityWebRequest.downloadHandler = new DownloadHandlerBuffer();

                if (req.DisableSslVerification == true)
                {
                    unityWebRequest.certificateHandler = new AcceptAllCertificates();
                }
                else
                {
                    unityWebRequest.certificateHandler = null;
                }

#if UNITY_2017_2_OR_NEWER
                unityWebRequest.SendWebRequest();
#else
                www.Send();
#endif
#if ENABLE_DEBUGGING
                Log.Debug("RESTConnector", "URL: {0}", url);
#endif

                // wait for the request to complete.
                float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout);
                while (!unityWebRequest.isDone)
                {
                    if (req.Cancel)
                    {
                        break;
                    }
                    if ((DateTime.Now - startTime).TotalSeconds > timeout)
                    {
                        break;
                    }
                    if (req.OnUploadProgress != null)
                    {
                        req.OnUploadProgress(unityWebRequest.uploadProgress);
                    }
                    if (req.OnDownloadProgress != null)
                    {
                        req.OnDownloadProgress(unityWebRequest.downloadProgress);
                    }

#if UNITY_EDITOR
                    if (!UnityEditorInternal.InternalEditorUtility.inBatchMode)
                    {
                        yield return(null);
                    }
#else
                    yield return(null);
#endif
                }

                if (req.Cancel)
                {
                    continue;
                }

                bool     bError = false;
                IBMError error  = null;
                if (!string.IsNullOrEmpty(unityWebRequest.error))
                {
                    switch (unityWebRequest.responseCode)
                    {
                    case HTTP_STATUS_OK:
                    case HTTP_STATUS_CREATED:
                    case HTTP_STATUS_ACCEPTED:
                        bError = false;
                        break;

                    default:
                        bError = true;
                        break;
                    }

                    string errorMessage = GetErrorMessage(unityWebRequest.downloadHandler.text);

                    error = new IBMError()
                    {
                        Url             = url,
                        StatusCode      = unityWebRequest.responseCode,
                        ErrorMessage    = errorMessage,
                        Response        = unityWebRequest.downloadHandler.text,
                        ResponseHeaders = unityWebRequest.GetResponseHeaders()
                    };
                    if (bError)
                    {
                        Log.Error("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, unityWebRequest.responseCode, unityWebRequest.error,
                                  string.IsNullOrEmpty(unityWebRequest.downloadHandler.text) ? "" : unityWebRequest.downloadHandler.text);
                    }
                    else
                    {
                        Log.Warning("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, unityWebRequest.responseCode, unityWebRequest.error,
                                    string.IsNullOrEmpty(unityWebRequest.downloadHandler.text) ? "" : unityWebRequest.downloadHandler.text);
                    }
                }
                if (!unityWebRequest.isDone)
                {
                    Log.Error("RESTConnector.ProcessRequestQueue()", "Request timed out for URL: {0}", url);
                    bError = true;
                }

                // generate the Response object now..
                if (!bError)
                {
                    resp.Success          = true;
                    resp.Data             = unityWebRequest.downloadHandler.data;
                    resp.HttpResponseCode = unityWebRequest.responseCode;
                }
                else
                {
                    resp.Success = false;
                    resp.Error   = error;
                }

                resp.Headers = unityWebRequest.GetResponseHeaders();

                resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds;

                // if the response is over a threshold, then log with status instead of debug
                if (resp.ElapsedTime > LogResponseTime)
                {
                    Log.Warning("RESTConnector.ProcessRequestQueue()", "Request {0} completed in {1} seconds.", url, resp.ElapsedTime);
                }

                if (req.OnResponse != null)
                {
                    req.OnResponse(req, resp);
                }

                unityWebRequest.Dispose();
            }

            // reduce the connection count before we exit.
            _activeConnections -= 1;
            yield break;
        }
        private void PostObject(PostObjectRequest request, AsyncOptions options, Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper)
        {
            string url;
            string subdomain = request.Region.Equals(RegionEndpoint.USEast1) ? "s3" : "s3-" + request.Region.SystemName;
            IDictionary<string, string> headers = new Dictionary<string, string>();

            if (request.Bucket.IndexOf('.') > -1)
                url = string.Format(CultureInfo.InvariantCulture, "https://{0}.amazonaws.com/{1}/", subdomain, request.Bucket);
            else
                url = string.Format(CultureInfo.InvariantCulture, "https://{0}.{1}.amazonaws.com", request.Bucket, subdomain);
            Uri uri = new Uri(url);

            UnityWebRequest webRequest = new UnityWebRequest(uri);

            var boundary = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Replace('=', 'z');

            headers[HeaderKeys.ContentTypeHeader] = string.Format(CultureInfo.InvariantCulture, "multipart/form-data; boundary={0}", boundary);
            headers[HeaderKeys.UserAgentHeader] = AWSSDKUtils.UserAgentHeader;

            webRequest.Method = "POST";

            using (var reqStream = new MemoryStream())
            {
                request.WriteFormData(boundary, reqStream);

                byte[] boundaryBytes = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "--{0}\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n", boundary));

                reqStream.Write(boundaryBytes, 0, boundaryBytes.Length);

                using (var inputStream = null == request.Path ? request.InputStream : File.OpenRead(request.Path))
                {
                    byte[] buf = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.Read(buf, 0, 1024)) > 0)
                    {
                        reqStream.Write(buf, 0, bytesRead);
                    }
                }

                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "\r\n--{0}--", boundary));

                reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

                webRequest.WriteToRequestBody(null, reqStream.ToArray(), headers);
            }

            var executionContext = new AsyncExecutionContext(
                new AsyncRequestContext(this.Config.LogMetrics)
                {
                    ClientConfig = this.Config,
                    OriginalRequest = request,
                    Action = callbackHelper,
                    AsyncOptions = options,
                    IsAsync = true
                },
                new AsyncResponseContext()
            );

            webRequest.SetRequestHeaders(headers);
            executionContext.RuntimeState = webRequest;


            executionContext.ResponseContext.AsyncResult =
                       new RuntimeAsyncResult(executionContext.RequestContext.Callback,
                           executionContext.RequestContext.State);
            executionContext.ResponseContext.AsyncResult.AsyncOptions = executionContext.RequestContext.AsyncOptions;
            executionContext.ResponseContext.AsyncResult.Action = executionContext.RequestContext.Action;
            executionContext.ResponseContext.AsyncResult.Request = executionContext.RequestContext.OriginalRequest;

            webRequest.BeginGetResponse(new AsyncCallback(ProcessPostResponse), executionContext);
        }
Пример #37
0
 public bool IsNetworkError(UnityWebRequest request)
 {
     return(request.isError && !IsHttpError(request));
 }