Exemplo n.º 1
0
    private void DownloadPhoto(string url)
    {
        var www = UnityWebRequestTexture.GetTexture(url);

        www.SendWebRequest()
        .AsAsyncOperationObservable()
        .SubscribeOn(Scheduler.ThreadPool)
        .ObserveOn(Scheduler.MainThread)
        .Subscribe(
            success =>
        {
            var photo = !www.downloadHandler.isDone
                        ? Global.Instance.errorImage.texture
                        : ((DownloadHandlerTexture)www.downloadHandler).texture;
            photos.Add(photo);
            if (photos.Count >= PerPage)
            {
                OnDownloadFinished?.Invoke(photos);
            }
        },
            failure =>
        {
            OnFailure(new Exception($"An exception occurred while downloading photo from {url}.", failure));
        }
            );
    }
Exemplo n.º 2
0
 public void OnReset()
 {
     downloadPhase  = DownloadPhase.REQUSET;
     bCheckMd5      = true;
     callBack       = null;
     remoteFileSize = 0;
     hasDownSize    = 0;
 }
        private void ReportEnd()
        {
            FinishedEventArgs e = new FinishedEventArgs();

            e.ResultType = FinishedEventArgs.Result.Success;

            e.File           = File;
            e.File.Completed = true;
            OnDownloadFinished?.Invoke(this, e);
        }
        private static void CheckDownloadFinished()
        {
            if (IsDownloading)
            {
                return;
            }

            VideoDownloadProgress = 0.0f;
            ChatDownloadProgress  = 0.0f;
            OnDownloadFinished?.Invoke();
        }
Exemplo n.º 5
0
        private void ProcessEvent()
        {
            if (m_Event.Count > 0)
            {
                DownloadEvent de = m_Event.Pop();
                m_Event.Clear();
                switch (de)
                {
                case DownloadEvent.Downloaded:
                {
                    SavaFileFromMemory();
                }
                break;

                case DownloadEvent.Begin:
                    break;

                case DownloadEvent.DownloadOrExit:
                    break;

                case DownloadEvent.Error:
                    OnDownloadError eL = m_OnError;
                    m_IsDownloading = false;
                    Clear();
                    if (eL != null)
                    {
                        eL(m_EventMsg);
                        eL = null;
                    }
                    break;

                case DownloadEvent.Finish:
                    OnDownloadFinished fL = m_OnFinished;
                    Clear();
                    if (fL != null)
                    {
                        fL(m_SaveFile, 0, 0);
                    }
                    break;

                case DownloadEvent.Progress:
                    break;

                default:
                    break;
                }
            }
        }
Exemplo n.º 6
0
        public bool AddDownloadTask(string uri, string localPath, int fileSize, OnDownloadProgress onProgress, OnDownloadError onError, OnDownloadFinished onFinshed, OnDownloadBegin onBegin, OnDownloadValidCheck validChecker, bool logError)
        {
            if (m_IsDownloading)
            {
                Log.e("HttpDownloaderMgr is busy!");
                return(false);
            }

            if (string.IsNullOrEmpty(uri) == true)
            {
                Log.e("uri is empty");
                return(false);
            }

            if (string.IsNullOrEmpty(localPath) == true)
            {
                Log.e("LocalPath is empty");
                return(false);
            }

            if (onError == null || onFinshed == null)
            {
                Log.e("onError & onFinshed should not be null!");
                return(false);
            }

            Clear();

            m_LogError        = logError;
            m_FileSize        = fileSize;
            m_OnProgress      = onProgress;
            m_OnError         = onError;
            m_OnFinished      = onFinshed;
            m_OnDownloadBegin = onBegin;
            m_OnValidCheck    = validChecker;

            m_Uri      = uri;
            m_SaveFile = localPath;

            m_IsDownloading = true;

            m_PreSize        = 0;
            m_LastChangeTime = currentTimeTick;

            StartCoroutine(StartIEnumeratorTask());
            return(true);
        }
Exemplo n.º 7
0
        private void Progress()
        {
            if (!isRunning)
            {
                isRunning = true;
            }

            string url = string.Empty;

            while (_downloadQueue.Count > 0 && _downloadQueue.TryDequeue(out url) && !string.IsNullOrWhiteSpace(url))
            {
                DownloadWithUrl($"http://cstrike.surf.ga/{url}");
            }

            isRunning = false;
            OnDownloadFinished?.Invoke(this, new EventArgs());
        }
        private void ReportEnd()
        {
            FinishedEventArgs e = new FinishedEventArgs();

            if (File.Downloaded == File.Size)
            {
                e.ResultType = FinishedEventArgs.Result.Success;
            }
            else
            {
                e.ResultType = FinishedEventArgs.Result.Unsuccessful;
            }

            e.File = File;
            if (e.File.Downloaded == e.File.Size)
            {
                e.File.Completed = true;
            }
            OnDownloadFinished?.Invoke(this, e);
        }
Exemplo n.º 9
0
        // 添加下载任务,目前只支持一个任务同时进行
        public bool AddDownloadTask(string uri, string localPath, OnDownloadProgress onProgress, OnDownloadError onError, OnDownloadFinished onFinshed, OnDownloadBegin onBegin = null)
        {
            if (m_IsDownloading)
            {
                Log.e("HttpDownloaderMgr is busy!");
                return(false);
            }

            if (string.IsNullOrEmpty(uri) == true)
            {
                Log.e("uri is empty");
                return(false);
            }

            if (string.IsNullOrEmpty(localPath) == true)
            {
                Log.e("LocalPath is empty");
                return(false);
            }

            if (onError == null || onFinshed == null)
            {
                Log.e("onError & onFinshed should not be null!");
                return(false);
            }

            m_OnProgress      = onProgress;
            m_OnError         = onError;
            m_OnFinished      = onFinshed;
            m_OnDownloadBegin = onBegin;

            m_Uri      = uri;
            m_SaveFile = localPath;

            m_TaskCount++;

            //Log.i("[HttpDownload]about to download new data:" + m_Uri);

            return(true);
        }
Exemplo n.º 10
0
        public void StartDownload(IApplicationVersion version)
        {
            if (isDownloading)
            {
                return;
            }

            _httpClient = new HttpClient();

            Task.Run(() =>
            {
                isDownloading = true;
                DownloadSpeed = new DownloadSpeed();

                OnProgressChanged  += DownloadSpeed.DownloadProgressChanged;
                OnDownloadFinished += DownloadSpeed.webClient_DownloadFileCompleted;

                var downloadFileWithRange = DownloadFileWithRange(version);
                OnDownloadFinished?.Invoke(this, new UpdateProgressChangedEventArgs(downloadFileWithRange, 0, 0, 0));
                isDownloading = false;
            });
        }
Exemplo n.º 11
0
        public async Task StartDownloadAsync(IApplicationVersion version)
        {
            if (_downloadTask == null)
            {
                _cancellationSource = _cancellationSourceFactory.CreateSource();
                _downloadTask       = Task.Run(() =>
                {
                    _httpClient = new HttpClient();

                    DownloadSpeed = new DownloadSpeed();

                    OnProgressChanged  += DownloadSpeed.DownloadProgressChanged;
                    OnDownloadFinished += DownloadSpeed.webClient_DownloadFileCompleted;

                    var downloadFileWithRange = DownloadFileWithRange(version);
                    OnDownloadFinished?.Invoke(this, new UpdateProgressChangedEventArgs(downloadFileWithRange, 0, 0, 0));
                    _downloadTask = null;
                }, _cancellationSource.Token);
            }

            await _downloadTask;
        }
Exemplo n.º 12
0
        public void Clear()
        {
            if (m_IsDownloading)
            {
                return;
            }

            if (m_WWW != null)
            {
                m_WWW.Dispose();
                m_WWW = null;
            }

            m_PreSize        = 0;
            m_LastChangeTime = currentTimeTick;
            m_Event.Clear();

            m_OnProgress      = null;
            m_OnError         = null;
            m_OnFinished      = null;
            m_OnDownloadBegin = null;
            m_OnValidCheck    = null;
            //StopAllCoroutines();
        }
Exemplo n.º 13
0
        /// <summary>
        /// </summary>
        private void UpdateDownloads(bool bHasConnection)
        {
            List <Guid> ActiveManifestIds = new List <Guid>();

            foreach (DownloadState State in StateCollection.States)
            {
                bool UpdateManifestId = true;

                // If not set to auto update and we already have a completed download, do nothing else.
                if (!State.UpdateAutomatically && State.ActiveManifestId != Guid.Empty)
                {
                    ManifestDownloadState OldVersionDownloader = ManifestDownloader.GetDownload(State.ActiveManifestId);
                    if (OldVersionDownloader != null && OldVersionDownloader.State == ManifestDownloadProgressState.Complete)
                    {
                        UpdateManifestId = false;
                    }
                }

                if (bHasConnection && UpdateManifestId)
                {
                    Guid NewManifestId = GetTargetManifestForState(State);
                    if (NewManifestId != Guid.Empty)
                    {
                        if (State.ActiveManifestId != NewManifestId && !State.Paused)
                        {
                            OnDownloadStarted?.Invoke(State);
                        }

                        State.ActiveManifestId = NewManifestId;
                    }
                }

                if (State.ActiveManifestId == Guid.Empty)
                {
                    continue;
                }

                ActiveManifestIds.Add(State.ActiveManifestId);

                ManifestDownloadState Downloader = ManifestDownloader.GetDownload(State.ActiveManifestId);
                if (Downloader != null)
                {
                    // If state is downloading but we've paused it, pause it and ignore.
                    if (State.Paused)
                    {
                        if (!Downloader.Paused)
                        {
                            ManifestDownloader.PauseDownload(State.ActiveManifestId);
                            continue;
                        }
                    }
                    else
                    {
                        if (Downloader.Paused)
                        {
                            ManifestDownloader.ResumeDownload(State.ActiveManifestId);
                        }
                    }

                    // Hackily change the priority - should change this to a SetDownloadPriority method.
                    Downloader.Priority          = State.Priority;
                    Downloader.InstallOnComplete = State.InstallAutomatically;
                    Downloader.InstallDeviceName = State.InstallDeviceName;
                    Downloader.InstallLocation   = State.InstallLocation;

                    // Have we finished this download?
                    if (Downloader.State == ManifestDownloadProgressState.Complete &&
                        State.PreviousDownloaderState != Downloader.State &&
                        State.PreviousDownloaderState != ManifestDownloadProgressState.Unknown)
                    {
                        OnDownloadFinished?.Invoke(State);
                    }

                    State.PreviousDownloaderState = Downloader.State;

                    // Store the amount of time the download is in each state to make
                    // time estimates a bit better.
                    if (Downloader.State != ManifestDownloadProgressState.Complete && !State.Paused && Downloader.Manifest != null && (bHasConnection || Downloader.State != ManifestDownloadProgressState.Downloading))
                    {
                        if (State.PendingDurationHistory == null)
                        {
                            State.PendingDurationHistory           = new DownloadStateDuration();
                            State.PendingDurationHistory.TotalSize = Downloader.Manifest.GetTotalSize();
                        }

                        ulong CurrentTime = TimeUtils.Ticks;
                        if (State.PendingDurationTimer > 0)
                        {
                            ulong Elapsed   = TimeUtils.Ticks - State.PendingDurationTimer;
                            ulong StartTime = State.PendingDurationHistory.GetDuration(Downloader.State);
                            ulong NewTime   = StartTime + Elapsed;
                            State.PendingDurationHistory.SetDuration(Downloader.State, NewTime);
                            //Console.WriteLine("State:{0} Time:{1}", Downloader.State.ToString(), StringUtils.FormatAsDuration((long)State.PendingDurationHistory.StateDurations[Downloader.State] / 1000));
                        }
                        State.PendingDurationTimer = CurrentTime;
                    }
                    else if (Downloader.State == ManifestDownloadProgressState.Complete)
                    {
                        if (State.PendingDurationHistory != null)
                        {
                            State.DurationHistory.Add(State.PendingDurationHistory);
                            State.PendingDurationHistory = null;

                            // Only keep a few history entries.
                            while (State.DurationHistory.Count > 15)
                            {
                                State.DurationHistory.RemoveAt(0);
                            }
                        }
                    }
                }
                else
                {
                    // Start downloading this manifest.
                    ManifestDownloader.StartDownload(State.ActiveManifestId, State.Priority);
                }
            }

            // Go through each manifest download and pause any that are no longer relevant.
            foreach (ManifestDownloadState Downloader in ManifestDownloader.States.States)
            {
                if (!ActiveManifestIds.Contains(Downloader.ManifestId))
                {
                    if (!Downloader.Paused)
                    {
                        ManifestDownloader.PauseDownload(Downloader.ManifestId);
                    }

                    Downloader.Active = false;
                }
                else
                {
                    Downloader.Active     = true;
                    Downloader.LastActive = DateTime.Now;
                }
            }

            // Only download a single auto-replication download at a time, more efficient than dozens downloading at the same time.
            Guid UnpausedAutoDownload = Guid.Empty;

            // Remove auto replication downloads as required.
            for (int i = 0; i < StateCollection.States.Count; i++)
            {
                DownloadState State = StateCollection.States[i];

                if (State.ActiveManifestId == Guid.Empty)
                {
                    continue;
                }

                if (!State.IsAutomaticReplication)
                {
                    continue;
                }

                ManifestDownloadState Downloader = ManifestDownloader.GetDownload(State.ActiveManifestId);
                if (Downloader != null)
                {
                    bool ShouldRemove = false;

                    // Always remove downloads that have completed.
                    if (Downloader.State == ManifestDownloadProgressState.Complete)
                    {
                        ShouldRemove = true;
                    }

                    // Download has not recieved any blocks in a long time, remove.
                    TimeSpan Elapsed = DateTime.UtcNow - Downloader.LastRecievedData;
                    if (Elapsed.TotalHours > ReplicationMaxIdleHours)
                    {
                        ShouldRemove = true;
                    }

                    // Automatically resume replication downloads if they are in an error state.
                    if (UnpausedAutoDownload == Guid.Empty)
                    {
                        UnpausedAutoDownload = State.ActiveManifestId;
                    }

                    State.Paused = (UnpausedAutoDownload != State.ActiveManifestId);

                    if (ShouldRemove)
                    {
                        StateCollection.States.RemoveAt(i);
                        AreStatesDirty = false;
                        i--;
                    }
                }
            }
        }
Exemplo n.º 14
0
 private void SinglePartUnknownDownloader_OnDownloadFinished(object sender, FinishedEventArgs e)
 {
     DownloadStatus = Status.NotDownloading;
     OnDownloadFinished?.Invoke(this, e);
 }
Exemplo n.º 15
0
        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public bool Download(string url, string localfile)
        {
            Url          = url;
            SaveFilePath = localfile;

            long       startPosition = 0;    // 上次下载的文件起始位置
            FileStream writeStream   = null; // 写入本地文件流对象

            try
            {
                // 判断要下载的文件夹是否存在
                if (File.Exists(localfile))
                {
                    writeStream   = File.OpenWrite(localfile);           // 存在则打开要下载的文件
                    startPosition = writeStream.Length;                  // 获取已经下载的长度
                    writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
                }
                else
                {
                    writeStream   = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                    startPosition = 0;
                }


                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }

                var myResponse = (HttpWebResponse)myRequest.GetResponse();
                FileTotalBytes = myResponse.ContentLength;

                FileDownloadedBytes = startPosition;

                Stream readStream = myRequest.GetResponse().GetResponseStream();  // 向服务器请求,获得服务器的回应数据流

                byte[] btArray     = new byte[512];                               // 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int    contentSize = readStream.Read(btArray, 0, btArray.Length); // 向远程文件读第一次

                IsRunning = true;

                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    if (_isStop)
                    {
                        break;
                    }

                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    FileDownloadedBytes += contentSize;
                    OnDownloading?.Invoke(this);

                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }

                //关闭流
                writeStream.Close();
                readStream.Close();

                IsDownloadSuccess = true;        //返回true下载成功
            }
            catch (Exception e)
            {
                Logger.Error(e, logger);

                if (writeStream != null)
                {
                    writeStream.Close();
                }

                IsDownloadSuccess = false;       //返回false下载失败
            }

            IsRunning = false;

            OnDownloadFinished?.Invoke(this);

            return(IsDownloadSuccess);
        }