public static void DownloadRecording(string recordingFileName, string resultFileOutputPath)
        {
            var logger = new AQALogger();

            var projectId   = Application.cloudProjectId;
            var downloadUri =
                $"{AutomatedQARuntimeSettings.GAMESIM_API_ENDPOINT}/v1/recordings/{recordingFileName}/download?projectId={projectId}";

            var dh = new DownloadHandlerFile(resultFileOutputPath);

            dh.removeFileOnAbort = true;
            logger.Log("Starting download" + downloadUri);
            using (var webrx = UnityWebRequest.Get(downloadUri))
            {
                webrx.downloadHandler = dh;
                AsyncOperation request = webrx.SendWebRequest();

                while (!request.isDone)
                {
                }

                if (webrx.IsError())
                {
                    logger.LogError($"Couldn't download file. Error - {webrx.error}");
                }
                else
                {
                    logger.Log($"Downloaded file saved to {resultFileOutputPath}.");
                }
            }
        }
        private static bool DownloadTo(bool isLocal, string path, string target)
        {
            var prefix = isLocal ?
#if UNITY_EDITOR || UNITY_IOS
                         "file://"
#else
                         string.Empty
#endif
                : string.Empty;
            var source  = prefix + path;
            var request = new UnityWebRequest(source);

            Log.Info($"extracting {request.url}");
            var handler = new DownloadHandlerFile(target);

            request.downloadHandler = handler;
            request.SendWebRequest();
            while (!request.isDone)
            {
            }
            if (request.error != null)
            {
                Log.Error(request.error);
                return(false);
            }
            while (!handler.isDone)
            {
                Thread.Sleep(100);
            }
            return(true);
        }
        private static void DownloadLastPackage(string shaKey)
        {
            //Create path
            string url  = "https://api.github.com/repos/resemble-ai/resemble-unity-text-to-speech/git/blobs/" + shaKey;
            string dir  = new DirectoryInfo(Application.dataPath).Parent.FullName + "/ResemblePackages/";
            string name = "ResemblePlugin-" + version.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture);
            string path = dir + name + ".unitypackage";


            Directory.CreateDirectory(dir);

            //Make request
            downloadRequest        = new UnityWebRequest(url);
            downloadRequest.method = UnityWebRequest.kHttpVerbGET;
            var handler = new DownloadHandlerFile(path, false);

            handler.removeFileOnAbort       = true;
            downloadRequest.downloadHandler = handler;
            downloadRequest.SetRequestHeader("Accept", "application/vnd.github.v3.raw");
            downloadRequest.SendWebRequest().completed += (asyncOp) => { OpenFile(path); };
            abort = false;
            if (EditorUtility.DisplayCancelableProgressBar("Resemble plugin update", "Preparing to download...", 0.0f))
            {
                abort = true;
                downloadRequest.Abort();
            }
            EditorApplication.update += DownloadCallback;
        }
        IEnumerator DownLoadVideo(string url, string videoPath, Action <bool, string, string> callback, Action <float> downloadProgress)
        {
            var uwr = new UnityWebRequest(url);

            uwr.method = UnityWebRequest.kHttpVerbGET;
            var dh = new DownloadHandlerFile(videoPath);

            dh.removeFileOnAbort = true;
            uwr.downloadHandler  = dh;
            uwr.SendWebRequest();

            while (!uwr.isDone)
            {
                downloadProgress?.Invoke(uwr.downloadProgress);
                yield return(null);
            }

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                Debug.Log(uwr.error);
                callback?.Invoke(false, url, videoPath);
            }
            else
            {
                callback?.Invoke(true, url, videoPath);
                Debug.Log("Download saved to: " + videoPath.Replace("/", "\\") + "\r\n" + uwr.error);
            }
        }
Example #5
0
        internal void SendRequest(string savePath, int failedTryAgain, int timeout)
        {
            if (string.IsNullOrEmpty(savePath))
            {
                throw new ArgumentNullException();
            }

            if (_webRequest == null)
            {
                _savePath       = savePath;
                _failedTryAgain = failedTryAgain;
                _timeout        = timeout;
                _requestCount++;
                _requestURL = GetRequestURL();

                // 重置超时相关变量
                _isAbort                = false;
                _latestDownloadBytes    = 0;
                _latestDownloadRealtime = Time.realtimeSinceStartup;

                _webRequest = new UnityWebRequest(_requestURL, UnityWebRequest.kHttpVerbGET);
                DownloadHandlerFile handler = new DownloadHandlerFile(savePath);
                handler.removeFileOnAbort   = true;
                _webRequest.downloadHandler = handler;
                _webRequest.disposeDownloadHandlerOnDispose = true;
                _operationHandle = _webRequest.SendWebRequest();
            }
        }
Example #6
0
        public override IEnumerator DownLoad()
        {
            // Check fatal
            if (LoadState != EWebLoadState.None)
            {
                throw new Exception($"Web file download state is not none state. {URL}");
            }

            LoadState = EWebLoadState.Loading;

            // 下载文件
            CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
            DownloadHandlerFile handler = new DownloadHandlerFile(SavePath);

            handler.removeFileOnAbort    = true;
            CacheRequest.downloadHandler = handler;
            CacheRequest.disposeDownloadHandlerOnDispose = true;
            CacheRequest.timeout = ResDefine.WebRequestTimeout;
            yield return(CacheRequest.SendWebRequest());

            // Check error
            if (CacheRequest.isNetworkError || CacheRequest.isHttpError)
            {
                LogSystem.Log(ELogType.Warning, $"Failed to download web file : {URL} Error : {CacheRequest.error}");
                LoadState = EWebLoadState.LoadFailed;
            }
            else
            {
                LoadState = EWebLoadState.LoadSucceed;
            }

            // Invoke callback
            LoadCallback?.Invoke(this);
        }
Example #7
0
    IEnumerator DownloadExtract()
    {
        string downloadPath = string.Join("/", Application.persistentDataPath, latest + ".zip");
        bool   toExtract    = false;

        if (!File.Exists(downloadPath))
        {
            using (UnityWebRequest www = UnityWebRequest.Get(string.Join("/", "http://gimmearecipe.000webhostapp.com", latest + ".zip")))
            {
                DownloadHandlerFile dhf = new DownloadHandlerFile(downloadPath)
                {
                    removeFileOnAbort = true
                };
                www.downloadHandler = dhf;
                print("Started download at " + Time.time);
                yield return(www.SendWebRequest());

                if (www.isNetworkError || www.isHttpError)
                {
                    print("Error: " + www.error);
                }
                else
                {
                    print("Finished download at " + Time.time);
                    toExtract = true;
                }
            }
        }
        if (!Directory.Exists(string.Join("/", Application.persistentDataPath, latest)) || toExtract)
        {
            print("Started extraction at " + Time.time);
            ZipFile.ExtractToDirectory(downloadPath, Application.persistentDataPath);
            print("Finished extraction at " + Time.time);
        }
    }
    private IEnumerator DownloadFile(string fileUrl, string savePath)
    {
        var uwr = new UnityWebRequest(fileUrl);

        uwr.method = UnityWebRequest.kHttpVerbGET;
        var dh = new DownloadHandlerFile(savePath);

        dh.removeFileOnAbort = true;
        uwr.downloadHandler  = dh;

        yield return(uwr.SendWebRequest());

        if (uwr.result == UnityWebRequest.Result.ConnectionError || uwr.result == UnityWebRequest.Result.ProtocolError)
        {
            WriteToLinkConsole("ERROR " + fileUrl + " :" + uwr.error);
            _downloadDictionary[fileUrl] = false;
        }
        else
        {
            //Debug.Log("Download saved to: " + savePath.Replace("/", "\\") + "\r\n" + uwr.error);
            _downloadDictionary[fileUrl] = true;
        }

        HtmlToMarkdownUIManager.Instance.IncreaseProgress();
        _amountOfImagesDownloaded++;
        HtmlToMarkdownUIManager.Instance.SetStatusText("Images downloaded: " + _amountOfImagesDownloaded + " / " + _downloadDictionary.Count);
    }
Example #9
0
    IEnumerator CoDownLoadFile(string url, string filename, Action <bool> action)
    {
        UnityWebRequest downloader = UnityWebRequest.Get(url);
        string          dir        = FileHelper.GetDir(filename);

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        DownloadHandlerFile downloadHandlerFile = new DownloadHandlerFile(filename);

        downloadHandlerFile.removeFileOnAbort = true; //TODO 定点续传等
        downloader.downloadHandler            = downloadHandlerFile;

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

        if (downloader.error != null)
        {
            Debug.LogError(downloader.error);
            action(false);
        }
        else
        {
            action(true);
        }
    }
    private IEnumerator DownloadFile(string url, string targetFolder)
    {
        Uri    uri        = new Uri(url);
        string filename   = Path.GetFileName(uri.LocalPath);
        string targetPath = Path.Combine(targetFolder, filename);

        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            AddToLog($"Starting file download for {uri}.");
            DownloadHandlerFile downloadHandler = new DownloadHandlerFile(targetPath);
            downloadHandler.removeFileOnAbort = true;
            request.downloadHandler           = downloadHandler;

            StartCoroutine(TrackProgress(request, targetPath));

            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                AddToLog("Error downloading the requested file!");
            }
            else
            {
                statusLabel.text = "100%";
                AddToLog($"Download saved to {targetPath}. {request.error}");
            }
        }

        yield return(null);
    }
Example #11
0
        /// <summary>
        /// 取得
        /// </summary>
        protected virtual IEnumerator CopyFile(string sourcePath, string targetPath)
        {
            var www = UnityWebRequest.Get(sourcePath);
            //	DLハンドラ
            var handler = new DownloadHandlerFile(targetPath);

            handler.removeFileOnAbort = true;
            www.downloadHandler       = handler;

            //	開始
            var request = www.SendWebRequest();

            while (!request.isDone)
            {
                var w = request.webRequest;
                if (w.isDone)
                {
                    break;
                }
                if (w.isHttpError || w.isNetworkError)
                {
                    throw new FileLoadException(w.error);
                }
                yield return(null);
            }
            yield return(request);
        }
Example #12
0
    public static IEnumerator AsyncDownloadFileRequest(string url, string fileFullName,
                                                       Action <UnityWebRequest, byte[]> completeCallback = null,
                                                       Action <UnityWebRequest> errorCallback            = null,
                                                       Action <UnityWebRequest> httpErrorCallback        = null,
                                                       Action <UnityWebRequest> newworkCallback          = null)
    {
        UnityWebRequest req = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);

        req.useHttpContinue = false;
        req.chunkedTransfer = false;
        req.redirectLimit   = 0; // disable redirects
        req.timeout         = 60;
        DownloadHandlerFile handler = new DownloadHandlerFile(fileFullName);

        handler.removeFileOnAbort = true;
        req.downloadHandler       = handler;
        yield return(req.SendWebRequest());

        if (string.IsNullOrEmpty(req.error))
        {
            if (errorCallback != null)
            {
                errorCallback(req);
            }

            yield break;
        }

        if (req.isHttpError)
        {
            if (httpErrorCallback != null)
            {
                httpErrorCallback(req);
            }

            yield break;
        }

        if (req.isNetworkError)
        {
            if (newworkCallback != null)
            {
                newworkCallback(req);
            }

            yield break;
        }

        while (req.isDone == false || req.responseCode != 200)
        {
            yield return(null);
        }

        if (completeCallback != null)
        {
            completeCallback(req, handler.data);
        }

        yield break;
    }
Example #13
0
        public override IEnumerator DownLoad()
        {
            // Check fatal
            if (States != EWebRequestStates.None)
            {
                throw new Exception($"{nameof(WebFileRequest)} is downloading yet : {URL}");
            }

            States = EWebRequestStates.Loading;

            // 下载文件
            CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
            DownloadHandlerFile handler = new DownloadHandlerFile(SavePath);

            handler.removeFileOnAbort    = true;
            CacheRequest.downloadHandler = handler;
            CacheRequest.disposeDownloadHandlerOnDispose = true;
            CacheRequest.timeout = Timeout;
            yield return(CacheRequest.SendWebRequest());

            // Check error
            if (CacheRequest.isNetworkError || CacheRequest.isHttpError)
            {
                MotionLog.Log(ELogLevel.Warning, $"Failed to download web file : {URL} Error : {CacheRequest.error}");
                States = EWebRequestStates.Fail;
            }
            else
            {
                States = EWebRequestStates.Success;
            }
        }
Example #14
0
    public static void DownloadXLSX(string docId, Action <string> callback, string fileName = "tmpXLSX")
    {
        string url =
            "https://docs.google.com/spreadsheets/d/" + docId + "/export?format=xlsx";
        UnityWebRequest www = UnityWebRequest.Get(url);

        string savePath = string.Format("{0}/{1}.xlsx", GameConstant.ExcelSourceFolder, fileName);
        var    dh       = new DownloadHandlerFile(savePath);

        dh.removeFileOnAbort = true;
        www.downloadHandler  = dh;

        UnityWebRequestAsyncOperation asyncOperation = www.SendWebRequest();

        asyncOperation.completed += (async) =>
        {
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log("Download success! File at:" + savePath);
                dh.Dispose();
                callback(savePath);
                www.Dispose();
            }
        };
    }
        IEnumerator DownloadFile()
        {
            Uri request = BuildRequests.BuildDownloadFileRequest(
                DownloadFileChannel,
                DownloadFileID.ToString(),
                DownloadFileName.ToString(),
                this.PubNubInstance,
                null
                );

            downloadWWW = new UnityWebRequest(request.OriginalString);
            #if (ENABLE_PUBNUB_LOGGING)
            this.PubNubInstance.PNLog.WriteToLog(string.Format("Download URL: {0}", request.OriginalString), PNLoggingMethod.LevelInfo);
            #endif

            downloadWWW.method = UnityWebRequest.kHttpVerbGET;
            var dh = new DownloadHandlerFile(DownloadFileSavePath);
            dh.removeFileOnAbort = true;

            downloadWWW.downloadHandler = dh;

            yield return(downloadWWW.SendWebRequest());

            DownloadCallback(CreatePNStatus(downloadWWW));
        }
Example #16
0
            public override UnityWebRequest CreateRequest(IAccessLocation location)
            {
                var req     = UnityWebRequest.Get(location.FullPath);
                var handler = new DownloadHandlerFile(m_local.FullPath);

                handler.removeFileOnAbort = true;
                req.downloadHandler       = handler;
                return(req);
            }
Example #17
0
        public static void DownloadSamples()
        {
            Debug.Log("[Build] - Downloading samples");
            try {
                for (int i = 0; i < kSamplesUrls.Length; i++)
                {
                    Tuple <string, string> sample = kSamplesUrls[i];
                    string filePath = Path.Combine(kSamplesPath, sample.Item2);

                    UnityWebRequest request = UnityWebRequest.Get(sample.Item1);
                    request.timeout = 10;
                    DownloadHandlerFile downloadHandlerFile = new DownloadHandlerFile(filePath);
                    downloadHandlerFile.removeFileOnAbort = true;
                    request.downloadHandler = downloadHandlerFile;

                    UnityWebRequestAsyncOperation requestAsyncOperation = request.SendWebRequest();
                    while (!requestAsyncOperation.isDone)
                    {
                        bool result = EditorUtility.DisplayCancelableProgressBar(
                            $"Downloading Sample {i + 1}/{kSamplesUrls.Length}",
                            String.Format(
                                "Downloading archive... {0} MB/{1} MB",
                                Math.Round(requestAsyncOperation.webRequest.downloadedBytes / 1000f / 1000f, 2),
                                Math.Round((double)Convert.ToUInt32(requestAsyncOperation.webRequest.GetResponseHeader("Content-Length")) / 1000f / 1000f, 2)
                                ),
                            requestAsyncOperation.progress
                            );

                        if (result)
                        {
                            request.Abort();
                            throw new OperationCanceledException();
                        }

                        Thread.Sleep(50);
                    }

                    if (request.isNetworkError)
                    {
                        throw new Exception($"Network error while downloading {sample.Item1}");
                    }

                    if (request.isHttpError)
                    {
                        throw new Exception($"HTTP error {request.responseCode} while downloading {sample.Item1}");
                    }
                }
            } catch (OperationCanceledException) {
                // Ignored
            } finally {
                EditorUtility.ClearProgressBar();
            }
        }
 /// <summary>
 /// 发送GET请求
 /// </summary>
 public void SendRequest(string url, string savePath)
 {
     if (_webRequest == null)
     {
         URL         = url;
         _webRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
         DownloadHandlerFile handler = new DownloadHandlerFile(savePath);
         handler.removeFileOnAbort   = true;
         _webRequest.downloadHandler = handler;
         _webRequest.disposeDownloadHandlerOnDispose = true;
         _operationHandle = _webRequest.SendWebRequest();
     }
 }
Example #19
0
 // Update is called once per frame
 void Update()
 {
     if (mIsDownloading && mUwr != null)
     {
         //Debug.Log(mUwr.downloadProgress);
         float progress = mUwr.downloadProgress;
         mUIText.text    = string.Format("{0:F}%", progress * 100);
         mUISlider.value = progress;
         DownloadHandlerFile downloadHandler = (DownloadHandlerFile)mUwr.downloadHandler;
         //mUIText2.text = GetDownloadSpeedStr(downloadHandler.GetDownloadSpeed());
         mUIText2.text = mUwr.downloadedBytes.ToString();
     }
 }
Example #20
0
        // Request a TTS service download
        public static WitUnityRequest RequestTTSDownload(string downloadPath, WitConfiguration configuration, string textToSpeak,
                                                         Dictionary <string, string> data, Action <float> onProgress, Action <string> onDownloadComplete)
        {
            // Download to temp path
            string tempDownloadPath = downloadPath + ".tmp";

            try
            {
                if (File.Exists(tempDownloadPath))
                {
                    File.Delete(tempDownloadPath);
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"Deleting Temp File Failed\nPath: {tempDownloadPath}\n{e}");
            }

            // Request file
            return(RequestTTS(configuration, textToSpeak, data, (response, uri) =>
            {
                DownloadHandlerFile fileHandler = new DownloadHandlerFile(tempDownloadPath, true);
                response.downloadHandler = fileHandler;
                response.disposeDownloadHandlerOnDispose = true;
            }, onProgress, (response, error) =>
            {
                // If file found
                try
                {
                    if (File.Exists(tempDownloadPath))
                    {
                        // For error, remove
                        if (!string.IsNullOrEmpty(error))
                        {
                            File.Delete(tempDownloadPath);
                        }
                        // For success, move to final path
                        else
                        {
                            File.Move(tempDownloadPath, downloadPath);
                        }
                    }
                }
                catch (Exception exception)
                {
                    error = exception.ToString();
                    Debug.LogError($"Moving File Failed\nFrom: {tempDownloadPath}\nTo: {downloadPath}\nError: {error}");
                }
                onDownloadComplete?.Invoke(error);
            }));
        }
Example #21
0
    public static UnityWebRequest DownloadFileRequest(string url, string fileFullName)
    {
        UnityWebRequest req = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);

        req.useHttpContinue = false;
        req.chunkedTransfer = false;
        req.redirectLimit   = 0; // disable redirects
        req.timeout         = 60;
        DownloadHandlerFile handler = new DownloadHandlerFile(fileFullName);

        handler.removeFileOnAbort = true;
        req.downloadHandler       = handler;
        return(req);
    }
Example #22
0
        /// <summary>
        /// Starts a file download from the specified URL to the specified file path, returning a
        /// UnityWebRequest representing the in-flight request.
        /// </summary>
        public static UnityWebRequest StartFileDownload(string url, string fileSavePath)
        {
#if UNITY_2017_2_OR_NEWER
            var downloadHandler = new DownloadHandlerFile(fileSavePath)
            {
                removeFileOnAbort = true
            };
            var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET, downloadHandler, null);
#else
            var request = UnityWebRequest.Get(url);
#endif
            SendWebRequest(request);
            return(request);
        }
Example #23
0
        private IEnumerator Copy(IAccessLocation source, IAccessLocation dest)
        {
            ChipstarLog.Log_WriteLocalBundle(source, dest);
            if (File.Exists(dest.FullPath))
            {
                ChipstarLog.Log($"Exsists File::{dest}");
                yield break;
            }
            var www     = UnityWebRequest.Get(source.FullPath);
            var handler = new DownloadHandlerFile(dest.FullPath);

            www.downloadHandler = handler;
            yield return(www.SendWebRequest());
        }
Example #24
0
    public IEnumerator DownloadFileAsync(Action <ulong> onRequestCompleted, Action <int, string> onRequestFailed)
    {
        string url = "http://dl3.webmfiles.org/big-buck-bunny_trailer.webm";

        string vidSavePath = Path.Combine(Application.persistentDataPath, "Videos");

        vidSavePath = Path.Combine(vidSavePath, "MyVideo.webm");

        //Create Directory if it does not exist
        if (!Directory.Exists(Path.GetDirectoryName(vidSavePath)))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(vidSavePath));
        }

        var uwr = new UnityWebRequest(url);

        uwr.method = UnityWebRequest.kHttpVerbGET;
        var dh = new DownloadHandlerFile(vidSavePath);

        dh.removeFileOnAbort = true;
        uwr.downloadHandler  = dh;

        yield return(uwr.SendWebRequest());

        //  Comprobamos si es error o acierto para ejecutar los callback
        if (uwr.isNetworkError || uwr.isHttpError)  //  Si hay error
        {
            if (onRequestFailed != null)
            {
                onRequestFailed.Invoke(Convert.ToInt32(uwr.responseCode), uwr.downloadHandler.text);
            }
        }
        else  //    Si no hay error
        {
            if (onRequestCompleted != null)
            {
                onRequestCompleted.Invoke(uwr.downloadedBytes);
            }
        }

        if (uwr.isNetworkError || uwr.isHttpError)
        {
            Debug.Log(uwr.error);
        }
        else
        {
            Debug.Log("Download saved to: " + vidSavePath.Replace("/", "\\") + "\r\n" + uwr.error);
        }
    }
Example #25
0
    private void DownloadFile(string fileName)
    {
        var uri                 = DownloadState.GetUri(serverConfiguration.FileDownloadServerUrl, port, resourcePathForFilesToDownload + fileName);
        var request             = UnityWebRequest.Get(uri);
        var filePath            = Path.Combine(pathToSaveFiles, fileName);
        var fileDownloadHandler = new DownloadHandlerFile(filePath)
        {
            removeFileOnAbort = true
        };

        request.downloadHandler = fileDownloadHandler;
        request.SendWebRequest().completed += operation => SingleFileDownloadFinished(request, fileName);
        activeRequestAndFileNameTupleList.Add(new Tuple <UnityWebRequest, string>(request, fileName));
        ++concurrentDownloadCounter;
    }
        public override void DownLoad()
        {
            if (CacheRequest != null)
            {
                return;
            }

            // 下载文件
            CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET);
            DownloadHandlerFile handler = new DownloadHandlerFile(SavePath);

            handler.removeFileOnAbort    = true;
            CacheRequest.downloadHandler = handler;
            CacheRequest.disposeDownloadHandlerOnDispose = true;
            AsyncOperationHandle = CacheRequest.SendWebRequest();
        }
Example #27
0
 IObservable <UnityWebRequest> DoDownload(IProgress <float> progress) => Observable.Defer(() =>
 {
     string tempPath         = TempPath ?? SavePath + ".tmp";
     var request             = new UnityWebRequest(Url);
     var handler             = new DownloadHandlerFile(tempPath);
     request.downloadHandler = handler;
     return(request.SendAsObservable(progress).Do(req =>
     {
         req.downloadHandler.Dispose();
         BeforeSave?.Invoke(new CallbackParam(this, req));
         File.Delete(SavePath);
         File.Move(tempPath, SavePath);
         AfterSave?.Invoke(new CallbackParam(this, req));
         OnDownloaded(req);
     }));
 });
        /**
         * Downloads a file to a local path, then loads the file
         */
        private IEnumerator DownloadFile(ModelDataTemplate.ModelImportData modelData, Text progressDisplay, int index, string localPathAndFilename, System.Action <ModelFile> callback = null)
        {
            UnityWebRequest fileDownloader = UnityWebRequest.Get(modelData.url);

            //get size of model first to allocate what is needed
            long modelSize = 0;

            yield return(StartCoroutine(GetFileSize(modelData.url, (size) =>
            {
                modelSize = size;
            })
                                        ));

            //set our model download settings
            fileDownloader.method = UnityWebRequest.kHttpVerbGET;
            using (var dh = new DownloadHandlerFile(localPathAndFilename))
            {
                dh.removeFileOnAbort           = true;
                fileDownloader.downloadHandler = dh;
                fileDownloader.SendWebRequest();

                while (!fileDownloader.isDone)
                {
                    string stats = WebGLMemoryStats.GetMoreStats("Downloading");
                    progressDisplay.text = $"Downloading {modelData.name}: {fileDownloader.downloadProgress.ToString("P")}\n{stats}";

                    yield return(null);
                }
            }

            System.GC.Collect();

            //Debug.Log($"Successfully downloaded model {modelData.name}, size {fileDownloader.downloadedBytes} bytes.");

            if (fileDownloader.result == UnityWebRequest.Result.ConnectionError || fileDownloader.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError(fileDownloader.error);
            }

            //Debug.Log($"Successfully downloaded asset {assetData.name}, size {fileDownloader.downloadedBytes} bytes.");

            ulong downloadedSize = fileDownloader.downloadedBytes;

            fileDownloader = null;

            callback(new ModelFile(localPathAndFilename, modelData.name, downloadedSize));
        }
Example #29
0
        /// <summary>
        /// Downloads the plugin file for a given network.
        /// </summary>
        /// <param name="network">Network for which to download the current version.</param>
        /// <returns></returns>
        public IEnumerator DownloadPlugin(Network network)
        {
            var path = Path.Combine(Application.temporaryCachePath, network.PluginFileName); // TODO: Maybe delete plugin file after finishing import.

#if UNITY_2017_2_OR_NEWER
            var downloadHandler = new DownloadHandlerFile(path);
#else
            var downloadHandler = new AppLovinDownloadHandler(path);
#endif
            webRequest = new UnityWebRequest(network.DownloadUrl)
            {
                method          = UnityWebRequest.kHttpVerbGET,
                downloadHandler = downloadHandler
            };

#if UNITY_2017_2_OR_NEWER
            var operation = webRequest.SendWebRequest();
#else
            var operation = webRequest.Send();
#endif

            while (!operation.isDone)
            {
                yield return(new WaitForSeconds(0.1f)); // Just wait till webRequest is completed. Our coroutine is pretty rudimentary.

                CallDownloadPluginProgressCallback(network.DisplayName, operation.progress, operation.isDone);
            }


#if UNITY_2020_1_OR_NEWER
            if (webRequest.result != UnityWebRequest.Result.Success)
#elif UNITY_2017_2_OR_NEWER
            if (webRequest.isNetworkError || webRequest.isHttpError)
#else
            if (webRequest.isError)
#endif
            {
                MaxSdkLogger.UserError(webRequest.error);
            }
            else
            {
                importingNetwork = network;
                AssetDatabase.ImportPackage(path, true);
            }

            webRequest = null;
        }
Example #30
0
        private IEnumerator GetUpdateFileAndSave(AssetDownloadData asset)
        {
            DownloadHandlerFile downloadHandler = new DownloadHandlerFile(Path.Combine(EnvironmentVariables.ExportAssetsRoot, asset.localPath));

            using (UnityWebRequest uwr1 = UnityWebRequest.Get(asset.uri1))
            {
                uwr1.certificateHandler = new UpdateCertificateHandler();
                uwr1.downloadHandler    = downloadHandler;
                uwr1.SendWebRequest();
                while (!uwr1.isDone)
                {
                    asset.progress = uwr1.downloadProgress;
                    yield return(new WaitForEndOfFrame());
                }

                if (uwr1.isNetworkError)
                {
                    ErrorList.Add(asset);
                    yield break;
                }
                else if (uwr1.isHttpError)
                {
                    using (UnityWebRequest uwr2 = UnityWebRequest.Get(asset.uri2))
                    {
                        uwr2.certificateHandler = new UpdateCertificateHandler();
                        uwr2.downloadHandler    = downloadHandler;
                        uwr2.SendWebRequest();
                        while (!uwr2.isDone)
                        {
                            asset.progress = uwr2.downloadProgress;
                            yield return(new WaitForEndOfFrame());
                        }

                        if (uwr2.isNetworkError || uwr2.isHttpError)
                        {
                            ErrorList.Add(asset);
                            yield break;
                        }
                    }
                }
                else
                {
                    asset.isSuccess = true;
                }
            }
        }