Exemple #1
0
        /// <summary>
        /// Найти все фоновые загрузки и обработать их.
        /// </summary>
        public async void DiscoverActiveDownloads()
        {
            lock (_lockObject)
            {
                if (_downloadsAttached)
                {
                    return;
                }
                _downloadsAttached = true;
            }

            IsLoading = true;

            await Task.Run(async() =>
            {
                IReadOnlyList <DownloadOperation> downloads = null;

                try { downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup); }
                catch (Exception ex)
                {
                    WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                    _logService.LogText($"Getting downloads error - {error}\n{ex.ToString()}");
                }

                if (downloads != null && downloads.Count > 0)
                {
                    for (int i = 0; i < downloads.Count; i++)
                    {
                        HandleDownloadAsync(downloads[i], false);
                    }
                }
            });

            IsLoading = false;
        }
Exemple #2
0
        /// <summary>
        /// Initialize the view model by enumerating all existing downloads.
        /// </summary>
        public override async Task Initialize()
        {
            if (_activeDownloads != null)
            {
                return;
            }

            IsDownloading    = false;
            IsIndeterminate  = false;
            Description      = null;
            InstallationStep = null;
            _activeDownloads = new ConcurrentDictionary <string, DownloadOperation>();

            IEnumerable <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                telemetry.TrackException(ex, new Dictionary <string, string> {
                    { "Scenario", "InitializeDownloads" }
                });
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                await QuranApp.NativeProvider.ShowErrorMessageBox("Error getting active downloads: " + error.ToString());

                return;
            }

            if (downloads.Any())
            {
                await HandleDownloadsAsync(downloads.ToList(), false);
            }
        }
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            string errorMsg = null;

            if (download == null)
            {
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error));

                errorMsg = String.Format(CultureInfo.CurrentCulture, "{0}: {1}", title, error);
            }
            else
            {
                Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.Guid, title, error));
                errorMsg = String.Format(CultureInfo.CurrentCulture, "{0} - {1}: {2}", download.Guid, title, error);
            }

            // Event calling for status msg
            DownloadStatusMessageChanged?.Invoke("Error", download.ResultFile.Name);

            return(true);
        }
Exemple #4
0
        /// <summary>
        /// 监视指定的后台下载任务
        /// </summary>
        /// <param name="download">后台下载任务</param>
        private async Task HandleDownloadAsync(DownloadManage.HandleModel model)
        {
            try
            {
                DownloadProgress(model.downOp);
                //进度监控
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await model.downOp.AttachAsync().AsTask(model.cts.Token, progressCallback);

                //保存任务信息
                //  StorageFolder folder = ApplicationData.Current.LocalFolder;
                StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists);

                StorageFile file = await DowFolder.GetFileAsync(model.Guid + ".bili");

                //用Url编码是因为不支持读取中文名
                //含会出现:在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。错误
                string        path   = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);

                StorageFile files = await folder.CreateFileAsync(model.Guid + ".json", CreationCollisionOption.OpenIfExists); //await StorageFile.GetFileFromPathAsync(path+@"\" + model.Guid + ".json");

                string json = await FileIO.ReadTextAsync(files);

                DownloadManage.DownModel info = JsonConvert.DeserializeObject <DownloadManage.DownModel>(json);
                info.downloaded = true;
                string      jsonInfo  = JsonConvert.SerializeObject(info);
                StorageFile fileWrite = await folder.CreateFileAsync(info.Guid + ".json", CreationCollisionOption.ReplaceExisting);

                await FileIO.WriteTextAsync(fileWrite, jsonInfo);

                //移除正在监控
                HandleList.Remove(model.downModel.Guid);
                GetDownOk_New();
            }
            catch (TaskCanceledException)
            {
                //取消通知
                //ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
                //XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
                //XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                //IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                //((XmlElement)toastNode).SetAttribute("duration", "short");
                //toastTextElements[0].AppendChild(toastXml.CreateTextNode(String.Format("取消任务{0}", model.downModel.title)));
                //ToastNotification toast = new ToastNotification(toastXml);
                //ToastNotificationManager.CreateToastNotifier().Show(toast);
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                return;
            }
            finally
            {
                list_Downing.Items.Remove(model);
            }
        }
Exemple #5
0
        public bool IsExceptionHandled(string title, Exception ex)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }
            return(true);
        }
Exemple #6
0
        /// 监视指定的后台下载任务
        /// </summary>
        /// <param name="download">后台下载任务</param>
        private async Task HandleDownloadAsync(DownloadModel model)
        {
            try
            {
                DownloadProgress(model.handel.downOp);
                //进度监控
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await model.handel.downOp.AttachAsync().AsTask(model.handel.cts.Token, progressCallback);

                model.videoinfo.downstatus = true;
                var PartFolder = await StorageFolder.GetFolderFromPathAsync(model.videoinfo.folderPath);

                StorageFile sefile = await PartFolder.CreateFileAsync(model.videoinfo.mid + ".json", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(sefile, JsonConvert.SerializeObject(model.videoinfo));

                ////保存任务信息
                ////  StorageFolder folder = ApplicationData.Current.LocalFolder;
                //StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists);
                //StorageFile file = await DowFolder.GetFileAsync(model.Guid + ".bili");
                ////用Url编码是因为不支持读取中文名
                ////含会出现:在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。错误
                //string path = WebUtility.UrlDecode(await FileIO.ReadTextAsync(file));
                //StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(path);
                //StorageFile files = await folder.CreateFileAsync(model.Guid + ".json", CreationCollisionOption.OpenIfExists); //await StorageFile.GetFileFromPathAsync(path+@"\" + model.Guid + ".json");
                //string json = await FileIO.ReadTextAsync(files);
                //DownloadManage.DownModel info = JsonConvert.DeserializeObject<DownloadManage.DownModel>(json);
                //info.downloaded = true;
                //string jsonInfo = JsonConvert.SerializeObject(info);
                //StorageFile fileWrite = await folder.CreateFileAsync(info.Guid + ".json", CreationCollisionOption.ReplaceExisting);
                //await FileIO.WriteTextAsync(fileWrite, jsonInfo);
                ////移除正在监控
                SendToast("《" + model.videoinfo.title + " " + model.videoinfo.partTitle + "》下载完成");
                HandleList.Remove(model.videoinfo.downGUID);
                list_Downing.Items.Remove(model);
                //GetDownOk_New();
                GetDownOk();
                // list_Downing.Items.Remove(model);
            }
            catch (TaskCanceledException)
            {
                //取消通知
                SendToast("取消任务《" + model.videoinfo.title + " " + model.videoinfo.partTitle + "》");
                list_Downing.Items.Remove(model);
                GetDownOk();
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                return;
            }
        }
        /// <summary>
        /// 处理并监视指定的后台上传任务
        /// </summary>
        /// <param name="upload">后台上传任务</param>
        /// <param name="isNew">是否是新增的任务</param>
        private async Task HandleUploadAsync(UploadOperation upload, bool isNew)
        {
            try
            {
                // 将 UploadOperation 附加到 TransferModel,以便上传进度可通知
                TransferModel transfer = new TransferModel();
                transfer.UploadOperation = upload;
                transfer.Source          = "多个文件";
                transfer.Destination     = upload.RequestedUri.ToString();
                transfer.Progress        = upload.Progress.Status.ToString() + "0 / 0";

                _transfers.Add(transfer);

                WriteLine("Task Count: " + _transfers.Count.ToString());

                // 当上传进度发生变化时的回调函数
                Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);

                if (isNew)
                {
                    await upload.StartAsync().AsTask(_cancelToken.Token, progressCallback); // 启动一个后台上传任务
                }
                else
                {
                    await upload.AttachAsync().AsTask(_cancelToken.Token, progressCallback); // 监视已存在的后台上传任务
                }
                // 上传完成后获取服务端的响应信息
                ResponseInformation response = upload.GetResponseInformation();
                WriteLine("Completed: " + response.ActualUri + ", HttpStatusCode: " + response.StatusCode.ToString());
            }
            catch (TaskCanceledException) // 调用 CancellationTokenSource.Cancel() 后会抛出此异常
            {
                WriteLine("Canceled: " + upload.Guid);
            }
            catch (Exception ex)
            {
                // 将异常转换为 WebErrorStatus 枚举,如果获取到的是 WebErrorStatus.Unknown 则说明此次异常不是涉及 web 的异常
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

                WriteLine(ex.ToString());
            }
            finally
            {
                _transfers.Remove(_transfers.First(p => p.UploadOperation == upload));
            }
        }
Exemple #8
0
        private bool IsWebException(string title, Exception ex)
        {
            WebErrorStatus error   = BackgroundTransferError.GetStatus(ex.HResult);
            bool           result  = (error != WebErrorStatus.Unknown);
            string         message = result ? error.ToString() : ex.Message;

            if (download == null)
            {
                rootPage.NotifyUser($"{title}: {message}", NotifyType.ErrorMessage);
            }
            else
            {
                rootPage.NotifyUser($"{download.Guid} - {title}: {message}", NotifyType.ErrorMessage);
            }

            return(result);
        }
        public async Task InitTasks()
        {
            IReadOnlyList <DownloadOperation> download;

            try {
                download = await BackgroundDownloader.GetCurrentDownloadsAsync();
            } catch (Exception e) {
                if (BackgroundTransferError.GetStatus(e.HResult) == WebErrorStatus.Unknown)
                {
                    throw;
                }
                return;
            }
            if (download.Count > 0)
            {
                await Task.WhenAll(download.Select((item) => HandleDownloadAsync(item, false)));
            }
        }
Exemple #10
0
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (download == null)
            {
                LogHelper.WriteLine(string.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error));
            }
            else
            {
                LogHelper.WriteLine(string.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", download.Guid, title, error));
            }

            return(true);
        }
        private bool IsExceptionHandled(string title, Exception ex, UploadOperation upload = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (upload == null)
            {
                MarshalProgress(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error), 0);
            }
            else
            {
                MarshalProgress(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", upload.Guid, title, error), 0);
            }

            return(true);
        }
Exemple #12
0
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (download is null)
            {
                //rootPage.ShowMessageBox(String.Format($"Error: {title}: {error}"));
            }
            else
            {
                //rootPage.ShowMessageBox(String.Format($"Error: {download.Guid} - {title}: {error}"));
            }

            return(true);
        }
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (download == null)
            {
                LogStatus(String.Format("Error: {0}: {1}", title, error), NotifyType.ErrorMessage);
            }
            else
            {
                LogStatus(String.Format("Error: {0} - {1}: {2}", download.Guid, title, error), NotifyType.ErrorMessage);
            }

            return(true);
        }
        private bool IsExceptionHandled(string title, Exception ex, DownloadOperation download = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (download == null)
            {
                ToastManager.ShowError("Something went wrong.");
            }

            else
            {
                ToastManager.ShowError("Something went wrong.");
            }

            return(true);
        }
Exemple #15
0
        private bool IsExceptionHandled(string title, Exception ex, UploadOperation upload = null)
        {
            var error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (upload == null)
            {
                //LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error),
                //    NotifyType.ErrorMessage);
            }
            else
            {
                //LogStatus(String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", upload.Guid, title,
                //    error), NotifyType.ErrorMessage);
            }

            return(true);
        }
Exemple #16
0
        private bool IsExceptionHandled(string title, Exception ex, IBackgroundTransferOperation operation = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (operation == null)
            {
                Trace.LogStatus(rootPage, String.Format(CultureInfo.CurrentCulture, "Error: {0}: {1}", title, error),
                                NotifyType.ErrorMessage);
            }
            else
            {
                Trace.LogStatus(rootPage, String.Format(CultureInfo.CurrentCulture, "Error: {0} - {1}: {2}", operation.Guid, title,
                                                        error), NotifyType.ErrorMessage);
            }

            return(true);
        }
Exemple #17
0
        public async void DiscoverActiveDownloads()
        {
            IsLoading = true;
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_transferGroup);
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
            }

            if (downloads != null && downloads.Count > 0)
            {
                for (int i = 0; i < downloads.Count; i++)
                {
                    HandleDownloadAsync(downloads[i], false);
                }
            }
            IsLoading = false;
        }
Exemple #18
0
        private bool IsExceptionHandled(string title, Exception ex, UploadOperation upload = null)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            if (error == WebErrorStatus.Unknown)
            {
                return(false);
            }

            if (upload == null)
            {
                var fileUploadResponse = new FileUploadResponse(error.ToString(), -1, string.Empty, null);
                FileUploadError(this, fileUploadResponse);
            }
            else
            {
                string response = string.Empty;
                using (var inputStream = upload.GetResultStreamAt(0))
                {
                    using (StreamReader tr = new StreamReader(inputStream.AsStreamForRead()))
                    {
                        response = tr.ReadToEnd();
                    }
                }
                ResponseInformation responseInfo = upload.GetResponseInformation();

                if (string.IsNullOrEmpty(response))
                {
                    response = error.ToString();
                }

                var fileUploadResponse = new FileUploadResponse(response, (int)responseInfo.StatusCode, upload.TransferGroup.Name, null);
                FileUploadError(this, fileUploadResponse);
            }

            return(true);
        }
Exemple #19
0
        public async void DiscoverActiveUploads()
        {
            lock (_lockObject)
            {
                if (_uploadsAttached)
                {
                    return;
                }
                _uploadsAttached = true;
            }

            IsLoading = true;

            await Task.Run(async() =>
            {
                IReadOnlyList <UploadOperation> uploads = null;

                try { uploads = await BackgroundUploader.GetCurrentUploadsForTransferGroupAsync(_transferGroup); }
                catch (Exception ex)
                {
                    WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                    _logService.LogText($"Getting uploads error - {error}\n{ex.ToString()}");
                }

                if (uploads != null && uploads.Count > 0)
                {
                    foreach (var upload in uploads)
                    {
                        var cachedUpload = await _database.GetAsync(upload.Guid);
                        HandleUploadAsync(upload, cachedUpload, false);
                    }
                }
            });

            IsLoading = false;
        }
Exemple #20
0
        private bool IsExceptionHandled(string title, Exception ex, UploadOperation upload = null)
        {
            var error = BackgroundTransferError.GetStatus(ex.HResult);

            return(error != WebErrorStatus.Unknown);
        }
        private bool IsExceptionHandled(Exception ex)
        {
            WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);

            return(error != WebErrorStatus.Unknown);
        }
Exemple #22
0
        private async Task <bool> HandleDownloadsAsync(List <DownloadOperation> downloads, bool start)
        {
            UnconstrainedTransferRequestResult result;

            try
            {
                result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(downloads);
            }
            catch (NotImplementedException ex)
            {
                telemetry.TrackException(ex);
            }

            try
            {
                List <DownloadOperation> successfullyAddedDownloads = new List <DownloadOperation>();
                foreach (var download in downloads)
                {
                    if (_activeDownloads.TryAdd(download.RequestedUri.ToString(), download))
                    {
                        successfullyAddedDownloads.Add(download);
                        _totalDownloads++;
                    }
                }

                // Store the download so we can pause/resume.
                foreach (var download in successfullyAddedDownloads)
                {
                    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);
                    }
                }

                return(true);
            }
            catch (TaskCanceledException)
            {
                InstallationStep = "Cancelled";
                return(false);
            }
            catch (Exception ex)
            {
                WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                telemetry.TrackException(ex, new Dictionary <string, string> {
                    { "Scenario", "GettingActiveDownloads" }
                });
                await QuranApp.NativeProvider.ShowErrorMessageBox("Error getting active downloads: " + error.ToString());

                return(false);
            }
            finally
            {
                try
                {
                    await FinishActiveDownloads();
                }
                catch (Exception ex)
                {
                    telemetry.TrackException(ex, new Dictionary <string, string> {
                        { "Scenario", "GettingActiveDownloads" }
                    });
                }
            }
        }