d25a857e19144e00216d667a3204bd5d95d0a1ef
[youtube-cgi] / youtube.cgi
1 #!/usr/bin/env python3
2
3 import cgi
4 import html.parser
5 import http.cookiejar
6 import json
7 import os
8 import re
9 import shutil
10 import subprocess
11 import sys
12 import time
13 import urllib.error
14 import urllib.parse
15 import urllib.request
16
17
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"
20
21 MIMETYPES = {
22 "video/mp4": "mp4",
23 "video/x-flv": "flv",
24 "video/3gpp": "3gp",
25 }
26
27 QUALITIES = {
28 "hd1080": 5,
29 "hd720": 4,
30 "large": 3,
31 "medium": 2,
32 "small": 1,
33 }
34
35
36 class VideoUnavailable(Exception):
37 pass
38
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")
42 sys.stdout.write("""
43 <!DOCTYPE html>
44 <html>
45 <head>
46 <title>delx.net.au - YouTube Scraper</title>
47 <link rel="stylesheet" type="text/css" href="/style.css">
48 <style type="text/css">
49 input[type="text"] {
50 width: 100%;
51 }
52 .error {
53 color: red;
54 }
55 </style>
56 </head>
57 <body>
58 <h1>delx.net.au - YouTube Scraper</h1>
59 {0}
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>
65 </form>
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>
70 </body>
71 </html>
72 """.replace("{0}", msg).replace("{1}", url).replace("{2}", script_url))
73
74 cookiejar = http.cookiejar.CookieJar()
75 urlopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
76 referrer = ""
77
78 def urlopen(url, offset=None):
79 if url.startswith("//"):
80 url = "https:" + url
81 if not url.startswith("http://") and not url.startswith("https://"):
82 url = "https://www.youtube.com" + url
83
84 global referrer
85 req = urllib.request.Request(url)
86 if not referrer:
87 referrer = url
88 else:
89 req.add_header("Referer", referrer)
90
91 req.add_header("User-Agent", USER_AGENT)
92
93 if offset:
94 req.add_header("Range", "bytes=%d-" % offset)
95
96 res = urlopener.open(req)
97
98 content_range = res.getheader("Content-Range")
99 if content_range:
100 tokens = content_range.split()
101 assert tokens[0] == "bytes"
102 start = int(tokens[1].split("-")[0])
103 assert start == offset
104 return res
105
106 def parse_url(url, parser):
107 f = urlopen(url)
108 parser.feed(f.read().decode("utf-8"))
109 parser.close()
110 f.close()
111
112 def append_to_qs(url, params):
113 r = list(urllib.parse.urlsplit(url))
114 qs = urllib.parse.parse_qs(r[3])
115 qs.update(params)
116 r[3] = urllib.parse.urlencode(qs, True)
117 url = urllib.parse.urlunsplit(r)
118 return url
119
120 def get_player_config(scripts):
121 player_config = None
122 for script in scripts:
123 for line in script.split("\n"):
124 s = "ytplayer.config = {"
125 if s in line:
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])
130
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)
136
137 return script[len(PREFIX):-len(SUFFIX)]
138
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
144
145 match = re.search(PATTERN, script)
146 func_name = match.groups()[0]
147 return func_name
148
149 def decode_signature(js_url, signature):
150 f = urlopen(js_url)
151 script = f.read().decode("utf-8")
152 f.close()
153
154 func_name = find_func_name(script)
155
156 params = {
157 "func_name": func_name,
158 "signature": json.dumps(signature),
159 "code": json.dumps(extract_js(script)),
160 }
161 p = subprocess.Popen(
162 "node",
163 shell=True,
164 close_fds=True,
165 stdin=subprocess.PIPE,
166 stdout=subprocess.PIPE
167 )
168 js_decode_script = ("""
169 var vm = require('vm');
170
171 var sandbox = {
172 location: {
173 hash: '',
174 href: '',
175 protocol: 'http:'
176 },
177 history: {
178 pushState: function(){}
179 },
180 document: {},
181 navigator: {
182 userAgent: ''
183 },
184 matchMedia: () => ({matches: () => {}, media: ''}),
185 signature: %(signature)s,
186 transformed_signature: null,
187 g: function(){} // this is _yt_player
188 };
189 sandbox.window = sandbox;
190
191 var code_string = %(code)s + ';';
192 var exec_string = 'transformed_signature = %(func_name)s(signature);';
193 vm.runInNewContext(code_string + exec_string, sandbox);
194
195 console.log(sandbox.transformed_signature);
196 """ % params)
197
198 p.stdin.write(js_decode_script.encode("utf-8"))
199 p.stdin.close()
200
201 transformed_signature = p.stdout.read().decode("utf-8").strip()
202 if p.wait() != 0:
203 raise Exception("js failed to execute: %d" % p.returncode)
204
205 return transformed_signature
206
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"]
210
211 best_url = None
212 best_quality = None
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]
218
219 if "stereo3d" in url_data:
220 continue
221 if quality not in QUALITIES:
222 continue
223 if mimetype not in MIMETYPES:
224 continue
225
226 extension = MIMETYPES[mimetype]
227 quality = QUALITIES.get(quality, -1)
228
229 if best_quality is not None and quality < best_quality:
230 continue
231
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])
237 else:
238 signature = None
239
240 if signature:
241 video_url = append_to_qs(video_url, {"signature": signature})
242
243 best_url = video_url
244 best_quality = quality
245 best_extension = extension
246
247 return best_url, best_extension
248
249 def sanitize_filename(filename):
250 return (
251 re.sub("\s+", " ", filename.strip())
252 .replace("\\", "-")
253 .replace("/", "-")
254 .replace("\0", " ")
255 )
256
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")
261
262 video_url, extension = get_best_video(player_config)
263 if not video_url:
264 return None, None
265
266 filename = sanitize_filename(page.title)
267 filename += "." + extension
268
269 return video_url, filename
270
271 class YouTubeVideoPageParser(html.parser.HTMLParser):
272 def __init__(self):
273 super().__init__()
274 self.title = None
275 self.unavailable_message = None
276 self.scripts = []
277
278 def handle_starttag(self, tag, attrs):
279 attrs = dict(attrs)
280 self._handle_title(tag, attrs)
281 self._handle_unavailable_message(tag, attrs)
282 self._handle_script(tag, attrs)
283
284 def handle_endtag(self, tag):
285 self.handle_data = self._ignore_data
286
287 def _ignore_data(self, _):
288 pass
289
290 def _handle_title(self, tag, attrs):
291 if tag == "title":
292 self.handle_data = self._handle_title_data
293
294 def _handle_title_data(self, data):
295 self.title = data.strip()
296
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
300
301 def _handle_unavailable_message_data(self, data):
302 self.unavailable_message = data.strip()
303
304 def _handle_script(self, tag, attrs):
305 if tag == "script":
306 self.handle_data = self._handle_script_data
307
308 def _handle_script_data(self, data):
309 if data:
310 self.scripts.append(data)
311
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"))
317 )
318 sys.stdout.buffer.write(
319 b"Content-Length: {0}\r\n"
320 .replace(b"{0}", video_data.getheader("Content-Length").encode("utf-8"))
321 )
322 sys.stdout.buffer.write(b"\r\n")
323 shutil.copyfileobj(video_data, sys.stdout.buffer)
324 video_data.close()
325
326 def cgimain():
327 args = cgi.parse()
328 try:
329 url = args["url"][0]
330 except:
331 print_form(url="http://www.youtube.com/watch?v=FOOBAR")
332 return
333
334 try:
335 page = YouTubeVideoPageParser()
336 parse_url(url, page)
337 video_url, filename = get_video_url(page)
338 video_data = urlopen(video_url)
339 except VideoUnavailable as e:
340 print_form(
341 url=url,
342 msg="<p class='error'>Sorry, there was an error: %s</p>" % cgi.escape(e.args[0])
343 )
344 except Exception as e:
345 print_form(
346 url=url,
347 msg="<p class='error'>Sorry, there was an error. Check your URL?</p>"
348 )
349 return
350
351 write_video(filename, video_data)
352
353 def pp_size(size):
354 suffixes = ["", "KiB", "MiB", "GiB"]
355 for i, suffix in enumerate(suffixes):
356 if size < 1024:
357 break
358 size /= 1024
359 return "%.2f %s" % (size, suffix)
360
361 def copy_with_progress(content_length, infile, outfile):
362 def print_status():
363 rate = 0
364 if now != last_ts:
365 rate = last_bytes_read / (now - last_ts)
366 sys.stdout.write("\33[2K\r")
367 sys.stdout.write("%s / %s (%s/sec)" % (
368 pp_size(bytes_read),
369 pp_size(content_length),
370 pp_size(rate),
371 ))
372 sys.stdout.flush()
373
374 last_ts = 0
375 last_bytes_read = 0
376 bytes_read = 0
377 while True:
378 now = time.time()
379 if now - last_ts > 0.5:
380 print_status()
381 last_ts = now
382 last_bytes_read = 0
383
384 buf = infile.read(32768)
385 if not buf:
386 break
387 outfile.write(buf)
388 last_bytes_read += len(buf)
389 bytes_read += len(buf)
390
391 # Newline at the end
392 print_status()
393 print()
394
395 def main():
396 try:
397 url = sys.argv[1]
398 except:
399 print("Usage: %s http://youtube.com/watch?v=FOOBAR" % sys.argv[0], file=sys.stderr)
400 sys.exit(1)
401
402 page = YouTubeVideoPageParser()
403 parse_url(url, page)
404 video_url, filename = get_video_url(page)
405 print("Downloading", filename)
406
407 outfile = open(filename, "ab")
408 offset = outfile.tell()
409 if offset > 0:
410 print("Resuming download from", pp_size(offset))
411 total_size = None
412
413 while True:
414 try:
415 video_data = urlopen(video_url, offset)
416 except urllib.error.HTTPError as e:
417 if e.code == 416:
418 print("File is complete!")
419 break
420 else:
421 raise
422
423 content_length = int(video_data.getheader("Content-Length"))
424 if total_size is None:
425 total_size = content_length
426
427 try:
428 copy_with_progress(content_length, video_data, outfile)
429 except IOError as e:
430 print()
431
432 video_data.close()
433 if outfile.tell() != total_size:
434 old_offset = offset
435 offset = outfile.tell()
436 if old_offset == offset:
437 time.sleep(1)
438 print("Restarting download from", pp_size(offset))
439 else:
440 break
441
442 outfile.close()
443
444
445 if __name__ == "__main__":
446 if "SCRIPT_NAME" in os.environ:
447 cgimain()
448 else:
449 try:
450 main()
451 except KeyboardInterrupt:
452 print("\nExiting...")
453 sys.exit(1)
454