Exemplo n.º 1
0
 private void Abort()
 {
     mRequester?.Abort();
     if (IsLoading)
     {
         AfterCheckResult();
         Asyncer = default;
     }
     else
     {
     }
 }
Exemplo n.º 2
0
 public void abort()
 {
     req?.Abort();
     req = null;
     requestHandle?.Dispose();
     requestHandle = null;
 }
Exemplo n.º 3
0
 public void DoAbort(Action onComplete)
 {
     try
     {
         m_WebRequest?.Abort();
         m_WebRequest = null;
         var error = Cache.TryDelete(Name);
         if (error != null)
         {
             Log.Exception(error);
         }
     }
     catch (Exception ex)
     {
         Log.Exception(ex);
     }
     finally
     {
         onComplete();
     }
 }
Exemplo n.º 4
0
    /// <summary>
    /// Checks if the UnityWebRequest made is uploading and responsive.
    /// </summary>
    /// <remarks>
    /// If the Web Request is unresponsive for more than 10 secs it is likely that the internet connection is cut-off
    /// </remarks>
    /// <param name="uwr">UnityWebRequest object</param>
    /// <returns></returns>
    private IEnumerator CheckUploadConnection(UnityWebRequest uwr)
    {
        bool  IsAborted = false;
        int   counter = 0;
        float previousProgress, currentProgress, deltaProgress;

        while (!uwr.isDone && !IsAborted)
        {
            previousProgress = uwr.uploadProgress;
            yield return(new WaitForSeconds(1.0f));

            try
            {
                currentProgress = uwr.uploadProgress;
            }
            catch (ArgumentNullException ex)
            {
                Debug.Log("[Web Request Object is Disposed] : " + ex.Message);
                break;
            }
            deltaProgress = currentProgress - previousProgress;
            if (deltaProgress <= 0.0f)
            {
                counter++;
            }
            else
            {
                counter = 0;
            }
            if (counter > 10)
            {
                Debug.Log("10 Secs elapsed without any progress.");
                if (uwr != null)
                {
                    Debug.Log("Aborted!");
                    IsAborted = true;
                    uwr.Abort();
                }
            }
        }
    }
Exemplo n.º 5
0
        private static IEnumerator SendAndWait <T>(this UnityWebRequest self, Response <T> resp)
        {
            SetupDownloadAndUploadHanders(self, resp);
            resp.duration = Stopwatch.StartNew();
            var timer = Stopwatch.StartNew();

            self.ApplyAllCookiesToRequest();
            if (self.downloadHandler == null)
            {
                self.downloadHandler = resp.createDownloadHandler();
            }
            resp.debugInfo = self.method + " " + self.url + " with cookies=[" + self.GetRequestHeader("Cookie") + "]";
            Log.d("Sending: " + resp);
            var req = self.SendWebRequest();

            timer.AssertUnderXms(40);
            while (!req.isDone)
            {
                var currentProgress = req.progress * 100;
                if (resp.progressInPercent.setNewValue(currentProgress))
                {
                    timer.Restart();
                    resp.onProgress.InvokeIfNotNull(resp.progressInPercent.value);
                }
                yield return(resp.wait);

                if (timer.ElapsedMilliseconds > resp.maxMsWithoutProgress)
                {
                    self.Abort();
                }
            }
            resp.duration.Stop();
            Log.d("   > Finished " + resp);
            AssertResponseLooksNormal(self, resp);
            self.SaveAllNewCookiesFromResponse();
            if (self.error.IsNullOrEmpty())
            {
                resp.progressInPercent.setNewValue(100);
            }
            resp.getResult = () => { return(self.GetResult <T>()); };
        }
Exemplo n.º 6
0
        public void Cancel(bool save = false)
        {
            CloseStream();

            if (!save)
            {
                if (File.Exists(tempPath))
                {
                    File.Delete(tempPath);
                }
            }

            canceled = true;

            if (_request != null)
            {
                _request.Abort();
            }

            DisposeRequest();
        }
Exemplo n.º 7
0
        public override void Dispose()
        {
            m_onProgress  = null;
            m_onCompleted = null;
            if (m_request != null)
            {
                if (!m_request.isDone)
                {
                    m_request.Abort();
                }

                m_request.Dispose();
                m_request = null;
            }

            if (m_downloadHandler != null)
            {
                m_downloadHandler.Close();
                m_downloadHandler = null;
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 停止加载
        /// </summary>
        public virtual void Stop()
        {
            _stats.Reset();
            _state = LoadState.STOPED;

            if (_task != null)
            {
                _task.Stop();
            }

            if (_request != null)
            {
                _request.Abort();
                _request.Dispose();
                _request = null;
            }

            if (_stopCallback != null)
            {
                _stopCallback.Invoke(this);
            }
        }
Exemplo n.º 9
0
        public void Cancel(bool throwException = false)
        {
            if (request == null)
            {
                return;
            }

            if (throwException)
            {
                throw new UnityWebRequestErrorException(request);
            }

            try
            {
                request.Abort();
            }
            finally
            {
                request.Dispose();
                request = null;
            }
        }
Exemplo n.º 10
0
        internal static bool CheckUrlExists(string url)
        {
            bool result = false;

            using (UnityWebRequest req = UnityWebRequest.Get(url))
            {
                req.SendWebRequest();

                while (req.downloadedBytes > 0)
                {
                }

                if (req.WebRequestSucceded())
                {
                    result = true;
                }

                req.Abort();
            }

            return(result);
        }
Exemplo n.º 11
0
    IEnumerator RequestPicture(string url, float timeOut, OnImageLoaded onImageLoaded, OnDownloadProgress onDownloadProgress)
    {
        UnityWebRequest webRequest            = UnityWebRequestTexture.GetTexture(url);
        UnityWebRequestAsyncOperation handler = webRequest.SendWebRequest();

        float timeIn    = 0f;
        bool  isAborted = false;

        while (!handler.isDone)
        {
            timeIn += Time.deltaTime;
            if (onDownloadProgress != null)
            {
                onDownloadProgress(handler.progress);
            }
            if (timeIn > timeOut)
            {
                //Security
                isAborted = true;
                webRequest.Abort();
                break;
            }
            yield return(null);
        }

        if (webRequest.isNetworkError || webRequest.isHttpError || isAborted)
        {
            Debug.Log(webRequest.error);
            onImageLoaded(null);
        }
        else
        {
            //Call end
            Texture2D textureRequested = DownloadHandlerTexture.GetContent(webRequest);
            onImageLoaded(textureRequested);
        }

        yield break;
    }
Exemplo n.º 12
0
    void OnGUI()
    {
        if (GUILayout.Button("Download"))
        {
            WebRequestMgr.DownloadFile(url, Application.dataPath + "/../new_pack.zip", (e) => { uwr = e; }, (e) =>
            {
                downloadInfo.text = "Finish";
                slider.value      = 1f;
            }, (msg) => { downloadInfo.text = "Error"; }, (asyncOp) =>
            {
                var downloadHandler = asyncOp.webRequest.downloadHandler as DownloadHandlerFileRange;
                //var hint = $"Progress:{asyncOp.progress}\nDownload:{handler.DownloadProgress}\nSpeed:{handler.Speed}";
                long totalSize    = downloadHandler.FileSize;
                long curSize      = downloadHandler.DownloadedSize;
                var hint          = $"下载补丁包中...({curSize}/{totalSize})({downloadHandler.DownloadProgress * 100}%)";
                downloadInfo.text = hint;
                slider.value      = asyncOp.progress;
                Debug.Log(hint);
            });
        }

        if (GUILayout.Button("Abort"))
        {
            if (uwr != null)
            {
                uwr.Abort();
            }
        }

        if (GUILayout.Button("GamePatch Check"))
        {
            patcher.CheckResVer((str) => { downloadInfo.text = str; }, (val) => { slider.value = val; }, () =>
            {
                downloadInfo.text = "GamePatch Finish";
                slider.value      = 1f;
            });
        }
    }
Exemplo n.º 13
0
        private void CancelOperation()
        {
            // Stop any async action taking place.
            if (_downloader != null)
            {
                _downloader.Abort(); // The coroutine should resume and clean up.
                return;
            }

            if (_editorCoroutine != null)
            {
                this.StopCoroutine(_editorCoroutine.routine);
            }

            if (_editorCoroutineSelfUpdate != null)
            {
                this.StopCoroutine(_editorCoroutineSelfUpdate.routine);
            }

            _editorCoroutineSelfUpdate = null;
            _editorCoroutine           = null;
            _downloader = null;
        }
Exemplo n.º 14
0
    static IEnumerator WEBRequestxxx()
    {
        Dictionary <string, string> dic = new Dictionary <string, string>();

        dic.Add("gameid", "12");
        UnityWebRequest webRequest = UnityWebRequest.Post("https://cdkey.longtubas.com/Cdk/shiyong", dic);

        webRequest.SetRequestHeader("apikey", "geMLnco7TiehcfddrB16NuSV3lUBn1Yz");
        yield return(webRequest.Send());

        print("发送王弼");
        if (webRequest.error != null)
        {
            print("error");
        }
        else
        {
            print("xxxx");
            string returnMessage = webRequest.downloadHandler.text;
            print(returnMessage);
        }
        webRequest.Abort();
    }
Exemplo n.º 15
0
        private static string DownloadRepository()
        {
            string repositoryFilePath;

            using (UnityWebRequest request = UnityWebRequest.Get(_githubRepoUri))
            {
                UnityWebRequestAsyncOperation operation = request.SendWebRequest();
                while (!operation.isDone)
                {
                    bool cancelPressed = EditorUtility.DisplayCancelableProgressBar("Downloading from GitHub", $"Downloading from repository Uri: {_githubRepoUri}", operation.progress);
                    if (!cancelPressed)
                    {
                        continue;
                    }
                    request.Abort();
                    EditorUtility.ClearProgressBar();
                    return(null);
                }
                repositoryFilePath = WriteDownloadedData(request.downloadHandler.data);
            }
            EditorUtility.ClearProgressBar();
            return(repositoryFilePath);
        }
Exemplo n.º 16
0
        private static async Task <UnityWebRequest> SendWebRequest(UnityWebRequest request, CancellationTokenSource cancelationToken = null, System.Action <float> progress = null)
        {
            while (!Caching.ready)
            {
                if (cancelationToken != null && cancelationToken.IsCancellationRequested)
                {
                    return(null);
                }
                await Task.Yield();
            }

#pragma warning disable CS4014
            request.SendWebRequest();
#pragma warning restore CS4014

            while (!request.isDone)
            {
                if (cancelationToken != null && cancelationToken.IsCancellationRequested)
                {
                    request.Abort();
                    var url = request.url;
                    request.Dispose();
                    throw new Exception(string.Format("Netowrk.SendWebRequest - cancel download: {0}", url));
                }
                else
                {
                    progress?.Invoke(request.downloadProgress);
                    await Task.Yield();
                }
            }

            if (!request.isNetworkError)
            {
                progress?.Invoke(1f);
            }
            return(request);
        }
Exemplo n.º 17
0
    /// <summary>
    /// Send a request to the server, if fails, will try again for a total of 5 times
    /// </summary>
    /// <param name="form">The form to be submitted</param>
    /// <param name="targetScript">The php script to send to</param>
    /// <param name="onSuccess">Success request callback</param>
    /// <param name="onFail">Failed request callback</param>
    /// <param name="onAttemptsFailed">All attempts failed callback</param>
    /// <returns></returns>
    private IEnumerator SendPostRequest(WWWForm form, string targetScript, Action <String> onSuccess, Action onFail, Action onAttemptsFailed)
    {
        int attempts = 0;

        while (attempts < 5)
        {
            Logger.LogToFile("Sending to: " + currentServer + targetScript + ", attempt: " + attempts);

            using (UnityWebRequest www = UnityWebRequest.Post(currentServer + targetScript, form))
            {
                www.timeout = 5;

                yield return(www.SendWebRequest());

                if (www.isNetworkError || www.isHttpError)
                {
                    Logger.LogToFile("Network error " + www.error);
                    onFail();
                    Debug.Log("Error " + www.error);
                    www.Abort();
                    www.Dispose();
                    attempts++;
                }
                else
                {
                    //Debug.Log("Server OK " + www.downloadHandler.text);
                    Logger.LogToFile("Successful reply " + www.downloadHandler.text);
                    onSuccess(www.downloadHandler.text);
                    www.Dispose();
                    yield break;
                }
            }
        }
        Logger.LogToFile("Finished send form coroutine");
        onAttemptsFailed();
        yield break;
    }
Exemplo n.º 18
0
        IEnumerator DownloadFileSizeHandler()
        {
            HeadHandler     handler = new HeadHandler();
            UnityWebRequest request = UnityWebRequest.Head(mDownloadObj.url);

            request.downloadHandler = handler;
            request.timeout         = UnityDownloadManager.TIMEOUT;
            request.chunkedTransfer = true;
            request.disposeDownloadHandlerOnDispose = true;
            yield return(request.SendWebRequest());

            //Dictionary<string, string> dic = request.GetResponseHeaders();
            //foreach (var item in dic) Debug.Log(item.Key + "     " + item.Value);
            //item.Key:Content-Type  item.Value:video/mp4
            //item.Key:Content-Disposition  item.Value:inline; filename = "o_1d6hoeipu1bem1rdjvqtush1gu8l.mp4"; filename *= utf - 8' 'o_1d6hoeipu1bem1rdjvqtush1gu8l.mp4

            //设置文件名的后缀
            string content_Type = request.GetResponseHeader("Content-Type");

            string[] arr     = content_Type.Split('/');
            string   houzhui = string.Format(".{0}", arr[arr.Length - 1]);

            if (!mDownloadObj.fileName.Contains("."))
            {
                mDownloadObj.fileName += houzhui;
                Debug.Log("添加后缀:" + mDownloadObj.fileName);
            }

            if (mDownloadObj.OnGetFileSizeAction != null)
            {
                mDownloadObj.SetContentLength(handler.ContentLength);
                mDownloadObj.OnGetFileSizeAction((int)request.responseCode, mDownloadObj);//request.responseCode == 200 代表获取文件大小成功
            }
            request.Abort();
            request.Dispose();
        }
Exemplo n.º 19
0
        private IEnumerator sendRequest()
        {
#if HAS_TIMEOUT
            Request.timeout = Timeout;
#else
            _timeoutCounter = Timeout;
#endif

            // send the request
            AsyncOperation op = null;
            try
            {
                op = Request.SendWebRequest();
            }
            catch (Exception e)
            {
                UploadException = e;
                yield break;
            }

            // block until request is finished
            while (!op.isDone)
            {
                yield return(new WaitForEndOfFrame());

#if !HAS_TIMEOUT
                _timeoutCounter -= Time.deltaTime;
                if (_timeoutCounter <= 0)
                {
                    _requestTimedOut = true;
                    Request.Abort();
                    break;
                }
#endif
            }
        }
Exemplo n.º 20
0
    private IEnumerator IPostAPI(string url, WWWForm form, Action <ErrorResponse, string> cb)
    {
        Debug.Log("PostAPI " + url);
        using (UnityWebRequest www = UnityWebRequest.Post(url, form)) {
            AsyncOperation op = www.SendWebRequest();

            float timer  = 0;
            bool  failed = false;

            while (op.isDone == false)
            {
                if (timer > 15)
                {
                    www.Abort();
                    failed = true;
                    break;
                }
                timer += Time.deltaTime;

                yield return(null);
            }

            if (failed)
            {
                cb(new ErrorResponse(GameDefines.LOCAL_ERROR_TIME_OUT, "Time out"), null);
            }
            else if (www.isNetworkError)
            {
                cb(new ErrorResponse(www.responseCode, www.error), null);
            }
            else
            {
                cb(null, www.downloadHandler.text);
            }
        }
    }
Exemplo n.º 21
0
        // Load complete
        private void LoadComplete(bool destroy)
        {
            // Early
            if (!_request.isDone)
            {
                Log("REQUEST ABORTED\nURL: " + _request.url, true);
                _request.Abort();
            }

            // Errors
            if (_request.isHttpError)
            {
                Log("REQUEST HTTP ERROR\nURL: " + _request.url + "\nERROR: " + _request.error, true);
            }
            if (_request.isNetworkError)
            {
                Log("REQUEST NETWORK ERROR\nURL: " + _request.url + "\nERROR: " + _request.error, true);
            }

            // Call on complete delegate
            if (_onComplete != null)
            {
                _onComplete(_request);
                _onComplete = null;
            }

            // Dispose request
            _request.Dispose();
            _request = null;

            // Destroy
            if (destroy)
            {
                DestroyImmediate(gameObject);
            }
        }
Exemplo n.º 22
0
        public static void doCheckWWWTimeout(UnityWebRequest www, NewList list)
        {
            //yield return new WaitForSeconds(checkProgressSec);
            string      url                = list[0] as string;
            object      timeoutCallback    = list[1];
            float       checkProgressSec   = (float)(list[2]);
            object      orgs               = list[3];
            float       oldProgress        = (float)(list[4]);
            float       oldSize            = (float)(list[5]);
            float       lastCheckTime      = (float)(list[6]);
            int         maxFailTimes       = (int)(list[7]);
            int         failedTimes        = (int)(list[8]);
            RedCallback redrectioncallback = list[9] as RedCallback;

            if (Time.realtimeSinceStartup - lastCheckTime < 0)
            {
                return;
            }
            try
            {
                if (www != null)
                {
                    if (www.isDone)
                    {
                        wwwMap4Check.Remove(www);
                        list.Clear();
                        ObjPool.listPool.returnObject(list);
                    }
                    else
                    {
                        float curProgress = 0;
                        float curSize     = 0;
                        if (www.method == "PUT")
                        {
                            curProgress = www.uploadProgress;
                            if (www.uploadHandler != null && www.uploadHandler.data != null)
                            {
                                curSize = www.uploadHandler.data.Length;
                            }
                        }
                        else
                        {
                            curProgress = www.downloadProgress;
                            if (www.downloadHandler != null && www.downloadHandler.data != null)
                            {
                                curSize = www.downloadHandler.data.Length;
                            }
                        }

                        if (Mathf.Abs(curProgress - oldProgress) < 0.0001f &&
                            Mathf.Abs(curSize - oldSize) < 0.0001f)
                        {
                            //说明没有变化,可能网络不给力
                            if (maxFailTimes > failedTimes + 1)
                            {
                                if (redrectioncallback != null)
                                {
                                    redrectioncallback(url);
                                }
                            }
                            else
                            {
                                Coroutine corout = wwwMap4Get[url] as Coroutine;
                                if (corout != null)
                                {
                                    self.StopCoroutine(corout);
                                }
                                wwwMap4Get.Remove(url);
                                wwwMapUrl.Remove(url);

                                list.Clear();
                                ObjPool.listPool.returnObject(list);
                                wwwMap4Check.Remove(www);

                                www.Abort();
                                www.Dispose();
                                www = null;
                                Debug.LogError("www time out! url==" + url);
                                Utl.doCallback(timeoutCallback, null, orgs);
                            }
                        }
                        else
                        {
                            //Coroutine cor = self.StartCoroutine(doCheckWWWTimeout(www, url, checkProgressSec, timeoutCallback, curProgress, orgs));
                            list[4]           = curProgress;
                            list[5]           = curSize;
                            list[6]           = Time.realtimeSinceStartup + checkProgressSec;
                            wwwMap4Check[www] = list;
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
            }
        }
Exemplo n.º 23
0
        protected IEnumerator LoadAssetBundleWithDeps(string baseUrl, string hash, Action OnSuccess, Action OnFail)
        {
            string finalUrl = baseUrl + hash;

            if (failedRequestUrls.Contains(finalUrl))
            {
                OnFail?.Invoke();
                yield break;
            }

            yield return(WaitForConcurrentRequestsSlot());

            RegisterConcurrentRequest();
#if UNITY_EDITOR
            assetBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(finalUrl, Hash128.Compute(hash));
#else
            //NOTE(Brian): Disable in build because using the asset bundle caching uses IDB.
            assetBundleRequest = UnityWebRequestAssetBundle.GetAssetBundle(finalUrl);
#endif
            asyncOp = assetBundleRequest.SendWebRequest();

            if (!DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash))
            {
                CoroutineStarter.Start(DependencyMapLoadHelper.GetDepMap(baseUrl, hash));
            }

            yield return(DependencyMapLoadHelper.WaitUntilDepMapIsResolved(hash));

            if (DependencyMapLoadHelper.dependenciesMap.ContainsKey(hash))
            {
                using (var it = DependencyMapLoadHelper.dependenciesMap[hash].GetEnumerator())
                {
                    while (it.MoveNext())
                    {
                        var dep     = it.Current;
                        var promise = new AssetPromise_AB(baseUrl, dep, containerTransform);
                        AssetPromiseKeeper_AB.i.Keep(promise);
                        dependencyPromises.Add(promise);
                    }
                }
            }

            while (!asyncOp.isDone)
            {
                yield return(null);
            }

            //NOTE(Brian): For some reason, another coroutine iteration can be triggered after Cleanup().
            //             So assetBundleRequest can be null here.
            if (assetBundleRequest == null)
            {
                OnFail?.Invoke();
                yield break;
            }

            if (!assetBundleRequest.WebRequestSucceded())
            {
                if (VERBOSE)
                {
                    Debug.Log($"Request failed? {assetBundleRequest.error} ... {finalUrl}");
                }
                failedRequestUrls.Add(finalUrl);
                assetBundleRequest.Abort();
                assetBundleRequest = null;
                OnFail?.Invoke();
                yield break;
            }

            UnregisterConcurrentRequest();

            foreach (var promise in dependencyPromises)
            {
                yield return(promise);
            }

            AssetBundle assetBundle = DownloadHandlerAssetBundle.GetContent(assetBundleRequest);

            if (assetBundle == null || asset == null)
            {
                assetBundleRequest.Abort();
                assetBundleRequest = null;
                OnFail?.Invoke();

                failedRequestUrls.Add(finalUrl);
                yield break;
            }

            asset.ownerAssetBundle     = assetBundle;
            asset.assetBundleAssetName = assetBundle.name;

            assetBundlesLoader.MarkAssetBundleForLoad(asset, assetBundle, containerTransform, OnSuccess, OnFail);
        }
Exemplo n.º 24
0
    private IEnumerator LoadAssetFromStream()
    {
        string checkTagPath = Application.persistentDataPath + "/checkHold.txt";

        if (File.Exists(checkTagPath))
        {
            StreamReader tagReader = new StreamReader(checkTagPath);
            string       str       = tagReader.ReadLine();
            tagReader.Dispose();
            bool isNewVersion = AppVersionCompare(Utils.AppVersion(), str);
            if (isNewVersion)
            {
                File.Delete(checkTagPath);
                string msg = "游戏版本过低,请下载最新安装包进行游戏";
                Utils.MessagePopup(msg, UpdateIphonePackage, 1, true, "前往");
            }
            else
            {
                CreatTag();
                GetAssetServerUrlFromWeb();
            }
            yield break;
        }
        yield return(null);

        _msgText.text = "准备资源文件..";
        Utils.Log("准备资源文件..");

        string assetname = "/jzsh";
        string path      = Application.streamingAssetsPath + assetname;

#if UNITY_EDITOR
        path = Application.streamingAssetsPath + assetname;
#elif UNITY_ANDROID
        path = "jar:file://" + Application.dataPath + "!/assets/AssetsList.txt";
#elif UNITY_IPHONE
        path = Application.streamingAssetsPath + assetname;
#endif

        unZipOk = false;
        string fullPath             = Application.persistentDataPath;
        string unZipToDirectoryPath = Application.persistentDataPath;

        if (File.Exists(fullPath))
        {
            File.Delete(fullPath);
        }

#if UNITY_IPHONE || UNITY_EDITOR
        if (!Directory.Exists(path))
        {
            CreatTag();
            GetAssetServerUrlFromWeb();
            yield break;
        }
        UtilsZipHelper.CopyFileMultiSync(path, fullPath, OnUnZipFileResult);
#elif UNITY_ANDROID
        UnityWebRequest uwr = UnityWebRequest.Get(path);
        yield return(uwr.SendWebRequest());//读取数据

        List <string> assetsList = new List <string>();
        if (string.IsNullOrEmpty(uwr.error))
        {
            string data = uwr.downloadHandler.text;
            uwr.Abort();
            int index = -1;
            while ((index = data.LastIndexOf("jzsh")) != -1)
            {
                assetsList.Add(data.Substring(index));
                //Utils.Log(assetsList[assetsList.Count - 1]);
                data = data.Substring(0, index);
            }
            path = "jar:file://" + Application.dataPath + "!/assets";
            UtilsZipHelper.CopyFileByWebRequest(assetsList, path, fullPath, OnUnZipFileResult);
        }
        else
        {
            Utils.Log("获取初始包资源列表文件失败:" + uwr.error);
            uwr.Abort();
            CreatTag();
            GetAssetServerUrlFromWeb();
        }
#endif
        yield return(null);

        _msgText.text = "开始加载初始化资源..不消耗流量";
        Utils.Log(_msgText.text);

        yield return(null);

        while (!unZipOk)
        {
            _msgText.text = string.Format("已初始化资源...{0}/{1}", UtilsZipHelper.TestCurrentFileNumber, UtilsZipHelper.TestCurrentFileNumberTotal);
            Utils.Log(_msgText.text);
            yield return(new WaitForSeconds(0.1f));
        }
    }
Exemplo n.º 25
0
        public static IEnumerator DownloadAvatarCoroutine(string hash)
        {
            queuedAvatars.Add(hash);
            string          downloadUrl = "";
            string          avatarName  = "";
            UnityWebRequest www         = UnityWebRequest.Get("https://modelsaber.com/api/v1/avatar/get.php?filter=hash:" + hash);

            www.timeout = 10;

            yield return(www.SendWebRequest());

            if (www.isNetworkError || www.isHttpError)
            {
                Plugin.log.Error($"Unable to download avatar! {(www.isNetworkError ? $"Network error: " + www.error : (www.isHttpError ? $"HTTP error: "+www.error : "Unknown error"))}");
                queuedAvatars.Remove(hash);
                yield break;
            }
            else
            {
                Plugin.log.Debug("Received response from ModelSaber...");
                JSONNode node = JSON.Parse(www.downloadHandler.text);

                if (node.Count == 0)
                {
                    Plugin.log.Error($"Avatar with hash {hash} doesn't exist on ModelSaber!");
                    cachedAvatars.Add(hash, null);
                    queuedAvatars.Remove(hash);
                    yield break;
                }

                downloadUrl = node[0]["download"].Value;
                avatarName  = downloadUrl.Substring(downloadUrl.LastIndexOf("/") + 1);
            }

            if (string.IsNullOrEmpty(downloadUrl))
            {
                queuedAvatars.Remove(hash);
                yield break;
            }


            bool  timeout = false;
            float time    = 0f;
            UnityWebRequestAsyncOperation asyncRequest;

            try
            {
                www         = UnityWebRequest.Get(downloadUrl);
                www.timeout = 0;

                asyncRequest = www.SendWebRequest();
            }
            catch (Exception e)
            {
                Plugin.log.Error($"Unable to download avatar! Exception: {e}");
                queuedAvatars.Remove(hash);
                yield break;
            }

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

                time += Time.deltaTime;

                if ((time >= 5f && asyncRequest.progress <= float.Epsilon))
                {
                    www.Abort();
                    timeout = true;
                    Plugin.log.Error("Connection timed out!");
                }
            }


            if (www.isNetworkError || www.isHttpError || timeout)
            {
                queuedAvatars.Remove(hash);
                Plugin.log.Error("Unable to download avatar! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
            }
            else
            {
                Plugin.log.Debug("Received response from ModelSaber...");
                string docPath          = "";
                string customAvatarPath = "";

                byte[] data = www.downloadHandler.data;

                try
                {
                    docPath          = Application.dataPath;
                    docPath          = docPath.Substring(0, docPath.Length - 5);
                    docPath          = docPath.Substring(0, docPath.LastIndexOf("/"));
                    customAvatarPath = docPath + "/CustomAvatars/" + avatarName;

                    File.WriteAllBytes(customAvatarPath, data);
                    Plugin.log.Debug($"Saving avatar to \"{customAvatarPath}\"...");

                    CustomAvatar.CustomAvatar downloadedAvatar = CustomExtensions.CreateInstance <CustomAvatar.CustomAvatar>(customAvatarPath);

                    Plugin.log.Debug("Downloaded avatar!");
                    Plugin.log.Debug($"Loading avatar...");

                    downloadedAvatar.Load(
                        (CustomAvatar.CustomAvatar avatar, CustomAvatar.AvatarLoadResult result) =>
                    {
                        if (result == CustomAvatar.AvatarLoadResult.Completed)
                        {
                            queuedAvatars.Remove(hash);
                            cachedAvatars.Add(hash, downloadedAvatar);
                            avatarDownloaded?.Invoke(hash);
                        }
                        else
                        {
                            Plugin.log.Error("Unable to load avatar! " + result.ToString());
                        }
                    });
                }
                catch (Exception e)
                {
                    Plugin.log.Critical(e);
                    queuedAvatars.Remove(hash);
                    yield break;
                }
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// URLに指定された画像をダウンロードし、テクスチャとして返す
        /// </summary>
        /// <param name="regionId"></param>
        /// <returns></returns>
        public static IEnumerator GetImage(string url)
        {
            float addTime = 0f;//タイムアウト監視

            WWWForm ps = new WWWForm();

            using (UnityWebRequest request = UnityWebRequest.Post(url, ps))
            {
                AsyncOperation op = request.SendWebRequest();
                while (true)
                {
                    if (op.isDone == false)
                    {
                        //通信中
                        yield return(null);

                        addTime += Time.deltaTime;

                        if ((int)addTime >= 3)
                        {
                            //3秒経過したらループを抜ける

                            //通信を切断する
                            request.Abort();
                            break;
                        }
                    }
                    else
                    {
                        //通信完了でループを抜ける
                        break;
                    }
                }

                if (request.responseCode == 200)
                {
                    yield return(TextureUtil.GetTextureFromFile(request.downloadHandler.data));
                }
                else
                {
                    yield return(null);
                }

                //yield return request.SendWebRequest();

                //if (request.isNetworkError)
                //{
                //    Debug.Log(request.error);

                //    yield return null;
                //}
                //else
                //{
                //    if (request.responseCode == 200)
                //    {
                //        yield return TextureUtil.GetTextureFromFile(request.downloadHandler.data);
                //    }
                //    else
                //    {
                //        yield return null;
                //    }
                //}
            }
        }
Exemplo n.º 27
0
        internal static IEnumerator SendRequest(NCMBConnection connection, UnityWebRequest req, object callback)
        {
            NCMBException error = null;

            byte[] byteData     = new byte[32768];
            string json         = "";
            string responseCode = "";

            // 通信実行
            // yield return req.Send ();

            // 通信実行
                        #if UNITY_2017_2_OR_NEWER
            req.SendWebRequest();
                        #else
            req.Send();
                        #endif

            // タイムアウト処理
            float elapsedTime = 0.0f;
            float waitTime    = 0.2f;
            while (!req.isDone)
            {
                //elapsedTime += Time.deltaTime;
                elapsedTime += waitTime;
                if (elapsedTime >= REQUEST_TIME_OUT)
                {
                    req.Abort();
                    error = new NCMBException();
                    break;
                }
                //yield return new WaitForEndOfFrame ();
                yield return(new WaitForSeconds(waitTime));
            }

            // 通信結果判定
            if (error != null)
            {
                // タイムアウト
                error.ErrorCode    = "408";
                error.ErrorMessage = "Request Timeout.";
                                #if UNITY_2017_1_OR_NEWER
            }
            else if (req.isNetworkError)
            {
                                #else
            }
            else if (req.isError)
            {
                                #endif
                // 通信エラー
                error              = new NCMBException();
                error.ErrorCode    = req.responseCode.ToString();
                error.ErrorMessage = req.error;
            }
            else if (req.responseCode != 200 && req.responseCode != 201)
            {
                // mBaaSエラー
                error = new NCMBException();
                var jsonData = MiniJSON.Json.Deserialize(req.downloadHandler.text) as Dictionary <string, object>;
                error.ErrorCode    = jsonData ["code"].ToString();
                error.ErrorMessage = jsonData ["error"].ToString();
            }
            else
            {
                // 通信成功
                byteData = req.downloadHandler.data;
                json     = req.downloadHandler.text;
            }

            //check E401001 error
            if (error != null)
            {
                connection._checkInvalidSessionToken(error.ErrorCode);
            }

            // check response signature
            if (callback != null && !(callback is NCMBExecuteScriptCallback))
            {
                // スクリプト機能はレスポンスシグネチャ検証外
                responseCode = req.responseCode.ToString();
                string responsText = req.downloadHandler.text;
                if (callback is HttpClientFileDataCallback)
                {
                    // NCMBFileのGETではbyteでシグネチャ計算を行うよう空文字にする
                    responsText = "";
                }
                connection._checkResponseSignature(responseCode, responsText, req, ref error);
            }

            if (callback != null)
            {
                if (callback is NCMBExecuteScriptCallback)
                {
                    ((NCMBExecuteScriptCallback)callback)(byteData, error);
                }
                else if (callback is HttpClientCallback)
                {
                    ((HttpClientCallback)callback)((int)req.responseCode, json, error);
                }
                else if (callback is HttpClientFileDataCallback)
                {
                    ((HttpClientFileDataCallback)callback)((int)req.responseCode, byteData, error);
                }
            }
        }
        private void RequestServicesApiFlags(Action <Dictionary <string, bool> > callback)
        {
            if (m_ServiceRequest != null)
            {
                m_ServiceRequest?.Abort();
                m_ServiceRequest?.Dispose();
                m_ServiceRequest = null;
            }

            ServicesConfiguration.instance.RequestCurrentProjectApiUrl(currentProjectApiUrl =>
            {
                m_ServiceRequest = new UnityWebRequest(currentProjectApiUrl,
                                                       UnityWebRequest.kHttpVerbGET)
                {
                    downloadHandler = new DownloadHandlerBuffer()
                };
                m_ServiceRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                m_ServiceRequest.SendWebRequest().completed += op =>
                {
                    if (op.isDone)
                    {
                        Dictionary <string, bool> serviceFlags = null;
                        if ((m_ServiceRequest != null) &&
                            (m_ServiceRequest.result != UnityWebRequest.Result.ConnectionError) &&
                            (m_ServiceRequest.result != UnityWebRequest.Result.ProtocolError) &&
                            (m_ServiceRequest.downloadHandler != null))
                        {
                            if (m_ServiceRequest.downloadHandler.text.Length != 0)
                            {
                                var jsonParser = new JSONParser(m_ServiceRequest.downloadHandler.text);
                                try
                                {
                                    var json     = jsonParser.Parse();
                                    serviceFlags = new Dictionary <string, bool>();
                                    Dictionary <string, JSONValue> jsonFlags = null;

                                    if (json.AsDict().ContainsKey(k_serviceFlagsKey))
                                    {
                                        jsonFlags = json.AsDict()[k_serviceFlagsKey].AsDict();
                                    }

                                    if (jsonFlags != null)
                                    {
                                        foreach (var key in jsonFlags.Keys)
                                        {
                                            serviceFlags.Add(key, jsonFlags[key].AsBool());
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Debug.LogException(ex);
                                    NotificationManager.instance.Publish(Notification.Topic.AdsService, Notification.Severity.Error, ex.Message);
                                }
                            }
                        }

                        m_ServiceRequest?.Abort();
                        m_ServiceRequest?.Dispose();
                        m_ServiceRequest = null;

                        callback?.Invoke(serviceFlags);
                    }
                };
            });
        }
Exemplo n.º 29
0
        private static IEnumerator DownloadSong_internal(string hash, bool refreshWhenDownloaded = true, Action <string, bool> songDownloaded = null, Action <string, float> downloadProgressChanged = null, string customHostUrl = null)
        {
            var songUrl = $"{beatSaverDownloadUrl}{hash}.zip";

            if (!string.IsNullOrEmpty(customHostUrl))
            {
                songUrl = $"{customHostUrl}{hash.ToUpper()}.zip";
            }
            UnityWebRequest www          = UnityWebRequest.Get(songUrl);
            bool            timeout      = false;
            float           time         = 0f;
            float           lastProgress = 0f;

            www.SetRequestHeader("user-agent", SharedConstructs.Name);
            UnityWebRequestAsyncOperation asyncRequest = www.SendWebRequest();

            while (!asyncRequest.isDone || asyncRequest.progress < 1f)
            {
                yield return(null);

                time += Time.deltaTime;

                if (time >= 15f && asyncRequest.progress == 0f)
                {
                    www.Abort();
                    timeout = true;
                }

                if (lastProgress != asyncRequest.progress)
                {
                    lastProgress = asyncRequest.progress;
                    downloadProgressChanged?.Invoke($"custom_level_{hash.ToUpper()}", asyncRequest.progress);
                }
            }

            if (www.isNetworkError || www.isHttpError || timeout)
            {
                Logger.Error($"Error downloading song {hash}: {www.error}");
                songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false);
            }
            else
            {
                string zipPath         = "";
                string customSongsPath = CustomLevelPathHelper.customLevelsDirectoryPath;
                string customSongPath  = "";

                byte[] data = www.downloadHandler.data;

                try
                {
                    customSongPath = customSongsPath + "/" + hash + "/";
                    zipPath        = customSongPath + hash + ".zip";
                    if (!Directory.Exists(customSongPath))
                    {
                        Directory.CreateDirectory(customSongPath);
                    }
                    File.WriteAllBytes(zipPath, data);
                }
                catch (Exception e)
                {
                    Logger.Error($"Error writing zip: {e}");
                    songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false);
                    yield break;
                }

                try
                {
                    ZipFile.ExtractToDirectory(zipPath, customSongPath);
                }
                catch (Exception e)
                {
                    Logger.Error($"Unable to extract ZIP! Exception: {e}");
                    songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", false);
                    yield break;
                }

                try
                {
                    File.Delete(zipPath);
                }
                catch (IOException e)
                {
                    Logger.Warning($"Unable to delete zip! Exception: {e}");
                    yield break;
                }

                Logger.Success($"Downloaded!");

                if (refreshWhenDownloaded)
                {
                    Action <Loader, ConcurrentDictionary <string, CustomPreviewBeatmapLevel> > songsLoaded = null;
                    songsLoaded = (_, __) =>
                    {
                        Loader.SongsLoadedEvent -= songsLoaded;
                        songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", true);
                    };
                    Loader.SongsLoadedEvent += songsLoaded;
                    Loader.Instance.RefreshSongs(false);
                }
                else
                {
                    songDownloaded?.Invoke($"custom_level_{hash.ToUpper()}", true);
                }
            }
        }
Exemplo n.º 30
0
        //Download songs. Taken from BeatSaberMultiplayer
        //availableSongs: List of IBeatmapLevel which may hold levels already approved for display
        //downloadQueue: List of beatsaver ids representing songs left to download
        //completedDownloads: List of beatsaver ids representing songs that have successfully downloaded
        //songId: The song this instance of the Coroutine is supposed to download
        //slvc: The song list view controller to display the downloaded songs to
        private static IEnumerator DownloadSongs(string songHash, SongListViewController slvc)
        {
            UnityWebRequest www = UnityWebRequest.Get($"{beatSaverDownloadUrl}{songHash}");

#if BETA
            Logger.Info($"DOWNLOADING: {beatSaverDownloadUrl}{songHash}");
#endif
            bool  timeout = false;
            float time    = 0f;

            www.SetRequestHeader("user-agent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");
            UnityWebRequestAsyncOperation asyncRequest = www.SendWebRequest();

            while (!asyncRequest.isDone || asyncRequest.progress < 1f)
            {
                yield return(null);

                time += Time.deltaTime;

                if (time >= 15f && asyncRequest.progress == 0f)
                {
                    www.Abort();
                    timeout = true;
                }
            }

            if (www.isNetworkError || www.isHttpError || timeout)
            {
                Logger.Error($"Error downloading song {songHash}: {www.error}");
                slvc.ErrorHappened($"Error downloading song {songHash}: {www.error}");
            }
            else
            {
                //Logger.Info("Received response from BeatSaver.com...");

                string zipPath         = "";
                string customSongsPath = CustomLevelPathHelper.customLevelsDirectoryPath;
                string customSongPath  = "";

                byte[] data = www.downloadHandler.data;

                try
                {
                    customSongPath = customSongsPath + "/" + songHash + "/";
                    zipPath        = customSongPath + songHash + ".zip";
                    if (!Directory.Exists(customSongPath))
                    {
                        Directory.CreateDirectory(customSongPath);
                    }
                    File.WriteAllBytes(zipPath, data);
                    //Logger.Info("Downloaded zip file!");
                }
                catch (Exception e)
                {
                    Logger.Error($"Error writing zip: {e}");
                    slvc.ErrorHappened($"Error writing zip: {e}");
                    yield break;
                }

                //Logger.Info("Extracting...");

                try
                {
                    ZipFile.ExtractToDirectory(zipPath, customSongPath);
                }
                catch (Exception e)
                {
                    Logger.Error($"Unable to extract ZIP! Exception: {e}");
                    slvc.ErrorHappened($"Unable to extract ZIP! Exception: {e}");
                    yield break;
                }

                try
                {
                    File.Delete(zipPath);
                }
                catch (IOException e)
                {
                    Logger.Warning($"Unable to delete zip! Exception: {e}");
                    slvc.ErrorHappened($"Unable to delete zip! Exception: {e}");
                    yield break;
                }

                Logger.Success($"Downloaded!");
            }
        }