]>
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):
83 req
= urllib2
.Request(url
)
85 req
.add_header("Referer", referrer
)
88 req
.add_header("User-Agent", USER_AGENT
)
91 req
.add_header("Range", "bytes=%d-" % offset
)
93 res
= urlopener
.open(req
)
95 content_range
= res
.info().getheader("Content-Range")
97 tokens
= content_range
.split()
98 assert tokens
[0] == "bytes"
99 start
= int(tokens
[1].split("-")[0])
100 assert start
== offset
105 doc
= html
.parse(f
, html
.HTMLParser(encoding
="utf-8", recover
=True))
109 def append_to_qs(url
, params
):
110 r
= list(urlparse
.urlsplit(url
))
111 qs
= urlparse
.parse_qs(r
[3])
113 r
[3] = urllib
.urlencode(qs
, True)
114 url
= urlparse
.urlunsplit(r
)
117 def convert_from_old_itag(player_config
):
118 url_data
= urlparse
.parse_qs(player_config
["args"]["url_encoded_fmt_stream_map"])
120 for itag_url
in url_data
["itag"]:
121 pos
= itag_url
.find("url=")
122 url_data
["url"].append(itag_url
[pos
+4:])
123 player_config
["args"]["url_encoded_fmt_stream_map"] = urllib
.urlencode(url_data
, True)
125 def get_player_config(doc
):
127 for script
in doc
.xpath("//script"):
130 for line
in script
.text
.split("\n"):
131 if "yt.playerConfig =" in line
:
134 if p1
>= 0 and p2
> 0:
135 return json
.loads(line
[p1
+1:p2
])
136 if "ytplayer.config =" in line
:
137 p1
= line
.find("ytplayer.config =")
139 if p1
>= 0 and p2
> 0:
140 return json
.loads(line
[p1
+18:p2
])
141 if "'PLAYER_CONFIG': " in line
:
144 player_config
= json
.loads(line
[p1
+1:])
145 convert_from_old_itag(player_config
)
148 def decode_signature(js_url
, s
):
149 script
= urlopen(js_url
).read()
150 func_name
= re
.search(R
"\b([a-z]+)\([a-z]+\.s\);", script
).groups()[0]
151 p1
= script
.find("function " + func_name
)
152 p2
= script
.find("}", p1
)
153 func_block
= script
[p1
:p2
+1]
155 p
= subprocess
.Popen(
159 stdin
=subprocess
.PIPE
,
160 stdout
=subprocess
.PIPE
162 p
.stdin
.write(func_block
+ "\n")
163 p
.stdin
.write("console.log(%s('%s'));\n" % (func_name
, s
))
166 signature
= p
.stdout
.read().strip()
168 raise Exception("js failed to execute: %d" % p
.returncode
)
172 def get_best_video(player_config
):
173 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
174 js_url
= player_config
["assets"]["js"]
178 best_extension
= None
179 for url_data
in url_data_list
:
180 url_data
= urlparse
.parse_qs(url_data
)
181 mimetype
= url_data
["type"][0].split(";")[0]
182 quality
= url_data
["quality"][0]
184 if quality
not in QUALITIES
:
186 if mimetype
not in MIMETYPES
:
189 extension
= MIMETYPES
[mimetype
]
190 quality
= QUALITIES
.get(quality
, -1)
192 if best_quality
is not None and quality
< best_quality
:
195 video_url
= url_data
["url"][0]
196 if "sig" in url_data
:
197 signature
= url_data
["sig"][0]
199 signature
= decode_signature(js_url
, url_data
["s"][0])
200 video_url
= append_to_qs(video_url
, {"signature": signature
})
203 best_quality
= quality
204 best_extension
= extension
206 return best_url
, best_extension
208 def sanitize_filename(filename
):
210 re
.sub("\s+", " ", filename
.strip())
216 def get_video_url(doc
):
217 unavailable
= doc
.xpath("//div[@id='unavailable-message']/text()")
219 raise VideoUnavailable(unavailable
[0].strip())
221 player_config
= get_player_config(doc
)
222 if not player_config
:
223 raise VideoUnavailable("Could not find video URL")
225 video_url
, extension
= get_best_video(player_config
)
229 title
= doc
.xpath("/html/head/title/text()")[0]
230 filename
= sanitize_filename(title
)
231 filename
+= "." + extension
233 return video_url
, filename
235 def write_video(filename
, video_data
):
236 httpinfo
= video_data
.info()
237 encoded_filename
= urllib
.quote(filename
.encode("utf-8"))
238 sys
.stdout
.write("Content-Disposition: attachment; filename*=UTF-8''%s\r\n" % encoded_filename
)
239 sys
.stdout
.write("Content-Length: %s\r\n" % httpinfo
.getheader("Content-Length"))
240 sys
.stdout
.write("\r\n")
241 shutil
.copyfileobj(video_data
, sys
.stdout
)
249 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
254 video_url
, filename
= get_video_url(doc
)
255 video_data
= urlopen(video_url
)
256 write_video(filename
, video_data
)
257 except VideoUnavailable
, e
:
260 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.message
)
265 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
270 suffixes
= ["", "KiB", "MiB", "GiB"]
271 for i
, suffix
in enumerate(suffixes
):
275 return "%.2f %s" % (size
, suffix
)
277 def copy_with_progress(content_length
, infile
, outfile
):
281 rate
= last_bytes_read
/ (now
- last_ts
)
282 sys
.stdout
.write("\33[2K\r")
283 sys
.stdout
.write("%s / %s (%s/sec)" % (
285 pp_size(content_length
),
295 if now
- last_ts
> 0.5:
300 buf
= infile
.read(32768)
304 last_bytes_read
+= len(buf
)
305 bytes_read
+= len(buf
)
315 print >>sys
.stderr
, "Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0]
319 video_url
, filename
= get_video_url(doc
)
320 print "Downloading", filename
.encode("utf-8")
322 outfile
= open(filename
, "a")
323 offset
= outfile
.tell()
325 print "Resuming download from", pp_size(offset
)
330 video_data
= urlopen(video_url
, offset
)
331 except urllib2
.HTTPError
, e
:
333 print "File is complete!"
338 content_length
= int(video_data
.info().getheader("Content-Length"))
339 if total_size
is None:
340 total_size
= content_length
343 copy_with_progress(content_length
, video_data
, outfile
)
348 if outfile
.tell() != total_size
:
350 offset
= outfile
.tell()
351 if old_offset
== offset
:
353 print "Restarting download from", pp_size(offset
)
360 if __name__
== "__main__":
361 ### resource.setrlimit(resource.RLIMIT_AS, (MAX_MEMORY_BYTES, MAX_MEMORY_BYTES))
362 if os
.environ
.has_key("SCRIPT_NAME"):
367 except KeyboardInterrupt: