Exemplo n.º 1
0
    // recursive enumerator for downloading all valid file-containing urls in 'PendingURLS'
    private async void RecursiveDownload()
    {
        if (PendingURLS.Count == 0)       // handle no URL case
        {
            HandleCancel();
            return;
        }
        string uri = PendingURLS[0];

        if ((OnURIToFilename == null && !UseURIFilenameMap) || (UseURIFilenameMap && !URIFilenameMap.ContainsKey(uri)))
        {
            HandleCancel();
            return;
        }
        string fileName = UseURIFilenameMap ? URIFilenameMap[uri]: OnURIToFilename(uri);

        if (fileName == null && AbandonOnFailure)
        {
            HandleCancel();
            return;
        }
        var fileResultPath = Path.Combine(DownloadPath, fileName);

        PendingURLS.RemoveAt(0);
        if (!Downloading)       // case cancel invoked
        {
            HandleCancel(uri, fileResultPath);
            if (AbandonOnFailure)
            {
                return;
            }
        }
        var uwr = new UnityWebRequest(uri);

        uwr.timeout = Timeout;
        uwr.method  = UnityWebRequest.kHttpVerbGET;
        var dh = new DownloadHandlerFile(fileResultPath);

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

        while (!operation.isDone)
        {
            await Task.Delay(100);
        }
        if (uwr.isNetworkError || uwr.isHttpError || !Downloading)       // case network error or cancel invoked
        {
            HandleCancel(uri, fileResultPath);
            if (PendingURLS.Count > 0)
            {
                RecursiveDownload();
            }
        }
        else         // case succcesful download
        {
            _progress += (float)(1f / (float)_initialCount);
            CompletedURLS.Add(uri);
            CompletedURLPaths.Add(fileResultPath);
            if (PendingURLS.Count > 0)       // case more files to download
            {
                OnDownloadSuccess?.Invoke(DidFinish, uri, fileResultPath);
                RecursiveDownload();
            }
            else         // case no more files to download
            {
                _downloading = false;
                _endTime     = DateTime.Now.Millisecond;
                _elapsedTime = EndTime - StartTime;
                OnDownloadSuccess?.Invoke(DidFinish, uri, fileResultPath);
            }
        }
    }