private async Task DiscoverActiveDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();

            downloads = null;
            downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            //downloads = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(music.musicGroup);

            //Log("Loading background downloads: " + downloads.Count);
            DataContext = downloads;


            //DataContext = ActiveDownloadInitialiser.dl;
            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (DownloadOperation download in downloads)
                {
                    // Attach progress and completion handlers.
                    tasks.Add(HandleDownloadAsync(download, false));
                }


                // Don't await HandleDownloadAsync() in the foreach loop since we would attach to the second
                // download only when the first one completed; attach to the third download when the second one
                // completes etc. We want to attach to all downloads immediately.
                // If there are actions that need to be taken once downloads complete, await tasks here, outside
                // the loop.

                await Task.WhenAll(tasks);
            }
        }
Esempio n. 2
0
        // Enumerate the downloads that were going on in the background while the app was closed.
        private async Task DiscoverActiveDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();

            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                return;
            }

            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (DownloadOperation download in downloads)
                {
                    // Attach progress and completion handlers.
                    tasks.Add(HandleDownloadAsync(download, false));
                }

                // Don't await HandleDownloadAsync() in the foreach loop since we would attach to the second
                // download only when the first one completed; attach to the third download when the second one
                // completes etc. We want to attach to all downloads immediately.
                // If there are actions that need to be taken once downloads complete, await tasks here, outside
                // the loop.
                await Task.WhenAll(tasks);
            }
        }
#pragma warning restore

        public async Task <DownloadItem> AddDownloadingImageAsync(DownloadItem item)
        {
            if (DownloadingImages == null)
            {
                DownloadingImages = new ObservableCollection <DownloadItem>();
            }

            var existItem = DownloadingImages.Where(s =>
            {
                return(s.ImageItem.Image.ID == item.ImageItem.Image.ID);
            }).FirstOrDefault();

            if (existItem != null)
            {
                if (existItem.DisplayIndex == (int)DisplayMenu.Retry)
                {
                    return(existItem);
                }
            }

            DownloadingImages.Insert(0, item);
            item.OnMenuStatusChanged += Item_OnMenuStatusChanged;
            var list = await BackgroundDownloader.GetCurrentDownloadsAsync();

            return(item);
        }
Esempio n. 4
0
        /// <summary>
        /// 加载下载任务
        /// </summary>
        private async Task DiscoverDownloadsAsync()
        {
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                if (downloads.Count > 0)
                {
                    List <Task> tasks = new List <Task>();
                    foreach (DownloadOperation download in downloads)
                    {
                        tasks.Add(HandleDownloadAsync(download));
                    }
                }
                //什么也不做
                else
                {
                }
            }
            catch (Exception ex)
            {
                Link.ShowToast(ex.Message);
            }
        }
Esempio n. 5
0
        public static async Task ReconnectBackgroundDownloadsAsync()
        {
            try
            {
                var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                foreach (DownloadOperation download in downloads)
                {
                    var requestUri = download.RequestedUri.ToString();

                    var episode = GetEpisodeByUri(requestUri);

                    if (episode == null || Path.GetFileName(episode.LocalFilename) + ".tmp" != download.ResultFile.Name)
                    {
                        await CancelDownload(download);

                        continue;
                    }

                    if (episode.DownloadAttached)
                    {
                        continue;
                    }

                    episode.AttachAsync(download);
                }
            }
            catch
            {
                // Ignore
            }
        }
Esempio n. 6
0
        // 加载存在的下载任务
        private async Task LoadDownloadAsync()
        {
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                // 获取存在的下载任务
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                WriteLine(ex.ToString());
                return;
            }

            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (DownloadOperation download in downloads)
                {
                    // 监视指定的后台下载任务
                    tasks.Add(HandleDownloadAsync(download, false));
                }

                await Task.WhenAll(tasks);
            }
        }
        private async Task DiscoverActiveDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                status.Log(ex.Message);
                return;
            }

            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (DownloadOperation download in downloads)
                {
                    status.Log(string.Format(CultureInfo.CurrentCulture,
                                             LocalizableStrings.BACKGROUND_TRANSFER_FOUND, download.Guid, download.Progress.Status));
                    tasks.Add(HandleDownloadAsync(download, false));
                }

                await Task.WhenAll(tasks);
            }
        }
        private async Task DiscoverActiveDownloadsAsync()
        {
            // list containing all the operations (except grouped ones)
            IReadOnlyList <DownloadOperation> downloads;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch
            {
                // failed silently
                return;
            }

            // no downloads? exit!
            if (downloads.Count == 0)
            {
                return;
            }

            foreach (var download in downloads)
            {
                // With the uri get the song
                var songEntry = service.Songs.FirstOrDefault(p => p.DownloadId == download.Guid.ToString());

                if (songEntry != null)
                {
                    HandleDownload(songEntry, download, false);
                }
            }
        }
Esempio n. 9
0
        private async Task DiscoverDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();
            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                if (downloads.Count > 0)
                {
                    List <Task> tasks = new List <Task>();
                    foreach (DownloadOperation download in downloads)
                    {
                        HandleModel handModel = new HandleModel
                        {
                            Name         = download.ResultFile.Name,
                            DownOpration = download,
                            Size         = download.Progress.BytesReceived.ToString(),
                        };
                        if (download.Progress.TotalBytesToReceive > 0)
                        {
                            handModel.Progress = (download.Progress.BytesReceived / download.Progress.TotalBytesToReceive) * 100;
                        }
                        list_now.Items.Add(handModel);
                        tasks.Add(HandleDownloadAsync(handModel));
                    }
                    await Task.WhenAll(tasks);
                }
            }
            catch (Exception e)
            {
                await new ContentDialog {
                    Content = "错误:" + e.ToString(), IsSecondaryButtonEnabled = false, PrimaryButtonText = "确定"
                }.ShowAsync();
            }
        }
Esempio n. 10
0
        /// <summary>
        /// 加载下载任务
        /// </summary>
        private async Task DiscoverDownloadsAsync()
        {
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                // 不建议在下载中关闭应用.该操作
                // 可能导致下面的语句删除之前已
                // 部分下载的文件.
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                if (downloads.Count > 0)
                {
                    List <Task> tasks = new List <Task>();
                    foreach (DownloadOperation download in downloads)
                    {
                        tasks.Add(HandleDownloadAsync(download, false));
                    }
                    await Task.WhenAll(tasks);
                }
                else
                {
                    txt.Visibility = Visibility.Visible;
                }
            }
            catch { }
        }
        private async Task DiscoverActiveDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();

            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return;
            }


            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (DownloadOperation download in downloads)
                {
                    Debug.WriteLine(String.Format(CultureInfo.CurrentCulture,
                                                  "Discovered background download: {0}, Status: {1}", download.Guid,
                                                  download.Progress.Status));

                    tasks.Add(HandleDownloadAsync(download, false));
                }

                await Task.WhenAll(tasks);
            }
        }
        public HttpTransferTasks()
        {
            BackgroundUploader
            .GetCurrentUploadsAsync()
            .AsTask()
            .ContinueWith(result =>
            {
                foreach (var task in result.Result)
                {
                    var config = new TaskConfiguration(task.RequestedUri.ToString(), task.SourceFile.Path)
                    {
                        HttpMethod           = task.Method,
                        UseMeteredConnection = task.CostPolicy != BackgroundTransferCostPolicy.UnrestrictedOnly
                    };
                    this.Add(new UploadHttpTask(config, task, true));
                }
            });

            BackgroundDownloader
            .GetCurrentDownloadsAsync()
            .AsTask()
            .ContinueWith(result =>
            {
                foreach (var task in result.Result)
                {
                    var config = new TaskConfiguration(task.RequestedUri.ToString())
                    {
                        HttpMethod           = task.Method,
                        UseMeteredConnection = task.CostPolicy != BackgroundTransferCostPolicy.UnrestrictedOnly
                    };
                    this.Add(new DownloadHttpTask(config, task, true));
                }
            });
        }
Esempio n. 13
0
        private async Task FindAllDownloadsAsync()
        {
            activeDownloads = new List <DownloadOperation>();
            IReadOnlyList <DownloadOperation> downloads = null;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Discovery error", ex))
                {
                    ACDEBUG.Print(ex.Message);
                }
                return;
            }

            if (downloads.Count > 0)
            {
                List <Task> tasks = new List <Task>();
                foreach (var download in downloads)
                {
                    this.activeDownloads.Add(download);
                    tasks.Add(HandleDownload(download, false));
                }
                UpdateDownloadData();

                await Task.WhenAll(tasks);
            }
        }
Esempio n. 14
0
        public override IObservable <HttpTransfer> WhenUpdated() => Observable.Create <HttpTransfer>(async(ob, ct) =>
        {
            var downloads = await BackgroundDownloader
                            .GetCurrentDownloadsAsync()
                            .AsTask();

            foreach (var download in downloads)
            {
                download
                .AttachAsync()
                .AsTask(
                    ct,
                    new Progress <DownloadOperation>(_ =>
                                                     ob.OnNext(download.FromNative())
                                                     )
                    );
            }

            var uploads = await BackgroundUploader
                          .GetCurrentUploadsAsync()
                          .AsTask();

            foreach (var upload in uploads)
            {
                upload
                .AttachAsync()
                .AsTask(
                    ct,
                    new Progress <UploadOperation>(_ =>
                                                   ob.OnNext(upload.FromNative())
                                                   )
                    );
            }
        });
Esempio n. 15
0
        private async void DownLoadControl()
        {
            IReadOnlyList <DownloadOperation> currentDownloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            if (currentDownloads.Count > 0)
            {
                List <Task <DownloadOperation> > tasks = new List <Task <DownloadOperation> >();
                foreach (DownloadOperation downloadOperation in currentDownloads)
                {
                    // 每次进入时恢复所有下载
                    //if (downloadOperation.Progress.Status == BackgroundTransferStatus.PausedByApplication)
                    //{
                    //    downloadOperation.Resume();
                    //}
                    //else if (downloadOperation.Progress.Status == BackgroundTransferStatus.PausedNoNetwork)
                    //{
                    //    await Task.Factory.StartNew(() =>
                    //        {
                    //            downloadOperation.Pause();
                    //            downloadOperation.Resume();
                    //        });

                    //}
                    await downloadOperation.AttachAsync().AsTask(progressCallback);

                    tasks.Add(downloadOperation.AttachAsync().AsTask());
                }
            }
        }
Esempio n. 16
0
        public async void Start()
        {
            try
            {
                var downloads = await BackgroundDownloader
                                .GetCurrentDownloadsAsync()
                                .AsTask();

                foreach (var dl in downloads)
                {
                    dl.Resume();
                }

                var uploads = await BackgroundUploader
                              .GetCurrentUploadsAsync()
                              .AsTask();

                foreach (var ul in uploads)
                {
                    ul.StartAsync();
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex);
            }
        }
Esempio n. 17
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;
                }
            }
        }
Esempio n. 18
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);
            }
        }
Esempio n. 19
0
        protected override async Task LoadExistingDownloads()
        {
            IReadOnlyList <DownloadOperation> oldDownloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            foreach (var d in oldDownloads)
            {
                Downloads.Add(await Models.DownloadItem.Create(d));
            }
        }
Esempio n. 20
0
        public async Task CancelAll()
        {
            var tasks = await BackgroundDownloader.GetCurrentDownloadsAsync().AsTask();

            foreach (var task in tasks)
            {
                task.AttachAsync().Cancel();
            }
        }
Esempio n. 21
0
        public static async Task AttachToDownloads()
        {
            var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            foreach (var download in downloads)
            {
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                await download.AttachAsync().AsTask(progressCallback);
            }
        }
Esempio n. 22
0
        public async Task <IReadOnlyList <DownloadOperation> > GetCurrentDownLoader()
        {
            var result = await BackgroundDownloader.GetCurrentDownloadsAsync();

            if (result != null)
            {
                Count = result.Count;
            }
            return(result);
        }
Esempio n. 23
0
        public static async Task <bool> IsDownloading(Uri sourceUri)
        {
            var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            if (downloads.Where(dl => dl.RequestedUri == sourceUri).FirstOrDefault() != null)
            {
                return(true);
            }

            return(false);
        }
Esempio n. 24
0
        protected override async Task <IEnumerable <HttpTransfer> > GetDownloads(QueryFilter filter)
        {
            var items = await BackgroundDownloader
                        .GetCurrentDownloadsAsync()
                        .AsTask();

            //x.GetResponseInformation().IsResumable
            return(items
                   .Select(x => x.FromNative())
                   .ToList());
        }
Esempio n. 25
0
        public async Task <Uri[]> FollowActiveDownloadsAsync()
        {
            IReadOnlyList <DownloadOperation> downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

            List <Task <Uri> > tasks = new List <Task <Uri> >();

            foreach (var download in downloads)
            {
                tasks.Add(AttachProgressFollower(download));
            }
            return(await Task.WhenAll(tasks));
        }
Esempio n. 26
0
        public DownloadManagerImplementation()
        {
            _queue = new List <IDownloadFile>();

            // Enumerate outstanding downloads.
            BackgroundDownloader.GetCurrentDownloadsAsync().AsTask().ContinueWith((downloadOperationsTask) => {
                foreach (var downloadOperation in downloadOperationsTask.Result)
                {
                    var downloadFile = new DownloadFileImplementation(downloadOperation);
                    _queue.Add(downloadFile);
                }
            });
        }
Esempio n. 27
0
        private async void GetCurrentDownloads_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                CurrentBlock.Text = String.Format("Count: {0}", downloads.Count);
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }
        }
Esempio n. 28
0
        private async Task DiscoverActiveDownloadsAsync()
        {
            //list containing all the operations (except grouped ones)
            IReadOnlyList <DownloadOperation> downloads;

            try
            {
                downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                Debug.WriteLine("Found " + downloads.Count + " BackgroundDownload(s).");
            }
            catch
            {
                //failed silently
                return;
            }

            //no downloads? exit!
            if (downloads.Count == 0)
            {
                foreach (var track in _libraryService.Tracks.Where(p => p.Status == TrackStatus.Downloading).ToList())
                {
                    track.Status = TrackStatus.None;
                    await _libraryService.UpdateTrackAsync(track);
                }
                return;
            }

            foreach (var download in downloads)
            {
                //With the file name get the song
                var id        = long.Parse(download.ResultFile.Name.Replace(download.ResultFile.FileType, ""));
                var songEntry = _libraryService.Tracks.FirstOrDefault(p => p.Id == id);

                if (songEntry != null)
                {
                    Debug.WriteLine("Handling downoad for {0}", songEntry);
                    HandleDownload(songEntry, download, false);
                }
            }

            // reset those without a bg download
            foreach (
                var track in
                _libraryService.Tracks.Where(
                    p => p.Status == TrackStatus.Downloading && p.BackgroundDownload == null).ToList())
            {
                track.Status = TrackStatus.None;
                await _libraryService.UpdateTrackAsync(track);
            }
        }
Esempio n. 29
0
        public override async Task Cancel(string id)
        {
            var guid  = Guid.Parse(id);
            var tasks = await BackgroundDownloader
                        .GetCurrentDownloadsAsync()
                        .AsTask();

            var task = tasks.FirstOrDefault(x => x.Guid == guid);

            if (task != null)
            {
                task.AttachAsync().Cancel();
            }
        }
        //first method to be called upon starting the app
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
            SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;

            //check to see if app is loaded just now
            if (App.started == true)
            {
                try
                {  //if app is loaded just now then try to navigate to homepage
                    MainWeb.Navigate(new Uri((string)AllSettings.Values["HomePage"]));
                    AllSettings.Values["Incognito"] = "Off";
                }
                catch (Exception)
                {
                    //if try fails, probably this is the first time app is launched and hence we need to set up envionment
                    AllSettings.Values["HomePage"]  = " ";
                    AllSettings.Values["Incognito"] = "Off";
                }

                try
                {
                    var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

                    foreach (var download in downloads)
                    {
                        CancellationTokenSource cts = new CancellationTokenSource();
                        await download.AttachAsync().AsTask(cts.Token);

                        cts.Cancel();
                    }
                }
                catch (Exception)
                {
                }


                //app is launched just now hence no history or future or present, so disable all buttons
                Backbtn.IsEnabled         = false;
                Forwardbtn.IsEnabled      = false;
                Stop_Refreshbtn.IsEnabled = false;
                App.started = false;//give sign that app is now running so that next time, we won't fall here
            }
            //if we've got a url from history that needs to launched then check its existence
            else if (!string.IsNullOrEmpty(App.urlFromOtherWindows))
            {
                MainWeb.Navigate(new Uri(App.urlFromOtherWindows));//and navigate to it
                App.urlFromOtherWindows = null;
            }
        }