]>
code.delx.au - youtube-cgi/blob - youtube.cgi
d6273bae80b9eced9dae63abc52aa4727931c3c2
3 from __future__
import division
21 MAX_MEMORY_BYTES
= 128 * 1024*1024
22 USER_AGENT
= "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
47 class VideoUnavailable(Exception):
50 def print_form(url
="", msg
=""):
51 script_url
= "http://%s%s" % (os
.environ
["HTTP_HOST"], os
.environ
["REQUEST_URI"])
52 sys
.stdout
.write("Content-Type: application/xhtml+xml\r\n\r\n")
54 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
55 <html xmlns="http://www.w3.org/1999/xhtml">
57 <title>delx.net.au - YouTube Scraper</title>
58 <link rel="stylesheet" type="text/css" href="/style.css"/>
59 <style type="text/css">
69 <h1>delx.net.au - YouTube Scraper</h1>
71 <form action="" method="get">
72 <p>This page will let you easily download YouTube videos to watch offline. It
73 will automatically grab the highest quality version.</p>
74 <div><input type="text" name="url" value="{1}"/></div>
75 <div><input type="submit" value="Download!"/></div>
77 <p>Tip! Use this bookmarklet: <a href="javascript:(function(){window.location='{2}?url='+escape(location);})()">YouTube Download</a>
78 to easily download videos. Right-click the link and add it to bookmarks,
79 then when you're looking at a YouTube page select that bookmark from your
80 browser's bookmarks menu to download the video straight away.</p>
83 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
85 cookiejar
= cookielib
.CookieJar()
86 urlopener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cookiejar
))
89 def urlopen(url
, offset
=None):
90 if url
.startswith("//"):
94 req
= urllib2
.Request(url
)
98 req
.add_header("Referer", referrer
)
100 req
.add_header("User-Agent", USER_AGENT
)
103 req
.add_header("Range", "bytes=%d-" % offset
)
105 res
= urlopener
.open(req
)
107 content_range
= res
.info().getheader("Content-Range")
109 tokens
= content_range
.split()
110 assert tokens
[0] == "bytes"
111 start
= int(tokens
[1].split("-")[0])
112 assert start
== offset
117 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
121 def append_to_qs(url
, params
):
122 r
= list(urlparse
.urlsplit(url
))
123 qs
= urlparse
.parse_qs(r
[3])
125 r
[3] = urllib
.urlencode(qs
, True)
126 url
= urlparse
.urlunsplit(r
)
129 def get_player_config(doc
):
131 for script
in doc
.xpath("//script"):
134 for line
in script
.text
.split("\n"):
135 s
= "ytplayer.config = {"
137 p1
= line
.find(s
) + len(s
) - 1
138 p2
= line
.find("};", p1
) + 1
139 if p1
>= 0 and p2
> 0:
140 return json
.loads(line
[p1
:p2
])
142 def extract_js(script
):
143 PREFIX
= "(function(){"
145 assert script
.startswith(PREFIX
)
146 assert script
.endswith(SUFFIX
)
148 return script
[len(PREFIX
):-len(SUFFIX
)]
150 def find_func_name(script
):
151 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
152 FUNC_PARAMS
= R
"(\([a-zA-Z]+\.s\))"
153 PATTERN
= FUNC_NAME
+ FUNC_PARAMS
+ ";"
155 match
= re
.search(PATTERN
, script
)
156 func_name
= match
.groups()[0]
159 def decode_signature(js_url
, s
):
160 script
= urlopen(js_url
).read()
161 func_name
= find_func_name(script
)
163 p
= subprocess
.Popen(
167 stdin
=subprocess
.PIPE
,
168 stdout
=subprocess
.PIPE
172 w(extract_js(script
))
173 w("console.log(%s('%s'));\n" % (func_name
, s
))
176 signature
= p
.stdout
.read().strip()
178 raise Exception("js failed to execute: %d" % p
.returncode
)
182 def get_best_video(player_config
):
183 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
184 js_url
= player_config
["assets"]["js"]
188 best_extension
= None
189 for url_data
in url_data_list
:
190 url_data
= urlparse
.parse_qs(url_data
)
191 mimetype
= url_data
["type"][0].split(";")[0]
192 quality
= url_data
["quality"][0]
194 if url_data
.has_key("stereo3d"):
196 if quality
not in QUALITIES
:
198 if mimetype
not in MIMETYPES
:
201 extension
= MIMETYPES
[mimetype
]
202 quality
= QUALITIES
.get(quality
, -1)
204 if best_quality
is not None and quality
< best_quality
:
207 video_url
= url_data
["url"][0]
208 if "sig" in url_data
:
209 signature
= url_data
["sig"][0]
210 elif "s" in url_data
:
211 signature
= decode_signature(js_url
, url_data
["s"][0])
216 video_url
= append_to_qs(video_url
, {"signature": signature
})
219 best_quality
= quality
220 best_extension
= extension
222 return best_url
, best_extension
224 def sanitize_filename(filename
):
226 re
.sub("\s+", " ", filename
.strip())
232 def get_video_url(doc
):
233 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
235 raise VideoUnavailable(unavailable
[0].strip())
237 player_config
= get_player_config(doc
)
238 if not player_config
:
239 raise VideoUnavailable("Could not find video URL")
241 video_url
, extension
= get_best_video(player_config
)
245 title
= doc
.xpath("/html/head/title/text()")[0]
246 filename
= sanitize_filename(title
)
247 filename
+= "." + extension
249 return video_url
, filename
251 def write_video(filename
, video_data
):
252 httpinfo
= video_data
.info()
253 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
254 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
255 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
256 sys
.stdout
.write("\r\n")
257 shutil
.copyfileobj(video_data
, sys
.stdout
)
265 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
270 video_url
, filename
= get_video_url(doc
)
271 video_data
= urlopen(video_url
)
272 write_video(filename
, video_data
)
273 except VideoUnavailable
, e
:
276 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
281 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
286 suffixes
= ["", "KiB", "MiB", "GiB"]
287 for i
, suffix
in enumerate(suffixes
):
291 return "%.2f %s" % (size
, suffix
)
293 def copy_with_progress(content_length
, infile
, outfile
):
297 rate
= last_bytes_read
/ (now
- last_ts
)
298 sys
.stdout
.write("\33[2K\r")
299 sys
.stdout
.write("%s / %s (%s/sec)" % (
301 pp_size(content_length
),
311 if now
- last_ts
> 0.5:
316 buf
= infile
.read(32768)
320 last_bytes_read
+= len(buf
)
321 bytes_read
+= len(buf
)
331 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
335 video_url
, filename
= get_video_url(doc
)
336 print "Downloading", filename
.encode("utf-8")
338 outfile
= open(filename
, "a")
339 offset
= outfile
.tell()
341 print "Resuming download from", pp_size(offset
)
346 video_data
= urlopen(video_url
, offset
)
347 except urllib2
.HTTPError
, e
:
349 print "File is complete!"
354 content_length
= int(video_data
.info().getheader("Content-Length"))
355 if total_size
is None:
356 total_size
= content_length
359 copy_with_progress(content_length
, video_data
, outfile
)
364 if outfile
.tell() != total_size
:
366 offset
= outfile
.tell()
367 if old_offset
== offset
:
369 print "Restarting download from", pp_size(offset
)
376 if __name__
== "__main__":
377 ### resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY_BYTES, MAX_MEMORY_BYTES))
378 if os
.environ
.has_key("SCRIPT_NAME"):
383 except KeyboardInterrupt: