public async Task <Result <YoutubeDownloadResult, string> > DownloadYoutubeVideo(YTEVideoFormat video)
        {
            if (video == null)
            {
                throw new Exception("null video passed to DownloadYoutubeVideo");
            }

            // We combine the VideoID with a DateTime hashcode just incase multiple copies
            // of the same video are being downloaded.  That way there won't be any file clashes.
            string filepath = $"{Guid.NewGuid().ToString()}.temp";

            try
            {
                if (video.YTEVideoInfo.RequiresDecryption)
                {
                    await Task.Run(() => DownloadUrlResolver.DecryptDownloadUrl(video.YTEVideoInfo));
                }

                var downloader = new VideoDownloader(video.YTEVideoInfo, filepath);
                await Task.Run(() => downloader.Execute());

                return(new YoutubeDownloadResult(filepath));
            }
            catch (WebException e)
            {
                return((e.Response as HttpWebResponse).StatusCode.ToString());
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Exemple #2
0
        private void DownloadMp3(LinkInfo link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link.Link);

            // Extracting stream with highest quality
            VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var audioDownloader = new AudioDownloader(video, Path.Combine(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.AudioExtension));

            audioDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                downloader.ReportProgress((int)argss.ProgressPercentage);
            };
            audioDownloader.DownloadFinished += (sender, argss) =>
            {
            };

            audioDownloader.Execute();
        }
        public async Task <IActionResult> Get(string ytTrailerCode)
        {
            var cachedTrailer = _cachingService.GetCache(ytTrailerCode);

            if (cachedTrailer == null)
            {
                var trailer = await GetVideoInfoForStreamingAsync("http://www.youtube.com/watch?v=" + ytTrailerCode, YoutubeStreamingQuality.High);

                if (trailer != null && trailer.RequiresDecryption)
                {
                    await Task.Run(() => DownloadUrlResolver.DecryptDownloadUrl(trailer));

                    var response = new TrailerResponse {
                        TrailerUrl = trailer.DownloadUrl
                    };
                    _cachingService.SetCache(ytTrailerCode, JsonConvert.SerializeObject(response));
                    return(Json(response));
                }

                if (trailer != null && !trailer.RequiresDecryption)
                {
                    var response = new TrailerResponse {
                        TrailerUrl = trailer.DownloadUrl
                    };
                    _cachingService.SetCache(ytTrailerCode, JsonConvert.SerializeObject(response));
                    return(Json(response));
                }

                return(BadRequest());
            }

            return(Json(JsonConvert.DeserializeObject <TrailerResponse>(cachedTrailer)));
        }
        private void downloadButton(object sender, EventArgs e)
        {
            string downloadPath = Properties.Settings.Default.downloadPath;

            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;

            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(textBox1.Text);
            VideoInfo video = videoInfos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(comboBox1.Text));

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            VideoDownloader downloader = new VideoDownloader(video, Path.Combine(downloadPath, RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            downloader.DownloadProgressChanged += Downloader_DownloadProgressChanged;

            Thread thread = new Thread(() => { downloader.Execute(); })
            {
                IsBackground = true
            };

            thread.Start();

            downloader.DownloadFinished += Downloader_DownloadFinished;
            title = video.Title;
        }
Exemple #5
0
        private static async Task DownloadVideo(IEnumerable <VideoInfo> videoInfos)
        {
            var video = videoInfos.OrderByDescending(x => x.Resolution).FirstOrDefault(info => info.VideoType == VideoType.Mp4);

            if (video is null)
            {
                Console.WriteLine("Not Found");
            }

            Console.WriteLine($"Video: {video.Title}{video.VideoExtension} -> Resolution: {video.Resolution}");

            if (video.RequiresDecryption)
            {
                await DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video, $"{downloadPath}{RemoveIllegalPathCharacters(video.Title)}{video.VideoExtension}");

            // Register the ProgressChanged event and print the current progress
            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine($"{video.Title} -> {(int)args.ProgressPercentage}");

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            await videoDownloader.Execute();
        }
Exemple #6
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.myButton);

            button.Click += delegate {
                string url = "https://www.youtube.com/watch?v=ALUhXkqXuHs";

                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url, false);

                VideoInfo video = videoInfos
                                  .First(info => info.VideoType == VideoType.Mp4);

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                string DestinationFile = Path.Combine(Environment.ExternalStorageDirectory.AbsolutePath, "test.mp4");

                Download download = new Download();
                download.Run(video.DownloadUrl, DestinationFile);
            };
        }
Exemple #7
0
        private static void bw_downloadAudio(object send, DoWorkEventArgs e)
        {
            isVideo_ = false;
            isAudio_ = true;
            BackgroundWorker worker = send as BackgroundWorker;

            if (dir_ != " ")
            {
                //Parameter for video type
                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url_);
                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }
                audioDownloader_ = new AudioDownloader(video, dir_);
                audioDownloader_.AudioExtractionProgressChanged += (sender, args) => progBar_.Invoke((Action)(() => { worker.ReportProgress((int)(85 + args.ProgressPercentage * 0.15)); }));
                try
                {
                    audioDownloader_.Execute();
                }
                catch (WebException we)
                {
                    MessageBox.Show("The video returned an error, please try again later",
                                    we.Response.ToString(),
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        public static void DownloadVideo(IEnumerable <VideoInfo> videoInfos, int index)
        {
            try
            {
                VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\YouTubeVideos";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var filename = $"{ index } - { YouTubeHelpers.RemoveIllegalPathCharacters(video.Title) + video.VideoExtension }";

                var savePath = Path.Combine(path, filename);

                var videoDownloader = new VideoDownloader(video, savePath);

                videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

                videoDownloader.Execute();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void DownloadAudio(IEnumerable <VideoInfo> videoInfos)
        {
            try
            {
                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\YouTubeAudios";

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var savePath = Path.Combine(path, YouTubeHelpers.RemoveIllegalPathCharacters(video.Title) + video.AudioExtension);

                var audioDownloader = new AudioDownloader(video, savePath);

                audioDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage * 0.85);

                audioDownloader.AudioExtractionProgressChanged += (sender, args) => Console.WriteLine(85 + args.ProgressPercentage * 0.15);

                audioDownloader.Execute();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #10
0
        private static void DownloadVideo()
        {
            // gets current working directory     ../bin/Debug
            dir = Directory.GetCurrentDirectory();

            // creates unum instance of URL resolver class and passes url
            IEnumerable <VideoInfo> v = DownloadUrlResolver.GetDownloadUrls(url);

            // gets video info from URL resolver and assigns into global
            video = v.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == resolution);

            // checks if url needs special decryption to format it
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video); // formats and decrypts url
                Console.WriteLine("Decyrpetd");
            }

            // makes downloader instance and passes video info and full path to save it
            VideoDownloader vd = new VideoDownloader(video, Path.Combine(dir + "\\", video.Title + video.VideoExtension));

            // built in function gets called when download status changes
            vd.DownloadProgressChanged += Vd_DownloadProgressChanged;
            // built in function gets called when download finishes
            vd.DownloadFinished += Vd_DownloadFinished;

            // executes the download
            vd.Execute();
        }
Exemple #11
0
        internal override async Task PrepareAsync(YoutubeStreamingQuality qualityHint)
        {
            VideoInfo video = null;

            try
            {
                video = await GetVideoInfoForStreaming(this.OriginalPath, qualityHint);

                if (video != null && video.RequiresDecryption)
                {
                    await Task.Run(() => DownloadUrlResolver.DecryptDownloadUrl(video));
                }
            }

            catch (Exception ex) if (ex is WebException || ex is VideoNotAvailableException || ex is YoutubeParseException)
                {
                    throw new SongPreparationException(ex);
                }

            if (video == null)
            {
                throw new SongPreparationException("No suitable video found");
            }

            this.playbackPath = video.DownloadUrl;
        }
Exemple #12
0
        private void DownloadVideo(VideoInfo video, Action <int> downloadProgressChanged)
        {
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var videoDownloader = new VideoDownloader(video,
                                                      Path.Combine(SaveToTextBox.Text, video.Title.RemoveIllegalPathCharacters() + video.VideoExtension));

            videoDownloader.NotOverideExistingFile = !OverrideExistingFileCheckBox.Checked;

            // Register the ProgressChanged event and print the current progress
            var prevValue = 0;

            videoDownloader.DownloadProgressChanged += (sender, args) =>
            {
                if (downloadProgressChanged != null)
                {
                    var newValue = (int)args.ProgressPercentage;
                    if (newValue > prevValue)
                    {
                        downloadProgressChanged(newValue);
                        prevValue = newValue;
                    }
                }
            };
            videoDownloader.Execute();
        }
        static void DownloadMP4(string link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);

            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var videoDownloader = new VideoDownloader(video, Path.Combine(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            videoDownloader.DownloadStarted += (sender, argss) => Console.WriteLine("Started downloading " + video.Title + video.VideoExtension);

            int ticks = 0;

            videoDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                ticks++;

                if (ticks > 1000)
                {
                    Console.Write("#");
                    ticks -= 1000;
                }
            };
            videoDownloader.DownloadFinished += (sender, argss) => Console.WriteLine("Finished downloading " + video.Title + video.VideoExtension);

            videoDownloader.Execute();
        }
        static void DownloadMP3(string link, string downloadDir)
        {
            Directory.CreateDirectory(downloadDir);
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);

            // Extracting stream with highest quality
            VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var audioDownloader = new AudioDownloader(video, Path.Combine(downloadDir, RemoveIllegalPathCharacters(video.Title) + video.AudioExtension));
            int ticks           = 0;

            audioDownloader.DownloadProgressChanged += (sender, argss) =>
            {
                ticks++;

                if (ticks > 1000)
                {
                    Console.Write("#");
                    ticks -= 1000;
                }
            };
            audioDownloader.DownloadFinished += (sender, argss) =>
            {
                Console.WriteLine("\nFinished download " + video.Title + video.AudioExtension);
            };

            audioDownloader.Execute();
        }
Exemple #15
0
        private string DownloadAudio(string videoId, string albumName)
        {
            string location    = "/storage/external_SD/Muzika";
            string youtubeLink =
                "https://www.youtube.com/watch?v=" + videoId;

            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(youtubeLink);

            VideoInfo video = videoInfos
                              .Where(info => info.AudioType == AudioType.Aac)
                              .OrderByDescending(info => info.AudioBitrate)
                              .FirstOrDefault();

            if (video == null)
            {
                throw new NullReferenceException("Audio was not found");
            }

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var downloadUrl = video.DownloadUrl;

            return("");
        }
Exemple #16
0
        //this method download the video in background. Also makes the GUI responsive
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string link = textBox1.Text;
                IEnumerable <VideoInfo> videoInfo = DownloadUrlResolver.GetDownloadUrls(link);
                VideoInfo video = videoInfo.FirstOrDefault();//we take the first video from that url.

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                //just a trick to allow method call in background worker control;
                var videoDownloader = new VideoDownloader(video, Path.Combine(Invoke((Func <string>)(() => { return(GetPath("")); })).ToString(),
                                                                              video.Title.Replace(" ", string.Empty).Replace("/", "") + video.VideoExtension));

                //report the progress for progressbar1
                videoDownloader.DownloadProgressChanged += (y, x) => backgroundWorker1.ReportProgress((int)x.ProgressPercentage);
                videoDownloader.Execute();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Exemple #17
0
        public async Task DownloadTrailer(string moviePath)
        {
            string movieName = Path.GetFileNameWithoutExtension(Path.GetFileName(moviePath));
            string link      = await SearchVideo($"{movieName} trailer");

            if (link == null)
            {
                _logger.LogWarning($"No trailer for {movieName}");
                return;
            }

            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
            VideoInfo video = videoInfos.OrderByDescending(x => x.Resolution)
                              .First(x => x.VideoType == VideoType.Mp4 && x.AdaptiveType == AdaptiveType.None);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            var videoDownloader = new VideoDownloader(video,
                                                      Path.Combine(Path.GetDirectoryName(moviePath), $"{video.Title.RemoveIllegalCharacters()}-trailer{video.VideoExtension}"));

            _logger.LogInformation($"Start downloading trailer for {movieName}");
            videoDownloader.Execute();
            _logger.LogInformation($"Downloading trailer for {movieName} finished.");
        }
        private async Task DownloadFromYoutube(VideoInfo videoInfo, Func <Task> downloadFunction)
        {
            this.DownloadProgress = 0;
            this.DownloadFailed   = false;

            try
            {
                await Task.Run(() => DownloadUrlResolver.DecryptDownloadUrl(videoInfo));
            }

            catch (YoutubeParseException)
            {
                this.DownloadFailed = true;
                return;
            }

            try
            {
                await downloadFunction();
            }

            catch (YoutubeDownloadException)
            {
                this.DownloadFailed = true;
            }
        }
Exemple #19
0
        public IHttpActionResult DownloadYT(int channelId, [FromBody] MyUrl url)
        {
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url.Url);
            VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }
            string videoPath       = Path.Combine(FileLocations.BaseDir, video.Title + video.VideoExtension);
            var    videoDownloader = new VideoDownloader(video, videoPath);

            videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);
            videoDownloader.Execute();

            string mp3Path   = Path.Combine(FileLocations.BaseDir, video.Title + ".mp3");
            var    inputFile = new MediaFile {
                Filename = videoPath
            };
            var outputFile = new MediaFile {
                Filename = mp3Path
            };

            using (var engine = new Engine())
            {
                engine.Convert(inputFile, outputFile);
            }

            return(Ok(mp3Path));
        }
Exemple #20
0
        public void Download(string filename)
        {
            var video = GetVideoInfo();

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the audio downloader.
             * The first argument is the video where the audio should be extracted from.
             * The second argument is the path to save the audio file.
             */
            var audioDownloader = new AudioDownloader(video, filename);

            // Register the progress events. We treat the download progress as 85% of the progress and the extraction progress only as 15% of the progress,
            // because the download will take much longer than the audio extraction.
            audioDownloader.DownloadProgressChanged        += (sender, args) => RaiseProgressEvent(args.ProgressPercentage * 0.85);
            audioDownloader.AudioExtractionProgressChanged += (sender, args) => RaiseProgressEvent(85 + args.ProgressPercentage * 0.15);
            audioDownloader.DownloadFinished += (sender, args) => RaiseProgressEvent(101.0);

            /*
             * Execute the audio downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            audioDownloader.Execute();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ProgressBarLoad.Minimum = 0;
            ProgressBarLoad.Maximum = 100;

            IEnumerable <VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(UriTextBox.Text);

            VideoInfo video = videos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(ResolutionCombobox.Text));

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }
            VideoDownloader downloader = new VideoDownloader(video, System.IO.Path.Combine(Environment.CurrentDirectory));

            downloader.DownloadProgressChanged += DownloadProgressChanged;
            Thread thread = new Thread(() =>
            {
                downloader.Execute();
            })
            {
                IsBackground = true
            };

            thread.Start();
        }
        public void DoDownloadVideo(string url)
        {
            DownloadItem downloadItem = new DownloadItem("Last Download", FormatType.None, "Pending", 0);

            downloadList.addToDownloadsList(downloadItem);
            IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url);
            VideoInfo video = videoInfos
                              .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720 || info.Resolution == 480);

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }
            downloadItem.Progress = 0;
            downloadItem.Status   = "Downloading";
            downloadItem.Title    = video.Title;
            downloadItem.Type     = FormatType.Mp4;

            ExtendedVideoDownloader videoDownloader = new ExtendedVideoDownloader(video, Path.Combine(SavePath, video.Title +
                                                                                                      video.VideoExtension), downloadItem);

            videoDownloader.DownloadProgressChanged += new EventHandler <ProgressEventArgs>(OnProgressChangedVideo);
            videoDownloader.DownloadFinished        += new EventHandler(OnDownloadFinishVideo);
            try{
                videoDownloader.Execute();
            }
            catch (Exception exc) {
                MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Download " + video.Title + " failed!\n" + exc.Message);
                md.Run();
                md.Destroy();
            }
        }
Exemple #23
0
        private void DownloadVideo(IEnumerable <VideoInfo> videoInfos)
        {
            VideoInfo video = videoInfos
                              .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == vidQuality);

            textBox2.Text = video.Title;

            /*
             * If the video has a decrypted signature, decipher it
             */

            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                                                      Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                                   RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            // Register the ProgressChanged event and send the progress to progressbar(downloadbar)
            videoDownloader.DownloadProgressChanged += (sender, args) => progressBar1.Value = (int)args.ProgressPercentage;

            //Start download

            videoDownloader.Execute();
        }
Exemple #24
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            try
            {
                IEnumerable <VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(txtUrl.Text);

                VideoInfo video = videos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(cmbQuality.Text));
                cmbQuality.Text = video.Resolution.ToString();
                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }


                VideoDownloader downloader = new VideoDownloader(video, Path.Combine(Application.StartupPath + "\\", video.Title + video.VideoExtension));
                downloader.DownloadProgressChanged += downloader_DownloadProgressChanged;
                Thread thread = new Thread(() => { downloader.Execute(); })
                {
                    IsBackground = true
                };
                thread.Start();
            }
            catch (System.Net.WebException)
            {
                MessageBox.Show("There is a problem with your internet connection");
            }
            catch (System.ArgumentException o)
            {
                MessageBox.Show(o.Message);
            }
        }
Exemple #25
0
        private void button10_Click(object sender, EventArgs e)
        {
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;

            IEnumerable <VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(textBox2.Text);
            VideoInfo video;

            video = videos.First(p => p.VideoType == VideoType.Mp4 && p.Resolution == Convert.ToInt32(comboBox1.Text));
            SaveFileDialog sv = new SaveFileDialog();

            sv.AddExtension = true;
            sv.DefaultExt   = "Mp4";
            if (sv.ShowDialog() == DialogResult.OK)
            {
                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }
                VideoDownloader downloader = new VideoDownloader(video, sv.FileName);
                downloader.DownloadProgressChanged += DownloadProgresChanged;
                downloader.DownloadFinished        += DownloadFinished;
                Thread thread = new Thread(() => { downloader.Execute(); })
                {
                    IsBackground = true
                };
                thread.Start();
            }
        }
        private string DownloadVideoAndReturnPath(VideoSearchComponents video, string outputPath)
        {
            var toDownload = DownloadUrlResolver.GetDownloadUrls(video.getUrl())
                             .OrderBy(x => x.FileSize)
                             .First(x => x.AudioBitrate > 0 && x.FileSize > 0);
            var dl             = new VideoDownloader();
            var videoExtension = toDownload.VideoExtension;

            if (toDownload.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(toDownload);
            }

            var basePath = Path.Combine(outputPath, Path.GetRandomFileName());

            var request  = (HttpWebRequest)WebRequest.Create(toDownload.DownloadUrl);
            var response = (HttpWebResponse)request.GetResponse();

            var outFilePath = basePath + videoExtension;

            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var ms = new MemoryStream();
                response.GetResponseStream().CopyTo(ms);
                var outFile = File.Create(outFilePath);
                ms.WriteTo(outFile);
                outFile.Close();
            }
            return(outFilePath);
        }
 public static void GetYouTubeVideoUri(string uri, int preferredQuality, Action <bool, Uri> resultCallback)
 {
     if (preferredQuality <= 0)
     {
         preferredQuality = 480;
     }
     DownloadUrlResolver.GetDownloadUrlsAsync(uri, false).ContinueWith((Action <Task <IEnumerable <VideoInfo> > >)(task =>
     {
         if (task.Status != TaskStatus.RanToCompletion || task.Result == null || !Enumerable.Any <VideoInfo>(task.Result))
         {
             resultCallback(false, null);
         }
         else
         {
             VideoInfo videoInfo = (VideoInfo)Enumerable.FirstOrDefault <VideoInfo>(Enumerable.Concat <VideoInfo>(Enumerable.OrderBy <VideoInfo, int>(Enumerable.Where <VideoInfo>(task.Result, (Func <VideoInfo, bool>)(video =>
             {
                 if (video.Resolution < preferredQuality)
                 {
                     return(false);
                 }
                 if (video.VideoType != VideoType.Mp4)
                 {
                     return(video.VideoType == VideoType.Mobile);
                 }
                 return(true);
             })), (Func <VideoInfo, int>)(video => video.Resolution)), Enumerable.OrderBy <VideoInfo, int>(Enumerable.Where <VideoInfo>(task.Result, (Func <VideoInfo, bool>)(video =>
             {
                 if (video.Resolution >= preferredQuality)
                 {
                     return(false);
                 }
                 if (video.VideoType != VideoType.Mp4)
                 {
                     return(video.VideoType == VideoType.Mobile);
                 }
                 return(true);
             })), (Func <VideoInfo, int>)(video => - video.Resolution))));
             if (videoInfo == null)
             {
                 resultCallback(false, null);
             }
             else if (videoInfo.RequiresDecryption)
             {
                 try
                 {
                     DownloadUrlResolver.DecryptDownloadUrl(videoInfo);
                     resultCallback(true, new Uri(videoInfo.DownloadUrl));
                 }
                 catch (Exception)
                 {
                     resultCallback(false, null);
                 }
             }
             else
             {
                 resultCallback(true, new Uri(videoInfo.DownloadUrl));
             }
         }
     }));
 }
        protected override CompletionResult DownloadImpDefault(DownloadInfo info)
        {
            if (info.SelectedVideoInfo.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(info.SelectedVideoInfo);
            }
            var forMatTitle = new string(info.SelectedVideoInfo.Title.Where(x => !(Path.GetInvalidPathChars().Contains(x) || Path.GetInvalidFileNameChars().Contains(x))).ToArray()) + info.Extension;

            VideoDownloader downloader = new VideoDownloader(info.SelectedVideoInfo, info.OutputPath + forMatTitle);

            downloader.DownloadProgressChanged += (obj, e) =>
            {
                Reporter.Report(e.ProgressPercentage);
            };

            try
            {
                downloader.Execute();
                return(new CompletionResult("Download Successful:" + Environment.NewLine + info.OutputPath + forMatTitle));
            }

            catch (Exception e)
            {
                return(new CompletionResult(string.Format("Download Failed :( - {0} : {1}", e.GetType().Name, e.Message), e)
                {
                    RanToCompletion = false
                });
            }
        }
        private static void DownloadVideo(IEnumerable <VideoInfo> videoInfos)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                              .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */
            var videoDownloader = new VideoDownloader(video,
                                                      Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                                   RemoveIllegalPathCharacters(video.Title) + video.VideoExtension));

            // Register the ProgressChanged event and print the current progress
            //videoDownloader.DownloadProgressChanged += (sender, args) => Console.WriteLine(args.ProgressPercentage);

            /*
             * Execute the video downloader.
             * For GUI applications note, that this method runs synchronously.
             */
            videoDownloader.Execute();
        }
Exemple #30
0
        public void Get()
        {
            var    tdNow     = DateTime.Now;
            string nowFolder = $"{tdNow.Year}-{tdNow.Month:00}-{tdNow.Day:00}-{tdNow.Hour:00}-{tdNow.Minute:00}";

            foreach (var myVideo in MyVideos)
            {
                IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(VideoBaseUrl + myVideo.Id);

                VideoInfo video = videoInfos
                                  .First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);

                if (video.RequiresDecryption)
                {
                    DownloadUrlResolver.DecryptDownloadUrl(video);
                }

                var savePath = Path.Combine(VideoDownloadDir, nowFolder);
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                var videoDownloader = new VideoDownloader(video,
                                                          Path.Combine(savePath, GetValidDirectoryName(video.Title + video.VideoExtension)));

                videoDownloader.DownloadProgressChanged += (sender, args) =>
                {
                    OnDownload?.Invoke(myVideo.Id, args.ProgressPercentage);
                };

                videoDownloader.Execute();
            }
        }