]>
code.delx.au - youtube-cgi/blob - youtube.cgi
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
)
88 req
.add_header("Referer", referrer
)
91 req
.add_header("User-Agent", USER_AGENT
)
94 req
.add_header("Range", "bytes=%d-" % offset
)
96 res
= urlopener
.open(req
)
98 content_range
= res
.info().getheader("Content-Range")
100 tokens
= content_range
.split()
101 assert tokens
[0] == "bytes"
102 start
= int(tokens
[1].split("-")[0])
103 assert start
== offset
108 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
112 def append_to_qs(url
, params
):
113 r
= list(urlparse
.urlsplit(url
))
114 qs
= urlparse
.parse_qs(r
[3])
116 r
[3] = urllib
.urlencode(qs
, True)
117 url
= urlparse
.urlunsplit(r
)
120 def convert_from_old_itag(player_config
):
121 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
123 for itag_url
in url_data
["itag"]:
124 pos
= itag_url
.find("url=")
125 url_data
["url"].append(itag_url
[pos
+4:])
126 player_config
["args"]["url_encoded_fmt_stream_map"] = urllib
.urlencode(url_data
, True)
128 def get_player_config(doc
):
130 for script
in doc
.xpath("//script"):
133 for line
in script
.text
.split("\n"):
134 if "yt.playerConfig =" in line
:
137 if p1
>= 0 and p2
> 0:
138 return json
.loads(line
[p1
+1:p2
])
139 if "ytplayer.config =" in line
:
140 p1
= line
.find("ytplayer.config =")
142 if p1
>= 0 and p2
> 0:
143 return json
.loads(line
[p1
+18:p2
])
144 if "'PLAYER_CONFIG': " in line
:
147 player_config
= json
.loads(line
[p1
+1:])
148 convert_from_old_itag(player_config
)
151 def extract_function(output
, script
, func_name
):
152 p1
= script
.find("function " + func_name
+ "(")
153 p2
= script
.find("}", p1
)
154 code
= script
[p1
:p2
+1]
156 deps
= re
.findall(R
"[^\.][= ]([\$0-9a-zA-Z]+)\(", code
)
158 deps
.remove(func_name
)
160 extract_function(output
, script
, dep
)
162 def decode_signature(js_url
, s
):
163 script
= urlopen(js_url
).read()
164 func_name
= re
.search(R
"\b([a-zA-Z]+)\([a-zA-Z]+\.s\);", script
).groups()[0]
167 extract_function(codes
, script
, func_name
)
169 p
= subprocess
.Popen(
173 stdin
=subprocess
.PIPE
,
174 stdout
=subprocess
.PIPE
177 p
.stdin
.write(code
+ "\n")
178 p
.stdin
.write("console.log(%s('%s'));\n" % (func_name
, s
))
181 signature
= p
.stdout
.read().strip()
183 raise Exception("js failed to execute: %d" % p
.returncode
)
187 def get_best_video(player_config
):
188 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
189 js_url
= player_config
["assets"]["js"]
193 best_extension
= None
194 for url_data
in url_data_list
:
195 url_data
= urlparse
.parse_qs(url_data
)
196 mimetype
= url_data
["type"][0].split(";")[0]
197 quality
= url_data
["quality"][0]
199 if url_data
.has_key("stereo3d"):
201 if quality
not in QUALITIES
:
203 if mimetype
not in MIMETYPES
:
206 extension
= MIMETYPES
[mimetype
]
207 quality
= QUALITIES
.get(quality
, -1)
209 if best_quality
is not None and quality
< best_quality
:
212 video_url
= url_data
["url"][0]
213 if "sig" in url_data
:
214 signature
= url_data
["sig"][0]
215 elif "s" in url_data
:
216 signature
= decode_signature(js_url
, url_data
["s"][0])
221 video_url
= append_to_qs(video_url
, {"signature": signature
})
224 best_quality
= quality
225 best_extension
= extension
227 return best_url
, best_extension
229 def sanitize_filename(filename
):
231 re
.sub("\s+", " ", filename
.strip())
237 def get_video_url(doc
):
238 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
240 raise VideoUnavailable(unavailable
[0].strip())
242 player_config
= get_player_config(doc
)
243 if not player_config
:
244 raise VideoUnavailable("Could not find video URL")
246 video_url
, extension
= get_best_video(player_config
)
250 title
= doc
.xpath("/html/head/title/text()")[0]
251 filename
= sanitize_filename(title
)
252 filename
+= "." + extension
254 return video_url
, filename
256 def write_video(filename
, video_data
):
257 httpinfo
= video_data
.info()
258 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
259 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
260 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
261 sys
.stdout
.write("\r\n")
262 shutil
.copyfileobj(video_data
, sys
.stdout
)
270 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
275 video_url
, filename
= get_video_url(doc
)
276 video_data
= urlopen(video_url
)
277 write_video(filename
, video_data
)
278 except VideoUnavailable
, e
:
281 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
286 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
291 suffixes
= ["", "KiB", "MiB", "GiB"]
292 for i
, suffix
in enumerate(suffixes
):
296 return "%.2f %s" % (size
, suffix
)
298 def copy_with_progress(content_length
, infile
, outfile
):
302 rate
= last_bytes_read
/ (now
- last_ts
)
303 sys
.stdout
.write("\33[2K\r")
304 sys
.stdout
.write("%s / %s (%s/sec)" % (
306 pp_size(content_length
),
316 if now
- last_ts
> 0.5:
321 buf
= infile
.read(32768)
325 last_bytes_read
+= len(buf
)
326 bytes_read
+= len(buf
)
336 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
340 video_url
, filename
= get_video_url(doc
)
341 print "Downloading", filename
.encode("utf-8")
343 outfile
= open(filename
, "a")
344 offset
= outfile
.tell()
346 print "Resuming download from", pp_size(offset
)
351 video_data
= urlopen(video_url
, offset
)
352 except urllib2
.HTTPError
, e
:
354 print "File is complete!"
359 content_length
= int(video_data
.info().getheader("Content-Length"))
360 if total_size
is None:
361 total_size
= content_length
364 copy_with_progress(content_length
, video_data
, outfile
)
369 if outfile
.tell() != total_size
:
371 offset
= outfile
.tell()
372 if old_offset
== offset
:
374 print "Restarting download from", pp_size(offset
)
381 if __name__
== "__main__":
382 ### resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY_BYTES, MAX_MEMORY_BYTES))
383 if os
.environ
.has_key("SCRIPT_NAME"):
388 except KeyboardInterrupt: