private async Task <Uri> HandleDownload(DownloadOperation download, bool alreadyStarted)
        {
            var bindableDownload = new BindableDownloadOperation(download);

            try {
                ActiveDownloads.Add(bindableDownload);
                var callback = new Progress <DownloadOperation>(OnDownloadStatusUpdate);
                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> op = null;
                if (alreadyStarted)
                {
                    var d = download.AttachAsync();
                    op = download.AttachAsync();
                }
                else
                {
                    op = download.StartAsync();
                }
                op.Progress = (a, p) => {
                    OnBindableStatusUpdate(bindableDownload);
                };
                // awaits completion of download
                DownloadOperation completedDownload = await op.AsTask(Cts.Token, callback);

                return(FileUtils.UriFor(completedDownload.ResultFile));
            } finally {
                // download complete
                ActiveDownloads.Remove(bindableDownload);
            }
        }
Exemple #2
0
        private async Task Handel(DownloadOperation downloadOperation, CancellationTokenSource cancellationTokenSource)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (cancellationTokenSource != null)
                {
                    await downloadOperation.AttachAsync().AsTask(cancellationTokenSource.Token, progressCallback);
                }
                else
                {
                    await downloadOperation.AttachAsync().AsTask(progressCallback);
                }

                //var ls = list_Downing.ItemsSource as ObservableCollection<DisplayModel>;
                GetDowned();
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("0x80072EF1") || ex.Message.Contains("0x80070002") || ex.Message.Contains("0x80004004"))
                {
                    return;
                }
                await new MessageDialog(ex.Message).ShowAsync();
            }
            finally
            {
                RemoveItem(downloadOperation.Guid.ToString());
            }
        }
Exemple #3
0
        private async Task HandleDownloadAsync(DownloadOperation download, DownloadInfo info, bool start)
        {
            try
            {
                _activeDownloads[info.ChannelId] = download;
                _cts[info.ChannelId]             = new CancellationTokenSource();

                var progressCallback = new Progress <DownloadOperation>(downOperation =>
                {
                    DownloadProgress(downOperation, info);
                });
                if (start)
                {
                    await download.StartAsync().AsTask(_cts[info.ChannelId].Token, progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(_cts[info.ChannelId].Token, progressCallback);
                }

                _activeDownloads.Remove(info.ChannelId);
                _cts.Remove(info.ChannelId);
                var response = download.GetResponseInformation();
                _isDownloading = false;
                DownloadCompleted(info);
            }
            catch (System.Threading.Tasks.TaskCanceledException) { }
            catch (Exception ex)
            {
                _isDownloading = false;
                DownloadFailture(info, ex.Message);
            }
        }
        private async Task HandleDownload(DownloadOperation download, bool start)
        {
            try
            {
                activeDownloads.Add(download);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                string statusCode = response != null?response.StatusCode.ToString() : string.Empty;
            }
            catch (Exception ex)
            {
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
        public async void AttachDownloadOperation(DownloadOperation download, bool IsForResuming = false)
        {
            cts = new CancellationTokenSource();
            Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged);

            if (IsForResuming)
            {
                try
                {
                    await download.AttachAsync().AsTask(cts.Token, progress);
                }
                catch (Exception ex)
                {
                    this.SetStatusText = ex.Message;
                }
            }
            else
            {
                try
                {
                    await download.StartAsync().AsTask(cts.Token, progress);
                }
                catch (Exception ex)
                {
                    this.SetStatusText = ex.Message;
                }
            }
        }
Exemple #6
0
        private async Task Run()
        {
            if (_downloadOperation != null)
            {
                _cancellationToken = new CancellationTokenSource();
                await _downloadOperation.AttachAsync().AsTask(_cancellationToken.Token);
            }
            else
            {
                string fullPath = AddBackslash(RemoteFile.Path);
                fullPath += RemoteFile.Name;

                BackgroundDownloader downloader = new BackgroundDownloader();
                downloader.SetRequestHeader("Authorization", "Bearer " + RemoteFile.Account.Token);
                _downloadOperation =
                    downloader.CreateDownload(new Uri("https://graph.microsoft.com/v1.0/me" + fullPath + ":/content"),
                                              _loсalFile);
                _cancellationToken = new CancellationTokenSource();
                _proccessId        = _downloadOperation.Guid.GetHashCode();
                await _downloadOperation.StartAsync().AsTask(_cancellationToken.Token);
            }

            try
            {
                StorageApplicationPermissions.FutureAccessList.Remove(_localFileToken);
            }
            catch (Exception e)
            {
            }
        }
Exemple #7
0
        //处理正在下载的任务
        private async Task HandleDownloadAsync(DownloadOperation download, bool v)
        {
            try
            {
                TransferModel transfer = new TransferModel();
                transfer.DownloadOperation   = download;
                transfer.Source              = download.RequestedUri.ToString();
                transfer.Destination         = download.ResultFile.Path;
                transfer.BytesReceived       = download.Progress.BytesReceived;
                transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
                transfer.Progress            = 0;
                transfers.Add(transfer);
                //当下载进度发生变化时的回调函数

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(downloadprogressAsync);
                //监听已存在的后台下载任务
                await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
                await new MessageDialog("任务取消:").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog("处理下载任务失败:" + ex).ShowAsync();
            }
            finally
            {
                transfers.Remove(transfers.First(p => p.DownloadOperation == download));
                DownloadList.Remove(download);
                NoTask.Visibility = Visibility.Visible;
            }
        }
Exemple #8
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            IReadOnlyList <DownloadOperation> downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            if (downloads.Count > 0)
            {
                downloadOperation = downloads.First();
                cancellationToken = new CancellationTokenSource();
                Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged);
                btnDownload.IsEnabled    = false;
                btnCancel.IsEnabled      = true;
                btnPauseResume.IsEnabled = true;
                try
                {
                    txtStatus.Text = "Initializing...";
                    await downloadOperation.AttachAsync().AsTask(cancellationToken.Token, progress);
                }
                catch (TaskCanceledException)
                {
                    txtStatus.Text = "Download cancelled";
                    downloadOperation.ResultFile.DeleteAsync();
                    btnPauseResume.Content   = "Resume";
                    btnCancel.IsEnabled      = false;
                    btnPauseResume.IsEnabled = false;
                    btnDownload.IsEnabled    = true;
                    downloadOperation        = null;
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Handle the Background download operation
        /// </summary>
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    ModelDownloadStarted?.Invoke(this, null);
                    await download.StartAsync().AsTask(_cts.Token, progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(_cts.Token, progressCallback);
                }

                var response = download.GetResponseInformation();
            }
            catch (TaskCanceledException ex)
            {
            }
            catch (Exception ex)
            {
                ModelDownloadError?.Invoke(this, null);
            }
        }
Exemple #10
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync();
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync();
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);

                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                TransferModel transfer = new TransferModel();
                transfer.DownloadOperation   = download;
                transfer.Source              = download.RequestedUri.ToString();
                transfer.Destination         = download.ResultFile.Path;
                transfer.BytesReceived       = download.Progress.BytesReceived;
                transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
                transfer.Progress            = 0;
                transfer.Title    = download.ResultFile.Name.Replace(".mp4", "");
                transfer.PhanTram = "0 %";
                App.ViewModel.transfers.Add(transfer);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);

                ResponseInformation response = download.GetResponseInformation();
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                                              download.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                Debug.WriteLine("Canceled: " + download.Guid);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                App.ViewModel.transfers.Remove(App.ViewModel.transfers.First(p => p.DownloadOperation == download));
                activeDownloads.Remove(download);
            }
        }
Exemple #13
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try {
                //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                //LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                //    download.Guid, response.StatusCode), NotifyType.StatusMessage);
            } catch (TaskCanceledException) {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            } catch (Exception ex) {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            } finally {
                activeDownloads.Remove(download);
            }
        }
 /// <summary>
 /// Download Handle
 /// </summary>
 /// <param name="download"></param>
 /// <param name="start">ture or false; ture:start,false:attach</param>
 /// <returns></returns>
 private async Task HandleDownloadAsync(DownloadOperation download, bool start)
 {
     try
     {
         this._listDownloads.Add(download);
         Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
         if (start)
         {
             await download.StartAsync().AsTask(this._cts.Token, progressCallback);
         }
         else
         {
             await download.AttachAsync().AsTask(this._cts.Token, progressCallback);
         }
     }
     catch (TaskCanceledException)
     {
         Debug.WriteLine("task canceled");
     }
     catch (Exception ex)
     {
         if (!IsExceptionHandled("Execution error", ex))
         {
             if (this.ErrorException != null)
             {
                 this.ErrorException(this, ex.Message);
             }
         }
     }
     finally
     {
         this._listDownloads.Remove(download);
     }
 }
Exemple #15
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the upload and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The upload was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
            }
            catch (TaskCanceledException)
            {
                XmlDocument toastXML = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                XmlNodeList texts    = toastXML.GetElementsByTagName("text");
                texts[0].AppendChild(toastXML.CreateTextNode("HAP+ - Download Canceled"));
                texts[1].AppendChild(toastXML.CreateTextNode("The download of " + download.ResultFile.Name + " has been Canceled."));
                ((XmlElement)toastXML.SelectSingleNode("/toast")).SetAttribute("launch", "{\"type\":\"toast\"}");
                ToastNotification toast = new ToastNotification(toastXML);
                ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
        }
Exemple #16
0
        public async Task <StorageFile> Download(string uri)
        {
            Uri        source = new Uri(uri + @"/download");
            HttpClient client = new HttpClient();
            var        result = await client.GetAsync(source, HttpCompletionOption.ResponseHeadersRead);

            var content = result.Content;
            var header  = content.Headers;
            //Clean invalid chars in filename
            string        fileName = CleanFileName(header.ContentDisposition.FileName);
            StorageFolder d        = await StorageFolder.GetFolderFromPathAsync(ApplicationData.Current.LocalCacheFolder.Path);

            StorageFile file = await d.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            var size = await file.GetBasicPropertiesAsync();

            if (size.Size == 0)
            {
                _progress = new DownloadProgress();
                _progress.ShowAsync();
                _backgroundDownloader = new BackgroundDownloader();
                Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged);
                _downloadOperation = _backgroundDownloader.CreateDownload(source, file);
                _downloadOperation.StartAsync();
                await _downloadOperation.AttachAsync().AsTask(_cancellationTokenSourceken.Token, progress);
            }
            return(file);
        }
Exemple #17
0
        private async Task Handel(DownloadOperation downloadOperation)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await downloadOperation.AttachAsync().AsTask(progressCallback);

                var ls   = list_Downing.ItemsSource as ObservableCollection <DisplayModel>;
                var item = ls.First(x => x.guid == downloadOperation.Guid.ToString());
                ls.Remove(item);
                //LoadDowning();
                GetDowned();
            }
            catch (TaskCanceledException)
            {
                //SqlHelper.GetDownload(downloadOperation.Guid.ToString());
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("0x80072EF1") || ex.Message.Contains("0x80070002"))
                {
                    return;
                }
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download)
        {
            try
            {
                // For more advanced Background Transfer features, please take a look at the
                // BackgroundTransfer sample.
                if (download.Progress.Status == BackgroundTransferStatus.Idle)
                {
                    await download.StartAsync();
                }
                else
                {
                    await download.AttachAsync();
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                  "Successfully completed background download: {0}, Status Code: {1}",
                                                  download.Guid,
                                                  statusCode),
                                    NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }
Exemple #19
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
                string statusCode            = response != null?response.StatusCode.ToString() : String.Empty;
            }
            catch (TaskCanceledException)
            {
                //LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                /*
                 * if (!IsExceptionHandled("Execution error", ex, download))
                 * {
                 *  throw;
                 * }
                 */
            }
        }
    public bool CancelDownloading(Uri uri)
    {
        bool bRes = false;

#if UNITY_WSA && ENABLE_WINMD_SUPPORT
        if (_operations.ContainsKey(uri))
        {
            bRes = true;

            DownloadOperation oper = _operations[uri].operation;
            IStorageFile      file = oper.ResultFile;

            CancellationTokenSource canceledToken = new CancellationTokenSource();
            canceledToken.Cancel();

            oper.AttachAsync().AsTask(canceledToken.Token).ContinueWith((task) =>
            {
                if (file != null)
                {
                    try
                    {
                        file.DeleteAsync();
                    }
                    catch { }
                }
            });

            _operations.Remove(uri);
        }
#endif
        return(bRes);
    }
        /// <summary>
        /// Handles download operation.
        /// </summary>
        /// <param name="download">The download operation.</param>
        /// <param name="progress">The progress.</param>
        /// <param name="start">if set to <c>true</c> starts a new operation, else attach to exist operation.</param>
        private static async Task HandleDownloadAsync(DownloadOperation download, IProgress progress, bool start)
        {
            try
            {
                var progressCallback = new Progress <DownloadOperation>(
                    operation =>
                {
                    if (operation.Progress.TotalBytesToReceive > 0)
                    {
                        progress.UpdateProgress(operation.Progress.BytesReceived, operation.Progress.TotalBytesToReceive);
                    }
                });

                if (start)
                {
                    await download.StartAsync().AsTask(progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(progressCallback);
                }
            }
            catch (Exception ex)
            {
                throw HttpUtilities.ProcessException(ex);
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                //LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                activeDownloads.Add(download);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                //CancellationTokenSource cts = new CancellationTokenSource();
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.AttachAsync().AsTask(progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    //await download.AttachAsync().AsTask(App.cts.Token, progressCallback);
                    try
                    {
                        await download.AttachAsync().AsTask(progressCallback);
                    }
                    catch (Exception ex)
                    {
                        //Helper.HelperMethods.MessageUser("Something went wrong. Please try again");
                    }
                }


                //ResponseInformation response = download.GetResponseInformation();

                //LogStatus(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
                //    download.Guid, response.StatusCode), NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                Helper.HelperMethods.MessageUser("Something went wrong. Please try again");
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
Exemple #23
0
        /// <summary>
        ///     Hanbdles a single BackgroundDownload for a song.
        /// </summary>
        private async void HandleDownload(Track track, DownloadOperation download, bool start)
        {
            track.BackgroundDownload = new BackgroundDownload(download);
            ActiveDownloads.Add(track);
            Debug.WriteLine("Added {0} to active downloads", track);

            try
            {
                var progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the BackgroundDownload and attach a progress handler.
                    await
                    download.StartAsync()
                    .AsTask(track.BackgroundDownload.CancellationTokenSrc.Token, progressCallback);
                }
                else
                {
                    // The BackgroundDownload was already running when the application started, re-attach the progress handler.
                    await
                    download.AttachAsync()
                    .AsTask(track.BackgroundDownload.CancellationTokenSrc.Token, progressCallback);
                }

                //Download Completed
                var response = download.GetResponseInformation();

                //Make sure it is success
                if (response.StatusCode < 400)
                {
                    await DownloadFinishedForAsync(track);
                }
                else
                {
                    Debug.WriteLine("Download status code for {0} is bad :/", track);
                    track.Status = TrackStatus.None;
                    await _libraryService.UpdateTrackAsync(track);

                    await((DownloadOperation)track.BackgroundDownload.DownloadOperation).ResultFile.DeleteAsync();
                }
            }
            catch
            {
                Debug.WriteLine("Download cancelled {0}", track);

                track.AudioLocalUri = null;
                track.Status        = TrackStatus.None;
                await _libraryService.UpdateTrackAsync(track);

                await((DownloadOperation)track.BackgroundDownload.DownloadOperation).ResultFile.DeleteAsync();
            }
            finally
            {
                ActiveDownloads.Remove(track);
            }
        }
Exemple #24
0
        public DownloadFileImplementation(DownloadOperation downloadOperation)
        {
            DownloadOperation = downloadOperation;

            var progress = new Progress <DownloadOperation>(ProgressChanged);

            _cancellationToken = new CancellationTokenSource();

            DownloadOperation.AttachAsync().AsTask(_cancellationToken.Token, progress);
        }
Exemple #25
0
        private async Task RestoreDonloadOperation(NicoVideoCacheProgress progress, DownloadOperation operation)
        {
            await AddDownloadOperation(progress);

            var action = operation.AttachAsync();

            action.Progress = OnDownloadProgress;
            var task = action.AsTask()
                       .ContinueWith(OnDownloadCompleted)
                       .ConfigureAwait(false);
        }
Exemple #26
0
        private void AttachDownloadOperationHandles(DownloadOperation download)
        {
            CurrentBlock.Text += String.Format(
                "Download {0} has status {1}.\r\n",
                download.Guid,
                download.Progress.Status);

            var asyncInfo = download.AttachAsync();

            asyncInfo.Progress  = new AsyncOperationProgressHandler <DownloadOperation, DownloadOperation>(OnAttachedDownloadProgress);
            asyncInfo.Completed = new AsyncOperationWithProgressCompletedHandler <DownloadOperation, DownloadOperation>(OnAttachedDownloadCompleted);
        }
Exemple #27
0
 static async Task CancelDownload(DownloadOperation download)
 {
     try
     {
         download.AttachAsync().Cancel();
         await download.ResultFile.DeleteAsync();
     }
     catch
     {
         // Ignore error
     }
 }
Exemple #28
0
        private async Task Handel(DownloadOperation downloadOperation, CancellationTokenSource cancellationTokenSource)
        {
            bool success = true;

            try
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (cancellationTokenSource != null)
                {
                    await downloadOperation.AttachAsync().AsTask(cancellationTokenSource.Token, progressCallback);
                }
                else
                {
                    await downloadOperation.AttachAsync().AsTask(progressCallback);
                }

                //var ls = list_Downing.ItemsSource as ObservableCollection<DisplayModel>;
                RefreshDownloaded();
            }
            catch (TaskCanceledException)
            {
                success = false;
            }
            catch (Exception ex)
            {
                success = false;
                if (ex.Message.Contains("0x80072EF1") || ex.Message.Contains("0x80070002") || ex.Message.Contains("0x80004004"))
                {
                    return;
                }
                var guid = downloadOperation.Guid.ToString();
                var item = Downloadings.FirstOrDefault(x => x.Items.FirstOrDefault(y => y.GUID == guid) != null);
                await Utils.ShowDialog("下载出现问题", $"失败视频:{item.Title ?? ""} {item.EpisodeTitle ?? ""}\r\n" + ex.Message);
            }
            finally
            {
                RemoveItem(downloadOperation.Guid.ToString(), success);
            }
        }
Exemple #29
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            DownloadViewModel Selected = Downloads.FirstOrDefault(p => p.Address == download.RequestedUri.ToString());

            try {
                // LogStatus("Running: " + download.Guid, NotifyType.StatusMessage);

                // Store the download so we can pause/resume.
                // activeDownloads.Add(download);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token, progressCallback);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                string statusCode = response != null?response.StatusCode.ToString() : String.Empty;

                // download completed
                Selected.Status            = "decompressing...";
                Selected.IsDownloadVisible = false;

                // Unzip
                var zipFile = await ApplicationData.Current.LocalFolder.GetFileAsync(Selected.FullFileName);

                var unzipFolder = await FileHelper.GetFolderNotNullAsync(
                    ApplicationData.Current.LocalFolder, "cards");

                await ZipHelper.UnZipFileAsync(zipFile, unzipFolder);

                // end
                Selected.Complete();
            } catch (TaskCanceledException) {
                // LogStatus("Canceled: " + download.Guid, NotifyType.StatusMessage);
            } catch (Exception) {
                if (Selected != null)
                {
                    await Selected.Delete();
                }
            } finally {
                // activeDownloads.Remove(download);
            }
        }
Exemple #30
0
        //private void StartDownload_Click(object sender, RoutedEventArgs e)
        //{
        //    StartDownload(BackgroundTransferPriority.Default);
        //}

        //private void PauseAll_Click(object sender, RoutedEventArgs e)
        //{
        //    Log("Downloads: " + activeDownloads.Count);

        //    foreach (DownloadOperation download in activeDownloads)
        //    {
        //        // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
        //        // we must make a local copy so that we can have a consistent view of that ever-changing state
        //        // throughout this method's lifetime.
        //        BackgroundDownloadProgress currentProgress = download.Progress;

        //        if (currentProgress.Status == BackgroundTransferStatus.Running)
        //        {
        //            download.Pause();
        //            Log("Paused: " + download.Guid);
        //        }
        //        else
        //        {
        //            Log(String.Format(CultureInfo.CurrentCulture, "Skipped: {0}, Status: {1}", download.Guid,
        //                currentProgress.Status));
        //        }
        //    }
        //}

        //private void ResumeAll_Click(object sender, RoutedEventArgs e)
        //{
        //    Log("Downloads: " + activeDownloads.Count);

        //    foreach (DownloadOperation download in activeDownloads)
        //    {
        //        // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
        //        // we must make a local copy so that we can have a consistent view of that ever-changing state
        //        // throughout this method's lifetime.
        //        BackgroundDownloadProgress currentProgress = download.Progress;

        //        if (currentProgress.Status == BackgroundTransferStatus.PausedByApplication)
        //        {
        //            download.Resume();
        //            Log("Resumed: " + download.Guid);
        //        }
        //        else
        //        {
        //            Log(String.Format(CultureInfo.CurrentCulture, "Skipped: {0}, Status: {1}", download.Guid,
        //                currentProgress.Status));
        //        }
        //    }
        //}

        //private void CancelAll_Click(object sender, RoutedEventArgs e)
        //{
        //    Log("Canceling Downloads: " + activeDownloads.Count);

        //    cts.Cancel();
        //    cts.Dispose();

        //    // Re-create the CancellationTokenSource and activeDownloads for future downloads.
        //    cts = new CancellationTokenSource();
        //    activeDownloads = new List<DownloadOperation>();
        //}

        // Note that this event is invoked on a background thread, so we cannot access the UI directly.
        //private void DownloadProgress(DownloadOperation download)
        //{
        //    // DownloadOperation.Progress is updated in real-time while the operation is ongoing. Therefore,
        //    // we must make a local copy so that we can have a consistent view of that ever-changing state
        //    // throughout this method's lifetime.
        //    BackgroundDownloadProgress currentProgress = download.Progress;

        //    MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", download.Guid,
        //        currentProgress.Status));

        //    double percent = 100;
        //    if (currentProgress.TotalBytesToReceive > 0)
        //    {
        //        percent = currentProgress.BytesReceived * 100 / currentProgress.TotalBytesToReceive;
        //    }

        //    MarshalLog(String.Format(
        //        CultureInfo.CurrentCulture,
        //        " - Transfered bytes: {0} of {1}, {2}%",
        //        currentProgress.BytesReceived,
        //        currentProgress.TotalBytesToReceive,
        //        percent));

        //    if (currentProgress.HasRestarted)
        //    {
        //        MarshalLog(" - Download restarted");
        //    }

        //    if (currentProgress.HasResponseChanged)
        //    {
        //        // We have received new response headers from the server.
        //        // Be aware that GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
        //        ResponseInformation response = download.GetResponseInformation();
        //        int headersCount = response != null ? response.Headers.Count : 0;

        //        MarshalLog(" - Response updated; Header count: " + headersCount);

        //        // If you want to stream the response data this is a good time to start.
        //        // download.GetResultStreamAt(0);
        //    }
        //}

        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                log.Info("Running: " + download.Guid);

                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                //Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
                if (start)
                {
                    // Start the download and attach a progress handler.
                    await download.StartAsync().AsTask(cts.Token);
                }
                else
                {
                    // The download was already running when the application started, re-attach the progress handler.
                    await download.AttachAsync().AsTask(cts.Token /*, progressCallback*/);
                }

                //ResponseInformation response = download.GetResponseInformation();

                // GetResponseInformation() returns null for non-HTTP transfers (e.g., FTP).
                //string statusCode = response != null ? response.StatusCode.ToString() : String.Empty;

                //LogStatus(
                //    String.Format(
                //        CultureInfo.CurrentCulture,
                //        "Completed: {0}, Status Code: {1}",
                //        download.Guid,
                //        statusCode),
                //    NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
                log.Info("Canceled: " + download.Guid);
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }