]>
code.delx.au - youtube-cgi/blob - youtube.cgi
da6109c27b47ced33f153b60319cf7ebf8e55a36
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"
39 class VideoUnavailable(Exception):
42 def print_form(url
="", msg
=""):
43 script_url
= "http://%s%s" % (os
.environ
["HTTP_HOST"], os
.environ
["REQUEST_URI"])
44 sys
.stdout
.write("Content-Type: application/xhtml+xml\r\n\r\n")
46 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
47 <html xmlns="http://www.w3.org/1999/xhtml">
49 <title>delx.net.au - YouTube Scraper</title>
50 <link rel="stylesheet" type="text/css" href="/style.css"/>
51 <style type="text/css">
61 <h1>delx.net.au - YouTube Scraper</h1>
63 <form action="" method="get">
64 <p>This page will let you easily download YouTube videos to watch offline. It
65 will automatically grab the highest quality version.</p>
66 <div><input type="text" name="url" value="{1}"/></div>
67 <div><input type="submit" value="Download!"/></div>
69 <p>Tip! Use this bookmarklet: <a href="javascript:(function(){window.location='{2}?url='+escape(location);})()">YouTube Download</a>
70 to easily download videos. Right-click the link and add it to bookmarks,
71 then when you're looking at a YouTube page select that bookmark from your
72 browser's bookmarks menu to download the video straight away.</p>
75 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
77 cookiejar
= cookielib
.CookieJar()
78 urlopener
= urllib2
.build_opener(urllib2
.HTTPCookieProcessor(cookiejar
))
81 def urlopen(url
, offset
=None):
82 if url
.startswith("//"):
86 req
= urllib2
.Request(url
)
90 req
.add_header("Referer", referrer
)
92 req
.add_header("User-Agent", USER_AGENT
)
95 req
.add_header("Range", "bytes=%d-" % offset
)
97 res
= urlopener
.open(req
)
99 content_range
= res
.info().getheader("Content-Range")
101 tokens
= content_range
.split()
102 assert tokens
[0] == "bytes"
103 start
= int(tokens
[1].split("-")[0])
104 assert start
== offset
109 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
113 def append_to_qs(url
, params
):
114 r
= list(urlparse
.urlsplit(url
))
115 qs
= urlparse
.parse_qs(r
[3])
117 r
[3] = urllib
.urlencode(qs
, True)
118 url
= urlparse
.urlunsplit(r
)
121 def get_player_config(doc
):
123 for script
in doc
.xpath("//script"):
126 for line
in script
.text
.split("\n"):
127 s
= "ytplayer.config = {"
129 p1
= line
.find(s
) + len(s
) - 1
130 p2
= line
.find("};", p1
) + 1
131 if p1
>= 0 and p2
> 0:
132 return json
.loads(line
[p1
:p2
])
134 def extract_js(script
):
135 PREFIX
= "(function(){"
137 assert script
.startswith(PREFIX
)
138 assert script
.endswith(SUFFIX
)
140 return script
[len(PREFIX
):-len(SUFFIX
)]
142 def find_func_name(script
):
143 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
144 FUNC_PARAMS
= R
"(\([a-zA-Z]+\.s\))"
145 PATTERN
= FUNC_NAME
+ FUNC_PARAMS
+ ";"
147 match
= re
.search(PATTERN
, script
)
148 func_name
= match
.groups()[0]
151 def decode_signature(js_url
, signature
):
152 script
= urlopen(js_url
).read()
153 func_name
= find_func_name(script
)
156 "func_name": func_name
,
157 "signature": json
.dumps(signature
),
158 "code": json
.dumps(extract_js(script
)),
160 p
= subprocess
.Popen(
164 stdin
=subprocess
.PIPE
,
165 stdout
=subprocess
.PIPE
167 js_decode_script
= ("""
168 var vm = require("vm");
174 pushState: function(){}
179 signature: %(signature)s,
180 transformed_signature: null
183 var execstring = ";transformed_signature = %(func_name)s(signature);";
184 vm.runInNewContext(%(code)s + execstring, sandbox);
186 console.log(sandbox.transformed_signature);
189 p
.stdin
.write(js_decode_script
)
192 transformed_signature
= p
.stdout
.read().strip()
194 raise Exception("js failed to execute: %d" % p
.returncode
)
196 return transformed_signature
198 def get_best_video(player_config
):
199 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
200 js_url
= player_config
["assets"]["js"]
204 best_extension
= None
205 for url_data
in url_data_list
:
206 url_data
= urlparse
.parse_qs(url_data
)
207 mimetype
= url_data
["type"][0].split(";")[0]
208 quality
= url_data
["quality"][0]
210 if url_data
.has_key("stereo3d"):
212 if quality
not in QUALITIES
:
214 if mimetype
not in MIMETYPES
:
217 extension
= MIMETYPES
[mimetype
]
218 quality
= QUALITIES
.get(quality
, -1)
220 if best_quality
is not None and quality
< best_quality
:
223 video_url
= url_data
["url"][0]
224 if "sig" in url_data
:
225 signature
= url_data
["sig"][0]
226 elif "s" in url_data
:
227 signature
= decode_signature(js_url
, url_data
["s"][0])
232 video_url
= append_to_qs(video_url
, {"signature": signature
})
235 best_quality
= quality
236 best_extension
= extension
238 return best_url
, best_extension
240 def sanitize_filename(filename
):
242 re
.sub("\s+", " ", filename
.strip())
248 def get_video_url(doc
):
249 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
251 raise VideoUnavailable(unavailable
[0].strip())
253 player_config
= get_player_config(doc
)
254 if not player_config
:
255 raise VideoUnavailable("Could not find video URL")
257 video_url
, extension
= get_best_video(player_config
)
261 title
= doc
.xpath("/html/head/title/text()")[0]
262 filename
= sanitize_filename(title
)
263 filename
+= "." + extension
265 return video_url
, filename
267 def write_video(filename
, video_data
):
268 httpinfo
= video_data
.info()
269 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
270 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
271 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
272 sys
.stdout
.write("\r\n")
273 shutil
.copyfileobj(video_data
, sys
.stdout
)
281 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
286 video_url
, filename
= get_video_url(doc
)
287 video_data
= urlopen(video_url
)
288 write_video(filename
, video_data
)
289 except VideoUnavailable
, e
:
292 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
297 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
302 suffixes
= ["", "KiB", "MiB", "GiB"]
303 for i
, suffix
in enumerate(suffixes
):
307 return "%.2f %s" % (size
, suffix
)
309 def copy_with_progress(content_length
, infile
, outfile
):
313 rate
= last_bytes_read
/ (now
- last_ts
)
314 sys
.stdout
.write("\33[2K\r")
315 sys
.stdout
.write("%s / %s (%s/sec)" % (
317 pp_size(content_length
),
327 if now
- last_ts
> 0.5:
332 buf
= infile
.read(32768)
336 last_bytes_read
+= len(buf
)
337 bytes_read
+= len(buf
)
347 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
351 video_url
, filename
= get_video_url(doc
)
352 print "Downloading", filename
.encode("utf-8")
354 outfile
= open(filename
, "a")
355 offset
= outfile
.tell()
357 print "Resuming download from", pp_size(offset
)
362 video_data
= urlopen(video_url
, offset
)
363 except urllib2
.HTTPError
, e
:
365 print "File is complete!"
370 content_length
= int(video_data
.info().getheader("Content-Length"))
371 if total_size
is None:
372 total_size
= content_length
375 copy_with_progress(content_length
, video_data
, outfile
)
380 if outfile
.tell() != total_size
:
382 offset
= outfile
.tell()
383 if old_offset
== offset
:
385 print "Restarting download from", pp_size(offset
)
392 if __name__
== "__main__":
393 ### resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY_BYTES, MAX_MEMORY_BYTES))
394 if os
.environ
.has_key("SCRIPT_NAME"):
399 except KeyboardInterrupt: