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