]>
code.delx.au - youtube-cgi/blob - youtube.cgi
d25a857e19144e00216d667a3204bd5d95d0a1ef
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 matchMedia: () => ({matches: () => {}, media: ''}),
185 signature: %(signature)s,
186 transformed_signature: null,
187 g: function(){} // this is _yt_player
189 sandbox.window = sandbox;
191 var code_string = %(code)s + ';';
192 var exec_string = 'transformed_signature = %(func_name)s(signature);';
193 vm.runInNewContext(code_string + exec_string, sandbox);
195 console.log(sandbox.transformed_signature);
198 p
.stdin
.write(js_decode_script
.encode("utf-8"))
201 transformed_signature
= p
.stdout
.read().decode("utf-8").strip()
203 raise Exception("js failed to execute: %d" % p
.returncode
)
205 return transformed_signature
207 def get_best_video(player_config
):
208 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
209 js_url
= player_config
["assets"]["js"]
213 best_extension
= None
214 for url_data
in url_data_list
:
215 url_data
= urllib
.parse
.parse_qs(url_data
)
216 mimetype
= url_data
["type"][0].split(";")[0]
217 quality
= url_data
["quality"][0]
219 if "stereo3d" in url_data
:
221 if quality
not in QUALITIES
:
223 if mimetype
not in MIMETYPES
:
226 extension
= MIMETYPES
[mimetype
]
227 quality
= QUALITIES
.get(quality
, -1)
229 if best_quality
is not None and quality
< best_quality
:
232 video_url
= url_data
["url"][0]
233 if "sig" in url_data
:
234 signature
= url_data
["sig"][0]
235 elif "s" in url_data
:
236 signature
= decode_signature(js_url
, url_data
["s"][0])
241 video_url
= append_to_qs(video_url
, {"signature": signature
})
244 best_quality
= quality
245 best_extension
= extension
247 return best_url
, best_extension
249 def sanitize_filename(filename
):
251 re
.sub("\s+", " ", filename
.strip())
257 def get_video_url(page
):
258 player_config
= get_player_config(page
.scripts
)
259 if not player_config
:
260 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
262 video_url
, extension
= get_best_video(player_config
)
266 filename
= sanitize_filename(page
.title
)
267 filename
+= "." + extension
269 return video_url
, filename
271 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
275 self
.unavailable_message
= None
278 def handle_starttag(self
, tag
, attrs
):
280 self
._handle
_title
(tag
, attrs
)
281 self
._handle
_unavailable
_message
(tag
, attrs
)
282 self
._handle
_script
(tag
, attrs
)
284 def handle_endtag(self
, tag
):
285 self
.handle_data
= self
._ignore
_data
287 def _ignore_data(self
, _
):
290 def _handle_title(self
, tag
, attrs
):
292 self
.handle_data
= self
._handle
_title
_data
294 def _handle_title_data(self
, data
):
295 self
.title
= data
.strip()
297 def _handle_unavailable_message(self
, tag
, attrs
):
298 if attrs
.get("id", None) == "unavailable-message":
299 self
.handle_data
= self
._handle
_unavailable
_message
_data
301 def _handle_unavailable_message_data(self
, data
):
302 self
.unavailable_message
= data
.strip()
304 def _handle_script(self
, tag
, attrs
):
306 self
.handle_data
= self
._handle
_script
_data
308 def _handle_script_data(self
, data
):
310 self
.scripts
.append(data
)
312 def write_video(filename
, video_data
):
313 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
314 sys
.stdout
.buffer.write(
315 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
316 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
318 sys
.stdout
.buffer.write(
319 b
"Content-Length: {0}\r\n"
320 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
322 sys
.stdout
.buffer.write(b
"\r\n")
323 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
331 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
335 page
= YouTubeVideoPageParser()
337 video_url
, filename
= get_video_url(page
)
338 video_data
= urlopen(video_url
)
339 except VideoUnavailable
as e
:
342 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
344 except Exception as e
:
347 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
351 write_video(filename
, video_data
)
354 suffixes
= ["", "KiB", "MiB", "GiB"]
355 for i
, suffix
in enumerate(suffixes
):
359 return "%.2f %s" % (size
, suffix
)
361 def copy_with_progress(content_length
, infile
, outfile
):
365 rate
= last_bytes_read
/ (now
- last_ts
)
366 sys
.stdout
.write("\33[2K\r")
367 sys
.stdout
.write("%s / %s (%s/sec)" % (
369 pp_size(content_length
),
379 if now
- last_ts
> 0.5:
384 buf
= infile
.read(32768)
388 last_bytes_read
+= len(buf
)
389 bytes_read
+= len(buf
)
399 print("Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
402 page
= YouTubeVideoPageParser()
404 video_url
, filename
= get_video_url(page
)
405 print("Downloading", filename
)
407 outfile
= open(filename
, "ab")
408 offset
= outfile
.tell()
410 print("Resuming download from", pp_size(offset
))
415 video_data
= urlopen(video_url
, offset
)
416 except urllib
.error
.HTTPError
as e
:
418 print("File is complete!")
423 content_length
= int(video_data
.getheader("Content-Length"))
424 if total_size
is None:
425 total_size
= content_length
428 copy_with_progress(content_length
, video_data
, outfile
)
433 if outfile
.tell() != total_size
:
435 offset
= outfile
.tell()
436 if old_offset
== offset
:
438 print("Restarting download from", pp_size(offset
))
445 if __name__
== "__main__":
446 if "SCRIPT_NAME" in os
.environ
:
451 except KeyboardInterrupt:
452 print("\nExiting...")