private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { IList <VideoQuality> list = null; list = YouTubeDownloader.GetYouTubeVideoUrls((string)e.Argument); e.Result = list; }
private void GetVideoButton_Click(object sender, EventArgs e) { string url; try { bool isYoutubeUrl = YoutubeExtractor.DownloadUrlResolver.TryNormalizeYoutubeUrl(urlTextBox.Text, out url); if (!isYoutubeUrl || !Helper.IsValidUrl(url) || !url.ToLowerInvariant().Contains("youtube.com/watch?")) //@org: "www.youtube.com/watch?" { MessageBox.Show(this, "You enter invalid YouTube URL, Please correct it." + Environment.NewLine + Environment.NewLine + "Note: URL should start with:" + Environment.NewLine + "http://www.youtube.com/watch?", "Invalid URL", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { getVideoButton.Enabled = urlTextBox.Enabled = false; progressBar.Visible = true; videoPictureBox.ImageLocation = string.Format(CultureInfo.InvariantCulture, "http://i3.ytimg.com/vi/{0}/default.jpg", YouTubeDownloader.GetVideoIdFromUrl(url)); backgroundWorker.RunWorkerAsync(url); } } catch (Exception ex) { MessageBox.Show(this, ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//private static int ThreadCount = 0; private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { var argument = (ConversionTaskParameters)e.Argument; BackgroundWorker backgroundWorker = argument.BackgroundWorker; backgroundWorker.ReportProgress(0, "Waiting in queue"); semaphore.Wait(); //while (ThreadCount>=2) //{ // backgroundWorker.ReportProgress(0,"Waiting in queue"); // Thread.Sleep(5000); //} ////ThreadCount++; //Interlocked.Increment(ref ThreadCount); //this.CreateDownloadFolder(); if (argument.ConversionProfile != null) { string fileNameWithoutExtension; string uRL; string str3; if (argument.OriginalFileLocation == null) { throw new Exception("Incorect video location specified"); } var result = new VideoResult(); bool flag = false; if ( Regex.Match(argument.OriginalFileLocation, @"(?:[Yy][Oo][Uu][Tt][Uu][Bb][Ee]\.[Cc][Oo][Mm]/((?:(?:(?:watch)|(?:watch_popup))(?:(?:\?|\#|\!|\&)?[\w]*=[\w]*)*(?:\?|\#|\!|\&)?v=(?<vid>-?[\w|-]*))|(?:v/(?<vid>-?[\w|-]*))))|(?:[Yy][Oo][Uu][Tt][Uu].[Bb][Ee]/(?<vid>-?[\w|-]*))") .Success) { string str4; backgroundWorker.ReportProgress(0, "Determining location of the video stream"); var u = new YouTubeDownloader.YouTubeDownloader(); ResourceLocation location = u.ResolveVideoURL(argument.OriginalFileLocation, argument.QualityIndex, argument.ConversionProfile.PreferedType, out str4); if ((location == null) || string.IsNullOrEmpty(location.URL)) { throw new Exception("Unable to obtain initial information about this video"); } flag = ((argument.ConversionProfile.PreferedType != YouTubeDownloader.YouTubeDownloader.VideoStreamTypes.Any) && !string.IsNullOrEmpty(argument.ConversionProfile.AlternativeConversionString)) && (location.StreamType != argument.ConversionProfile.PreferedType); str3 = !flag ? argument.ConversionProfile.ConversionStringTemplate : argument.ConversionProfile.AlternativeConversionString; uRL = location.URL; fileNameWithoutExtension = TextUtil.FormatFileName(str4); result.Title = str4; } else { fileNameWithoutExtension = Path.GetFileNameWithoutExtension(argument.OriginalFileLocation); uRL = argument.OriginalFileLocation; result.Title = fileNameWithoutExtension; result.FileSize = new FileInfo(argument.OriginalFileLocation).Length; str3 = !string.IsNullOrEmpty(argument.ConversionProfile.ConversionStringTemplate) ? argument.ConversionProfile.ConversionStringTemplate : argument.ConversionProfile.AlternativeConversionString; } backgroundWorker.ReportProgress(0, "***" + fileNameWithoutExtension); string str5 = string.Format("{0}.{1}", fileNameWithoutExtension, argument.ConversionProfile.OutputExtension); string str6 = DateTime.Now.Ticks.ToString(); string targetTmpFile = Path.Combine(ApplicationSettings.Instance.DefaultDownloadFolder, str6); string targetFile = Path.Combine(ApplicationSettings.Instance.DefaultDownloadFolder, str5); if (File.Exists(targetFile)) { backgroundWorker.ReportProgress(0, "Exist file:" + fileNameWithoutExtension); return; } long resultSize = 0L; result.ResultPath = targetFile; if (((argument.ConversionProfile.ConversionStringTemplate != null) || flag) && !argument.IndirectConversion) { try { e.Cancel = DownloadHelper.DownloadAndConvert(backgroundWorker, str3, uRL, targetFile, targetTmpFile, out resultSize); } catch (Exception exception) { resultSize = 0L; result.ResultException = exception; } } else { e.Cancel = DownloadHelper.InternalDownload(backgroundWorker, str3, uRL, targetFile, targetTmpFile, out resultSize); } result.FileSize = resultSize; e.Result = result; try { DownloadSubtitle(uRL, fileNameWithoutExtension); } catch (Exception ex) { //todo } } }
//private static readonly string[] elValue = { // "", // "detailpage", // "embedded", // "vevo", //}; public static IList <VideoQuality> GetYouTubeVideoUrls(string videoUrl) { var list = new List <VideoQuality>(); var id = YouTubeDownloader.GetVideoIdFromUrl(videoUrl); var longId = YouTubeDownloader.GetLongVideoIdFromUrl(videoUrl); string stsValue = null; bool ageGateContent = false; string status; string title; string videoDuration; string[] videos; string infoUrl; string infoText; WebClient webClient = new WebClient(); webClient.Proxy = Helper.InitialProxy(); infoUrl = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}&gl=US&hl=en&has_verified=1&bpctr=9999999999", longId); infoText = webClient.DownloadString(infoUrl); ageGateContent = infoText.Contains("player-age-gate-content"); if (ageGateContent) { infoUrl = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/embed/{0}", longId); infoText = webClient.DownloadString(infoUrl); stsValue = Regex.Match(infoText, @"""sts"":([0-9]+?),").Groups[1].Value; } if (ageGateContent && !string.IsNullOrEmpty(stsValue)) { infoUrl = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/get_video_info?video_id={0}&eurl=https://youtube.googleapis.com/v/{1}&sts={2}", longId, id, stsValue); } else { infoUrl = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/get_video_info?&video_id={0}&el=detailpage&ps=default&eurl=&gl=US&hl=en", longId); } infoText = webClient.DownloadString(infoUrl); webClient.Dispose(); var infoValues = HttpUtility.ParseQueryString(infoText); #if DEBUG Dictionary <String, String> testInfoValues = new Dictionary <string, string>(); foreach (String key in infoValues) { testInfoValues.Add(key, infoValues[key]); } #endif String offerButtonText; offerButtonText = infoValues["ypc_offer_button_text"]; if (offerButtonText == null) { offerButtonText = String.Empty; } else { offerButtonText = ", Pay " + offerButtonText; } status = infoValues["status"]; if (status != null && status == "fail") { var errorcode = infoValues["errorcode"]; var errordetail = infoValues["errordetail"]; var reason = infoValues["reason"]; bool boolDetail = false; int intErrorCode = int.Parse(errorcode, CultureInfo.InvariantCulture); if (errordetail != null) { int detail = int.Parse(errordetail, CultureInfo.InvariantCulture); boolDetail = detail == 0 ? false : true; } throw new DownloaderException(reason, intErrorCode, boolDetail); } title = infoValues["title"]; videoDuration = infoValues["length_seconds"]; videos = infoValues["url_encoded_fmt_stream_map"].Split(','); string html = Helper.DownloadWebPage(videoUrl); var regex = new Regex(@"player-(.+?).js"); string playerVersion = regex.Match(html).Result("$1"); foreach (var item in videos) { if (String.IsNullOrEmpty(item)) { throw new ArgumentException("Cannot download \"" + title + "\"" + offerButtonText); } try { var data = HttpUtility.ParseQueryString(item); var fallback_host = data["fallback_host"]; String server = String.Empty; if (!String.IsNullOrEmpty(fallback_host)) { server = Uri.UnescapeDataString(fallback_host); } var signature = data["sig"] ?? data["signature"] ?? data["s"]; // Hans: Added "s" for encrypted signatures var url = Uri.UnescapeDataString(data["url"]) + "&fallback_host=" + server; if (!string.IsNullOrEmpty(signature) && data["s"] == null) { url += "&signature=" + signature; } // If the download-URL contains encrypted signature if (data["s"] != null) { string decryptedSignature; try { // Decrypt the signature decryptedSignature = Decipherer.DecipherWithVersion(signature.ToString(), playerVersion); } catch (Exception e) { //string ex = e.Message; throw new DownloaderException("Signature decipher problem", e); } // The new download-url with decrypted signature url += "&signature=" + decryptedSignature; } var size = GetSize(url); var videoItem = new VideoQuality(); videoItem.DownloadUrl = url; videoItem.VideoSize = size; if (!string.IsNullOrEmpty(title)) { videoItem.VideoTitle = title; } else { videoItem.VideoTitle = "Unknown"; } var tagInfo = new ITagInfo(Uri.UnescapeDataString(data["itag"])); videoItem.Dimension = tagInfo.VideoDimensions; videoItem.Extension = tagInfo.VideoExtensions; if (!string.IsNullOrEmpty(videoDuration)) { videoItem.Length = long.Parse(videoDuration, CultureInfo.InvariantCulture); } list.Add(videoItem); } catch (Exception) { //string ex = e.Message; throw; } } return(list); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { e.Result = YouTubeDownloader.GetYouTubeVideoUrls(videoUrls); }