Exemplo n.º 1
0
 void Dispose(bool disposing)
 {
     if (disposing)
     {
         UnityConnect.instance.ProjectStateChanged -= OnProjectStateChangedAfterRebind;
         UnityConnect.instance.ProjectStateChanged -= OnProjectStateChangedAfterCreation;
         m_CurrentRequest?.Dispose();
     }
 }
Exemplo n.º 2
0
            void Start()
            {
#if QC_USE_NETWORKING
                _request?.Dispose();
                _request = UnityWebRequestTexture.GetTexture(_url);
                _request.SendWebRequest();
                _failed = false;
#else
                Debug.Log("Can't Load {0} : QC_USE_NETWORKING is disabled".F(_url));
#endif
            }
 private void DownloadError(string message)
 {
     unityWebRequest?.Dispose();
     unityWebRequest    = null;
     lastDownloadedSize = 0;
     fileStream?.Dispose();
     fileStream?.Close();
     fileStream         = null;
     Task.DownloadState = enDownloadState.Error;
     Task.Done          = true;
     Task.DownloadErrorAction(Task, message);
 }
Exemplo n.º 4
0
 public void Dispose()
 {
     GameLoop.onUpdate -= Update;
     Request?.Dispose();
     Request  = null;
     isCancel = false;
 }
Exemplo n.º 5
0
 protected override void OnDestroy()
 {
     request?.Dispose();
     isDone     = true; // Destroyed queue item always complete
     url        = null;
     request    = null;
     onComplete = null;
 }
Exemplo n.º 6
0
        void LoadConfigurationsFromCdn()
        {
            try
            {
                if (m_GetServicesUrlsRequest != null)
                {
                    try
                    {
                        m_GetServicesUrlsRequest.Abort();
                    }
                    catch (Exception)
                    {
                        // ignored, we try to abort (best effort) but no need to panic if it fails
                    }
                    m_GetServicesUrlsRequest.Dispose();
                    m_GetServicesUrlsRequest = null;
                }

                m_GetServicesUrlsRequest = new UnityWebRequest(string.Format(k_CdnConfigUrl, UnityConnect.instance.GetEnvironment()),
                                                               UnityWebRequest.kHttpVerbGET)
                {
                    downloadHandler = new DownloadHandlerBuffer()
                };
                m_GetServicesUrlsRequest.suppressErrorsToConsole = true;
                var operation = m_GetServicesUrlsRequest.SendWebRequest();
                operation.completed += asyncOperation =>
                {
                    try
                    {
                        if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(m_GetServicesUrlsRequest))
                        {
                            LoadJsonConfiguration(m_GetServicesUrlsRequest.downloadHandler.text);
                            SessionState.SetString(k_ConfigJsonSessionStateKey, m_GetServicesUrlsRequest.downloadHandler.text);
                            BuildPaths();
                        }
                    }
                    catch (Exception)
                    {
                        //We fallback to hardcoded config
                        BuildPaths();
                    }
                    finally
                    {
                        m_GetServicesUrlsRequest?.Dispose();
                        m_GetServicesUrlsRequest = null;
                    }
                };
            }
            catch (Exception)
            {
                //We fallback to hardcoded config
                BuildPaths();
            }
        }
Exemplo n.º 7
0
        private void ClearRequestData()
        {
            _request?.Dispose();

            if (_asyncOperation != null)
            {
                _asyncOperation.completed -= AsyncOperationOnCompleted;
                _asyncOperation            = null;
            }

            _request = null;
        }
Exemplo n.º 8
0
        public override void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            base.Dispose();

            Request?.Dispose();
            Request  = null;
            isCancel = false;
        }
Exemplo n.º 9
0
        public static bool IsMember(string token, out string id)
        {
            UnityWebRequest request = null;

            try
            {
                Logger.LogDebug(nameof(IsMember));

                var args = new Dictionary <string, string>
                {
                    { "include", "memberships" },
                };
                var url = GetURL(PatreonIdentityURL, args);

                request         = UnityWebRequest.Get(url);
                request.timeout = 3;
                request.SetRequestHeader("Authorization", $"Bearer {token}");
                request.Send();

                while (!request.isDone)
                {
                }

                if (!request.isError)
                {
                    var jsonResult = JObject.Parse(request.downloadHandler.text);
                    var userData   = jsonResult["data"];
                    id = userData.Value <string>("id");
                    var isMember = userData["relationships"]["memberships"]["data"] is JArray data && data.Count != 0;

                    return(isMember);
                }
            }
            catch (Exception error)
            {
                Logger.LogError(() => nameof(IsMember), error);
            }
            finally
            {
                request?.Dispose();
            }
            id = null;
            return(false);
        }
Exemplo n.º 10
0
        public override void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }

            base.Dispose();
            headRequest?.Dispose();
            headRequest = null;
            foreach (UnityWebRequest dataRequest in this.dataRequests)
            {
                dataRequest.Dispose();
            }
            dataRequests.Clear();
            this.fileStream?.Close();
            this.fileStream?.Dispose();
            this.fileStream = null;
            this.isCancel   = false;
        }
Exemplo n.º 11
0
        private static bool ProcessTokenRequest(string url, out string accessToken, out string refreshToken)
        {
            UnityWebRequest request = null;

            try
            {
                Logger.LogDebug(nameof(ProcessTokenRequest));

                request         = UnityWebRequest.Post(url, string.Empty);
                request.timeout = 3;
                request.Send();

                while (!request.isDone)
                {
                }

                if (!request.isError)
                {
                    var jsonResult = JObject.Parse(request.downloadHandler.text);
                    if (jsonResult.TryGetValue("access_token", out JToken accessTokenValue) && jsonResult.TryGetValue("refresh_token", out JToken refreshTokenValue))
                    {
                        accessToken  = accessTokenValue.ToString();
                        refreshToken = refreshTokenValue.ToString();
                        return(true);
                    }
                }
            }
            catch (Exception error)
            {
                Logger.LogError(() => nameof(ProcessTokenRequest), error);
            }
            finally
            {
                request?.Dispose();
            }

            accessToken  = null;
            refreshToken = null;
            return(false);
        }
        protected override void OnLoad(Action OnSuccess, Action OnFail)
        {
            // Reuse the already-stored default texture, we duplicate it and set the needed config afterwards in AddToLibrary()
            if (library.Contains(idWithDefaultTexSettings) && !UsesDefaultWrapAndFilterMode())
            {
                OnSuccess?.Invoke();
                return;
            }

            if (!url.StartsWith(PLAIN_BASE64_PROTOCOL))
            {
                webRequest = UnityWebRequestTexture.GetTexture(url);
                webRequest.SendWebRequest().completed += (asyncOp) =>
                {
                    bool success = webRequest != null && webRequest.WebRequestSucceded() && asset != null;
                    if (success)
                    {
                        asset.texture = DownloadHandlerTexture.GetContent(webRequest);
                        OnSuccess?.Invoke();
                    }
                    else
                    {
                        OnFail?.Invoke();
                    }
                    webRequest?.Dispose();
                    webRequest = null;
                };
            }
            else
            {
                //For Base64 protocols we just take the bytes and create the texture
                //to avoid Unity's web request issue with large URLs
                byte[] decodedTexture = Convert.FromBase64String(url.Substring(PLAIN_BASE64_PROTOCOL.Length));
                asset.texture = new Texture2D(1, 1);
                asset.texture.LoadImage(decodedTexture);
                OnSuccess?.Invoke();
            }
        }
        static void StartDownloadState()
        {
            if (_packageDownloaderState == PackageDownloaderState.StartDownload || _packageDownloaderState == PackageDownloaderState.None)
            {
                EditorUtility.ClearProgressBar();
                _unityWebRequest?.Dispose();
                _unityWebRequest = new UnityWebRequest(GITHUB_DOWNLOAD_URL)
                {
                    downloadHandler = new DownloadHandlerBuffer(), timeout = 10
                };
                Debug.Log($"Downloaded File to [{_downloadLocation}]");
                var webRequest = _unityWebRequest.SendWebRequest();

                webRequest.completed += (e) =>
                {
                    if (_unityWebRequest.result != UnityWebRequest.Result.Success)
                    {
                        Debug.LogError($"[Unity Web Request Error]: {_unityWebRequest.error} |{_unityWebRequest.result}");
                        _packageDownloaderState = PackageDownloaderState.Error;
                    }
                    else
                    {
                        EditorUtility.ClearProgressBar();
                        // Or retrieve results as binary data
                        byte[] results = _unityWebRequest.downloadHandler.data;
                        File.WriteAllBytes(_downloadLocation, results);
                    }

                    EditorUtility.ClearProgressBar();
                    _packageDownloaderState = PackageDownloaderState.None;
                    AssetDatabase.ImportPackage(_downloadLocation, true);
                    AssetDatabase.Refresh();
                    _unityWebRequest.Dispose();
                };
                _packageDownloaderState = PackageDownloaderState.IsDownloading;
            }
        }
    /// <summary>
    /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching
    /// instantiate gameobject
    /// </summary>
    /// <param name="bundleURL">full url to assetbundle file</param>
    /// <param name="assetName">optional parameter to access specific asset from assetbundle</param>
    /// <returns></returns>
    /// IEnumerator DownloadAndCache(string bundleURL, string assetName = "")
    IEnumerator DownloadAndCache(string bundleURL)
    {
        // Wait for the Caching system to be ready
        while (!Caching.ready)
        {
            yield return(null);
        }

        // if you want to always load from server, can clear cache first
        //        Caching.CleanCache();

        // get current bundle hash from server, random value added to avoid caching
        UnityWebRequest uwrABManifest = UnityWebRequest.Get(bundleURL + ".manifest?r=" + RandomHash(32));

        //UnityWebRequest uwr = UnityWebRequest.Get(bundleURL + ".manifest");
        Debug.Log("Loading manifest:" + bundleURL + ".manifest");

        // wait for load to finish
        yield return(uwrABManifest.SendWebRequest());

        // if received error, exit
        if (uwrABManifest.isNetworkError)
        {
            Debug.LogError("www error: " + uwrABManifest.error);
            uwrABManifest.Dispose();
            uwrABManifest = null;
            yield break;
        }

        // create empty hash string
        Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

        // check if received data contains 'ManifestFileVersion'
        Debug.Log("manifest file " + uwrABManifest.downloadHandler.text);
        if (uwrABManifest.downloadHandler.text.Contains("ManifestFileVersion"))
        {
            // extract hash string from the received data, TODO should add some error checking here
            var hashRow = uwrABManifest.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
            hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

            if (hashString.isValid == true)
            {
                // we can check if there is cached version or not
                if (Caching.IsVersionCached(bundleURL, hashString) == true)
                {
                    Debug.Log("Bundle with this hash is already cached!");
                    isCached = true;
                }
                else
                {
                    Debug.Log("No cached version found for this hash..");
                    isCached = false;
                }
            }
            else
            {
                // invalid loaded hash, just try loading latest bundle
                Debug.LogError("Invalid hash:" + hashString);
                yield break;
            }
        }
        else
        {
            Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
            yield break;
        }

        // now download the actual bundle, with hashString parameter it uses cached version if available
        uwrAssetBundle = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + RandomHash(32), hashString, 0);
        Debug.Log("I am initiating a Unity Web Request for the Asset Bundle NOW.");
        // wait for load to finish
        isLoading = true;
        yield return(uwrAssetBundle.SendWebRequest());

        Debug.Log("Unity has returned from the UWR.");
        if (uwrAssetBundle.error != null || uwrAssetBundle.isNetworkError)
        {
            Debug.LogError("www error: " + uwrAssetBundle.error);
            uwrAssetBundle.Dispose();
            uwrAssetBundle = null;
            yield break;
        }

        // get bundle from downloadhandler
        //AssetBundle bundle = ((DownloadHandlerAssetBundle)uwr.downloadHandler).assetBundle;
        Debug.Log("The UWR came back fine and now I am initiating the actual download of the Asset Bundle.");
        AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(uwrAssetBundle);

        //isLoading = true;

        if (uwrAssetBundle.isDone)
        {
            isLoading = false;
            //AssetBundleManifest manifest = bundle.LoadAsset<AssetBundleManifest>(bundle.name);
            Debug.Log("The Asset Bundle has been downloaded successfully.");
            Debug.Log("bundle name " + bundle.name);
            Debug.Log("is Streamed Asset Bundle " + bundle.isStreamedSceneAssetBundle);
        }


        //AssetBundle manifestBundle = AssetBundle.LoadFromFile(manifestBundlePath);
        //AssetBundleManifest manifest = bundle.LoadAssetAsync<AssetBundleManifest>(ABFileName);
        //Debug.Log("manifest " + manifest);

        string[] assetBundlePaths = bundle.GetAllScenePaths();

        if (assetBundlePaths != null)
        {
            //AssetBundleLoadOperation request = AssetBundleManager.LoadLevelAsync(sceneAssetBundle, levelName, isAdditive);
            //if (request == null)
            //    yield break;
            //yield return StartCoroutine(request);

            for (int i = 0; i < assetBundlePaths.Length; i++)
            {
                Debug.Log("string # " + i + " is " + assetBundlePaths[i]);
            }

            //// fix pink shaders, NOTE: not always needed..
            //foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true))
            //{
            //    // FIXME: creates multiple materials, not good
            //    var material = Shader.Find(r.material.shader.name);
            //    r.material.shader = null;
            //    r.material.shader = material;
            //}

            SceneManager.LoadSceneAsync(bundle.GetAllScenePaths()[0]);
        }


        /*
         * //GameObject bundlePrefab = null;
         *
         * // if no asset name is given, take the first/main asset
         * if (assetName == "")
         * {
         *  bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
         * }
         * else
         * { // use asset name to access inside bundle
         *  bundlePrefab = (GameObject)bundle.LoadAsset(assetName);
         * }
         *
         * // if we got something out
         * if (bundlePrefab != null)
         * {
         *
         *  // instantiate at 0,0,0 and without rotation
         *  Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity);
         *
         *
         *  //// fix pink shaders, NOTE: not always needed..
         *  //foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true))
         *  //{
         *  //    // FIXME: creates multiple materials, not good
         *  //    var material = Shader.Find(r.material.shader.name);
         *  //    r.material.shader = null;
         *  //    r.material.shader = material;
         *  //}
         * }
         */

        uwrAssetBundle.Dispose();
        uwrAssetBundle = null;

        // try to cleanup memory
        Resources.UnloadUnusedAssets();
        bundle.Unload(false);
        bundle = null;
    }
    IEnumerator IsARExperienceCached(string bundleURL)
    {
        // Wait for the Caching system to be ready
        while (!Caching.ready)
        {
            yield return(null);
        }

        // if you want to always load from server, can clear cache first
        //        Caching.CleanCache();

        // get current bundle hash from server, random value added to avoid caching
        UnityWebRequest uwrABManifest = UnityWebRequest.Get(bundleURL + ".manifest?r=" + RandomHash(32));

        //UnityWebRequest uwr = UnityWebRequest.Get(bundleURL + ".manifest");
        Debug.Log("Loading manifest:" + bundleURL + ".manifest");
        isCheckingCache = true;
        // wait for load to finish
        yield return(uwrABManifest.SendWebRequest());

        // if received error, exit
        if (uwrABManifest.isNetworkError)
        {
            Debug.LogError("www error: " + uwrABManifest.error);
            uwrABManifest.Dispose();
            uwrABManifest = null;
            yield break;
        }

        if (uwrABManifest.isDone)
        {
            isCheckingCache = false;
            Debug.Log("I finished downloading the manifest file, now I will check if its valid and look for a hash");
        }

        // create empty hash string
        Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

        // check if received data contains 'ManifestFileVersion'
        Debug.Log("manifest file " + uwrABManifest.downloadHandler.text);
        if (uwrABManifest.downloadHandler.text.Contains("ManifestFileVersion"))
        {
            // extract hash string from the received data, TODO should add some error checking here
            var hashRow = uwrABManifest.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
            hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

            if (hashString.isValid == true)
            {
                // we can check if there is cached version or not
                if (Caching.IsVersionCached(bundleURL, hashString) == true)
                {
                    Debug.Log("Bundle with this hash is already cached!");
                    isCached = true;
                    yield break;
                    //isCached = true;
                }
                else
                {
                    Debug.Log("No cached version found for this hash..");
                    isCached = false;
                    yield break;
                    //isCached = false;
                }
            }
            else
            {
                // invalid loaded hash, just try loading latest bundle
                Debug.LogError("Invalid hash:" + hashString);
                yield break;
            }
        }
        else
        {
            Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
            yield break;
        }
    }
Exemplo n.º 16
0
    IEnumerator RegisterAccount()
    {
        List <IMultipartFormSection> form = new List <IMultipartFormSection>();

        form.Add(new MultipartFormDataSection("username", registerUsername.text));
        form.Add(new MultipartFormDataSection("password", registerPassword.text));
        form.Add(new MultipartFormDataSection("email", registerEmail.text));
        form.Add(new MultipartFormDataSection("firstName", registerFirstName.text));
        form.Add(new MultipartFormDataSection("lastName", registerLastName.text));
        if (notificationClass.NotificationToken != null || notificationClass.NotificationToken != "")
        {
            form.Add(new MultipartFormDataSection("notificationToken", notificationClass.NotificationToken));
        }
        UnityWebRequest webreq = UnityWebRequest.Post("http://mybarber.vlcapps.com/appscripts/register.php", form);

        yield return(webreq.SendWebRequest());

        if (webreq.downloadHandler.text[0] == '0')
        {
            registerUsername.text = "";
            registerPassword.text = "";
            registerEmail.text    = "";
            if (appmanager.SelectedLanguage == 2)
            {
                errorInfoTXT.text = "Account created successfully ! You can now login.";
            }
            else if (appmanager.SelectedLanguage == 1)
            {
                errorInfoTXT.text = "Contul a fost creat cu succes! Te poti conecta.";
            }
            errorInfoObj.SetActive(true);
        }
        else if (webreq.downloadHandler.text[0] == '1')
        {
            if (appmanager.SelectedLanguage == 2)
            {
                errorInfoTXT.text = "There is a problem with the server's connection. Please try again. If the problem continues contact an administrator.";
            }
            else if (appmanager.SelectedLanguage == 1)
            {
                errorInfoTXT.text = "A intervenit o problema cu conexiunea serverului. Te rugam sa incerci din nou. Daca problema persista contacteaza un administrator.";
            }
            errorInfoObj.SetActive(true);
        }
        else if (webreq.downloadHandler.text[0] == '3')
        {
            if (appmanager.SelectedLanguage == 2)
            {
                errorInfoTXT.text = "There is already an account created with that name. Try another one.";
            }
            else if (appmanager.SelectedLanguage == 1)
            {
                errorInfoTXT.text = "Exista deja un cont creat cu acest nume. Incearca altul.";
            }
            errorInfoObj.SetActive(true);
        }
        else
        {
            if (appmanager.SelectedLanguage == 2)
            {
                errorInfoTXT.text = "Something went wrong. Please try again later. If the problem continues contact an administrator.";
            }
            else if (appmanager.SelectedLanguage == 1)
            {
                errorInfoTXT.text = "Ceva nu a functionat. Te rugam sa incerci din nou mai tarziu. Daca problema continua contacteaza un administrator.";
            }
            errorInfoObj.SetActive(true);
        }
        webreq.Dispose();
        appmanager.afterLogin();
    }
Exemplo n.º 17
0
        /// <summary>
        /// 下载Assets
        /// 用于加载资源时,本地不存在则向服务器请求
        /// </summary>
        /// <param name="serverUrl"></param>
        /// <param name="localSaveAssetsPath"></param>
        /// <param name="downloadQueue"></param>
        /// <param name="onDownloadProccess"></param>
        /// <param name="failDownloadList"></param>
        /// <returns></returns>
        public IEnumerator IE_DownloadAssets(string serverUrl, string localSaveAssetsPath, Queue <AssetItem> downloadQueue, Action <AssetItem, List <AssetItem> > onDownloadProccess)
        {
            var failDownloadList = new List <AssetItem>();
            //url构建
            var platform = BApplication.GetPlatformPath(BApplication.RuntimePlatform);

            serverUrl           = IPath.Combine(serverUrl, platform);
            localSaveAssetsPath = IPath.Combine(localSaveAssetsPath, platform);
            //1.任务缓存
            var downloadCacheList = downloadQueue.ToList();

            //2.开始任务
            while (downloadQueue.Count > 0)
            {
                var downloadItem = downloadQueue.Dequeue();

                //本地存在hash文件
                var localDownloadFile = IPath.Combine(localSaveAssetsPath, downloadItem.HashName);
                //下载
                UnityWebRequest uwq = null;

                //先进行下载hash文件,所有的完成后再进行rename成资源
                var serverAssetUrl = IPath.Combine(serverUrl, downloadItem.HashName);
                //下载具体资源 ,任务会重试5次
                uwq = UnityWebRequest.Get(serverAssetUrl);

                for (int i = 0; i < RETRY_COUNT; i++)
                {
                    yield return(uwq.SendWebRequest());

                    if (uwq.isHttpError || uwq.isNetworkError)
                    {
                        //对比hash
                        var downloadFileHash = FileHelper.GetMurmurHash3(uwq.downloadHandler.data);
                        if (downloadFileHash == downloadItem.HashName)
                        {
                            BDebug.Log("下载成功:" + serverAssetUrl);
                            break;
                        }
                        else
                        {
                            BDebug.LogError("【版本控制】重下, hash校验失败! server-" + downloadItem.HashName + " local-" + downloadFileHash);
                        }
                    }
                }

                //
                if (!uwq.isHttpError && !uwq.isNetworkError)
                {
                    onDownloadProccess(downloadItem, downloadCacheList);
                    FileHelper.WriteAllBytes(localDownloadFile, uwq.downloadHandler.data);
                }
                else
                {
                    //这边需要继续下载,最后统计失败文件
                    failDownloadList.Add(downloadItem);
                    BDebug.LogError("下载失败:" + uwq.error);
                }

                uwq?.Dispose();
            }

            //3.写入本地
            foreach (var assetItem in downloadCacheList)
            {
                var localHashPath = IPath.Combine(localSaveAssetsPath, assetItem.HashName);
                var localRealPath = IPath.Combine(localSaveAssetsPath, assetItem.LocalPath);
                if (File.Exists(localHashPath))
                {
                    if (File.Exists(localRealPath))
                    {
                        File.Delete(localRealPath);
                    }

                    //移动(重命名)
                    FileHelper.Move(localHashPath, localRealPath);
                }
            }
        }
Exemplo n.º 18
0
    //这个是热更新打包系统支持的更新,由每一次新打包与上次打包的文件对比组成的
    //这个热更新系统不好维护,仅支持一些资源文件的更新等
    IEnumerator CheckNeedUpdate()
    {
        //仅在局域网下可用
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            //不可用
            GameStart();
            yield break;
        }
        else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork && GameStateMgr.gameStatus.OnlyWifi)
        {
            //3G-4G流量套餐
            //别更新
            GameStart();
            yield break;
        }
        else
        if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork || !GameStateMgr.gameStatus.OnlyWifi)
        {
            //Debug.LogError("download:" + string.Format(strVFile, strHost, Main.port, strProjectUrl, strPlatform, strVFileName));
            UnityWebRequest vFile = new UnityWebRequest();
            vFile.url     = string.Format(strFile, strHost, Main.port, strProjectUrl, strVFileName);
            vFile.timeout = 5;
            DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
            vFile.downloadHandler = dH;
            yield return(vFile.Send());

            if (vFile.isError || vFile.responseCode != 200)
            {
                Debug.LogError(string.Format("update version file:{0} error:{1} or responseCode:{2}", vFile.url, vFile.error, vFile.responseCode));
                vFile.Dispose();
                GameStart();
                yield break;
            }

            if (vFile.downloadHandler.data != null && vFile.downloadedBytes != 0)
            {
                if (File.Exists(ResMng.GetResPath() + "/" + strVFileName))
                {
                    File.Delete(ResMng.GetResPath() + "/" + strVFileName);
                }
                if (File.Exists(ResMng.GetResPath() + "/" + strVerFile))
                {
                    File.Delete(ResMng.GetResPath() + "/" + strVerFile);
                }
                Debug.Log(ResMng.GetResPath() + "/" + strVFileName);
                File.WriteAllBytes(ResMng.GetResPath() + "/" + strVFileName, vFile.downloadHandler.data);
                ZipUtility.UnzipFile(ResMng.GetResPath() + "/" + strVFileName, ResMng.GetResPath() + "/");
                vFile.Dispose();
            }
            else
            {
                GameStart();
                yield break;
            }
            List <VersionItem> v = ReadVersionJson(File.ReadAllText(ResMng.GetResPath() + "/" + strVerFile));
            //从版本信息下载指定压缩包
            for (int i = 0; i < v.Count; i++)
            {
                if (v[i].strVersion == AppInfo.AppVersion() && v[i].strVersionMax != v[i].strVersion)
                {
                    UpdateHelper.ApplyVersion(v[i], this);
                    yield break;
                }
            }

            GameStart();
            yield break;
        }
        else
        {
            Log.WriteError("Application.internetReachability != NetworkReachability.ReachableViaLocalAreaNetwork");
            GameStart();
            yield break;
        }
    }
        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);
                    }
                };
            });
        }
        IEnumerator ImportFromGoogleIE(DataboxObject database, DataboxGoogleSheetDownloader.ImportType _importType)
        {
            DataboxCSVConverter.firstTimeReplace = true;

            for (int i = 0; i < database.googleWorksheets.Count; i++)
            {
                var _url = database.googleSheetUrl;

                _url = FixURL(_url, database.googleWorksheets[i].id);

                UnityWebRequest _download = UnityWebRequest.Get(_url);

                yield return(_download.SendWebRequest());

                while (_download.isDone == false)
                {
                    yield return(null);
                }

                // handle an unknown internet error
                if (_download.isNetworkError || _download.isHttpError)
                {
                    Debug.LogWarningFormat("Couldn't retrieve file at <{0}> and error message was: {1}", _download.url, _download.error);
                }
                else
                {
                    // make sure the fetched file isn't just a Google login page
                    if (_download.downloadHandler.text.Contains("google-site-verification"))
                    {
                        Debug.LogWarningFormat("Couldn't retrieve file at <{0}> because the Google Doc didn't have public link sharing enabled", _download.url);
                        continue;
                    }


                    List <DataboxCSVConverter.Entry> entries = new List <DataboxCSVConverter.Entry>();
                    DataboxCSVConverter.ConvertCSV(_download.downloadHandler.text, out entries);


                    yield return(new WaitForSeconds(1f));


                    switch (_importType)
                    {
                    case DataboxGoogleSheetDownloader.ImportType.Append:
                        DataboxCSVConverter.AppendToDB(database, database.googleWorksheets[i].name, entries);
                        break;

                    case DataboxGoogleSheetDownloader.ImportType.Replace:
                        DataboxCSVConverter.ReplaceDB(database, database.googleWorksheets[i].name, entries);
                        break;
                    }
                }

                _download.Dispose();
            }


            if (database.OnImportFromGoogleComplete != null)
            {
                database.OnImportFromGoogleComplete();
            }
        }
Exemplo n.º 21
0
            void AddBuildTarget(VisualElement targetsContainer, Dictionary <string, JSONValue> buildEntry)
            {
                if (buildEntry[k_JsonNodeNameEnabled].AsBool())
                {
                    var buildTargetName = buildEntry[k_JsonNodeNameName].AsString();
                    var buildTargetId   = buildEntry[k_JsonNodeNameBuildTargetId].AsString();
                    var buildTargetUrls = buildEntry[k_JsonNodeNameLinks].AsDict();
                    var startBuildUrl   = ServicesConfiguration.instance.GetCloudBuildApiUrl() + buildTargetUrls[k_JsonNodeNameStartBuilds].AsDict()[k_JsonNodeNameHref].AsString();

                    var targetContainer = new VisualElement();
                    targetContainer.AddToClassList(k_ClassNameTargetEntry);
                    var buildNameTextElement = new TextElement();
                    buildNameTextElement.AddToClassList(k_ClassNameTitle);
                    buildNameTextElement.text = buildTargetName;
                    targetContainer.Add(buildNameTextElement);
                    var buildButton = new Button();
                    buildButton.name = k_BuildButtonNamePrefix + buildTargetId;
                    buildButton.AddToClassList(k_ClassNameBuildButton);
                    if (m_BillingPlanLabel.ToLower() == k_SubscriptionPersonal ||
                        k_SubscriptionTeamsBasic.ToLower() == k_SubscriptionPersonal)
                    {
                        buildButton.SetEnabled(false);
                    }
                    buildButton.text     = L10n.Tr(k_LabelBuildButton);
                    buildButton.clicked += () =>
                    {
                        var uploadHandler          = new UploadHandlerRaw(Encoding.UTF8.GetBytes(k_LaunchBuildPayload));
                        var launchBuildPostRequest = new UnityWebRequest(startBuildUrl,
                                                                         UnityWebRequest.kHttpVerbPOST)
                        {
                            downloadHandler = new DownloadHandlerBuffer(), uploadHandler = uploadHandler
                        };
                        launchBuildPostRequest.SetRequestHeader("AUTHORIZATION", $"Bearer {UnityConnect.instance.GetUserInfo().accessToken}");
                        launchBuildPostRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8");
                        m_Provider.m_BuildRequests.Add(launchBuildPostRequest);
                        var launchingMessage = string.Format(L10n.Tr(k_MessageLaunchingBuild), buildTargetName);

                        Debug.Log(launchingMessage);
                        NotificationManager.instance.Publish(
                            Notification.Topic.BuildService,
                            Notification.Severity.Info,
                            launchingMessage);

                        EditorAnalytics.SendLaunchCloudBuildEvent(new BuildPostInfo()
                        {
                            targetName = buildTargetName
                        });

                        var operation = launchBuildPostRequest.SendWebRequest();
                        operation.completed += asyncOperation =>
                        {
                            try
                            {
                                if (ServicesUtils.IsUnityWebRequestReadyForJsonExtract(launchBuildPostRequest))
                                {
                                    try
                                    {
                                        if (launchBuildPostRequest.responseCode == k_HttpResponseCodeAccepted)
                                        {
                                            var jsonLaunchedBuildParser = new JSONParser(launchBuildPostRequest.downloadHandler.text);
                                            var launchedBuildJson       = jsonLaunchedBuildParser.Parse();
                                            var launchedBuilds          = launchedBuildJson.AsList();

                                            foreach (var rawLaunchedBuild in launchedBuilds)
                                            {
                                                var launchedBuild = rawLaunchedBuild.AsDict();
                                                var buildNumber   = launchedBuild[k_JsonNodeNameBuild].AsFloat().ToString();
                                                var message       = string.Format(L10n.Tr(k_MessageLaunchedBuildSuccess), buildNumber, buildTargetName);
                                                Debug.Log(message);
                                                NotificationManager.instance.Publish(
                                                    Notification.Topic.BuildService,
                                                    Notification.Severity.Info,
                                                    message);
                                            }
                                        }
                                        else
                                        {
                                            var message = L10n.Tr(k_MessageLaunchedBuildFailure);
                                            Debug.LogError(message);
                                            NotificationManager.instance.Publish(
                                                Notification.Topic.BuildService,
                                                Notification.Severity.Error,
                                                message);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        NotificationManager.instance.Publish(
                                            Notification.Topic.BuildService,
                                            Notification.Severity.Error,
                                            L10n.Tr(k_MessageErrorForBuildLaunch));
                                        Debug.LogException(ex);
                                    }
                                }
                            }
                            finally
                            {
                                m_Provider.m_BuildRequests.Remove(launchBuildPostRequest);
                                launchBuildPostRequest.Dispose();
                                launchBuildPostRequest = null;
                            }
                        };
                    };
                    targetContainer.Add(buildButton);
                    targetsContainer.Add(targetContainer);

                    var separator = new VisualElement();
                    separator.AddToClassList(k_ClassNameSeparator);
                    targetsContainer.Add(separator);
                }
            }
    // サーバからアセットバンドルをダウンロードする
    private static IEnumerator Download(string[] assetBundleNames, OnDownloadProgressUpdate update)
    {
        // キャッシュできる状態か確認
        while (!Caching.ready)
        {
            yield return(null);
        }

        // アセットバンドルを全てダウンロードするまで回す
        fileIndex = 0;
        do
        {
            // baseURLにAssetBuddle名を付与してURL生成
            string bundleName  = assetBundleNames[fileIndex];
            string url         = baseURL + bundleName;
            string manifestURL = url + ".manifest";
            // URLキャッシュ防止のためタイムスタンプを付与
            url         += ((url.Contains("?")) ? "&" : "?") + "t=" + DateTime.Now.ToString("yyyyMMddHHmmss");
            manifestURL += ((manifestURL.Contains("?")) ? "&" : "?") + "t=" + DateTime.Now.ToString("yyyyMMddHHmmss");

            // CRCチェックを行うか確認
            // manifestファイルをDL
            UnityWebRequest wwwManifest = UnityWebRequest.Get(manifestURL);
            // ダウンロードを待つ
            yield return(wwwManifest.SendWebRequest());

            // manifestが存在していた場合はCRCチェックをする
            uint latestCRC = 0;
            if (string.IsNullOrEmpty(wwwManifest.error))
            {
                // manifest内部のCRCコードを抽出する
                string[] lines = wwwManifest.downloadHandler.text.Split(new string[] { "CRC: " }, StringSplitOptions.None);
                latestCRC = uint.Parse(lines[1].Split(new string[] { "\n" }, StringSplitOptions.None)[0]);

#if UNITY_2017_1_OR_NEWER
                // キャッシュを個別削除する
                string key = "km_assetbundleversioncache_" + bundleName;
                if (PlayerPrefs.HasKey(key))
                {
                    string currentCRC = PlayerPrefs.GetString(key);
                    if (currentCRC != latestCRC.ToString())
                    {
                        PlayerPrefs.SetString(key, latestCRC.ToString()); // 新しいcrcを保存
                        Caching.ClearAllCachedVersions(bundleName);       // 既存のキャッシュを削除
                    }
                    Debug.Log("[" + bundleName + ".manifest] \n" + "Latest CRC : " + latestCRC + "  Current CRC: " + currentCRC);
                }
                else
                {
                    PlayerPrefs.SetString(key, latestCRC.ToString()); // 新しいcrcを保存
                }
                latestCRC = 0;
#endif
            }
            else
            {
                Debug.Log(bundleName + ".manifest has not found.");
            }

            // CRCチェックしてダウンロード開始
            using (UnityWebRequest www = UnityWebRequest.GetAssetBundle(url, ver, latestCRC))
            {
                // ダウンロード開始
                www.SendWebRequest();
                // ダウンロードが完了するまでプログレスを更新する
                while (www.downloadProgress < 1f)
                {
                    // progress設定
                    float progress = 0f;
                    if (www.downloadProgress > 0)
                    {
                        progress = www.downloadProgress;
                    }
                    // 更新する
                    update(progress, fileIndex, false, www.error);
                    yield return(new WaitForEndOfFrame());
                }

                // エラー処理
                if (!string.IsNullOrEmpty(www.error))
                {
                    // 完了通知
                    update(0f, fileIndex, false, www.error);
                    string err = www.error;
                    Debug.Log(www.error);
                    // wwwを解放する
                    www.Dispose();
                    throw new Exception("WWW download had an error:" + err);
                }
                // ロードしたアセットバンドルをセット
                AssetBundle bundle = DownloadHandlerAssetBundle.GetContent(www);

                // AssetBundle内部に同名のCRYPTO_SIGNがあった場合、暗号化Assetと判断して復号する
                if (bundle.Contains(CRYPTO_SIGN + bundle.name))
                {
                    bundle = DecryptingAssetBundle(bundle);
                    yield return(bundle);
                }
                bundleDic.Add(bundleName, bundle);
                // wwwを解放する
                www.Dispose();
            }
        } while (++fileIndex < assetBundleNames.Length);

        // 完了通知
        update(1f, fileIndex, true, null);
    }
Exemplo n.º 23
0
    void OnGUI()
    {
        if (!File.Exists("font_apikey.txt"))
        {
            // TODO: provide a url so people can easily get an API key
            // TODO: provide an easy way to save the API key
            GUILayout.Label("No API key found! place a file font_apikey.txt in the root of your project with the api key inside!");
            return;
        }

        if (fontDatabase == null)
        {
            // State 1 : Download the database

            if (webRequest == null)
            {
                WebRequestButton();
            }
            else
            {
                if (fontDatabase == null)
                {
                    GUILayout.Label("Building font library...");

                    EditorGUI.ProgressBar(new Rect(0, this.position.height - EditorGUIUtility.singleLineHeight, position.width, EditorGUIUtility.singleLineHeight), webRequest.downloadProgress, "Progress");

                    if (webRequest.isDone)
                    {
                        string database = webRequest.downloadHandler.text;
                        File.WriteAllText(databasePath, database);
                        fontDatabase = JsonUtility.FromJson <GoogleFontResponse>(database);
                        webRequest.Dispose();
                        webRequest = null;
                        fontData   = null;
                    }
                }
            }
        }
        else if (fontData == null)
        {
            // State 2 : no current font

            if (webRequest == null)
            {
                if (GUILayout.Button("Grab a random font!"))
                {
                    GetRandomFont();
                }

                if (GUILayout.Button("Rebuild Database"))
                {
                    webRequest = UnityWebRequest.Get("https://www.googleapis.com/webfonts/v1/webfonts?key=" + apiKey);
                    webRequest.SendWebRequest();
                    fontDatabase = null;
                }
            }
            else
            {
                if (!webRequest.isDone)
                {
                    GUILayout.Label("Downloading!");
                    GUILayout.Label($"Response code: {webRequest.responseCode}");
                    EditorGUI.ProgressBar(new Rect(0, this.position.height - EditorGUIUtility.singleLineHeight, position.width, EditorGUIUtility.singleLineHeight), webRequest.downloadProgress, "Progress");
                }
                else
                {
                    fontData = webRequest.downloadHandler.data;

                    File.WriteAllBytes(tempPath, fontData);
                    AssetDatabase.Refresh();

                    currentFont            = AssetDatabase.LoadAssetAtPath <Font>(tempPath);
                    previewStyle           = new GUIStyle(GUI.skin.label);
                    previewStyle.fontSize *= 2;

                    previewStyle.font = currentFont;
                }
            }
        }
        else
        {
            // State 3 : current font, reroll, save

            GUILayout.Label("How's this cool font?", previewStyle);

            GUILayout.BeginHorizontal();

            if (GUILayout.Button("Save it!"))
            {
                File.WriteAllBytes(fontOutputPath + outputPath, fontData);
            }

            if (GUILayout.Button("Reroll"))
            {
                GetRandomFont();
            }

            GUILayout.EndHorizontal();
        }
    }
Exemplo n.º 24
0
        /// <summary>
        /// Co-routine that services one PendingRequest. This method must be called with StartCoroutine.
        /// </summary>
        /// <param name="request">The request to service.</param>
        private IEnumerator HandleWebRequest(PendingRequest request, BufferHolder bufferHolder)
        {
            // NOTE: This method runs on the main thread, but never blocks -- the blocking part of the work is
            // done by yielding the UnityWebRequest, which releases the main thread for other tasks while we
            // are waiting for the web request to complete (by the miracle of coroutines).

            // Let the caller create the UnityWebRequest, configuring it as they want. The caller can set the URL,
            // method, headers, anything they want. The only thing they can't do is call Send(), as we're in charge
            // of doing that.
            UnityWebRequest webRequest = request.creationCallback();

            PtDebug.LogVerboseFormat("Web request: {0} {1}", webRequest.method, webRequest.url);

            bool cacheAllowed = cache != null && webRequest.method == "GET" && request.maxAgeMillis != CACHE_NONE;

            // Check the cache (if it's a GET request and cache is enabled).
            if (cacheAllowed)
            {
                bool   cacheHit      = false;
                byte[] cacheData     = null;
                bool   cacheReadDone = false;
                cache.RequestRead(webRequest.url, request.maxAgeMillis, (bool success, byte[] data) => {
                    cacheHit      = success;
                    cacheData     = data;
                    cacheReadDone = true;
                });
                while (!cacheReadDone)
                {
                    yield return(null);
                }
                if (cacheHit)
                {
                    PtDebug.LogVerboseFormat("Web request CACHE HIT: {0}, response: {1} bytes",
                                             webRequest.url, cacheData.Length);
                    request.completionCallback(PolyStatus.Success(), /* responseCode */ 200, cacheData);

                    // Return the buffer to the pool for reuse.
                    CleanUpAfterWebRequest(bufferHolder);

                    yield break;
                }
                else
                {
                    PtDebug.LogVerboseFormat("Web request CACHE MISS: {0}.", webRequest.url);
                }
            }

            DownloadHandlerBuffer handler = new DownloadHandlerBuffer();

            webRequest.downloadHandler = handler;

            // We need to asset that we actually succeeded in setting the download handler, because this can fail
            // if, for example, the creation callback mistakenly called Send().
            PolyUtils.AssertTrue(webRequest.downloadHandler == handler,
                                 "Couldn't set download handler. It's either disposed of, or the creation callback mistakenly called Send().");

            // Start the web request. This will suspend this coroutine until the request is done.
            PtDebug.LogVerboseFormat("Sending web request: {0}", webRequest.url);
            yield return(UnityCompat.SendWebRequest(webRequest));

            // Request is finished. Call user-supplied callback.
            PtDebug.LogVerboseFormat("Web request finished: {0}, HTTP response code {1}, response: {2}",
                                     webRequest.url, webRequest.responseCode, webRequest.downloadHandler.text);
            PolyStatus status = UnityCompat.IsNetworkError(webRequest) ? PolyStatus.Error(webRequest.error) : PolyStatus.Success();

            request.completionCallback(status, (int)webRequest.responseCode, webRequest.downloadHandler.data);

            // Cache the result, if applicable.
            if (!UnityCompat.IsNetworkError(webRequest) && cacheAllowed)
            {
                byte[] data = webRequest.downloadHandler.data;
                if (data != null && data.Length > 0)
                {
                    byte[] copy = new byte[data.Length];
                    Buffer.BlockCopy(data, 0, copy, 0, data.Length);
                    cache.RequestWrite(webRequest.url, copy);
                }
            }

            // Clean up.
            webRequest.Dispose();
            CleanUpAfterWebRequest(bufferHolder);
        }
Exemplo n.º 25
0
        private IEnumerator Post(CallRequestContainer reqContainer)
        {
#if PLAYFAB_REQUEST_TIMING
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var startTime = DateTime.UtcNow;
#endif

            var www = new UnityWebRequest(reqContainer.FullUrl)
            {
                uploadHandler   = new UploadHandlerRaw(reqContainer.Payload),
                downloadHandler = new DownloadHandlerBuffer(),
                method          = "POST"
            };

            foreach (var headerPair in reqContainer.RequestHeaders)
            {
                if (!string.IsNullOrEmpty(headerPair.Key) && !string.IsNullOrEmpty(headerPair.Value))
                {
                    www.SetRequestHeader(headerPair.Key, headerPair.Value);
                }
                else
                {
                    Debug.LogWarning("Null header: " + headerPair.Key + " = " + headerPair.Value);
                }
            }

#if UNITY_2017_2_OR_NEWER
            yield return(www.SendWebRequest());
#else
            yield return(www.Send());
#endif

#if PLAYFAB_REQUEST_TIMING
            stopwatch.Stop();
            var timing = new PlayFabHttp.RequestTiming {
                StartTimeUtc        = startTime,
                ApiEndpoint         = reqContainer.ApiEndpoint,
                WorkerRequestMs     = (int)stopwatch.ElapsedMilliseconds,
                MainThreadRequestMs = (int)stopwatch.ElapsedMilliseconds
            };
            PlayFabHttp.SendRequestTiming(timing);
#endif

            if (!string.IsNullOrEmpty(www.error))
            {
                OnError(www.error, reqContainer);
            }
            else
            {
                try
                {
                    byte[] responseBytes = www.downloadHandler.data;
                    string responseText  = System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytes.Length);
                    OnResponse(responseText, reqContainer);
                }
                catch (Exception e)
                {
                    OnError("Unhandled error in PlayFabUnityHttp: " + e, reqContainer);
                }
            }
            www.Dispose();
        }
Exemplo n.º 26
0
    /// <summary>
    /// 执行下载视频任务的协程
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private static IEnumerator Download(string url)
    {
        if (string.IsNullOrEmpty(url))
        {
            yield break;
        }
        webRequest = UnityWebRequest.Get(url);
        UnityWebRequestAsyncOperation asyncOperation = webRequest.SendWebRequest();
        int progress = 0;

        while (!asyncOperation.isDone)
        {
            progress = (int)(asyncOperation.progress * 100) % 100;
            if (null != _onProgress)
            {
                _onProgress(progress);
            }

            yield return(oneSecond);
        }

        if (asyncOperation.isDone)
        {
            if (webRequest.downloadedBytes > 0 && !string.IsNullOrEmpty(localFilePath))
            {
                byte[] btArray = webRequest.downloadHandler.data;
                try
                {
                    FileStream WriteStream = new FileStream(localFilePath, FileMode.Create);
                    WriteStream.Write(btArray, 0, btArray.Length);
                    WriteStream.Close();
                    WriteStream.Dispose();
                }
                catch (Exception e)
                {
                    if (null != _onFailed)
                    {
                        _onFailed(DownLoadMovError.SaveError);
                    }
                    throw;
                }
                isLoading = false;

                //双重检查
                if (CheckLocalFileExist(localFilePath))
                {
                    if (null != localFilePath)
                    {
                        _onCompleted();
                    }
                }
                else
                {
                    if (null != _onFailed)
                    {
                        _onFailed(DownLoadMovError.SaveError);
                    }
                }
            }
        }

        if (!string.IsNullOrEmpty(webRequest.error) || webRequest.downloadedBytes <= 0)
        {
            isLoading = false;
            if (null != _onFailed)
            {
                _onFailed(DownLoadMovError.DownloadError);
            }
        }
        webRequest.Dispose();
        webRequest = null;
    }
Exemplo n.º 27
0
        public IEnumerator LoadIcon(ulong workshopId, string directory = null, AssetBundle bundle = null)
        {
            Skin str = null;
            AssetBundleRequest assetBundleRequest;

            TimeWarning.BeginSample("Skin.LoadIcon");
            if (bundle != null)
            {
                TimeWarning.BeginSample("ManifestName");
                str.manifestName = string.Concat("Assets/Skins/", workshopId, "/manifest.txt");
                TimeWarning.EndSample();
                TimeWarning.BeginSample("LoadAssetAsync");
                assetBundleRequest = bundle.LoadAssetAsync <TextAsset>(str.manifestName);
                TimeWarning.EndSample();
                TimeWarning.EndSample();
                yield return(assetBundleRequest);

                TimeWarning.BeginSample("Skin.LoadIcon");
                TimeWarning.BeginSample("AssetBundleRequest");
                str.manifestAsset = assetBundleRequest.asset as TextAsset;
                TimeWarning.EndSample();
                if (str.manifestAsset != null)
                {
                    TimeWarning.BeginSample("TextAsset");
                    str.manifestContent = str.manifestAsset.text;
                    TimeWarning.EndSample();
                }
                assetBundleRequest = null;
            }
            if (str.manifestContent == null && directory != null)
            {
                TimeWarning.BeginSample("ManifestName");
                str.manifestName = string.Concat(directory, "/manifest.txt");
                TimeWarning.EndSample();
                TimeWarning.BeginSample("File.Exists");
                bool flag = File.Exists(str.manifestName);
                TimeWarning.EndSample();
                if (flag)
                {
                    TimeWarning.EndSample();
                    yield return(Global.Runner.StartCoroutine(Parallel.Coroutine(new Action(str.LoadManifestFromFile))));

                    TimeWarning.BeginSample("Skin.LoadIcon");
                }
            }
            if (str.manifestContent != null)
            {
                TimeWarning.EndSample();
                yield return(Global.Runner.StartCoroutine(Parallel.Coroutine(new Action(str.DeserializeManifest))));

                TimeWarning.BeginSample("Skin.LoadIcon");
            }
            if (str.manifest == null)
            {
                UnityEngine.Debug.LogWarning(string.Concat("Invalid skin manifest: ", str.manifestName));
                TimeWarning.EndSample();
                yield break;
            }
            TimeWarning.BeginSample("Skinnable.FindForItem");
            str.Skinnable = Skinnable.FindForItem(str.manifest.ItemType);
            TimeWarning.EndSample();
            if (bundle != null)
            {
                TimeWarning.BeginSample("IconName");
                str.iconName = string.Concat("Assets/Skins/", workshopId, "/icon.png");
                TimeWarning.EndSample();
                TimeWarning.BeginSample("LoadAssetAsync");
                assetBundleRequest = bundle.LoadAssetAsync <Sprite>(str.iconName);
                TimeWarning.EndSample();
                TimeWarning.EndSample();
                yield return(assetBundleRequest);

                TimeWarning.BeginSample("Skin.LoadIcon");
                TimeWarning.BeginSample("AssetBundleRequest");
                Sprite sprite = assetBundleRequest.asset as Sprite;
                TimeWarning.EndSample();
                if (sprite != null)
                {
                    TimeWarning.BeginSample("Sprite");
                    str.sprite = sprite;
                    TimeWarning.EndSample();
                }
                assetBundleRequest = null;
            }
            if (str.sprite == null && SteamClient.IsValid)
            {
                string         empty       = string.Empty;
                InventoryDef[] definitions = SteamInventory.Definitions;
                TimeWarning.BeginSample("IconName");
                str.iconName = workshopId.ToString();
                TimeWarning.EndSample();
                if (definitions != null)
                {
                    TimeWarning.BeginSample("FindItemDefinition");
                    int length = (int)definitions.Length - 1;
                    while (length >= 0)
                    {
                        InventoryDef inventoryDef = definitions[length];
                        string       property     = inventoryDef.GetProperty("workshopdownload");
                        if (str.iconName != property)
                        {
                            length--;
                        }
                        else
                        {
                            empty = inventoryDef.IconUrlLarge;
                            break;
                        }
                    }
                    TimeWarning.EndSample();
                }
                if (!string.IsNullOrEmpty(empty))
                {
                    TimeWarning.BeginSample("UnityWebRequestTexture.GetTexture");
                    UnityWebRequest texture = UnityWebRequestTexture.GetTexture(empty);
                    texture.timeout = Mathf.CeilToInt(WorkshopSkin.DownloadTimeout);
                    TimeWarning.EndSample();
                    TimeWarning.EndSample();
                    yield return(texture.SendWebRequest());

                    TimeWarning.BeginSample("Skin.LoadIcon");
                    if (texture.isDone && !texture.isHttpError && !texture.isNetworkError)
                    {
                        TimeWarning.BeginSample("DownloadHandlerTexture.GetContent");
                        Texture2D content = DownloadHandlerTexture.GetContent(texture);
                        TimeWarning.EndSample();
                        TimeWarning.BeginSample("Sprite");
                        str.sprite = Sprite.Create(content, new Rect(0f, 0f, 512f, 512f), Vector2.zero, 100f, 0, SpriteMeshType.FullRect);
                        TimeWarning.EndSample();
                    }
                    TimeWarning.BeginSample("UnityWebRequest.Dispose");
                    texture.Dispose();
                    TimeWarning.EndSample();
                    texture = null;
                }
            }
            if (str.sprite == null && directory != null)
            {
                TimeWarning.BeginSample("IconName");
                str.iconName = string.Concat(directory, "/icon.png");
                TimeWarning.EndSample();
                TimeWarning.BeginSample("File.Exists");
                bool flag1 = File.Exists(str.iconName);
                TimeWarning.EndSample();
                if (flag1)
                {
                    TimeWarning.BeginSample("AsyncTextureLoad.Invoke");
                    AsyncTextureLoad asyncTextureLoad = new AsyncTextureLoad(str.iconName, false, false, true, false);
                    TimeWarning.EndSample();
                    TimeWarning.EndSample();
                    yield return(asyncTextureLoad);

                    TimeWarning.BeginSample("Skin.LoadIcon");
                    TimeWarning.BeginSample("AsyncTextureLoad.Texture");
                    Texture2D texture2D = asyncTextureLoad.texture;
                    TimeWarning.EndSample();
                    TimeWarning.BeginSample("Sprite");
                    str.sprite = Sprite.Create(texture2D, new Rect(0f, 0f, 512f, 512f), Vector2.zero, 100f, 0, SpriteMeshType.FullRect);
                    TimeWarning.EndSample();
                    asyncTextureLoad = null;
                }
            }
            if (str.sprite != null)
            {
                str.IconLoaded = true;
                if (str.OnIconLoaded != null)
                {
                    str.OnIconLoaded();
                }
            }
            TimeWarning.EndSample();
        }
Exemplo n.º 28
0
        /// <summary>
        /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching
        /// instantiate gameobject
        /// </summary>
        /// <param name="bundleURL">full url to assetbundle file</param>
        /// <param name="assetName">optional parameter to access specific asset from assetbundle</param>
        /// <returns></returns>
        IEnumerator DownloadAndCache(string bundleURL, string assetName = "")
        {
            // Wait for the Caching system to be ready
            while (!Caching.ready)
            {
                yield return(null);
            }

            // if you want to always load from server, can clear cache first
            //        Caching.CleanCache();

            // get current bundle hash from server, random value added to avoid caching
            UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest?r=" + (Random.value * 9999999));

            Debug.Log("Loading manifest:" + bundleURL + ".manifest");

            // wait for load to finish
            yield return(www.Send());

            // if received error, exit
            if (www.isNetworkError == true)
            {
                Debug.LogError("www error: " + www.error);
                www.Dispose();
                www = null;
                yield break;
            }

            // create empty hash string
            Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

            // check if received data contains 'ManifestFileVersion'
            if (www.downloadHandler.text.Contains("ManifestFileVersion"))
            {
                // extract hash string from the received data, TODO should add some error checking here
                var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
                hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

                if (hashString.isValid == true)
                {
                    // we can check if there is cached version or not
                    if (Caching.IsVersionCached(bundleURL, hashString) == true)
                    {
                        Debug.Log("Bundle with this hash is already cached!");
                    }
                    else
                    {
                        Debug.Log("No cached version founded for this hash..");
                    }
                }
                else
                {
                    // invalid loaded hash, just try loading latest bundle
                    Debug.LogError("Invalid hash:" + hashString);
                    yield break;
                }
            }
            else
            {
                Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
                yield break;
            }

            // now download the actual bundle, with hashString parameter it uses cached version if available
            www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL + "?r=" + (Random.value * 9999999), hashString, 0);

            // wait for load to finish
            yield return(www.Send());

            if (www.error != null)
            {
                Debug.LogError("www error: " + www.error);
                www.Dispose();
                www = null;
                yield break;
            }

            // get bundle from downloadhandler
            AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

            GameObject bundlePrefab = null;

            // if no asset name is given, take the first/main asset
            if (assetName == "")
            {
                bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
            }
            else
            { // use asset name to access inside bundle
                bundlePrefab = (GameObject)bundle.LoadAsset(assetName);
            }

            // if we got something out
            if (bundlePrefab != null)
            {
                // instantiate at 0,0,0 and without rotation
                Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity);

                /*
                 * // fix pink shaders, NOTE: not always needed..
                 * foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true))
                 * {
                 *  // FIXME: creates multiple materials, not good
                 *  var material = Shader.Find(r.material.shader.name);
                 *  r.material.shader = null;
                 *  r.material.shader = material;
                 * }*/
            }

            www.Dispose();
            www = null;

            // try to cleanup memory
            Resources.UnloadUnusedAssets();
            bundle.Unload(false);
            bundle = null;
        }
Exemplo n.º 29
0
        private IEnumerator ImageDownloader()
        {
            if (enableLog)
            {
                Debug.Log("[Stackeer] Download started.");
            }

            UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(url);
            UnityWebRequestAsyncOperation op1 = uwr.SendWebRequest();

            while (!op1.isDone)
            {
                if (uwr.error != null)
                {
                    Error("Error while downloading the image : " + uwr.error);
                    yield break;
                }

                progress = Mathf.FloorToInt(op1.progress * 100);
                if (onDownloadProgressChange != null)
                {
                    onDownloadProgressChange.Invoke(progress);
                }

                if (enableLog)
                {
                    Debug.Log("[Stackeer] Downloading progress : " + progress + "%");
                }

                yield return(null);
            }

            if (uwr.error == null)
            {
                Texture2D texture = ((DownloadHandlerTexture)uwr.downloadHandler).texture;

                switch (imageEncodeFormet)
                {
                case IMAGE_ENCODE_FORMET.JPEG:
                    File.WriteAllBytes(filePath + uniqueHash, texture.EncodeToJPG());
                    break;

                case IMAGE_ENCODE_FORMET.PNG:
                    File.WriteAllBytes(filePath + uniqueHash, texture.EncodeToPNG());
                    break;
                }
            }
            else
            {
                Error("Error while downloading the image : " + uwr.error);
                yield break;
            }

            uwr.Dispose();
            uwr = null;

            if (onDownloadedAction != null)
            {
                onDownloadedAction.Invoke();
            }

            LoadSpriteToImage();

            underProcessStackeers.Remove(uniqueHash);
        }
        protected override IEnumerator DoDownloadBundles(IProgressPromise <Progress, bool> promise, List <BundleInfo> bundles)
        {
            long              totalSize      = 0;
            long              downloadedSize = 0;
            Progress          progress       = new Progress();
            List <BundleInfo> list           = new List <BundleInfo>();

            for (int i = 0; i < bundles.Count; i++)
            {
                var info = bundles[i];
                totalSize += info.FileSize;
                if (BundleUtil.Exists(info, module))
                {
                    downloadedSize += info.FileSize;
                    continue;
                }
                list.Add(info);
            }

            progress.TotalCount     = bundles.Count;
            progress.CompletedCount = bundles.Count - list.Count;
            progress.TotalSize      = totalSize;
            progress.CompletedSize  = downloadedSize;
            yield return(null);

            List <KeyValuePair <BundleInfo, UnityWebRequest> > tasks = new List <KeyValuePair <BundleInfo, UnityWebRequest> >();

            for (int i = 0; i < list.Count; i++)
            {
                BundleInfo      bundleInfo = list[i];
                string          fullname   = GetFullSavePath(bundleInfo.Filename);
                UnityWebRequest www        = new UnityWebRequest(GetAbsoluteUri(bundleInfo.Filename));
                www.downloadHandler = new DownloadFileHandler(fullname);

#if UNITY_2018_1_OR_NEWER
                www.SendWebRequest();
#else
                www.Send();
#endif
                tasks.Add(new KeyValuePair <BundleInfo, UnityWebRequest>(bundleInfo, www));

                while (tasks.Count >= this.MaxTaskCount || (i == list.Count - 1 && tasks.Count > 0))
                {
                    long tmpSize = 0;
                    for (int j = tasks.Count - 1; j >= 0; j--)
                    {
                        var             task        = tasks[j];
                        BundleInfo      _bundleInfo = task.Key;
                        UnityWebRequest _www        = task.Value;

                        if (!_www.isDone)
                        {
                            tmpSize += (long)Math.Max(0, _www.downloadedBytes);//the UnityWebRequest.downloadedProgress has a bug in android platform
                            continue;
                        }

                        progress.CompletedCount += 1;
                        tasks.RemoveAt(j);
                        downloadedSize += _bundleInfo.FileSize;
#if UNITY_2018_1_OR_NEWER
                        if (_www.isNetworkError)
#else
                        if (_www.isNetworkError)
#endif
                        {
                            promise.SetException(new Exception(_www.error));
                            if (log.IsErrorEnabled)
                            {
                                log.ErrorFormat("Downloads AssetBundle '{0}' failure from the address '{1}'.Reason:{2}", _bundleInfo.FullName, GetAbsoluteUri(_bundleInfo.Filename), _www.error);
                            }
                            _www.Dispose();

                            try
                            {
                                foreach (var kv in tasks)
                                {
                                    kv.Value.Dispose();
                                }
                            }
                            catch (Exception) { }
                            yield break;
                        }
                        _www.Dispose();
                    }

                    progress.CompletedSize = downloadedSize + tmpSize;
                    promise.UpdateProgress(progress);

                    yield return(null);
                }
            }
            promise.SetResult(true);
        }