]>
code.delx.au - youtube-cgi/blob - youtube.cgi
3 from __future__
import division
22 MAX_MEMORY_BYTES
= 128 * 1024*1024
23 USER_AGENT
= "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
40 class VideoUnavailable(Exception):
43 def print_form(url
="", msg
=""):
44 script_url
= "http://%s%s" % (os
.environ
["HTTP_HOST"], os
.environ
["REQUEST_URI"])
45 sys
.stdout
.write("Content-Type: application/xhtml+xml\r\n\r\n")
47 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
48 <html xmlns="http://www.w3.org/1999/xhtml">
50 <title>delx.net.au - YouTube Scraper</title>
51 <link rel="stylesheet" type="text/css" href="/style.css"/>
52 <style type="text/css">
62 <h1>delx.net.au - YouTube Scraper</h1>
64 <form action="" method="get">
65 <p>This page will let you easily download YouTube videos to watch offline. It
66 will automatically grab the highest quality version.</p>
67 <div><input type="text" name="url" value="{1}"/></div>
68 <div><input type="submit" value="Download!"/></div>
70 <p>Tip! Use this bookmarklet: <a href="javascript:(function(){window.location='{2}?url='+escape(location);})()">YouTube Download</a>
71 to easily download videos. Right-click the link and add it to bookmarks,
72 then when you're looking at a YouTube page select that bookmark from your
73 browser's bookmarks menu to download the video straight away.</p>
76 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
78 cookiejar
= cookielib
.CookieJar()
79 urlopener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cookiejar
))
84 req
= urllib2
.Request(url
)
86 req
.add_header("Referer", referrer
)
88 req
.add_header("User-Agent", USER_AGENT
)
89 return urlopener
.open(req
)
93 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
97 def append_to_qs(url
, params
):
98 r
= list(urlparse
.urlsplit(url
))
99 qs
= urlparse
.parse_qs(r
[3])
101 r
[3] = urllib
.urlencode(qs
, True)
102 url
= urlparse
.urlunsplit(r
)
105 def convert_from_old_itag(player_config
):
106 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
108 for itag_url
in url_data
["itag"]:
109 pos
= itag_url
.find("url=")
110 url_data
["url"].append(itag_url
[pos
+4:])
111 player_config
["args"]["url_encoded_fmt_stream_map"] = urllib
.urlencode(url_data
, True)
113 def get_player_config(doc
):
115 for script
in doc
.xpath("//script"):
118 for line
in script
.text
.split("\n"):
119 if "yt.playerConfig =" in line
:
122 if p1
>= 0 and p2
> 0:
123 return json
.loads(line
[p1
+1:p2
])
124 if "'PLAYER_CONFIG': " in line
:
127 player_config
= json
.loads(line
[p1
+1:])
128 convert_from_old_itag(player_config
)
131 def get_best_video(player_config
):
132 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
133 url_data
= itertools
.izip_longest(
137 url_data
.get("sig", []),
141 best_extension
= None
142 for video_url
, mimetype
, quality
, signature
in url_data
:
143 mimetype
= mimetype
.split(";")[0]
144 if mimetype
not in MIMETYPES
:
146 extension
= MIMETYPES
[mimetype
]
147 quality
= QUALITIES
.get(quality
.split(",")[0], -1)
148 if best_quality
is None or quality
> best_quality
:
150 video_url
= append_to_qs(video_url
, {"signature": signature
})
152 best_quality
= quality
153 best_extension
= extension
155 return best_url
, best_extension
157 def sanitize_filename(filename
):
159 re
.sub("\s+", " ", filename
.strip())
165 def get_video_url(doc
):
166 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
168 raise VideoUnavailable(unavailable
[0].strip())
170 player_config
= get_player_config(doc
)
171 if not player_config
:
172 raise VideoUnavailable("Could not find video URL")
174 video_url
, extension
= get_best_video(player_config
)
178 title
= doc
.xpath("/html/head/title/text()")[0]
179 filename
= sanitize_filename(title
)
180 filename
+= "." + extension
182 return video_url
, filename
184 def write_video(filename
, video_data
):
185 httpinfo
= video_data
.info()
186 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
187 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
188 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
189 sys
.stdout
.write("\r\n")
190 shutil
.copyfileobj(video_data
, sys
.stdout
)
198 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
203 video_url
, filename
= get_video_url(doc
)
204 video_data
= urlopen(video_url
)
205 write_video(filename
, video_data
)
206 except VideoUnavailable
, e
:
209 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
214 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
218 def copy_with_progress(total_size
, infile
, outfile
):
220 suffixes
= ["", "KiB", "MiB", "GiB"]
221 for i
, suffix
in enumerate(suffixes
):
225 return "%.2f %s" % (size
, suffix
)
227 start_ts
= time
.time()
232 if now
- last_ts
> 0.5:
234 sys
.stdout
.write("\33[2K\r")
235 sys
.stdout
.write("%s / %s (%s/sec)" % (
238 pp_size(bytes_read
/ (now
- start_ts
)),
242 buf
= infile
.read(32768)
246 bytes_read
+= len(buf
)
255 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
258 video_url
, filename
= get_video_url(doc
)
259 video_data
= urlopen(video_url
)
260 outfile
= open(filename
, "w")
261 total_size
= int(video_data
.info().getheader("Content-Length"))
262 print "Downloading", filename
.encode("utf-8")
263 copy_with_progress(total_size
, video_data
, outfile
)
268 if __name__
== "__main__":
269 resource
.setrlimit(resource
.RLIMIT_AS
, (MAX_MEMORY_BYTES
, MAX_MEMORY_BYTES
))
270 if os
.environ
.has_key("SCRIPT_NAME"):
275 except KeyboardInterrupt: