void OnDownloadCompleted(int handle, int channel, int data, IntPtr User)
 {
     if (DownloadComplete != null)
     {
         DownloadComplete.Invoke();
     }
 }
Esempio n. 2
0
        public void DownloadAndInstallPackage(
			ReportInstallProgress reportProgress,
			DownloadComplete downloadComplete,
			DownloadError downloadError,
			VerificationError verificationError,
			IsCancelled isCancelled
		)
        {
            string downloadPath = PrepareDownloadFilePath (FileUtil.GetUniqueTempPathInProject (), config.Filename);

            new Detail.AsyncTaskRunnerBuilder<byte[]> ().Do ((object[] args) => {
                return Net.Validator.MakeRequest (() => {
                    return API.V1.DownloadFile (config.PackageUrl, (progress) => reportProgress(progress), () => { return isCancelled (); });
                });
            }).OnError ((System.Exception e) => {
                downloadError(e);
                return Detail.AsyncTaskRunner<byte[]>.ErrorRecovery.Nothing;
            }).OnCompletion ((byte[] downloadedBytes) => {
                if (downloadedBytes.Length == 0) {
                    return;
                }
                try {
                    System.IO.File.WriteAllBytes (downloadPath, downloadedBytes);
                    string signatureUrl = SignatureUrlFromPackageUrl (config.PackageUrl);

                    VerifySignature (signatureUrl, downloadedBytes, verificationError, downloadError, isCancelled, () => {
                        downloadComplete (downloadPath);
                        InstallPackage (downloadPath);
                    });
                } catch (IOException e) {
                    downloadError (e as Exception);
                }
            }).Run ();
        }
        public void DownloadAndInstallPackage(
            ReportInstallProgress reportProgress,
            DownloadComplete downloadComplete,
            DownloadError downloadError,
            VerificationError verificationError,
            IsCancelled isCancelled
            )
        {
            string downloadPath = PrepareDownloadFilePath(FileUtil.GetUniqueTempPathInProject(), config.Filename);

            new Detail.AsyncTaskRunnerBuilder <byte[]> ().Do((object[] args) => {
                return(Net.Validator.MakeRequest(() => {
                    return API.V1.DownloadFile(config.PackageUrl, (progress) => reportProgress(progress), () => { return isCancelled(); });
                }));
            }).OnError((System.Exception e) => {
                downloadError(e);
                return(Detail.AsyncTaskRunner <byte[]> .ErrorRecovery.Nothing);
            }).OnCompletion((byte[] downloadedBytes) => {
                if (downloadedBytes.Length == 0)
                {
                    return;
                }
                try {
                    System.IO.File.WriteAllBytes(downloadPath, downloadedBytes);
                    string signatureUrl = SignatureUrlFromPackageUrl(config.PackageUrl);

                    VerifySignature(signatureUrl, downloadedBytes, verificationError, downloadError, isCancelled, () => {
                        downloadComplete(downloadPath);
                        InstallPackage(downloadPath);
                    });
                } catch (IOException e) {
                    downloadError(e as Exception);
                }
            }).Run();
        }
Esempio n. 4
0
        private void downloadCallback(string url, string filename, object obj)
        {
            if (Complete != null)
            {
                Complete.Invoke(null, Tuple.Create(url, filename, jobs[(int)obj].Item2));
            }

            lock (add_lock)
            {
                remain_contents--;
                if (remain_contents == 0)
                {
                    DownloadComplete.Invoke(null, null);
                }
            }

            download_file_count[(int)obj]++;
            if (download_file_count[(int)obj] == file_count[(int)obj])
            {
                if (CompleteGroup != null)
                {
                    CompleteGroup.Invoke(null, Tuple.Create("", jobs[(int)obj].Item2));
                }
            }
        }
        public void StartDownloadManager(string title, GetMoviesObject.Movie video)
        {
            try
            {
                if (video != null && !string.IsNullOrEmpty(title))
                {
                    Video = video;
                    SqLiteDatabase dbDatabase = new SqLiteDatabase();
                    dbDatabase.Insert_WatchOfflineVideos(Video);
                    dbDatabase.Dispose();

                    Request.SetTitle(title);
                    Request.SetAllowedNetworkTypes(DownloadNetwork.Mobile | DownloadNetwork.Wifi);
                    Request.SetDestinationInExternalPublicDir(FilePath, Filename);
                    Request.SetNotificationVisibility(DownloadVisibility.Visible);
                    Request.SetAllowedOverRoaming(true);
                    //Request.SetVisibleInDownloadsUi(true);
                    DownloadId = Downloadmanager.Enqueue(Request);

                    DownloadComplete onDownloadComplete = new DownloadComplete();
                    Application.Context.ApplicationContext.RegisterReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ActionDownloadComplete));
                }
                else
                {
                    Toast.MakeText(ContextActivty, Application.Context.GetText(Resource.String.Lbl_Download_faileds), ToastLength.Short).Show();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Esempio n. 6
0
 public void DownloadFile(string url, bool openAfterDownload)
 {
     if (webClient.IsBusy)
     {
         throw new Exception("Данный клиент для скачивания занят");
     }
     try
     {
         var startDownloading = DateTime.UtcNow;
         webClient.Proxy = null;
         if (!SelectFolder(Path.GetFileName(url), out var filePath))
         {
             throw DownloadingError();
         }
         webClient.DownloadProgressChanged += (o, args) =>
         {
             ProgressPercentageChanged?.Invoke(args.ProgressPercentage);
             FileSizeChanged?.Invoke(args.TotalBytesToReceive);
             DownloadBytesChanged?.Invoke(args.BytesReceived, DateTime.UtcNow - startDownloading);
             if (args.ProgressPercentage >= 100 && openAfterDownload)
             {
                 Process.Start(filePath);
             }
         };
         webClient.DownloadFileCompleted += (o, args) => DownloadComplete?.Invoke();
         stopWatch.Start();
         webClient.DownloadFileAsync(new Uri(url), filePath);
     }
     catch (Exception e)
     {
         throw DownloadingError();
     }
 }
        /// <summary>
        /// 下载完成事件的回调函数
        /// </summary>
        private async void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (sender != client)
            {
                return;
            }
            try
            {
                string      path = StorageTools.Settings.DownloadFolderPath;
                StorageFile file = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);

                await file.MoveAsync(await StorageFolder.GetFolderFromPathAsync(StorageTools.Settings.DownloadFolderPath), Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);

                //播放一个通知
                Toasts.ToastManager.ShowDownloadCompleteToastAsync(Strings.AppResources.GetString("DownloadCompleted"), Message.FileName + ": " +
                                                                   Converters.StringConverter.GetPrintSize(_prog_.CurrentValue), file.Path);
                //触发事件
                DownloadComplete?.Invoke(Message);
            }
            catch (Exception ex)
            {
                //若用户把下载文件夹设置在奇怪的地方,这里会导致无法访问,触发异常
                Debug.WriteLine(ex.ToString());
                DownloadError?.Invoke(ex);
            }
        }
 public override void OnReceive(Context context, Intent intent)
 {
     if (intent.GetBooleanExtra("DownloadComplete", false))
     {
         DownloadComplete?.Invoke(this, EventArgs.Empty);
     }
 }
        private void DownloadServiceOnDownloadComplete(object sender, MyDownloadEventArgs myDownloadEventArgs)
        {
            CurrentProgress = 1.0;
            Download.State  = CurrentDownloadState.Finish;
            Debug.WriteLine("Download finisch");

            DownloadComplete?.Invoke(sender, myDownloadEventArgs);
        }
            public DownloadStats Merge(DownloadComplete complete)
            {
                var copy = Copy();

                copy.CompletedImages += complete.Images;
                copy.CompletedPages  += complete.HtmlPages;
                return(copy);
            }
Esempio n. 11
0
        /// <summary>
        /// Raises the <see cref="DownloadComplete"/> event
        /// </summary>
        /// <param name="e">Empty <see cref="EventArgs"/></param>
        protected virtual void OnDownloadComplete(EventArgs e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            DownloadComplete?.Invoke(this, e);
        }
Esempio n. 12
0
        private void bgw_download_DoWork(object sender, DoWorkEventArgs e)
        {
            //create new delegate to show progress on label and for the end of downloading
            ChangeTextSafe   safedelegate     = ChangeTextOnLabels;
            DownloadComplete downloadComplete = EndOfDownload;
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(RemoteFtpPath);

            request.Method = WebRequestMethods.Ftp.DownloadFile;

            //if we need authentfication - set credentials
            if (auth)
            {
                request.Credentials = new NetworkCredential(tb_login.Text, tb_pass.Text);
            }

            //need for show current speed
            Stopwatch speedTimer = new Stopwatch();
            //need for show estimated time
            TimeSpan elapsedTime;
            double   currentSpeed = -1;
            double   recivedBytes = 0;

            using (Stream ftpStream = request.GetResponse().GetResponseStream())
                using (Stream fileStream = File.Create(LocalDestinationPath))
                {
                    byte[]   buffer = new byte[buffsize];
                    int      read;
                    DateTime started = DateTime.Now;

                    speedTimer.Start();
                    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fileStream.Write(buffer, 0, read);
                        recivedBytes += read;

                        int position = (int)fileStream.Position;
                        //show progress on progressbar
                        pb_download.Invoke((MethodInvoker)(() => pb_download.Value = position));
                        //calculate transfer rate
                        currentSpeed = position / 1024d / speedTimer.Elapsed.TotalSeconds; //kb/sec

                        //calculate estimated time
                        elapsedTime = DateTime.Now - started;
                        TimeSpan estimatedTime = TimeSpan.FromSeconds((double)(size - recivedBytes) /*bytes left */ * elapsedTime.TotalSeconds / (double)recivedBytes);
                        //calculate how many percent we've already got
                        short percent = (short)((position * 100) / size);
                        //call the delegate to refresh progress on labels
                        this.Invoke(safedelegate, estimatedTime, position, percent, currentSpeed);
                    }

                    //we've received file
                    speedTimer.Stop();
                    this.Invoke(downloadComplete);
                }
        }
Esempio n. 13
0
        private void Btn_download_Click(object sender, EventArgs e)
        {
            string url = txt_url.Text;

            downloader = new MultiThreadDownloader();
            HelperDownload   h = this.UpdateProgress;
            DownloadComplete d = this.DisplayMessage;

            downloader.DownloadHelperDownload(url, h, d);
        }
Esempio n. 14
0
 private void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
 {
     if (asyncCompletedEventArgs.Cancelled == true)
     {
         DownloadCancel?.Invoke(this, new MyDownloadEventArgs());
     }
     else
     {
         DownloadComplete?.Invoke(this, new MyDownloadEventArgs());
     }
 }
Esempio n. 15
0
        private void ReceivedStreamComplete(DownloadComplete message)
        {
            _logger.Info($"[{nameof(StreamReceiver)}] got signaled that the stream completed.");
            Context.Parent.Tell(
                new HttpResult <string>
            {
                Response = $"Stream total length was, {_total}"
            });

            message.Stream.Flush();
            message.Stream.Dispose();
        }
Esempio n. 16
0
        private async Task DownloadAudio(DownloadAudioFile track)
        {
            if (!TimerStart)
            {
                this.Timer.Start();
            }


            CurrentDownloadTrack = track;
            DownloadAccess       = false;
            StorageFile trackFile = null;

            if (!track.FromAlbum)
            {
                var libraryTracks = await KnownFolders.MusicLibrary.GetFolderAsync("Music X");

                trackFile = await libraryTracks.CreateFileAsync($"{track.Artist} - {track.Title} (Music X).mp3");
            }
            else
            {
                var libraryTracks = await KnownFolders.MusicLibrary.GetFolderAsync("Music X");

                var albumName       = track.AlbumName.Replace("*", "").Replace(".", "").Replace("\"", "").Replace("\\", "").Replace("/", "").Replace("[", "").Replace("]", "").Replace(":", "").Replace(";", "").Replace("|", "").Replace("=", "").Replace(",", "");
                var libraryPlaylist = await libraryTracks.GetFolderAsync(track.AlbumName);

                if (await libraryPlaylist.TryGetItemAsync($"{track.Artist} - {track.Title} (Music X).mp3") != null)
                {
                    DownloadComplete?.Invoke(this, CurrentDownloadTrack);
                }
                else
                {
                    trackFile = await libraryPlaylist.CreateFileAsync($"{track.Artist} - {track.Title} (Music X).mp3");
                }
            }
            currentFileAudio = trackFile;
            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation    download   = downloader.CreateDownload(new Uri(track.Url), trackFile);

            CurrentDownloadOperation = download;
            Maximum = ulong.Parse(GetFileSize(new Uri(track.Url)));


            var task = Task.Run(() =>
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    CurrentDownloadFileChanged?.Invoke(this, null);
                });
            });

            DownloadAccess = true;
            await download.StartAsync();
        }
Esempio n. 17
0
        public void Download(Request r)
        {
            if (r == null)
            {
                return;
            }
            r.LeftTryTimes--;

            var beforR = BeforeDownloadPage?.Invoke(r) ?? r;

            var http = new HttpHelper();
            var p    = (Page)http.GetHtml(beforR);

            p.Request = beforR;

            if (p.Response == null || p.Response.StatusCode != HttpStatusCode.OK)
            {
                var failres = p.Response == null ? p.Html : p.Response.StatusDescription;

                if (p.Response != null && p.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    //找不到的页面.去掉
                    return;
                }

                if (r.LeftTryTimes > 0)
                {
                    Logger.Warn($"下载 {p.Request.Url} 失败,原因:{failres},剩余重试次数:{r.LeftTryTimes}");

                    Crawler.inst.Schduler.AddRequest(r);
                }
                else
                {
                    //下载失败
                    FailCount++;
                    Logger.Warn($"下载 {p.Request.Url} 失败,重试次数用完,当前配置重试次数:{Crawler.Config.TryTimes}");
                }


                return;
            }
            SuccessCount++;
            Logger.Info($"下载 {p.Request.Url} 成功");

            //把p的cookie存到总cookie中去
            if (p.CookieCollection.Count > 0)
            {
                Crawler.inst.Schduler.AddCookie(p.CookieCollection);
            }
            AfterDownloadPage?.Invoke(p);
            DownloadComplete?.Invoke(p);
        }
Esempio n. 18
0
 public void DownloadAsync(string cpath, string lpath)
 {
     if (FTP)
     {
         _ftpc.GetFileAsyncCompleted += (sender, args) => DownloadComplete.SafeInvoke(sender, args);
         _ftpc.GetFileAsync(cpath, lpath, FileAction.Create);
     }
     else
     {
         using (var f = new FileStream(lpath, FileMode.Create, FileAccess.ReadWrite))
             _sftpc.BeginDownloadFile(cpath, f, ar => DownloadComplete.SafeInvoke(_sftpc, EventArgs.Empty), state: null);
     }
 }
Esempio n. 19
0
        public async void StartAsync()
        {
            string path = Path.GetDirectoryName(sDestinationPath);

            if (!string.IsNullOrEmpty(path) && !Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            await Task.Run(() => StartDown());

            DownloadComplete?.Invoke(sDestinationPath);
        }
Esempio n. 20
0
        private void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                Log.O("Update Download Complete.");
            }
            else
            {
                Log.O("Update Download Error: " + e.Error);
            }

            DownloadComplete?.Invoke(e.Error != null, e.Error);
        }
Esempio n. 21
0
        public void DownloadHelperDownload(string url, HelperDownload h, DownloadComplete d)
        {
            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                WebClient client    = new WebClient();
                string[]  fileParts = url.Split('/');
                string    fileName  = fileParts.Last();

                Uri urlDownload = new Uri(url, UriKind.Absolute);
                client.DownloadFileAsync(urlDownload, $"C:\\Users\\Robin R\\Documents\\{fileName}");
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((send, ex) => Client_DownloadProgress(send, ex, fileName, h));
                client.DownloadFileCompleted   += new AsyncCompletedEventHandler((send, ex) => Client_DownloadCompleted(send, ex, fileName, d));
            }
        }
Esempio n. 22
0
        private void OnDownloadFileCompleted(DownloadComplete downloadComplete)
        {
            Task.Run(async() =>
            {
                await _mediator.Send(new UpdateDownloadCompleteOfDownloadTaskCommand(
                                         downloadComplete.Id,
                                         downloadComplete.DataReceived,
                                         downloadComplete.DataTotal));

                await _fileMerger.AddFileTask(downloadComplete.DownloadTask);
                await SetDownloadStatusAsync(downloadComplete.Id, DownloadStatus.Merging);
                Log.Information($"The download of {downloadComplete.DownloadTask.Title} has completed!");
                CheckDownloadQueue();
            });
        }
Esempio n. 23
0
 private void Updater_DownloadCompleted(object sender, DownloadComplete e)
 {
     //throw new NotImplementedException();
     // MessageBox.Show(e.IsSuccessful.ToString());
     if (e.IsSuccessful)
     {
         Process.Start(Directory.GetCurrentDirectory() + "\\lsyt.exe");
         System.Windows.Application.Current.Shutdown();
     }
     else
     {
         DownloadProgBar.Value = 0;
         UpdateButton.Content  = "Check for updates";
         MessageBox.Show("New version failed to download", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Esempio n. 24
0
        /// <summary>
        /// 下载完成事件的回调函数
        /// </summary>
        private async void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (sender != client)
            {
                return;
            }
            try
            {
                StorageFile file = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);

                StorageFolder folder = await StorageManager.TryGetFolderAsync(Message.FolderToken);

                if (folder == null)
                {
                    folder = await StorageManager.TryGetFolderAsync(Settings.DownloadsFolderToken);

                    Message.FolderToken = Settings.DownloadsFolderToken;
                    if (folder == null)
                    {
                        folder = ApplicationData.Current.LocalCacheFolder;
                        Message.FolderToken = StorageApplicationPermissions.FutureAccessList
                                              .Add(ApplicationData.Current.LocalCacheFolder);
                    }
                    Toasts.ToastManager.ShowSimpleToast(Strings.AppResources.GetString("DownloadFolderPathIllegal"),
                                                        Strings.AppResources.GetString("DownloadFolderPathIllegalMessage"));
                }

                await file.MoveAsync(folder, Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);

                Message.DownloadSize = (long)(await file.GetBasicPropertiesAsync()).Size;

                Message.IsDone = true;

                //触发事件
                State = DownloadState.Done;
                DownloadComplete?.Invoke(Message);
            }
            catch (Exception ex)
            {
                //若用户把下载文件夹设置在奇怪的地方,这里会导致无法访问,触发异常
                Debug.WriteLine(ex.ToString());
                DownloadError?.Invoke(ex);
            }
        }
Esempio n. 25
0
        void Timer_Tick(object sender, EventArgs e)
        {
            _torrents.Current = ListTorrents();
            Debug.WriteLine($"Torrents count: {_torrents.Current.Count}");
            if (_torrents.Last != null)
            {
                var completed = FindDone();
                var added     = FindNew();

                if (completed.Count > 0)
                {
                    DownloadComplete?.Invoke(completed);
                }

                if (added.Count > 0)
                {
                    TorrentAdded?.Invoke(added);
                }
            }
        }
Esempio n. 26
0
        private async Task CheckDownloadTimeout(AresUdpSocket socket)
        {
            DateTime now = DateTime.Now;

            if (now.Subtract(lastackinfo).TotalSeconds >= 30)
            {
                IsDownloading = false;
                try {
                    socket.Close();
                }
                catch {
                }
                socket.Dispose();
                DownloadComplete?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                await Task.Delay(1000);
            }
        }
Esempio n. 27
0
        private async Task OnDownloadComplete(IList <DownloadWorkerComplete> completeList)
        {
            _timeThreadContext.Dispose();

            var           orderedList = completeList.ToList().OrderBy(x => x.Id).ToList();
            StringBuilder builder     = new StringBuilder();

            foreach (var progress in orderedList)
            {
                builder.Append($"({progress.Id} - {progress.FileName} download completed!) + ");
                if (!progress.ReceivedAllBytes)
                {
                    var msg = $"Did not receive the correct number of bytes for download worker {progress.Id}.";
                    msg +=
                        $" Received {progress.BytesReceived} and not {progress.BytesReceivedGoal} with a difference of {progress.BytesReceivedGoal - progress.BytesReceived}";
                    Log.Error(msg);
                }
            }

            // Remove the last " + "
            if (builder.Length > 3)
            {
                builder.Length -= 3;
            }

            Log.Debug(builder.ToString());
            var downloadComplete = new DownloadComplete(DownloadTask)
            {
                DestinationPath         = DownloadTask.DestinationPath,
                DownloadWorkerCompletes = orderedList,
                DataReceived            = completeList.Sum(x => x.BytesReceived),
                DataTotal = TotalBytesToReceive,
            };

            Log.Debug($"Download of {DownloadTask.FileName} finished!");

            await ClearDownloadWorkers();

            SetDownloadStatus(DownloadStatus.Completed);
            _downloadFileCompleted.OnNext(downloadComplete);
        }
Esempio n. 28
0
        private async Task CheckIsDownloadDoneAsync(int operationCode)
        {
            lock (threadLock)
            {
                if (operationCode != CurrentOperationCode || State != DownloadState.Downloading)
                {
                    return;
                }
                if (Message.DownloadSize >= Message.FileSize)
                {
                    State = DownloadState.Done;
                    DisposeThreads();
                }
                else
                {
                    return;
                }
            }
            //进入这里没有return表示已经完成
            try
            {
                GC.Collect();

                string      path = StorageTools.Settings.DownloadFolderPath;
                StorageFile file = await StorageFile.GetFileFromPathAsync(Message.TempFilePath);

                await file.MoveAsync(await StorageFolder.GetFolderFromPathAsync(StorageTools.Settings.DownloadFolderPath), Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);

                //播放一个通知
                Toasts.ToastManager.ShowDownloadCompleteToastAsync(Strings.AppResources.GetString("DownloadCompleted"), Message.FileName + " - " +
                                                                   Converters.StringConverter.GetPrintSize((long)Message.FileSize), file.Path);
                //触发事件
                DownloadComplete?.Invoke(Message);
            }
            catch (Exception e)
            {
                //若用户把下载文件夹设置在奇怪的地方,这里会导致无法访问,触发异常
                Debug.WriteLine(e.ToString());
                HandleError(e, CurrentOperationCode);
            }
        }
Esempio n. 29
0
 public static void DownloadAsync(UpdateInfo updateInfo, object state, DownloadComplete complete)
 {
     new Thread(new ThreadStart(() =>
     {
         try
         {
             string fileName;
             Download(updateInfo, out fileName);
             if (complete != null)
             {
                 complete(fileName, state, null);
             }
         }
         catch (Exception e)
         {
             if (complete != null)
             {
                 complete(null, state, e);
             }
         }
     })).Start();
 }
Esempio n. 30
0
 public static void DownloadAsync(UpdateInfo updateInfo, object state, DownloadComplete complete)
 {
     new Thread(new ThreadStart(() =>
     {
         try
         {
             string fileName;
             Download(updateInfo, out fileName);
             if (complete != null)
             {
                 complete(fileName, state, null);
             }
         }
         catch (Exception e)
         {
             if (complete != null)
             {
                 complete(null, state, e);
             }
         }
     })).Start();
 }
        private void downloadCallback(string url, string filename, object obj)
        {
            var file_seg = (EmiliaFileSegment)obj;

            CompleteFile?.Invoke(null, file_seg);
            dispatcher_dictionary[file_seg.SeriesIndex].CompleteFile.Invoke(file_seg);

            lock (complete_lock)
            {
                int article_status = downloaded_count_dictionary[file_seg.SeriesIndex][file_seg.ArticleIndex] += 1;
                check_dictionary[file_seg.SeriesIndex][file_seg.ArticleIndex][file_seg.Index] = true;

                // 아티클 다운로드 완료
                if (article_status == series_dictionary[file_seg.SeriesIndex].Articles[file_seg.ArticleIndex].Files.Count)
                {
                    int series_status = downloaded_articles_count_dictionary[file_seg.SeriesIndex] += 1;
                    dispatcher_dictionary[file_seg.SeriesIndex].CompleteArticle.Invoke(series_dictionary[file_seg.SeriesIndex].Articles[file_seg.ArticleIndex]);
                    CompleteArticle?.Invoke(null, series_dictionary[file_seg.SeriesIndex].Articles[file_seg.ArticleIndex]);

                    // 시리즈 다운로드 완료
                    if (series_status == series_dictionary[file_seg.SeriesIndex].Articles.Count)
                    {
                        dispatcher_dictionary[file_seg.SeriesIndex].CompleteSeries();
                        CompleteSeries?.Invoke(null, series_dictionary[file_seg.SeriesIndex]);
                    }
                }
            }

            lock (add_lock)
            {
                remain_contents--;
                if (remain_contents == 0 && DownloadComplete != null)
                {
                    DownloadComplete.Invoke(null, null);
                }
            }
        }
Esempio n. 32
0
        public async Task DownloadToFolderAsync(string directory, CancellationToken cancellationToken = default)
        {
            if (IsRunning)
            {
                throw new InvalidOperationException("Download task was already started.");
            }
            IsRunning = true;

            var webClient = new WebClient();

            Directory.CreateDirectory(directory);

            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            webClient.DownloadFileCompleted   += WebClient_DownloadFileCompleted;

            await webClient.DownloadFileTaskAsync(new Uri(FileUrl), Path.Combine(directory, FileName));

            IsRunning = false;

            if (DownloadComplete != null)
            {
                _ = Task.Run(() => DownloadComplete.Invoke(this, new EventArgs()));
            }
        }
 public DownloadStats Merge(DownloadComplete complete)
 {
     var copy = Copy();
     copy.CompletedImages += complete.Images;
     copy.CompletedPages += complete.HtmlPages;
     return copy;
 }
Esempio n. 34
0
 private static void HandleMessage(DownloadComplete<V2FeedPackage> message)
 {
     System.Console.WriteLine("Finished downloading " + message.Item.Id);
 }
Esempio n. 35
0
        public static void DownloadAsync(string page, Dictionary<string, string> parameters, DownloadComplete onComplete, DownloadFailed onError)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += (sender, args) =>
            {
                if (args.Error != null)
                    onError(args.Error);
                else
                    onComplete(args.Result);
            };

            // Generate GET variables
            StringBuilder vars = new StringBuilder();
            foreach (var param in parameters)
                vars.Append(string.Format("{0}={1}&", param.Key, param.Value));

            Uri url = new Uri(baseUrl + page + "?" + vars.ToString());

            client.DownloadStringAsync(url);
        }