]>
code.delx.au - youtube-cgi/blob - youtube.cgi
18 MAX_MEMORY_BYTES
= 128 * 1024*1024
19 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: text/html\r\n\r\n")
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
= http
.cookiejar
.CookieJar()
75 urlopener
= urllib
.request
.build_opener(urllib
.request
.HTTPCookieProcessor(cookiejar
))
78 def urlopen(url
, offset
=None):
79 if url
.startswith("//"):
81 if not url
.startswith("http://") and not url
.startswith("https://"):
82 url
= "https://www.youtube.com" + url
85 req
= urllib
.request
.Request(url
)
89 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
.getheader("Content-Range")
100 tokens
= content_range
.split()
101 assert tokens
[0] == "bytes"
102 start
= int(tokens
[1].split("-")[0])
103 assert start
== offset
106 def parse_url(url
, parser
):
108 parser
.feed(f
.read().decode("utf-8"))
112 def append_to_qs(url
, params
):
113 r
= list(urllib
.parse
.urlsplit(url
))
114 qs
= urllib
.parse
.parse_qs(r
[3])
116 r
[3] = urllib
.parse
.urlencode(qs
, True)
117 url
= urllib
.parse
.urlunsplit(r
)
120 def get_player_config(scripts
):
122 for script
in scripts
:
123 for line
in script
.split("\n"):
124 s
= "ytplayer.config = {"
126 p1
= line
.find(s
) + len(s
) - 1
127 p2
= line
.find("};", p1
) + 1
128 if p1
>= 0 and p2
> 0:
129 return json
.loads(line
[p1
:p2
])
131 def extract_js(script
):
132 PREFIX
= "var _yt_player={};(function(g){var window=this;"
133 SUFFIX
= ";})(_yt_player);\n"
134 assert script
.startswith(PREFIX
)
135 assert script
.endswith(SUFFIX
)
137 return script
[len(PREFIX
):-len(SUFFIX
)]
139 def find_func_name(script
):
140 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
141 FUNC_PARAMS
= R
"(\([a-zA-Z]+\.s\))"
142 TERMINATOR
= R
"[,;\)]"
143 PATTERN
= FUNC_NAME
+ FUNC_PARAMS
+ TERMINATOR
145 match
= re
.search(PATTERN
, script
)
146 func_name
= match
.groups()[0]
149 def decode_signature(js_url
, signature
):
151 script
= f
.read().decode("utf-8")
154 func_name
= find_func_name(script
)
157 "func_name": func_name
,
158 "signature": json
.dumps(signature
),
159 "code": json
.dumps(extract_js(script
)),
161 p
= subprocess
.Popen(
165 stdin
=subprocess
.PIPE
,
166 stdout
=subprocess
.PIPE
168 js_decode_script
= ("""
169 var vm = require('vm');
178 pushState: function(){}
184 signature: %(signature)s,
185 transformed_signature: null,
186 g: function(){} // this is _yt_player
188 sandbox.window = sandbox;
190 var code_string = %(code)s + ';';
191 var exec_string = 'transformed_signature = %(func_name)s(signature);';
192 vm.runInNewContext(code_string + exec_string, sandbox);
194 console.log(sandbox.transformed_signature);
197 p
.stdin
.write(js_decode_script
.encode("utf-8"))
200 transformed_signature
= p
.stdout
.read().decode("utf-8").strip()
202 raise Exception("js failed to execute: %d" % p
.returncode
)
204 return transformed_signature
206 def get_best_video(player_config
):
207 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
208 js_url
= player_config
["assets"]["js"]
212 best_extension
= None
213 for url_data
in url_data_list
:
214 url_data
= urllib
.parse
.parse_qs(url_data
)
215 mimetype
= url_data
["type"][0].split(";")[0]
216 quality
= url_data
["quality"][0]
218 if "stereo3d" in url_data
:
220 if quality
not in QUALITIES
:
222 if mimetype
not in MIMETYPES
:
225 extension
= MIMETYPES
[mimetype
]
226 quality
= QUALITIES
.get(quality
, -1)
228 if best_quality
is not None and quality
< best_quality
:
231 video_url
= url_data
["url"][0]
232 if "sig" in url_data
:
233 signature
= url_data
["sig"][0]
234 elif "s" in url_data
:
235 signature
= decode_signature(js_url
, url_data
["s"][0])
240 video_url
= append_to_qs(video_url
, {"signature": signature
})
243 best_quality
= quality
244 best_extension
= extension
246 return best_url
, best_extension
248 def sanitize_filename(filename
):
250 re
.sub("\s+", " ", filename
.strip())
256 def get_video_url(page
):
257 player_config
= get_player_config(page
.scripts
)
258 if not player_config
:
259 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
261 video_url
, extension
= get_best_video(player_config
)
265 filename
= sanitize_filename(page
.title
)
266 filename
+= "." + extension
268 return video_url
, filename
270 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
274 self
.unavailable_message
= None
277 def handle_starttag(self
, tag
, attrs
):
279 self
._handle
_title
(tag
, attrs
)
280 self
._handle
_unavailable
_message
(tag
, attrs
)
281 self
._handle
_script
(tag
, attrs
)
283 def handle_endtag(self
, tag
):
284 self
.handle_data
= self
._ignore
_data
286 def _ignore_data(self
, _
):
289 def _handle_title(self
, tag
, attrs
):
291 self
.handle_data
= self
._handle
_title
_data
293 def _handle_title_data(self
, data
):
294 self
.title
= data
.strip()
296 def _handle_unavailable_message(self
, tag
, attrs
):
297 if attrs
.get("id", None) == "unavailable-message":
298 self
.handle_data
= self
._handle
_unavailable
_message
_data
300 def _handle_unavailable_message_data(self
, data
):
301 self
.unavailable_message
= data
.strip()
303 def _handle_script(self
, tag
, attrs
):
305 self
.handle_data
= self
._handle
_script
_data
307 def _handle_script_data(self
, data
):
309 self
.scripts
.append(data
)
311 def write_video(filename
, video_data
):
312 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
313 sys
.stdout
.buffer.write(
314 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
315 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
317 sys
.stdout
.buffer.write(
318 b
"Content-Length: {0}\r\n"
319 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
321 sys
.stdout
.buffer.write(b
"\r\n")
322 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
330 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
334 page
= YouTubeVideoPageParser()
336 video_url
, filename
= get_video_url(page
)
337 video_data
= urlopen(video_url
)
338 except VideoUnavailable
as e
:
341 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
343 except Exception as e
:
346 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
350 write_video(filename
, video_data
)
353 suffixes
= ["", "KiB", "MiB", "GiB"]
354 for i
, suffix
in enumerate(suffixes
):
358 return "%.2f %s" % (size
, suffix
)
360 def copy_with_progress(content_length
, infile
, outfile
):
364 rate
= last_bytes_read
/ (now
- last_ts
)
365 sys
.stdout
.write("\33[2K\r")
366 sys
.stdout
.write("%s / %s (%s/sec)" % (
368 pp_size(content_length
),
378 if now
- last_ts
> 0.5:
383 buf
= infile
.read(32768)
387 last_bytes_read
+= len(buf
)
388 bytes_read
+= len(buf
)
398 print("Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
401 page
= YouTubeVideoPageParser()
403 video_url
, filename
= get_video_url(page
)
404 print("Downloading", filename
)
406 outfile
= open(filename
, "ab")
407 offset
= outfile
.tell()
409 print("Resuming download from", pp_size(offset
))
414 video_data
= urlopen(video_url
, offset
)
415 except urllib
.error
.HTTPError
as e
:
417 print("File is complete!")
422 content_length
= int(video_data
.getheader("Content-Length"))
423 if total_size
is None:
424 total_size
= content_length
427 copy_with_progress(content_length
, video_data
, outfile
)
432 if outfile
.tell() != total_size
:
434 offset
= outfile
.tell()
435 if old_offset
== offset
:
437 print("Restarting download from", pp_size(offset
))
444 if __name__
== "__main__":
445 if "SCRIPT_NAME" in os
.environ
:
450 except KeyboardInterrupt:
451 print("\nExiting...")