예제 #1
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();
     }
 }
예제 #2
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 override void OnReceive(Context context, Intent intent)
 {
     if (intent.GetBooleanExtra("DownloadComplete", false))
     {
         DownloadComplete?.Invoke(this, EventArgs.Empty);
     }
 }
예제 #4
0
        /// <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);
            }
        }
예제 #5
0
 void OnDownloadCompleted(int handle, int channel, int data, IntPtr User)
 {
     if (DownloadComplete != null)
     {
         DownloadComplete.Invoke();
     }
 }
예제 #6
0
        /// <summary>
        /// Called when ffmpeg outputs data to its stderror output
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="dataReceivedEventArgs"></param>
        private void POnErrorDataReceived(object sender, DataReceivedEventArgs dataReceivedEventArgs)
        {
            if (_duration == TimeSpan.MinValue && dataReceivedEventArgs.Data.Contains("Duration:"))
            {
                var duration = dataReceivedEventArgs.Data.Substring(12, 8);
                _duration = TimeSpan.Parse(duration);

                OnDurationInfo?.Invoke(duration);
            }
            else if (dataReceivedEventArgs.Data != null && dataReceivedEventArgs.Data.Contains("time="))
            {
                var timeArr = dataReceivedEventArgs.Data.Split(new[] { "time=" }, StringSplitOptions.None);
                var timeStr = timeArr[1].Substring(0, 8);

                var time = TimeSpan.Parse(timeStr);

                var progress = (int)((time.TotalSeconds / _duration.TotalSeconds) * 100);
                if (progress != _progress)
                {
                    _progress = progress;

                    if (_progress >= 100)
                    {
                        OnProgress?.Invoke(100, timeStr);
                        OnDownloadComplete?.Invoke();
                    }
                    else
                    {
                        OnProgress?.Invoke(_progress, timeStr);
                    }
                }
            }
        }
        private void DownloadServiceOnDownloadComplete(object sender, MyDownloadEventArgs myDownloadEventArgs)
        {
            CurrentProgress = 1.0;
            Download.State  = CurrentDownloadState.Finish;
            Debug.WriteLine("Download finisch");

            DownloadComplete?.Invoke(sender, myDownloadEventArgs);
        }
예제 #8
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);
        }
예제 #9
0
 private void WebClientOnDownloadFileCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs)
 {
     if (asyncCompletedEventArgs.Cancelled == true)
     {
         DownloadCancel?.Invoke(this, new MyDownloadEventArgs());
     }
     else
     {
         DownloadComplete?.Invoke(this, new MyDownloadEventArgs());
     }
 }
예제 #10
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();
        }
예제 #11
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);
        }
예제 #12
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);
        }
예제 #13
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);
        }
예제 #14
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);
            }
        }
예제 #15
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);
                }
            }
        }
예제 #16
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);
            }
        }
예제 #17
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);
            }
        }
예제 #18
0
        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);
                }
            }
        }
예제 #19
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()));
            }
        }
 private void CompleteDownload(Model.Download download)
 {
     DownloadComplete?.Invoke(this, new MyDownloadEventArgs());
     download.FileRenameCancelToken = null;
 }
예제 #21
0
        private async void CheckProgress(object sender, object o)
        {
            if (CurrentDownloadOperation != null && CurrentDownloadTrack != null)
            {
                var a = CurrentDownloadOperation.Progress.BytesReceived;
                DownloadProgressChanged?.Invoke(this, a);
                if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Completed && DownloadAccess)
                {
                    DownloadAccess = false;
                    var trackFile = currentFileAudio;
                    var track     = CurrentDownloadTrack;


                    var mp3FileAbs = new FileMp3Abstraction()
                    {
                        Name        = trackFile.Name,
                        ReadStream  = await trackFile.OpenStreamForReadAsync(),
                        WriteStream = await trackFile.OpenStreamForWriteAsync(),
                    };

                    var task = Task.Run(() =>
                    {
                        using (var mp3File = TagLib.File.Create(mp3FileAbs))
                        {
                            mp3File.Tag.AlbumArtists = new string[] { track.Artist };
                            mp3File.Tag.Title        = track.Title;
                            mp3File.Tag.Album        = track.AlbumName;
                            mp3File.Tag.Year         = uint.Parse(track.AlbumYear);
                            mp3File.Tag.Lyrics       = "Загружено с ВКонтакте с помощью Music X Player (UWP)";
                            mp3File.Tag.Copyright    = "Music X Player (UWP)";
                            mp3File.Tag.Conductor    = "Music X Player";
                            mp3File.Tag.Comment      = "Загружено с ВКонтакте с помощью Music X Player (UWP)";
                            mp3File.Save();
                        }
                    });

                    var task2 = task.ContinueWith((b) =>
                    {
                        var currentDownloadedTrack = new DownloadAudioFile()
                        {
                            AlbumName = CurrentDownloadTrack.AlbumName,
                            FromAlbum = CurrentDownloadTrack.FromAlbum,
                            AudioFile = CurrentDownloadTrack.AudioFile,
                            AlbumYear = CurrentDownloadTrack.AlbumYear,
                            Artist    = CurrentDownloadTrack.Artist,
                            Cover     = CurrentDownloadTrack.Cover,
                            Title     = CurrentDownloadTrack.Title,
                            Url       = CurrentDownloadTrack.Url
                        };

                        currentDownloadedTrack.AudioFile.SourceString = currentFileAudio.Path;
                        currentDownloadedTrack.AudioFile.Source       = currentFileAudio;
                        currentDownloadedTrack.AudioFile.IsLocal      = true;

                        DispatcherHelper.CheckBeginInvokeOnUI(() =>
                        {
                            DownloadComplete?.Invoke(this, currentDownloadedTrack);
                        });
                    });
                }
                else if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Idle && DownloadAccess)
                {
                    try
                    {
                        await CurrentDownloadOperation.StartAsync();
                    }
                    catch
                    {
                        //ниче не делаем, операция уже запущена
                    }
                }
                else if (CurrentDownloadOperation.Progress.Status == BackgroundTransferStatus.Error && DownloadAccess)
                {
                    DownloadAccess = false;
                    await ContentDialogService.Show(new ExceptionDialog("Возникла ошибка при загрузке трека", "Возможно, ссылка недоступна", new Exception("BackgroundTransferStatus.Error")));

                    DownloadComplete?.Invoke(this, CurrentDownloadTrack);
                }
            }
        }
예제 #22
0
 private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
 {
     DownloadComplete?.Invoke(this, e);
 }
예제 #23
0
 protected virtual void RaiseDownloadComplete(OpenReadCompletedEventArgs e) => DownloadComplete?.Invoke(this, e);
 public void Fire_DownloadComplete(AsyncCompletedEventArgs asyncCompletedEventArgs)
 {
     DownloadComplete?.Invoke(this, asyncCompletedEventArgs);
 }
예제 #25
0
 private void VideoDownloader_DownloadFinished(object sender, EventArgs e)
 {
     DownloadComplete?.Invoke(this, e);
 }
예제 #26
0
 protected void OnDownloadComplete()
 {
     DownloadComplete?.Invoke(this, EventArgs.Empty);
 }
예제 #27
0
 protected void OnDownloadComplete(string path)
 {
     DownloadComplete?.Invoke(this, path);
 }
예제 #28
0
 public void CancelDownloading()
 {
     webClient.CancelAsync();
     webClient.Dispose();
     DownloadComplete?.Invoke();
 }
예제 #29
0
 private void OnDownloadComplete()
 {
     DownloadComplete?.Invoke(this, new EventArgs());
 }
예제 #30
0
        private async Task CheckIsDownloadDoneAsync(int operationCode)
        {
            if (operationCode != CurrentOperationCode || State != DownloadState.Downloading)
            {
                return;
            }

            lock (threadLock)
            {
                if (operationCode != CurrentOperationCode || State != DownloadState.Downloading)
                {
                    return;
                }
                if (Message.DownloadSize >= Message.FileSize)
                {
                    DisposeThreads();
                }
                else
                {
                    return;
                }
            }
            //进入这里没有return表示已经完成

            GC.Collect();

            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"));
            }

            try
            {
                await file.MoveAsync(folder, Message.FileName + Message.Extention, NameCollisionOption.GenerateUniqueName);
            }
            catch (Exception e)
            {
                HandleError(e, operationCode);
                return;
            }

            Message.IsDone = true;

            DisposeSpeedHelper();

            //触发事件
            State = DownloadState.Done;
            DownloadComplete?.Invoke(Message);
        }