Saturday, September 6, 2008

How to download Youtube Videos using Javascript?

You can use Javascript and AJAX technologies to download Youtube videos on your web page that is all client based solution. I have outlined the steps to extract the values needed to form the URL to download the Youtube videos.

First we should know Youtube download URL summary:
Youtube videos can be downloaded from the URL http://youtube.com/get_video.php?=&l=&t=&sk=&fs=1. All we need are the values of video_id, l , t, and sk. My script extracts these values from Youtube's HTML page.

The summary of the script:
Download the source of the page of the URL http://in.youtube.com/watch?v=VDAGIFjt6m4
(
VDAGIFjt6m4 is the ID of a video). Look for a particular pattern in the source. Once the pattern is extracted convert it into JSON format. From the JSON data walk through and get the values of id, l, t, and sk.

More detailed algorithm.
1) Get the page source from Youtube using the public URL - http://in.youtube.com/watch?v=VDAGIFjt6m4
In the example VDAGIFjt6m4 is the ID. The ID can change depending upon your video.

2) The source will be entire page which has the Youtube video embedded we are only interested in the following HTML -
var swfArgs = {"BASE_YT_URL": "http://in.youtube.com/", "vq": null, "sourceid": "y", "video_id": "VDAGIFjt6m4", "l": 65, "sk": "mkKFIRWXheJgUGsaU6Bx2LsnWvZldVraC", "fmt_map": "6/720000/7/0/0", "t": "OEgsToPDskK0DEe01pPPKzJJ700ykmac", "hl": "en", "plid": "AARWNMbnD8zgFCZ0AAAAoAAYAAA", "sdetail": "p%3A/"};

3) Extract the interested line using the following Regular Expression "swfArgs(\\s*)=(\\s*)\\{(.*)\\}"

var ytPattern = "swfArgs(\\s*)=(\\s*)\\{(.*)\\}";
var re = new RegExp(ytPattern);
var matchVar = eval('({' + re.exec(strDoc) + '})');
Now from matchVar get the values like matchVar['video_id'] or matchVar['sk']

Once you the values substitute in
http://youtube.com/get_video.php?video_id=&l=&t=&sk=&fs=1

Disclaimer: If Youtube changes its page this script will not work. This is working as of Sept 6 2008.