Пример #1
0
        public static async void DownloadVideo(string url, string filename, VideoItem caller)
        {
            try
            {
                HttpClientHandler aHandler = new HttpClientHandler();
                aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                HttpClient aClient = new HttpClient(aHandler);
                aClient.DefaultRequestHeaders.ExpectContinue = false;
                HttpResponseMessage response = await aClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); // Important! ResponseHeadersRead.

                var outputFolder = await Settings.GetOutputFolder();
                var audioFile = await outputFolder.CreateFileAsync(filename + caller.sourceFileFormat, CreationCollisionOption.ReplaceExisting);
                var fs = await audioFile.OpenAsync(FileAccessMode.ReadWrite);

                Stream stream = await response.Content.ReadAsStreamAsync();
                if (response.Content.Headers.ContentLength != null)
                {
                    ulong totalBytes = (ulong) response.Content.Headers.ContentLength;
                    IInputStream inputStream = stream.AsInputStream();
                    ulong totalBytesRead = 0;
                    while (true)
                    {
                        // Read from the web.
                        IBuffer buffer = new Buffer(1024);
                        buffer = await inputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

                        if (buffer.Length == 0)
                            break; //we're done nothing left to read... cya!

                        // Report progress.
                        totalBytesRead += buffer.Length;
                        var read = totalBytesRead;
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { caller.SetProgress((int) (100*read/totalBytes)); });

                        // Write to file.
                        await fs.WriteAsync(buffer);
                    }
                    inputStream.Dispose();
                }
                fs.Dispose();

                //Once we're done we are calling manager with info that item has been donwloaded.
                QueueManager.Instance.DownloadCompleted(caller.id);
                //And we have to queue it's conversion to different format.
                QueueManager.Instance.QueueNewItemConv(caller);

                //TODO Handle failure
            }
            catch (Exception exc)
            {
                Debug.WriteLine("DownloadVideo  " + url + "   " + exc.Message);
            }
        }