Ejemplo n.º 1
0
        private async Task DownloadAsync(DownloadOperation download)
        {
            Log(String.Format(CultureInfo.CurrentCulture, "Downloading {0}", download.ResultFile.Name));

            try
            {
                await download.StartAsync();

                LogStatus(String.Format(CultureInfo.CurrentCulture, "Downloading {0} completed.", download.ResultFile.Name), NotifyType.StatusMessage);
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                if (!IsExceptionHandled("Execution error", ex, download))
                {
                    throw;
                }
            }
        }
        internal void StartDownloadAsync(string destinationPathName, bool mobileNetworkAllowed)
        {
            var downloader = new BackgroundDownloader();

            var downloadUrl = new Uri(Url);

            if (Headers != null)
            {
                foreach (var header in Headers)
                {
                    downloader.SetRequestHeader(header.Key, header.Value);
                }
            }

            if (!mobileNetworkAllowed)
            {
                downloader.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
            }

            StorageFile file;

            if (destinationPathName != null)
            {
                var folder = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(destinationPathName)).AsTask().Result;
                file = folder.CreateFileAsync(Path.GetFileName(destinationPathName), CreationCollisionOption.ReplaceExisting).AsTask().Result;
            }
            else
            {
                var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                file = folder.CreateFileAsync(downloadUrl.Segments.Last(), CreationCollisionOption.GenerateUniqueName).AsTask().Result;
            }

            DownloadOperation = downloader.CreateDownload(downloadUrl, file);

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

            _cancellationToken = new CancellationTokenSource();

            DownloadOperation.StartAsync().AsTask(_cancellationToken.Token, progress);
        }
Ejemplo n.º 3
0
        private async void ladeDaten()
        {
            try
            {
                Uri source = new Uri("https://opendata.arcgis.com/datasets/917fc37a709542548cc3be077a786c17_0.csv", UriKind.Absolute);
                BackgroundDownloader downloader = new BackgroundDownloader();

                Debug.WriteLine(Windows.Storage.ApplicationData.Current.LocalFolder);
                StorageFile testfile = await folder.CreateFileAsync("data.csv", CreationCollisionOption.ReplaceExisting);

                DownloadOperation download = downloader.CreateDownload(source, testfile);
                await download.StartAsync();

                await Task.Delay(TimeSpan.FromSeconds(5));

                if (parser == null)
                {
                    parser = new CSV_Parser();
                }
                parser.getDaten();
                await Task.Delay(TimeSpan.FromSeconds(5));

                int lol = parser.getDatenLange();
                Debug.WriteLine(lol);
                LiveKachelCreator library = new LiveKachelCreator();
                library.sendMessage(OldDataService.getOldLandkreis(), parser.getIndex(OldDataService.getOldLandkreis()));
                try
                {
                    ladeGrid();
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Download Error", e);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Download Error", ex);
            }
        }
Ejemplo n.º 4
0
        public async Task <string> DownloadAndInstall(string versionFromWeb)
        {
            try
            {
                string fileType = obj.isDeviceHandheld ? "_ARM.appx" : "_x64.appxbundle";
                BackgroundDownloader downloader = new BackgroundDownloader();
                Uri           source            = new Uri("http://www.develok.ee/KoneskoWMS/Install/KoneskoWMS_" + versionFromWeb + fileType, UriKind.Absolute);
                StorageFolder fold     = KnownFolders.PicturesLibrary;
                StorageFile   testfile = await fold.CreateFileAsync("KoneskoWMS_" + versionFromWeb + fileType, CreationCollisionOption.ReplaceExisting);

                Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged);

                DownloadOperation       download          = downloader.CreateDownload(source, testfile);
                CancellationTokenSource cancellationToken = new CancellationTokenSource();
                await download.StartAsync().AsTask(cancellationToken.Token, progress);

                IReadOnlyList <StorageFile> filesInFolder = await KnownFolders.PicturesLibrary.GetFilesAsync();

                foreach (StorageFile file in filesInFolder)
                {
                    if (file.Name == "KoneskoWMS_" + versionFromWeb + fileType)
                    {
                        if (await Windows.System.Launcher.LaunchFileAsync(file))
                        {
                            return(null);
                        }
                        else
                        {
                            return("UUENDAMINE EI ÕNNESTUNUD!");
                        }
                    }
                }
                return("UUENDAMINE EI ÕNNESTUNUD!");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return("UUENDAMINE EI ÕNNESTUNUD! " + "\r\n" + ex.Message);
            }
        }
Ejemplo n.º 5
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                // Store the download so we can pause/resume.
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);

                var cts = new CancellationTokenSource();
                cancellationTokens.Add(download.Guid, cts);

                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;
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
        private async void Download(String url, String name)
        {
            Uri         source          = new Uri(url);
            StorageFile destinationFile =
                await MediaManager.Instance.SaveFolder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

            BackgroundDownloader downloader = new BackgroundDownloader();

            _downloadOperation = downloader.CreateDownload(source, destinationFile);
            Timer timer = new System.Timers.Timer(50);
            // Hook up the Elapsed event for the timer.
            //            timer.Elapsed += ShowCacheProgress;
            //            timer.AutoReset = true;
            //            timer.Enabled = false;
            await _downloadOperation.StartAsync();

            //            timer.Stop();
            //            timer.Dispose();
            CacheButton.Content   = "取消缓存";
            CacheButton.IsEnabled = true;
            MediaManager.Instance.LoadCachedItems();
        }
Ejemplo n.º 7
0
        private async Task DownloadCoupon()
        {
            try
            {
                Uri source = new Uri("https://localhost:44315/" + Promotion.Attachments[0].Path);

                StorageFile destinationFile = await DownloadsFolder.CreateFileAsync(
                    $"Stapp_Kortingsbon.pdf",
                    CreationCollisionOption.GenerateUniqueName);

                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(source, destinationFile);

                await download.StartAsync();

                await Launcher.LaunchFileAsync(destinationFile);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Download Error", ex.Message);
            }
        }
Ejemplo n.º 8
0
        private async Task <StorageFile> StartDownloadAsync(DownloadOperation downloadOperation)
        {
            try
            {
                Download = downloadOperation;
                await downloadOperation.StartAsync().AsTask(cts.Token, progressCallback);

                CurrentDownloadedBytes += (long)downloadOperation.Progress.BytesReceived;
                return((StorageFile)downloadOperation.ResultFile);
            }
            catch (Exception e)
            {
                Downloading            = false;
                CurrentDownloadedBytes = 0;
                foreach (Playlist downloadedPlaylist in currentlyDownloadingPlaylists)
                {
                    RemoveDownload(downloadedPlaylist);//may not have even started downloading this playlist when this is called
                }
                currentlyDownloadingPlaylists = new List <Playlist>();
                return(null);
            }
        }
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                status.Log(string.Format(
                               CultureInfo.CurrentCulture, LocalizableStrings.BACKGROUND_TRANSFER_RUNNING, download.Guid));
                activeDownloads.Add(download);

                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                if (start)
                {
                    await download.StartAsync().AsTask(cancelToken.Token, progressCallback);
                }
                else
                {
                    await download.AttachAsync().AsTask(cancelToken.Token, progressCallback);
                }

                ResponseInformation response = download.GetResponseInformation();
                status.Log(string.Format(
                               CultureInfo.CurrentCulture, LocalizableStrings.BACKGROUND_TRANSFER_COMPLETED,
                               download.Guid, response.StatusCode));
            }
            catch (TaskCanceledException)
            {
                status.Log(string.Format(
                               CultureInfo.CurrentCulture, LocalizableStrings.BACKGROUND_TRANSFER_CANCELLED, download.Guid));
            }
            catch (Exception ex)
            {
                status.Log(ex.Message);
                Debug.WriteLine(ex.ToString());
            }
            finally
            {
                activeDownloads.Remove(download);
            }
        }
Ejemplo n.º 10
0
        private static async Task HandleDownloadImageAsync(DownloadOperation download, bool start)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Running image: " + download.Guid);

                // Store the download so we can pause/resume.
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadImageProgress);
                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();

                System.Diagnostics.Debug.WriteLine(String.Format("Completed image: {0}, Status Code: {1}", download.Guid, response.StatusCode));
                // grDownload.Visibility = Visibility.Collapsed;

                if (response.StatusCode == 200)
                {
                    //image loaded
                    System.Diagnostics.Debug.WriteLine("Downloaded file: " + download.ResultFile.Name);
                }
            }
            catch (TaskCanceledException)
            {
                System.Diagnostics.Debug.WriteLine("Canceled: " + download.Guid);
                OnDownloadEvent?.Invoke(null, new DownloadEventArgs(download.ResultFile.Name, DownloadState.Canceled));
                cts = null;
            }
        }
Ejemplo n.º 11
0
        /// Download
        /// PART


        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            FolderPicker folderPicker = new FolderPicker();

            folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            folderPicker.ViewMode = PickerViewMode.Thumbnail;
            folderPicker.FileTypeFilter.Add("*");
            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);

                downloadOperation = backgroundDownloader.CreateDownload(new Uri(urlName), file);
                Progress <DownloadOperation> progress = new Progress <DownloadOperation>(progressChanged);
                cancellationToken        = new CancellationTokenSource();
                btnDownload.IsEnabled    = false;
                btnCancel.IsEnabled      = true;
                btnPauseResume.IsEnabled = true;

                try
                {
                    txtStatus.Text = "Initializing...";
                    await downloadOperation.StartAsync().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;
                }
            }
        }
Ejemplo n.º 12
0
        public async void Savefile()
        {
            FileSavePicker savefile = new FileSavePicker();

            savefile.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            string f = "保存文件类型";

            savefile.FileTypeChoices.Add(f, new List <string>()
            {
                ".jpg", ".png", ".bmp"
            });
            savefile.SuggestedFileName = imgname + "ID" + imgid;
            storagefile = await savefile.PickSaveFileAsync();

            //var a = new ToastDialog();

            if (storagefile != null)
            {
                CachedFileManager.DeferUpdates(storagefile);
                string Filename     = imgname + imgid;
                string _transferUri = imguri;
                Uri    transferUri;
                try
                {
                    transferUri = new Uri(Uri.EscapeUriString(_transferUri), UriKind.RelativeOrAbsolute);
                }
                catch
                {
                    return;
                }

                BackgroundDownloader backgrounddownloader = new BackgroundDownloader();//后台下载
                DownloadOperation    downloader           = backgrounddownloader.CreateDownload(transferUri, storagefile);
                await downloader.StartAsync();
                await showtast();
            }
        }//总是调起资源选择器
Ejemplo n.º 13
0
        private async Task RetryDownloads(IEnumerable <DownloadOperation> downloads, List <DownloadDesc> list)
        {
            BackgroundDownloader downloader = CreateBackgroundDownloader();

            foreach (DownloadOperation download in downloads)
            {
                try
                {
                    DownloadOperation        download1 = downloader.CreateDownload(download.RequestedUri, download.ResultFile);
                    Task <DownloadOperation> startTask = download1.StartAsync().AsTask();
                    var p = list.Find(a => a.Guid == download.Guid);
                    p.Guid = download1.Guid;
                    await SQLOperator.Current().UpdateDownload(p);

                    list.Remove(p);
                }
                catch (Exception)
                {
                    continue;
                }
            }

            downloader.CompletionGroup.Enable();
        }
Ejemplo n.º 14
0
        public async void DownloadVideo()
        {
            var client   = new YoutubeClient();
            var videoUrl = Constants.videoInfo.Muxed[0].Url;

            var savePicker = new Windows.Storage.Pickers.FileSavePicker {
                SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
            };

            savePicker.FileTypeChoices.Add("Video File", new List <string>()
            {
                ".mp4"
            });

            Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent updates to the remote version of the file until
                // we finish making changes and call CompleteUpdatesAsync.
                Windows.Storage.CachedFileManager.DeferUpdates(file);
                // write to file
                BackgroundDownloader downloader = new BackgroundDownloader();
                DownloadOperation    download   = downloader.CreateDownload(new Uri(videoUrl), file);

                DownloadProgress.Visibility = Visibility.Visible;

                Progress <DownloadOperation> progress = new Progress <DownloadOperation>();
                progress.ProgressChanged += Progress_ProgressChanged;
                await download.StartAsync().AsTask(CancellationToken.None, progress);
            }
            else
            {
                Log.Info("Download operation was cancelled.");
            }
        }
Ejemplo n.º 15
0
        private async Task StartOneDownload(string fileName, Uri uri, DownloadData dd)
        {
            StorageFile destinationFile = null;

            try
            {
                var acFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("ACFUNVideo", CreationCollisionOption.OpenIfExists);

                destinationFile = await acFolder.CreateFileAsync(fileName,
                                                                 CreationCollisionOption.ReplaceExisting);
            }
            catch (Exception ex)
            {
                return;
            }

            BackgroundDownloader downloader = new BackgroundDownloader();
            DownloadOperation    download   = downloader.CreateDownload(uri, destinationFile);

            dd.DownloadGuid.Add(download.Guid.ToString());
            SaveDB();
            download.Priority = BackgroundTransferPriority.Default;
            await download.StartAsync();
        }
Ejemplo n.º 16
0
        private async Task HandleDownloadAsync(DownloadOperation download, bool start)
        {
            try
            {
                //Log("Running: " + download.Guid);

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

                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);
                }
            }
            catch (TaskCanceledException)
            {
                //HelperMethods.HelperMethods.MessageUser("Downloads Cancelled", topStack);
                //Frame.Navigate(typeof(ActiveDownloads));
            }
            catch (Exception ex)
            {
                // Helper.HelperMethods.MessageUser("Something went wrong. Please try again");
            }

            finally
            {
                activeDownloads.Remove(download);
            }
        }
        private async Task TestBackgroundDownloader(string name, string URL)
        {
            BackgroundDownloader bd = new BackgroundDownloader();

            bd.FailureToastNotification = this.CreateFailureToast();
            bd.SuccessToastNotification = this.CreateSuccessToast();
            FolderPicker folderPicker = new FolderPicker();

            folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            folderPicker.ViewMode = PickerViewMode.Thumbnail;
            folderPicker.FileTypeFilter.Add("*");
            StorageFolder folder = await folderPicker.PickSingleFolderAsync();

            if (folder != null)
            {
                StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);

                Debug.WriteLine(file.Path);
                Uri uri = new Uri(URL);
                DownloadOperation op = bd.CreateDownload(uri, file);
                var progress         = op.StartAsync();
                progress.Completed = this.Completed;
            }
        }
Ejemplo n.º 18
0
        public static async Task SaveImageAsync(string imageName, string imageUri)
        {
            BackgroundDownloader backgroundDownload = new BackgroundDownloader();
            StorageFolder        folder             = null;
            StorageFile          newFile            = null;

            if (Setting.GetSettingValue("DownloadPath").Contains("我的文档\\图片\\Acafe"))
            {
                folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("Acafe", CreationCollisionOption.OpenIfExists);

                newFile = await folder.CreateFileAsync(imageName, CreationCollisionOption.OpenIfExists);
            }
            else
            {
                folder = await StorageFolder.GetFolderFromPathAsync(Setting.GetSettingValue("DownloadPath"));

                newFile = await folder.CreateFileAsync(imageName, CreationCollisionOption.OpenIfExists);
            }

            Uri uri = new Uri(imageUri);
            DownloadOperation download = backgroundDownload.CreateDownload(uri, newFile);

            await download.StartAsync();
        }
Ejemplo n.º 19
0
        private async Task StartDownloadAndReadContentsAsync()
        {
            try
            {
                // Retrieve a random access stream from the download operation. Every OpenReadAsync() operation returns
                // a new stream instance that is independent of previous ones (i.e., the seek position of one stream
                // isn't affected by calls on another stream).
                //
                // This sample demonstrates the direct usage of a DownloadOperation's random access stream and its
                // effects on the ongoing transfer. However, bear in mind that there are a variety of operations
                // that can manage the stream on the app's behalf for specific scenarios. For instance, a
                // DownloadOperation pointing to a video URL can be consumed by the MediaPlayer class in four easy
                // steps:
                //
                // var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
                // stream = await randomAccessStreamReference.OpenReadAsync();
                // var mediaPlayer = new Windows.Media.Playback.MediaPlayer();
                // mediaPlayer.Source = Windows.Media.Core.MediaSource.CreateFromStream(stream, stream.ContentType);

                var randomAccessStreamReference = download.GetResultRandomAccessStreamReference();
                randomAccessStream = await randomAccessStreamReference.OpenReadAsync();

                // Start the download. If the server doesn't support random access, the download will fail
                // with WebErrorStatus.InsufficientRangeSupport or WebErrorStatus.MissingContentLengthSupport.
                IAsyncOperationWithProgress <DownloadOperation, DownloadOperation> downloadOperation = download.StartAsync();
                downloadOperation.Progress += OnDownloadProgress;
                Task downloadTask = downloadOperation.AsTask();

                startDownloadButton.IsEnabled = false;
                pauseDownloadButton.IsEnabled = true;

                // Read data while the download is still ongoing. Use a 1 MB read buffer for that purpose.
                var readBuffer = new Windows.Storage.Streams.Buffer(BytesPerMegaByte);
                while (!downloadTask.IsCompleted)
                {
                    ulong readOffsetInBytes = randomAccessStream.Position;

                    PreviousReadText.Text = CurrentReadText.Text;
                    CurrentReadText.Text  = $"Reading from offset {readOffsetInBytes:n0}";

                    readOperation = randomAccessStream.ReadAsync(
                        readBuffer,
                        readBuffer.Capacity,
                        InputStreamOptions.None).
                                    AsTask(readCancellationTokenSource.Token);

                    // Update the UI to show the current read's position.
                    currentPositionSlider.Value = readOffsetInBytes / BytesPerMegaByte;

                    try
                    {
                        // Wait for the read to complete.
                        IBuffer bytesRead = await readOperation;
                        CurrentReadText.Text += $", completed with {bytesRead.Length:n0} bytes";

                        // At this point, a real app would process the 'bytesRead' data to do something interesting
                        // with it (e.g., display video and/or play audio).

                        if (randomAccessStream.Position >= randomAccessStream.Size)
                        {
                            // We have reached EOF. Wrap around to the beginning while we wait for the download to complete.
                            randomAccessStream.Seek(0);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // The ongoing read was canceled by SeekDownload_Click(...) in order for a new download
                        // position to take effect immediately.
                        CurrentReadText.Text += ", cancelled.";
                    }
                }

                // Wait for the download to complete.
                await downloadTask;

                rootPage.NotifyUser("Download completed successfully", NotifyType.StatusMessage);
            }
            catch (Exception ex) when(IsWebException("Execution error", ex))
            {
                // Abandon the operation if a web exception occurs.
            }
            finally
            {
                download           = null;
                randomAccessStream = null;
                readOperation      = null;

                startDownloadButton.IsEnabled  = true;
                pauseDownloadButton.IsEnabled  = false;
                resumeDownloadButton.IsEnabled = false;
            }
        }
Ejemplo n.º 20
0
 public Task Start()
 {
     DownloadStatus = DownloadStatus.Run;
     return(DownloadOperation.StartAsync().AsTask(Cts.Token, Progress));
 }
Ejemplo n.º 21
0
        public static async void StartDownload(DownloadModel m, int index)
        {
            try
            {
                if (folderList == null)
                {
                    await GetfolderList();
                }

                BackgroundDownloader downloader = new BackgroundDownloader();
                downloader.SetRequestHeader("Referer", "https://www.bilibili.com/blackboard/html5player.html?crossDomain=true");
                downloader.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
                //设置下载模式
                if (SettingHelper.Get_DownMode() == 0)
                {
                    group.TransferBehavior = BackgroundTransferBehavior.Serialized;
                }
                else
                {
                    group.TransferBehavior = BackgroundTransferBehavior.Parallel;
                }
                downloader.TransferGroup = group;
                //设置视频文件夹
                StorageFolder videoFolder = null;
                var           f           = folderList.Find(x => x.id == m.folderinfo.id);
                if (f == null)
                {
                    videoFolder = await DownFolder.CreateFolderAsync(m.folderinfo.id, CreationCollisionOption.OpenIfExists);

                    m.folderinfo.folderPath = videoFolder.Path;
                    m.folderinfo.thumb      = await DownThumb(m.folderinfo.thumb, m.folderinfo.id, videoFolder);

                    folderList.Add(m.folderinfo);
                }
                else
                {
                    try
                    {
                        videoFolder = await StorageFolder.GetFolderFromPathAsync(f.folderPath);
                    }
                    catch (Exception ex)
                    {
                        MessageDialog md = new MessageDialog("Get videoFolder Error!\r\n" + ex.Message);
                    }
                }

                //读取part文件夹
                StorageFolder PartFolder = null;
                var           partf      = await videoFolder.CreateFolderAsync(m.videoinfo.mid, CreationCollisionOption.OpenIfExists);

                if (partf == null)
                {
                    PartFolder = await videoFolder.CreateFolderAsync(m.videoinfo.mid, CreationCollisionOption.OpenIfExists);
                }
                else
                {
                    PartFolder = partf;
                }
                //创建相关文件
                //创建配置文件

                //创建视频文件
                StorageFile file = await PartFolder.CreateFileAsync(m.videoinfo.mid + "-" + index + ".flv", CreationCollisionOption.OpenIfExists);

                //下载弹幕文件
                await DownDanMu(m.videoinfo.mid, PartFolder);

                DownloadOperation downloadOp = downloader.CreateDownload(new Uri(m.videoinfo.videoUrl), file);
                //设置下载策略
                if (SettingHelper.Get_Use4GDown())
                {
                    downloadOp.CostPolicy = BackgroundTransferCostPolicy.Always;
                }
                else
                {
                    downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                }
                BackgroundTransferStatus downloadStatus = downloadOp.Progress.Status;
                m.videoinfo.downGUID   = downloadOp.Guid.ToString();
                m.videoinfo.videoPath  = downloadOp.ResultFile.Path;
                m.videoinfo.folderPath = PartFolder.Path;
                m.videoinfo.downstatus = false;
                StorageFile sefile = await PartFolder.CreateFileAsync(m.videoinfo.mid + ".json", CreationCollisionOption.OpenIfExists);

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

                downloadOp.StartAsync();
            }
            catch (Exception ex)
            {
                MessageDialog md = new MessageDialog("StartDownload Eroor!\r\n" + ex.Message);
                await md.ShowAsync();
            }
            finally
            {
                await SetfolderList();
                await GetfolderList();
            }
        }
Ejemplo n.º 22
0
 public async Task StartAsync()
 {
     await op.StartAsync().AsTask(cts.Token);
 }
Ejemplo n.º 23
0
        public async void StartDownload(DownModel downModel)
        {
            try
            {
                BackgroundDownloader downloader = new BackgroundDownloader();
                if (Mode == 0)
                {
                    DownModel.group.TransferBehavior = BackgroundTransferBehavior.Serialized;
                }
                else
                {
                    DownModel.group.TransferBehavior = BackgroundTransferBehavior.Parallel;
                }
                downloader.TransferGroup = DownModel.group;

                if (setting.SettingContains("UseWifi"))
                {
                    if ((bool)setting.GetSettingValue("UseWifi"))
                    {
                        downloader.CostPolicy = BackgroundTransferCostPolicy.Default;
                    }
                    else
                    {
                        downloader.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                    }
                }
                else
                {
                    downloader.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                    setting.SetSettingValue("UseWifi", false);
                }
                StorageFolder DowFolder = await KnownFolders.VideosLibrary.CreateFolderAsync("Bili-Down", CreationCollisionOption.OpenIfExists);

                StorageFolder VideoFolder = await DowFolder.CreateFolderAsync(ReplaceSymbol(downModel.title), CreationCollisionOption.OpenIfExists);

                StorageFolder PartFolder = await VideoFolder.CreateFolderAsync(downModel.part, CreationCollisionOption.OpenIfExists);

                StorageFile file = await PartFolder.CreateFileAsync(downModel.mid + ".mp4", CreationCollisionOption.OpenIfExists);

                DownloadOperation downloadOp = downloader.CreateDownload(new Uri(downModel.url), file);
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                BackgroundTransferStatus downloadStatus = downloadOp.Progress.Status;
                downModel.Guid = downloadOp.Guid.ToString();
                downModel.path = downloadOp.ResultFile.Path;
                string jsonInfo = JsonConvert.SerializeObject(downModel);

                StorageFile fileWrite = await PartFolder.CreateFileAsync(downModel.Guid + ".json", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(fileWrite, jsonInfo);

                StorageFile fileWrite2 = await DowFolder.CreateFileAsync(downModel.Guid + ".bili", CreationCollisionOption.OpenIfExists);

                await FileIO.WriteTextAsync(fileWrite2, WebUtility.UrlEncode(PartFolder.Path));

                DownDanMu(downModel.mid, PartFolder);
                downloadOp.StartAsync();
            }
            catch (Exception ex)
            {
                //WebErrorStatus error = BackgroundTransferError.GetStatus(ex.HResult);
                MessageDialog md = new MessageDialog(ex.Message);
                await md.ShowAsync();
            }
        }
Ejemplo n.º 24
0
        private static async void CreateDown(DownloadTaskModel m, int index, DownloadUrlInfo url, StorageFolder folder)
        {
            BackgroundDownloader downloader = new BackgroundDownloader();

            foreach (var item in url.Headers)
            {
                downloader.SetRequestHeader(item.Key, item.Value);
            }
            //downloader.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0");
            //if (!url.Contains("360.cn"))
            //{
            //    downloader.SetRequestHeader("Origin", "https://www.bilibili.com/");
            //    downloader.SetRequestHeader("Referer", "https://www.bilibili.com/");
            //}
            //设置下载模式
            if (SettingHelper.Get_DownMode() == 0)
            {
                group.TransferBehavior = BackgroundTransferBehavior.Serialized;
            }
            else
            {
                group.TransferBehavior = BackgroundTransferBehavior.Parallel;
            }
            downloader.TransferGroup = group;
            //创建视频文件
            var filetype = ".flv";

            if (url.Url.Contains(".mp4"))
            {
                filetype = ".mp4";
            }
            StorageFile file = await folder.CreateFileAsync(index.ToString("000") + filetype, CreationCollisionOption.OpenIfExists);

            DownloadOperation downloadOp = downloader.CreateDownload(new Uri(url.Url), file);

            //设置下载策略
            if (SettingHelper.Get_Use4GDown())
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.Always;
            }
            else
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
            }
            SqlHelper.InsertDownload(new DownloadGuidClass()
            {
                guid    = downloadOp.Guid.ToString(),
                cid     = m.cid,
                index   = index,
                aid     = (m.downloadMode == DownloadMode.Anime) ? m.sid : m.avid,
                eptitle = m.epTitle,
                title   = m.title,
                mode    = (m.downloadMode == DownloadMode.Anime) ? "anime" : "video"
            });
            try
            {
                await downloadOp.StartAsync();
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 25
0
        public static async Task <ObservableCollection <WeaponSkin> > GetSkins()
        {
            //Collection of the skins
            ObservableCollection <WeaponSkin> SkinCollection = new ObservableCollection <WeaponSkin>();

            //CSGO-File where the URIs are stored in
            StorageFile inputFile = await GetSkinsFileAsync();

            //Saves the text of the inputFile in a string for further editing
            string text = await Windows.Storage.FileIO.ReadTextAsync(inputFile);

            //erases all entries in the text before the first url
            if (!text.StartsWith("weapon"))
            {
                text = text.Substring(text.IndexOf("weapon"));
            }

            //downloading the pictures from the different urls
            while (text.Length != 0)
            {
                WeaponSkin skin = new WeaponSkin();
                skin.Id  = text.Substring(0, text.IndexOf("="));
                text     = text.Substring(text.IndexOf("=") + 1);
                skin.Url = text.Substring(0, text.IndexOf("\r\n"));
                text     = text.Substring(text.IndexOf("\n") + 1);
                try
                {
                    //downloading the pictures from the urls
                    Uri sourceUri = new Uri("ms-appx:///Images/WeaponSkins/defaultSkin.png");

                    string destination = "ms-appx:///Images/WeaponSkins/" + skin.Id + ".png";

                    //getting the destination Folder for the pictures, by receiving the parent folder from a default file
                    StorageFile defaultFile = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);

                    Windows.Storage.StorageFolder storageFolder = await defaultFile.GetParentAsync();

                    //creating the .png file for the picture
                    Windows.Storage.StorageFile destinationFile = await storageFolder.CreateFileAsync(skin.Id + ".png", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                    //StorageFile destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(destination, CreationCollisionOption.GenerateUniqueName);

                    //downloading the picture from the url
                    BackgroundDownloader downloader = new BackgroundDownloader();
                    DownloadOperation    download   = downloader.CreateDownload(new Uri(skin.Url), destinationFile);

                    // Attach progress and completion handlers.
                    var result = download.StartAsync();

                    //assign the downloaded picture to the skin
                    skin.Icon = destinationFile.Path;
                }
                catch (Exception ex)
                {
                    //LogException("Download Error", ex);
                }
                //adding the skin to the collection
                SkinCollection.Add(skin);
            }
            return(SkinCollection);
        }
Ejemplo n.º 26
0
        public static async void Download(string url, string thumbnail,
                                          bool isVideo = false, string username = null, string caption = null, bool sendNotify = false, bool story = false, bool userDownloader = false)
        {
            try
            {
                StorageFolder folder;
                if (story)
                {
                    folder = await Helper.GetPictureFolderForStories();
                }
                else
                {
                    folder = await Helper.GetPictureFolder();
                }
                var date = DateTime.UtcNow;

                //DateTime.Now.ToString("yyyy-dd-MMTh:mm:ss-0fffZ")
                var name = $"{username?.ToUpper()}_IMG_{date.ToString("yyyyddMM_hmmssfff", CultureInfo.CurrentCulture)}.jpg";
                if (isVideo)
                {
                    name = $"{username?.ToUpper()}_VID_{date.ToString("yyyyddMM_hmmssfff", CultureInfo.CurrentCulture)}.mp4";
                }

                var destinationFile = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);


                if (!string.IsNullOrEmpty(caption))
                {
                    if (caption.Length > 110)
                    {
                        caption = caption.Substring(0, 108);
                    }
                }
                if (caption == null)
                {
                    caption = string.Empty;
                }
                caption = ReplaceInvalidXmlCharacterReferences(caption);
                ToastNotification failed  = null;
                ToastNotification success = null;
                if (userDownloader)
                {
                    failed = NotificationHelper.GetSingleUserNotify(username, thumbnail, "Download failed");

                    success = NotificationHelper.GetSuccessUserNotify(username, thumbnail);
                }
                else
                {
                    try
                    {
                        failed = NotificationHelper.GetFailedNotify(caption, thumbnail);
                    }
                    catch
                    {
                        failed = NotificationHelper.GetFailedNotify(null, thumbnail);
                    }
                    try
                    {
                        success = NotificationHelper.GetSuccessNotify(caption, thumbnail);
                    }
                    catch
                    {
                        success = NotificationHelper.GetSuccessNotify(null, thumbnail);
                    }
                }
                BackgroundDownloader downloader = new BackgroundDownloader
                {
                    FailureToastNotification = failed,
                    SuccessToastNotification = success
                };
                if (sendNotify)
                {
                    MainPage.Current.ShowInAppNotify($"Download started...", 1200);
                }

                DownloadOperation download = downloader.CreateDownload(new Uri(url), destinationFile);
                await download.StartAsync().AsTask();
            }
            catch (Exception ex) { ex.PrintException("Download"); }
        }
Ejemplo n.º 27
0
 internal static async Task DownloadFileASync(string link, StorageFile destination, IProgress <DownloadOperation> progress, CancellationToken cancellationToken = default)
 {
     BackgroundDownloader downloader = new BackgroundDownloader();
     DownloadOperation    download   = downloader.CreateDownload(new Uri(link), destination);
     await download.StartAsync().AsTask(cancellationToken, progress);
 }
 private async Task StartDownloadAsync(DownloadOperation obj)
 {
     var process = new Progress <DownloadOperation>(ProgressCallback);
     await obj.StartAsync().AsTask(process);
 }
Ejemplo n.º 29
0
        // Picture Download Progress
        private async Task <DownloadOperation> PerformDownload(DownloadOperation download)
        {
            Progress <DownloadOperation> callback = new Progress <DownloadOperation>(UpdateDownloadProgress);

            return(await download.StartAsync().AsTask(callback));
        }
Ejemplo n.º 30
0
        public async Task <MediaSource> RequestMusic(MusicModel model)
        {
            EventHandler <DownloadOperation> downloadProgressHandler = (o, e) =>
            {
                _logger.Debug($"Downloading status of {model.Title}:\n\t{e.Progress.Status}, ({e.Progress.BytesReceived}/{e.Progress.TotalBytesToReceive})");
                switch (e.Progress.Status)
                {
                case BackgroundTransferStatus.Completed:
                    _utilityHelper.RunAtUIThread(() => model.HasCached = true);
                    break;

                default:
                    break;
                }
            };

            IRandomAccessStreamReference ras = null;
            DownloadOperation            downloadOperation = null;
            var downloadProgress = new Progress <DownloadOperation>();

            downloadProgress.ProgressChanged += downloadProgressHandler;

            var cacheFile = await _createMusicFile(model);

            if (cacheFile == null)
            {
                var operations = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(_backgroundDownloaderGroup);

                foreach (var item in operations)
                {
                    if (item.ResultFile is StorageFile cachedFile)
                    {
                        if (cachedFile.Name == _utilityHelper.CreateMd5HashString(model.Title))
                        {
                            downloadOperation = item;
                            break;
                        }
                    }
                }
                if (downloadOperation != null)
                {
                    ras = downloadOperation.GetResultRandomAccessStreamReference();
                    downloadOperation.AttachAsync().AsTask(downloadProgress);
                }
                else
                {
                    _logger.Warning($"Don't find the downloading task for {model.Title}");
                    return(null);
                }
            }
            else
            {
                downloadOperation = _backgroundDownloader.CreateDownload(model.Uri, cacheFile);
                downloadOperation.IsRandomAccessRequired = true;
                ras = downloadOperation.GetResultRandomAccessStreamReference();
                downloadOperation.StartAsync().AsTask(downloadProgress);
            }

            var source = MediaSource.CreateFromStreamReference(ras, "audio/mpeg");

            return(source);
        }