Skip to content

Instantly share code, notes, and snippets.

@Yasushi
Created September 18, 2008 05:21
Show Gist options
  • Save Yasushi/11379 to your computer and use it in GitHub Desktop.
Save Yasushi/11379 to your computer and use it in GitHub Desktop.
CmdUtils.CreateCommand({
name: "download-youtube",
description: "Download YouTube FLV",
icon: "http://s.ytimg.com/yt/favicon-vfl1123.ico",
_is_video: function(doc) {
var uri = Utils.url(doc.documentURI);
return(uri.host.indexOf("youtube.com") != -1 && uri.path.match("[?&]v=([^&]+)"));
},
_video_id: function(doc) {
var uri = Utils.url(doc.documentURI);
if(!uri.path.match("[?&]v=([^&]+)")) return;
return RegExp.$1;
},
_video_hash: function(doc) {
var params = jQuery("#movie_player", doc.body).attr("flashvars").split("&");
for (var i in params) {
if(params[i].match("\\??t=(.*)"))
return RegExp.$1;
}
},
_video_uri: function(doc) {
return "http://youtube.com/get_video?video_id="+this._video_id(doc) + "&t=" + this._video_hash(doc);
},
_video_title: function(doc) {
return jQuery("#watch-vid-title h1", doc.body).text();
},
preview: function(previewBlock, directObj) {
var doc = Application.activeWindow.activeTab.document;
if (!this._is_video(doc)) {
previewBlock.innerHTML = "Download YouYube movie."
} else {
previewBlock.innerHTML = "Download \"" + this._video_title(doc) + "\"";
}
},
execute: function() {
var doc = CmdUtils.getDocumentInsecure();
if (!this._is_video(doc)) return;
var title = this._video_title(doc);
var filepicker = Components.classes['@mozilla.org/filepicker;1']
.createInstance(Components.interfaces.nsIFilePicker);
filepicker.init(CmdUtils.getWindowInsecure(), "download youtube",
Components.interfaces.nsIFilePicker.modeSave);
filepicker.defaultString = title + ".flv";
if (filepicker.show()==Components.interfaces.nsIFilePicker.returnCancel) return;
var targetURI = Components.classes['@mozilla.org/network/io-service;1']
.getService(Components.interfaces.nsIIOService)
.newURI(this._video_uri(doc), null, null);
var dm = Components.classes["@mozilla.org/download-manager;1"]
.getService(Components.interfaces.nsIDownloadManager);
var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
.createInstance(Components.interfaces.nsIWebBrowserPersist);
var download = dm.addDownload(0, targetURI, filepicker.fileURL, filepicker.file.leafName, null, null, null, null, persist);
persist.progressListener = download;
persist.saveURI(targetURI, null, null, null, null, filepicker.file);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment