]>
code.delx.au - youtube-cgi/blob - youtube.cgi
17fcf1697b517ec053abb2ff98a6dfd74202ea93
20 MAX_MEMORY_BYTES
= 128 * 1024*1024
21 USER_AGENT
= "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
36 class VideoUnavailable(Exception):
39 def print_form(url
="", msg
=""):
40 script_url
= "http://%s%s" % (os
.environ
["HTTP_HOST"], os
.environ
["REQUEST_URI"])
41 sys
.stdout
.write("Content-Type: application/xhtml+xml\r\n\r\n")
43 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
44 <html xmlns="http://www.w3.org/1999/xhtml">
46 <title>delx.net.au - YouTube Scraper</title>
47 <link rel="stylesheet" type="text/css" href="/style.css"/>
48 <style type="text/css">
58 <h1>delx.net.au - YouTube Scraper</h1>
60 <form action="" method="get">
61 <p>This page will let you easily download YouTube videos to watch offline. It
62 will automatically grab the highest quality version.</p>
63 <div><input type="text" name="url" value="{1}"/></div>
64 <div><input type="submit" value="Download!"/></div>
66 <p>Tip! Use this bookmarklet: <a href="javascript:(function(){window.location='{2}?url='+escape(location);})()">YouTube Download</a>
67 to easily download videos. Right-click the link and add it to bookmarks,
68 then when you're looking at a YouTube page select that bookmark from your
69 browser's bookmarks menu to download the video straight away.</p>
72 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
74 cookiejar
= cookielib
.CookieJar()
75 urlopener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cookiejar
))
80 req
= urllib2
.Request(url
)
82 req
.add_header("Referer", referrer
)
84 req
.add_header("User-Agent", USER_AGENT
)
85 return urlopener
.open(req
)
89 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
93 def append_to_qs(url
, params
):
94 r
= list(urlparse
.urlsplit(url
))
95 qs
= urlparse
.parse_qs(r
[3])
97 r
[3] = urllib
.urlencode(qs
, True)
98 url
= urlparse
.urlunsplit(r
)
101 def convert_from_old_itag(player_config
):
102 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
104 for itag_url
in url_data
["itag"]:
105 pos
= itag_url
.find("url=")
106 url_data
["url"].append(itag_url
[pos
+4:])
107 player_config
["args"]["url_encoded_fmt_stream_map"] = urllib
.urlencode(url_data
, True)
109 def get_player_config(doc
):
111 for script
in doc
.xpath("//script"):
114 for line
in script
.text
.split("\n"):
115 if "yt.playerConfig =" in line
:
118 if p1
>= 0 and p2
> 0:
119 return json
.loads(line
[p1
+1:p2
])
120 if "'PLAYER_CONFIG': " in line
:
123 player_config
= json
.loads(line
[p1
+1:])
124 convert_from_old_itag(player_config
)
127 def get_best_video(player_config
):
128 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
129 url_data
= itertools
.izip_longest(
133 url_data
.get("sig", []),
137 best_extension
= None
138 for video_url
, mimetype
, quality
, signature
in url_data
:
139 mimetype
= mimetype
.split(";")[0]
140 if mimetype
not in MIMETYPES
:
142 extension
= MIMETYPES
[mimetype
]
143 quality
= QUALITIES
.get(quality
.split(",")[0], -1)
144 if best_quality
is None or quality
> best_quality
:
146 video_url
= append_to_qs(video_url
, {"signature": signature
})
148 best_quality
= quality
149 best_extension
= extension
151 return best_url
, best_extension
153 def sanitize_filename(filename
):
155 re
.sub("\s+", " ", filename
.strip())
161 def get_video_url(doc
):
162 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
164 raise VideoUnavailable(unavailable
[0].strip())
166 player_config
= get_player_config(doc
)
167 if not player_config
:
168 raise VideoUnavailable("Could not find video URL")
170 video_url
, extension
= get_best_video(player_config
)
174 title
= doc
.xpath("/html/head/title/text()")[0]
175 filename
= sanitize_filename(title
)
176 filename
+= "." + extension
178 return video_url
, filename
180 def write_video(filename
, video_data
):
181 httpinfo
= video_data
.info()
182 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
183 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
184 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
185 sys
.stdout
.write("\r\n")
186 shutil
.copyfileobj(video_data
, sys
.stdout
)
194 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
199 video_url
, filename
= get_video_url(doc
)
200 video_data
= urlopen(video_url
)
201 write_video(filename
, video_data
)
202 except VideoUnavailable
, e
:
205 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
210 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
214 def copy_with_progress(total_size
, infile
, outfile
):
216 suffixes
= ["", "KiB", "MiB", "GiB"]
217 for i
, suffix
in enumerate(suffixes
):
221 return "%d %s" % (size
, suffix
)
223 start_ts
= time
.time()
228 if now
- last_ts
> 0.5:
230 sys
.stdout
.write("\33[2K\r")
231 sys
.stdout
.write("%s / %s (%s/sec)" % (
234 pp_size(bytes_read
/ (now
- start_ts
)),
238 buf
= infile
.read(32768)
242 bytes_read
+= len(buf
)
248 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
251 video_url
, filename
= get_video_url(doc
)
252 video_data
= urlopen(video_url
)
253 outfile
= open(filename
, "w")
254 total_size
= int(video_data
.info().getheader("Content-Length"))
255 print "Downloading", filename
.encode("utf-8")
256 copy_with_progress(total_size
, video_data
, outfile
)
261 if __name__
== "__main__":
262 resource
.setrlimit(resource
.RLIMIT_AS
, (MAX_MEMORY_BYTES
, MAX_MEMORY_BYTES
))
263 if os
.environ
.has_key("SCRIPT_NAME"):
268 except KeyboardInterrupt: