Tuesday 17 May 2016

Video Download from youtube using url




Step1: Add an aspx page to you current project. In case of mine it is, YouTube.aspx

Step2: In the webform, add the async property to Page attribute. This will informs to ASP.NET engine, the page have async methods.

<%@ Page Language="C#" Async="true" AutoEventWireup="true"

Step3: Add a TextBox and Button controls to webform. TextBox is for accepting YouTube Video URL and Button event contains the core logic for downloading video to target path. (In my case, I am downloading videos to system downloads folder).

<span>Enter YouTube URL:</span>
<b r />
<asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
<b r />
<asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
<b r />
<b r />
<asp:Label ID="lblMessage" Text="" runat="server" />

Step4: YouTube URL's are not an actual video download URLs. We need to track all the URLs from the Page Source. Among all the URLs, get one of the URL having query string with type as 'video/mp4'. At the same time get Video title from Page Source itself. Once we are ready with Video URL and Title, make a request to server to download the video file from YouTube.







protected void btnDownload_Click(object sender, EventArgs e)
{
    DownloadYouTubeVideo();
}


private void DownloadYouTubeVideo()
{
    try
    {
        string sURL = txtYouTubeURL.Text.Trim();
        bool isDownloaded = false;
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 
        Stream responseStream = response.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader reader = new StreamReader(responseStream, encode);
 
        string pageSource = reader.ReadToEnd();
        pageSource = HttpUtility.HtmlDecode(pageSource);               
 
        List<Uri> urls = GetVideoDownloadUrls(pageSource);
 
        string videoTitle = HttpUtility.HtmlDecode(GetVideoTitle(pageSource));               
 
        foreach (Uri url in urls)
        {
            NameValueCollection queryValues = HttpUtility.ParseQueryString(url.OriginalString);
 
            if (queryValues["type"].ToString().StartsWith("video/mp4"))
            {
                string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string sFilePath = string.Format(Path.Combine(downloadPath, "Downloads\\{0}.mp4"), videoTitle);
 
                WebClient client = new WebClient();
                client.DownloadFileCompleted += client_DownloadFileCompleted;                       
                client.DownloadFileAsync(url, sFilePath);
                isDownloaded = true;
 
                break;
            }
        }
 
        if (urls.Count == 0 || !isDownloaded)
        {
            lblMessage.Text = "Unable to locate the Video.";
            return;
        }
    }
    catch (Exception e)
    {
        lblMessage.Text = "An error occurred while downloading video: " + e.Message;
    }
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    lblMessage.Text = "Your video has been downloaded.";
}
private List<Uri> GetVideoDownloadUrls(string pageSource)
{
    string pattern = "url=";
    string queryStringEnd = "&quality";
 
    List<Uri> finalURLs = new List<Uri>();
    List<string> urlList = Regex.Split(pageSource, pattern).ToList<string>();
 
    foreach (string url in urlList)
    {               
        string sURL = HttpUtility.UrlDecode(url).Replace("\\u0026", "&");
 
        int index = sURL.IndexOf(queryStringEnd, StringComparison.Ordinal);
        if (index > 0)
        {
            sURL = sURL.Substring(0, index).Replace("&sig=", "&signature=");
            finalURLs.Add(new Uri(Uri.UnescapeDataString(sURL)));
        }
    }
 
    return finalURLs;           
}

private string GetVideoTitle(string pageSource)
{
    int startIndex = pageSource.IndexOf("<title>");
    int endIndex = pageSource.IndexOf("</title>");
 
    if (startIndex > -1 && endIndex > -1)
    {
        string title = pageSource.Substring(startIndex + 7, endIndex - (startIndex + 7));
        return title;
    }
 
    return "Unknown";
}


Step5: Have a look at your target folder, you will see the Downloaded Video file.

Note: You might need to increase AsyncTimeOut on page directive in order to download larger videos. At the time of downloading video, even if you get TimeOut error, still the download will continue to target folder.

That's It! Thoutgh it is prety simple, it also involves the complexity of finding actual downloadable video URL. 


No comments:

Post a Comment