]> code.delx.au - youtube-cgi/blob - youtube.cgi
Fixed for latest changes
[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 MOZILLA_RELEASE_URL = "https://www.mozilla.org/en-US/firefox/releases/"
19 USER_AGENT_TEMPLATE = "Mozilla/5.0 (X11; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/%s"
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 class NotYouTube(Exception):
40 pass
41
42 def print_form(url="", msg=""):
43 script_url = "https://%s%s" % (os.environ["HTTP_HOST"], os.environ["REQUEST_URI"])
44 sys.stdout.write("Content-Type: text/html\r\n\r\n")
45 sys.stdout.write("""
46 <!DOCTYPE html>
47 <html>
48 <head>
49 <title>delx.net.au - YouTube Scraper</title>
50 <link rel="stylesheet" type="text/css" href="/style.css">
51 <style type="text/css">
52 input[type="text"] {
53 width: 100%;
54 }
55 .error {
56 color: red;
57 }
58 </style>
59 </head>
60 <body>
61 <h1>delx.net.au - YouTube Scraper</h1>
62 {0}
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>
68 </form>
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>
73 </body>
74 </html>
75 """.replace("{0}", msg).replace("{1}", url).replace("{2}", script_url))
76
77 cookiejar = http.cookiejar.CookieJar()
78 urlopener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar))
79 referrer = ""
80 user_agent = None
81
82 def urlopen(url, offset=None):
83 global user_agent
84 if not user_agent:
85 page = MozillaReleasesPageParser()
86 with urllib.request.urlopen(MOZILLA_RELEASE_URL) as f:
87 page.feed(f.read().decode("utf-8"))
88 page.close()
89 user_agent = USER_AGENT_TEMPLATE % page.latest_release
90
91 if url.startswith("//"):
92 url = "https:" + url
93 if not url.startswith("http://") and not url.startswith("https://"):
94 url = "https://www.youtube.com" + url
95
96 global referrer
97 req = urllib.request.Request(url)
98 if not referrer:
99 referrer = url
100 else:
101 req.add_header("Referer", referrer)
102
103 req.add_header("User-Agent", user_agent)
104
105 if offset:
106 req.add_header("Range", "bytes=%d-" % offset)
107
108 res = urlopener.open(req)
109
110 content_range = res.getheader("Content-Range")
111 if content_range:
112 tokens = content_range.split()
113 assert tokens[0] == "bytes"
114 start = int(tokens[1].split("-")[0])
115 assert start == offset
116 return res
117
118 def validate_url(url):
119 parsed_url = urllib.parse.urlparse(url)
120 scheme_ok = parsed_url.scheme == "https"
121 host = parsed_url.netloc.lstrip("www.").lstrip("m.")
122 host_ok = host in ["youtube.com", "youtu.be"]
123
124 if scheme_ok and host_ok:
125 return
126 else:
127 raise NotYouTube()
128
129 def load_parse_url(url, parser):
130 f = urlopen(url)
131 parser.feed(f.read().decode("utf-8"))
132 parser.close()
133 f.close()
134
135 def append_to_qs(url, params):
136 r = list(urllib.parse.urlsplit(url))
137 qs = urllib.parse.parse_qs(r[3])
138 qs.update(params)
139 r[3] = urllib.parse.urlencode(qs, True)
140 url = urllib.parse.urlunsplit(r)
141 return url
142
143 def get_player_config(scripts):
144 config_strings = [
145 ("ytcfg.set({\"", 2, "});", 1),
146 ("ytInitialPlayerResponse = {\"", 2, "};", 1),
147 ]
148 player_config = {}
149 for script in scripts:
150 for line in script.split("\n"):
151 for s1, off1, s2, off2 in config_strings:
152 if s1 in line:
153 p1 = line.find(s1) + len(s1) - off1
154 p2 = line.find(s2, p1) + off2
155 if p1 >= 0 and p2 > 0:
156 player_config.update(json.loads(line[p1:p2]))
157 return player_config
158
159 def extract_js(script):
160 PREFIX = "var _yt_player={};(function(g){var window=this;"
161 SUFFIX = ";})(_yt_player);\n"
162 assert script.startswith(PREFIX)
163 assert script.endswith(SUFFIX)
164
165 return script[len(PREFIX):-len(SUFFIX)]
166
167 def find_cipher_func(script):
168 FUNC_NAME = R"([a-zA-Z0-9$]+)"
169 DECODE_URI_COMPONENT = R"(\(decodeURIComponent)?"
170 FUNC_PARAMS = R"(\([a-zA-Z,\.]+\.s\))"
171 TERMINATOR = R"[,;\)]"
172 PATTERN = FUNC_NAME + DECODE_URI_COMPONENT + FUNC_PARAMS + TERMINATOR
173
174 match = re.search(PATTERN, script)
175 func_name = match.groups()[0]
176 return func_name
177
178 def construct_url_from_cipher_result(cipher_result):
179 for k, v in cipher_result.items():
180 if isinstance(v, str) and v.startswith("https://"):
181 temp_url = v
182 break
183 else:
184 raise Exception("Could not find URL-like string in cipher result!")
185
186 for k, v in cipher_result.items():
187 if isinstance(v, dict):
188 params = {}
189 for k2, v2 in v.items():
190 params[k2] = urllib.parse.unquote(v2)
191 return append_to_qs(temp_url, params)
192 else:
193 raise Exception("Could not find params-like structure in cipher result!")
194
195 def decode_cipher_url(js_url, cipher):
196 cipher = urllib.parse.parse_qs(cipher)
197 args = [
198 cipher["url"][0],
199 cipher["sp"][0],
200 cipher["s"][0],
201 ]
202
203 f = urlopen(js_url)
204 script = f.read().decode("utf-8")
205 f.close()
206
207 cipher_func_name = find_cipher_func(script)
208
209 params = {
210 "cipher_func_name": cipher_func_name,
211 "args": json.dumps(args),
212 "code": json.dumps(extract_js(script)),
213 }
214 p = subprocess.Popen(
215 "node",
216 shell=True,
217 close_fds=True,
218 stdin=subprocess.PIPE,
219 stdout=subprocess.PIPE
220 )
221 js_decode_script = ("""
222 const vm = require('vm');
223
224 const fakeGlobal = {};
225 fakeGlobal.window = fakeGlobal;
226 fakeGlobal.location = {
227 hash: '',
228 host: 'www.youtube.com',
229 hostname: 'www.youtube.com',
230 href: 'https://www.youtube.com',
231 origin: 'https://www.youtube.com',
232 pathname: '/',
233 protocol: 'https:'
234 };
235 fakeGlobal.history = {
236 pushState: function(){}
237 };
238 fakeGlobal.document = {
239 location: fakeGlobal.location
240 };
241 fakeGlobal.document = {};
242 fakeGlobal.navigator = {
243 userAgent: ''
244 };
245 fakeGlobal.XMLHttpRequest = class XMLHttpRequest {};
246 fakeGlobal.matchMedia = () => ({matches: () => {}, media: ''});
247 fakeGlobal.result = null;
248 fakeGlobal.g = function(){}; // this is _yt_player
249 fakeGlobal.TimeRanges = function(){};
250
251 const code_string = %(code)s + ';';
252 const exec_string = 'result = %(cipher_func_name)s(...%(args)s);';
253 vm.runInNewContext(code_string + exec_string, fakeGlobal);
254
255 console.log(JSON.stringify(fakeGlobal.result));
256 """ % params)
257
258 p.stdin.write(js_decode_script.encode("utf-8"))
259 p.stdin.close()
260
261 result = json.load(p.stdout)
262 if p.wait() != 0:
263 raise Exception("js failed to execute: %d" % p.returncode)
264
265 result_url = construct_url_from_cipher_result(result)
266 return result_url
267
268 def get_best_video(player_config):
269 formats = player_config["streamingData"]["formats"]
270
271 best_url = None
272 best_quality = None
273 best_extension = None
274 for format_data in formats:
275 mimetype = format_data["mimeType"].split(";")[0]
276 quality = format_data["quality"]
277
278 if quality not in QUALITIES:
279 continue
280 if mimetype not in MIMETYPES:
281 continue
282
283 extension = MIMETYPES[mimetype]
284 quality = QUALITIES.get(quality, -1)
285
286 if best_quality is not None and quality < best_quality:
287 continue
288
289 if "signatureCipher" in format_data:
290 js_url = player_config["PLAYER_JS_URL"]
291 video_url = decode_cipher_url(js_url, format_data["signatureCipher"])
292 else:
293 video_url = format_data["url"]
294
295 best_url = video_url
296 best_quality = quality
297 best_extension = extension
298
299 return best_url, best_extension
300
301 def sanitize_filename(filename):
302 return (
303 re.sub("\s+", " ", filename.strip())
304 .replace("\\", "-")
305 .replace("/", "-")
306 .replace("\0", " ")
307 )
308
309 def get_video_url(page):
310 player_config = get_player_config(page.scripts)
311 if not player_config:
312 raise VideoUnavailable(page.unavailable_message or "Could not find video URL")
313
314 video_url, extension = get_best_video(player_config)
315 if not video_url:
316 return None, None
317
318 title = player_config["videoDetails"].get("title", None)
319 if not title:
320 title = "Unknown title"
321
322 filename = sanitize_filename(title) + "." + extension
323
324 return video_url, filename
325
326 class YouTubeVideoPageParser(html.parser.HTMLParser):
327 def __init__(self):
328 super().__init__()
329 self.unavailable_message = None
330 self.scripts = []
331
332 def handle_starttag(self, tag, attrs):
333 attrs = dict(attrs)
334 self._handle_unavailable_message(tag, attrs)
335 self._handle_script(tag, attrs)
336
337 def handle_endtag(self, tag):
338 self.handle_data = self._ignore_data
339
340 def _ignore_data(self, _):
341 pass
342
343 def _handle_unavailable_message(self, tag, attrs):
344 if attrs.get("id", None) == "unavailable-message":
345 self.handle_data = self._handle_unavailable_message_data
346
347 def _handle_unavailable_message_data(self, data):
348 self.unavailable_message = data.strip()
349
350 def _handle_script(self, tag, attrs):
351 if tag == "script":
352 self.handle_data = self._handle_script_data
353
354 def _handle_script_data(self, data):
355 if data:
356 self.scripts.append(data)
357
358 class MozillaReleasesPageParser(html.parser.HTMLParser):
359 def __init__(self):
360 super().__init__()
361 self.latest_release = "1.0"
362
363 def handle_starttag(self, tag, attrs):
364 attrs = dict(attrs)
365 if attrs.get("data-latest-firefox", None):
366 self.latest_release = attrs.get("data-latest-firefox", None)
367
368 def write_video(filename, video_data):
369 quoted_filename = urllib.parse.quote(filename.encode("utf-8"))
370 sys.stdout.buffer.write(
371 b"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
372 .replace(b"{0}", quoted_filename.encode("utf-8"))
373 )
374 sys.stdout.buffer.write(
375 b"Content-Length: {0}\r\n"
376 .replace(b"{0}", video_data.getheader("Content-Length").encode("utf-8"))
377 )
378 sys.stdout.buffer.write(b"\r\n")
379 shutil.copyfileobj(video_data, sys.stdout.buffer)
380 video_data.close()
381
382 def cgimain():
383 args = cgi.parse()
384 try:
385 url = args["url"][0]
386 except:
387 print_form(url="https://www.youtube.com/watch?v=FOOBAR")
388 return
389
390 try:
391 page = YouTubeVideoPageParser()
392 validate_url(url)
393 with urlopen(url) as f:
394 page.feed(f.read().decode("utf-8"))
395 page.close()
396 video_url, filename = get_video_url(page)
397 video_data = urlopen(video_url)
398 except VideoUnavailable as e:
399 print_form(
400 url=url,
401 msg="<p class='error'>Sorry, there was an error: %s</p>" % cgi.escape(e.args[0])
402 )
403 except NotYouTube:
404 print_form(
405 url=url,
406 msg="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
407 )
408 except Exception as e:
409 print_form(
410 url=url,
411 msg="<p class='error'>Sorry, there was an unknown error.</p>"
412 )
413 return
414
415 write_video(filename, video_data)
416
417 def pp_size(size):
418 suffixes = ["", "KiB", "MiB", "GiB"]
419 for i, suffix in enumerate(suffixes):
420 if size < 1024:
421 break
422 size /= 1024
423 return "%.2f %s" % (size, suffix)
424
425 def copy_with_progress(content_length, infile, outfile):
426 def print_status():
427 rate = 0
428 if now != last_ts:
429 rate = last_bytes_read / (now - last_ts)
430 sys.stdout.write("\33[2K\r")
431 sys.stdout.write("%s / %s (%s/sec)" % (
432 pp_size(bytes_read),
433 pp_size(content_length),
434 pp_size(rate),
435 ))
436 sys.stdout.flush()
437
438 last_ts = 0
439 last_bytes_read = 0
440 bytes_read = 0
441 while True:
442 now = time.time()
443 if now - last_ts > 0.5:
444 print_status()
445 last_ts = now
446 last_bytes_read = 0
447
448 buf = infile.read(32768)
449 if not buf:
450 break
451 outfile.write(buf)
452 last_bytes_read += len(buf)
453 bytes_read += len(buf)
454
455 # Newline at the end
456 print_status()
457 print()
458
459 def main():
460 try:
461 url = sys.argv[1]
462 except:
463 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys.argv[0], file=sys.stderr)
464 sys.exit(1)
465
466 page = YouTubeVideoPageParser()
467 with urlopen(url) as f:
468 page.feed(f.read().decode("utf-8"))
469 page.close()
470 video_url, filename = get_video_url(page)
471 print("Downloading", filename)
472
473 outfile = open(filename, "ab")
474 offset = outfile.tell()
475 if offset > 0:
476 print("Resuming download from", pp_size(offset))
477 total_size = None
478
479 while True:
480 try:
481 video_data = urlopen(video_url, offset)
482 except urllib.error.HTTPError as e:
483 if e.code == 416:
484 print("File is complete!")
485 break
486 else:
487 raise
488
489 content_length = int(video_data.getheader("Content-Length"))
490 if total_size is None:
491 total_size = content_length
492
493 try:
494 copy_with_progress(content_length, video_data, outfile)
495 except IOError as e:
496 print()
497
498 video_data.close()
499 if outfile.tell() != total_size:
500 old_offset = offset
501 offset = outfile.tell()
502 if old_offset == offset:
503 time.sleep(1)
504 print("Restarting download from", pp_size(offset))
505 else:
506 break
507
508 outfile.close()
509
510
511 if __name__ == "__main__":
512 if "SCRIPT_NAME" in os.environ:
513 cgimain()
514 else:
515 try:
516 main()
517 except KeyboardInterrupt:
518 print("\nExiting...")
519 sys.exit(1)
520