JavaScriptでYouTube動画DL (2010/11/7時点)

Filed under JavaScript

絶賛JavaScript勉強中。

JavaScriptでYouTubeのページに動画までのリンクを張るスクリプトを書きました。

上の画像のように、タイトル下にリンクが出来ます。

以下、ソースです。

/*
 YouTubeダウンローダー
 2010/11/7 時点
*/
// fmt用の連想配列を作成
var fmt = {};
fmt["fmt5"] = "flv標準画質(古)(FLV1+mp3)";
fmt["fmt6"] = "flv高画質(古)(FLV1+mp3)";
fmt["fmt34"] = "flv標準画質(H264+AAC)";
fmt["fmt35"] = "flv高画質(H264+AAC)";
fmt["fmt13"] = "3GP(低画質 H.263/AMR)";
fmt["fmt17"] = "3GP(高画質 MPEG4/AAC)";
fmt["fmt18"] = "iPod用mp4(H264+AAC)";
fmt["fmt22"] = "mp4(D720p H264+AAC)";
fmt["fmt37"] = "mp4(HD1080p H264+AAC)";

// HTMLを取得し、そこから動画のURLを取得する。
var html = document.getElementsByTagName("html")[0].innerHTML;
var result = html.match(/\"fmt_url_map\": \"([^\"]*)\",/g);
var urls = result[0].split(",");

// 動画のタイトルを取得する。使えない文字は置き換え(適当)。
var video_title = document.getElementById("eow-title").getAttribute("title");
video_title = video_title.replace(/\\/g, "_");
video_title = video_title.replace(/&/g,"&");
video_title = video_title.replace(/\//g,"/");
video_title = video_title.replace(/#/g,"#");
video_title = video_title.replace(/\?/g,"?");
video_title = video_title.replace(/%/g,"%");
video_title = video_title.replace(/\:/g,":");
video_title = video_title.replace(/\*/g,"*");
video_title = video_title.replace(/\|/g,"|");
video_title = video_title.replace(/</g,"<");
video_title = video_title.replace(/>/g,">");
video_title = video_title.replace(/\"/g,"”");

// ID「watch-headline」の要素を取得。これに、DL用のHTMLを追加する。
var headline =  document.getElementById("watch-headline");

// div
var div = document.createElement("div");
div.style.margin = "10px 0 10px 0";
headline.appendChild(div);

// <p>タグ。「Download」を表示
var p = document.createElement("p");
p.innerHTML = "Download.";
p.style.fontWeight = "bold";
p.style.fontSize = "15px";
div.appendChild(p);

// <ul>タグ。リンクをリスト表示
var ul = document.createElement("ul");
ul.style.width = "300px";
ul.style.border = "1px solid #AAAAAA";
ul.style.backgroundColor = "#DDDDDD"
ul.style.padding = "5px";
ul.style.listStyleType = "disc";
div.appendChild(ul);

// 取得した動画のURLを解析して、リンクを作成する。
for(var i=0 ; i<urls.length-1 ; i++)
{
	// URLを解析
	var tmp = urls[i].replace("\"fmt_url_map\"\: \"", "").split("\|");

	// <li>タグ。
    var li = document.createElement("li");
    li.innerHTML = fmt["fmt" + tmp[0]];
    li.style.margin = "0 0 5px 15px";
    li.style.cursor = "Pointer";
    li.style.color = "#0000FF";
    ul.appendChild(li);

    // クリックされたらファイルをDLするようにする。
    var file_title = video_title + " " + fmt["fmt" + tmp[0]];
    var file_url = tmp[1].replace(/\\|\"/g, "");
    li.onclick = new Function("downloadVideo('"+file_url+"','"+file_title+"')");
}

// ダウンロードを行う関数
function downloadVideo(url, title)
{
	location.href =  url + "&title=" + title;
}

Post a Comment

Your email is never published nor shared.