Ejemplo n.º 1
0
        private static async void CreateDown(DownloadTaskModel m, int index, string url, StorageFolder folder)
        {
            BackgroundDownloader downloader = new BackgroundDownloader();

            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 (!url.Contains("360.cn"))
            {
                downloader.SetRequestHeader("Referer", "https://www.bilibili.com/blackboard/html5player.html?crossDomain=true");
            }
            //设置下载模式
            if (SettingHelper.Get_DownMode() == 0)
            {
                group.TransferBehavior = BackgroundTransferBehavior.Serialized;
            }
            else
            {
                group.TransferBehavior = BackgroundTransferBehavior.Parallel;
            }
            downloader.TransferGroup = group;
            //创建视频文件
            var filetype = ".flv";

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

            DownloadOperation downloadOp = downloader.CreateDownload(new Uri(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)
            {
            }
        }
        public override IHttpTask Download(TaskConfiguration config)
        {
            var task = new BackgroundDownloader
            {
                Method     = config.HttpMethod,
                CostPolicy = config.UseMeteredConnection
                    ? BackgroundTransferCostPolicy.Default
                    : BackgroundTransferCostPolicy.UnrestrictedOnly
            };

            foreach (var header in config.Headers)
            {
                task.SetRequestHeader(header.Key, header.Value);
            }

            var filePath  = config.LocalFilePath ?? Path.Combine(ApplicationData.Current.LocalFolder.Path, Path.GetRandomFileName());
            var fileName  = Path.GetFileName(filePath);
            var directory = Path.GetDirectoryName(filePath);

            // why are these async??
            var folder = StorageFolder.GetFolderFromPathAsync(directory).AsTask().Result;
            var file   = folder.CreateFileAsync(fileName).AsTask().Result;

            var operation = task.CreateDownload(new Uri(config.Uri), file);
            var httpTask  = new DownloadHttpTask(config, operation, false);

            this.Add(httpTask);

            return(httpTask);
        }
Ejemplo n.º 3
0
        public Task <Uri> Download(Uri source, string username, string password, StorageFile dest)
        {
            var downloader = new BackgroundDownloader();

            downloader.SetRequestHeader(HttpUtil.Authorization, HttpUtil.BasicAuthHeader(username, password));
            return(Download(source, dest, downloader));
        }
Ejemplo n.º 4
0
        public async Task <IHttpTransfer> Create(HttpTransferRequest request)
        {
            var task = new BackgroundDownloader
            {
                Method     = request.HttpMethod,
                CostPolicy = request.UseMeteredConnection
                    ? BackgroundTransferCostPolicy.Default
                    : BackgroundTransferCostPolicy.UnrestrictedOnly
            };

            foreach (var header in request.Headers)
            {
                task.SetRequestHeader(header.Key, header.Value);
            }

            //var filePath = config.LocalFilePath ?? Path.Combine(ApplicationData.Current.LocalFolder.Path, Path.GetRandomFileName());
            var winFile = await StorageFile.GetFileFromPathAsync(request.LocalFilePath.FullName).AsTask();

            var op = task.CreateDownload(new Uri(request.Uri), winFile);

            //var operation = task.CreateDownload(new Uri(config.Uri), file);
            //var httpTask = new DownloadHttpTask(config, operation, false);
            //this.Add(httpTask);
            return(null);
        }
Ejemplo n.º 5
0
        public async Task DownloadFile(string url, string fileName = null)
        {
            BackgroundDownloader bd = new BackgroundDownloader();
            string cookie           = cc.GetCookieHeader(new Uri("http://learn.tsinghua.edu.cn"));

            bd.SetRequestHeader("Cookie", cookie);
            StorageFile fileTemp = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(new Random().Next().ToString());

            var downOpr = bd.CreateDownload(new Uri(url), fileTemp);
            await downOpr.StartAsync();

            var picker = new Windows.Storage.Pickers.FileSavePicker();

            if (fileName != null)
            {
                picker.SuggestedFileName = fileName;
            }
            else
            {
                string head = downOpr.GetResponseInformation().Headers["Content-Disposition"];
                fileName = Regex.Replace(head, @".+filename=""", "");
                fileName = fileName.Substring(0, fileName.Length - 1);
                fileName = Regex.Replace(fileName, "_?[0-9]{6,}_?", "");
                picker.SuggestedFileName = fileName;
            }
            string typeName = new FileInfo(fileName).Extension;

            picker.FileTypeChoices.Add("文件", new List <string>()
            {
                typeName
            });
            StorageFile file = await picker.PickSaveFileAsync();

            await fileTemp.MoveAndReplaceAsync(file);
        }
Ejemplo n.º 6
0
        protected override async Task <HttpTransfer> CreateDownload(HttpTransferRequest request)
        {
            var task = new BackgroundDownloader
            {
                Method     = request.HttpMethod.Method,
                CostPolicy = request.UseMeteredConnection
                    ? BackgroundTransferCostPolicy.Default
                    : BackgroundTransferCostPolicy.UnrestrictedOnly
            };

            foreach (var header in request.Headers)
            {
                task.SetRequestHeader(header.Key, header.Value);
            }

            if (!request.LocalFile.Exists)
            {
                request.LocalFile.Create();
            }

            var winFile = await StorageFile.GetFileFromPathAsync(request.LocalFile.FullName).AsTask();

            var operation = task.CreateDownload(new Uri(request.Uri), winFile);

            operation.StartAsync();

            return(operation.FromNative());
        }
Ejemplo n.º 7
0
        private BackgroundDownloader CreateDownloader()
        {
            BackgroundDownloader downloader = new BackgroundDownloader();

            downloader.SetRequestHeader("Cookie", "time=" + DateTime.Now);
            return(downloader);
        }
Ejemplo n.º 8
0
        private async Task TryScheduleAttachmentDownload(SignalAttachment attachment)
        {
            if (Downloads.Count < 100)
            {
                if (attachment.Status != SignalAttachmentStatus.Finished && !Downloads.ContainsKey(attachment.Id))
                {
                    SignalServiceAttachmentPointer attachmentPointer = attachment.ToAttachmentPointer();
                    IStorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    IStorageFile   tmpDownload = await Task.Run(async() =>
                    {
                        return(await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(@"Attachments\" + attachment.Id + ".cipher", CreationCollisionOption.ReplaceExisting));
                    });

                    BackgroundDownloader downloader = new BackgroundDownloader();
                    downloader.SetRequestHeader("Content-Type", "application/octet-stream");
                    // this is the recommended way to call CreateDownload
                    // see https://docs.microsoft.com/en-us/uwp/api/windows.networking.backgroundtransfer.backgrounddownloader#Methods
                    DownloadOperation download = downloader.CreateDownload(new Uri(await MessageReceiver.RetrieveAttachmentDownloadUrl(CancelSource.Token, attachmentPointer)), tmpDownload);
                    attachment.Guid = download.Guid.ToString();
                    SignalDBContext.UpdateAttachmentGuid(attachment);
                    Downloads.Add(attachment.Id, download);
                    var downloadSuccessfulHandler = Task.Run(async() =>
                    {
                        Logger.LogInformation("Waiting for download {0}({1})", attachment.SentFileName, attachment.Id);
                        var t = await download.StartAsync();
                        await HandleSuccessfullDownload(attachment, tmpDownload, download);
                    });
                }
            }
        }
Ejemplo n.º 9
0
        internal async Task BackgroundDownload()
        {
            if (SelectedItem == null)
            {
                await new MessageDialog("No File Selected").ShowAsync();
            }

            FileSavePicker fileSavePicker = new FileSavePicker();

            fileSavePicker.SuggestedFileName = SelectedItem.Name;
            var ext = Path.GetExtension(SelectedItem.Name);

            fileSavePicker.FileTypeChoices.Add(ext, new string[] { ext });
            StorageFile saveFile = await fileSavePicker.PickSaveFileAsync();

            if (saveFile == null)
            {
                return;
            }

            var bgDownloader = new BackgroundDownloader();
            var test         = Path.Combine(Config.FilesEndpointUri.ToString(), string.Format(Constants.ContentPathString, SelectedItem.Id));

            bgDownloader.SetRequestHeader(Constants.AuthHeaderKey, string.Format(Constants.V2AuthString, Client.Auth.Session.AccessToken));
            var download = bgDownloader.CreateDownload(new Uri(test), saveFile);

            var testRes = await download.StartAsync();
        }
Ejemplo n.º 10
0
        private async Task Run()
        {
            if (_downloadOperation != null)
            {
                _cancellationToken = new CancellationTokenSource();
                await _downloadOperation.AttachAsync().AsTask(_cancellationToken.Token);
            }
            else
            {
                string fullPath = AddBackslash(RemoteFile.Path);
                fullPath += RemoteFile.Name;

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

            try
            {
                StorageApplicationPermissions.FutureAccessList.Remove(_localFileToken);
            }
            catch (Exception e)
            {
            }
        }
 /// <summary>
 /// Starts to download the file as an asynchronous operation.
 /// </summary>
 /// <param name="sdkClient">The SDK client.</param>
 /// <param name="path">The path to the file.</param>
 /// <param name="file">The file.</param>
 /// <param name="progress">The progress handler.</param>
 public static async Task StartDownloadFileAsync(this IDiskSdkClient sdkClient, string path, IStorageFile file, IProgress progress)
 {
     try
     {
         var uri        = new Uri(WebdavResources.ApiUrl + path);
         var downloader = new BackgroundDownloader();
         downloader.SetRequestHeader("Accept", "*/*");
         downloader.SetRequestHeader("TE", "chunked");
         downloader.SetRequestHeader("Accept-Encoding", "gzip");
         downloader.SetRequestHeader("Authorization", "OAuth " + sdkClient.AccessToken);
         downloader.SetRequestHeader("X-Yandex-SDK-Version", "winui, 1.0");
         var download = downloader.CreateDownload(uri, file);
         await HandleDownloadAsync(download, progress, true);
     }
     catch (Exception ex)
     {
         throw HttpUtilities.ProcessException(ex);
     }
 }
        async void StartDownload(string filePath, string directory)
        {
            try
            {
                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(directory).AsTask(_cancelSource.Token);

                var         fileName   = Path.GetFileName(filePath);
                StorageFile resultFile = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting).AsTask(_cancelSource.Token);

                var downloader = new BackgroundDownloader();
                downloader.TransferGroup = s_BackgroundDownloadGroup;
                if (config.requestHeaders != null)
                {
                    foreach (var header in config.requestHeaders)
                    {
                        if (header.Value != null)
                        {
                            foreach (var value in header.Value)
                            {
                                downloader.SetRequestHeader(header.Key, value);
                            }
                        }
                    }
                }
                switch (config.policy)
                {
                case BackgroundDownloadPolicy.AlwaysAllow:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.Always;
                    break;

                case BackgroundDownloadPolicy.AllowMetered:
                case BackgroundDownloadPolicy.Default:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.Default;
                    break;

                case BackgroundDownloadPolicy.UnrestrictedOnly:
                    downloader.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
                    break;
                }
                _download          = downloader.CreateDownload(config.url, resultFile);
                _downloadOperation = _download.StartAsync();
                var downloadTask = _downloadOperation.AsTask();
                downloadTask.ContinueWith(DownloadTaskFinished, _cancelSource.Token);
            }
            catch (OperationCanceledException)
            {
                _error  = "Download aborted";
                _status = BackgroundDownloadStatus.Failed;
            }
            catch (Exception e)
            {
                _error  = "Download: " + e.Message;
                _status = BackgroundDownloadStatus.Failed;
            }
        }
Ejemplo n.º 13
0
        private BackgroundDownloader ToDownloader(MusicItem track)
        {
            var    downloader = new BackgroundDownloader();
            var    cloud      = track.CloudServer;
            var    user       = track.Username;
            var    pass       = track.Password;
            string authHeader = cloud == null?HttpUtil.BasicAuthHeader(user, pass) : HttpUtil.Basic + " " + HttpUtil.Base64ColonSeparated(cloud, user, pass);

            downloader.SetRequestHeader(HttpUtil.Authorization, authHeader);
            return(downloader);
        }
Ejemplo n.º 14
0
        internal async 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 = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(destinationPathName));

                file = await folder.CreateFileAsync(Path.GetFileName(destinationPathName), CreationCollisionOption.ReplaceExisting);
            }
            else
            {
                var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
                file = await folder.CreateFileAsync(downloadUrl.Segments.Last(), CreationCollisionOption.GenerateUniqueName);
            }

            DownloadOperation = downloader.CreateDownload(downloadUrl, file);

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

            _cancellationToken = new CancellationTokenSource();

            try
            {
                var downloadOperation = await DownloadOperation.StartAsync().AsTask(_cancellationToken.Token, progress);

                ProgressChanged(downloadOperation);
            } catch (TaskCanceledException)
            {
            } catch (Exception e)
            {
                Status        = DownloadFileStatus.FAILED;
                StatusDetails = e.Message;
            }
        }
        /// <summary>
        /// Overrides the base execute logic to use the background downloader to download the file.
        /// </summary>
        protected async override void OnExecute()
        {
            var loginResult = await this.LiveClient.Session.AuthClient.GetLoginStatusAsync();

            if (loginResult.Error != null)
            {
                this.taskCompletionSource.SetException(loginResult.Error);
                return;
            }
            else
            {
                var downloader = new BackgroundDownloader();
                downloader.SetRequestHeader(
                    ApiOperation.AuthorizationHeader,
                    AuthConstants.BearerTokenType + " " + loginResult.Session.AccessToken);
                downloader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());

                downloader.Group = LiveConnectClient.LiveSDKDownloadGroup;
                this.downloadOp  = downloader.CreateDownload(this.Url, this.OutputFile);
                this.taskCompletionSource.SetResult(new LiveDownloadOperation(downloadOp));
            }
        }
Ejemplo n.º 16
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.º 17
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.º 18
0
 private void _initDownloader()
 {
     _backgroundDownloader = new BackgroundDownloader();
     _backgroundDownloader.TransferGroup = _backgroundDownloaderGroup;
     _backgroundDownloader.SetRequestHeader("Referer", KISSSUB_HOST);
 }
Ejemplo n.º 19
0
        private async static void DownloadVideo(DownloadInfo downloadInfo, DownloadUrlInfo url, StorageFolder episodeFolder)
        {
            BackgroundDownloader downloader = new BackgroundDownloader();

            if (url.HttpHeader != null)
            {
                foreach (var item in url.HttpHeader)
                {
                    downloader.SetRequestHeader(item.Key, item.Value);
                }
            }
            var parallelDownload = SettingHelper.GetValue <bool>(SettingHelper.Download.PARALLEL_DOWNLOAD, true);
            var allowCostNetwork = SettingHelper.GetValue <bool>(SettingHelper.Download.ALLOW_COST_NETWORK, false);

            //设置下载模式
            if (parallelDownload)
            {
                group.TransferBehavior = BackgroundTransferBehavior.Parallel;
            }
            else
            {
                group.TransferBehavior = BackgroundTransferBehavior.Serialized;
            }
            downloader.TransferGroup = group;


            //创建视频文件

            StorageFile file = await episodeFolder.CreateFileAsync(url.FileName, CreationCollisionOption.OpenIfExists);

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

            //设置下载策略
            if (allowCostNetwork)
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.Always;
            }
            else
            {
                downloadOp.CostPolicy = BackgroundTransferCostPolicy.UnrestrictedOnly;
            }
            var guid = downloadOp.Guid.ToString();

            SettingHelper.SetValue(guid, new DownloadGUIDInfo()
            {
                CID          = downloadInfo.CID,
                Path         = episodeFolder.Path,
                EpisodeTitle = downloadInfo.EpisodeTitle,
                FileName     = url.FileName,
                Title        = downloadInfo.Title,
                GUID         = guid,
                Type         = downloadInfo.Type,
                ID           = downloadInfo.Type == DownloadType.Video? downloadInfo.AVID: downloadInfo.SeasonID.ToString()
            });

            try
            {
                await downloadOp.StartAsync();
            }
            catch (Exception)
            {
            }
        }
Ejemplo n.º 20
0
        private async void downloadbutton_Click(object sender, RoutedEventArgs e)
        {
            loading.IsIndeterminate = true;
            pro.Visibility          = Windows.UI.Xaml.Visibility.Visible;
            pro.Value = 0;
            if (((JSONProperties)DataContext).Size.ToLower().Contains("mb") || ((JSONProperties)DataContext).Size.ToLower().Contains("gb"))
            {
                if (EnsureUnsnapped())
                {
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    // Dropdown of file types the user can save the file as
                    savePicker.FileTypeChoices.Add(string.IsNullOrEmpty(((JSONProperties)DataContext).Type) ? ((JSONProperties)DataContext).Extension : ((JSONProperties)DataContext).Type, new List <string>()
                    {
                        ((JSONProperties)DataContext).Extension
                    });
                    // Default file name if the user does not type one in or select a file to replace
                    savePicker.SuggestedFileName = ((JSONProperties)DataContext).Name;

                    StorageFile file = await savePicker.PickSaveFileAsync();

                    Uri uri = new Uri(HAPSettings.CurrentSite.Address, Path.Substring(1));
                    BackgroundDownloader downloader = new BackgroundDownloader();
                    downloader.Method = "GET";
                    downloader.SetRequestHeader("Cookie", string.Format("{0}={1}; token={2}", HAPSettings.CurrentToken[2], HAPSettings.CurrentToken[1], HAPSettings.CurrentToken[0]));
                    DownloadOperation download = downloader.CreateDownload(uri, file);
                    // Attach progress and completion handlers.
                    HandleDownloadAsync(download, true);
                    MessageDialog mes = new MessageDialog("The download of " + ((JSONProperties)DataContext).Name + " has started, you will get notified when it's done", "Downloading");
                    mes.Commands.Add(new UICommand("OK"));
                    mes.DefaultCommandIndex = 0;
                    mes.ShowAsync();
                    var ignored3 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { pro.Visibility = Windows.UI.Xaml.Visibility.Collapsed; loading.IsIndeterminate = false; });
                }
            }
            else
            {
                HttpWebRequest req = WebRequest.CreateHttp(new Uri(HAPSettings.CurrentSite.Address, Path.Substring(1)));
                req.Method          = "GET";
                req.Headers         = new WebHeaderCollection();
                req.CookieContainer = new CookieContainer();
                req.CookieContainer.Add(HAPSettings.CurrentSite.Address, new Cookie("token", HAPSettings.CurrentToken[0]));
                req.CookieContainer.Add(HAPSettings.CurrentSite.Address, new Cookie(HAPSettings.CurrentToken[2], HAPSettings.CurrentToken[1]));
                req.AllowReadStreamBuffering = false;
                req.BeginGetResponse(a =>
                {
                    using (WebResponse response = req.EndGetResponse(a))
                    {
                        int expected = (int)response.ContentLength;
                        using (System.IO.BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                        {
                            MemoryStream ms = new MemoryStream(expected);
                            bool canwrite   = true;
                            long count      = 0; int x = 0;
                            while (canwrite)
                            {
                                try
                                {
                                    ms.WriteByte(reader.ReadByte());
                                }
                                catch { canwrite = false; }
                                count++;
                                x++;
                                if (x == 100)
                                {
                                    x = 0;
                                    try
                                    {
                                        var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { try { pro.Value = count * 100.0 / expected; } catch { } });
                                    }
                                    catch { }
                                }
                            }
                            var ignored1 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { makefile(ms, (JSONProperties)a.AsyncState); });
                        }
                    }
                }
                                     , (JSONProperties)DataContext);
            }
        }