]>
code.delx.au - youtube-cgi/blob - youtube.cgi
0aadef35e5885458ec97282c27bfb2465cd9a375
18 USER_AGENT
= "Mozilla/5.0 (X11; Linux x86_64; rv:82.0) Gecko/20100101 Firefox/82.0"
35 class VideoUnavailable(Exception):
38 class NotYouTube(Exception):
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")
48 <title>delx.net.au - YouTube Scraper</title>
49 <link rel="stylesheet" type="text/css" href="/style.css">
50 <style type="text/css">
60 <h1>delx.net.au - YouTube Scraper</h1>
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>
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>
74 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
76 cookiejar
= http
.cookiejar
.CookieJar()
77 urlopener
= urllib
.request
.build_opener(urllib
.request
.HTTPCookieProcessor(cookiejar
))
80 def urlopen(url
, offset
=None):
81 if url
.startswith("//"):
83 if not url
.startswith("http://") and not url
.startswith("https://"):
84 url
= "https://www.youtube.com" + url
87 req
= urllib
.request
.Request(url
)
91 req
.add_header("Referer", referrer
)
93 req
.add_header("User-Agent", USER_AGENT
)
96 req
.add_header("Range", "bytes=%d-" % offset
)
98 res
= urlopener
.open(req
)
100 content_range
= res
.getheader("Content-Range")
102 tokens
= content_range
.split()
103 assert tokens
[0] == "bytes"
104 start
= int(tokens
[1].split("-")[0])
105 assert start
== offset
108 def validate_url(url
):
109 parsed_url
= urllib
.parse
.urlparse(url
)
110 scheme_ok
= parsed_url
.scheme
== "https"
111 host
= parsed_url
.netloc
.lstrip("www.").lstrip("m.")
112 host_ok
= host
in ["youtube.com", "youtu.be"]
114 if scheme_ok
and host_ok
:
119 def parse_url(url
, parser
):
121 parser
.feed(f
.read().decode("utf-8"))
125 def append_to_qs(url
, params
):
126 r
= list(urllib
.parse
.urlsplit(url
))
127 qs
= urllib
.parse
.parse_qs(r
[3])
129 r
[3] = urllib
.parse
.urlencode(qs
, True)
130 url
= urllib
.parse
.urlunsplit(r
)
133 def get_player_config(scripts
):
135 ("ytplayer.config = {", 1, "};", 1),
136 ("ytcfg.set({\"", 2, "});", 1),
139 for script
in scripts
:
140 for line
in script
.split("\n"):
141 for s1
, off1
, s2
, off2
in config_strings
:
143 p1
= line
.find(s1
) + len(s1
) - off1
144 p2
= line
.find(s2
, p1
) + off2
145 if p1
>= 0 and p2
> 0:
146 player_config
.update(json
.loads(line
[p1
:p2
]))
149 def extract_js(script
):
150 PREFIX
= "var _yt_player={};(function(g){var window=this;"
151 SUFFIX
= ";})(_yt_player);\n"
152 assert script
.startswith(PREFIX
)
153 assert script
.endswith(SUFFIX
)
155 return script
[len(PREFIX
):-len(SUFFIX
)]
157 def find_cipher_func(script
):
158 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
159 DECODE_URI_COMPONENT
= R
"(\(decodeURIComponent)?"
160 FUNC_PARAMS
= R
"(\([a-zA-Z,\.]+\.s\))"
161 TERMINATOR
= R
"[,;\)]"
162 PATTERN
= FUNC_NAME
+ DECODE_URI_COMPONENT
+ FUNC_PARAMS
+ TERMINATOR
164 match
= re
.search(PATTERN
, script
)
165 func_name
= match
.groups()[0]
168 def find_url_func(script
):
169 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
170 PATTERN
= R
"this\.url\s*=\s*" + FUNC_NAME
+ R
"\s*\(\s*this\s*\)"
172 match
= re
.search(PATTERN
, script
)
173 func_name
= match
.groups()[0]
176 def decode_cipher_url(js_url
, cipher
):
177 cipher
= urllib
.parse
.parse_qs(cipher
)
185 script
= f
.read().decode("utf-8")
188 cipher_func_name
= find_cipher_func(script
)
189 url_func_name
= find_url_func(script
)
192 "cipher_func_name": cipher_func_name
,
193 "url_func_name": url_func_name
,
194 "args": json
.dumps(args
),
195 "code": json
.dumps(extract_js(script
)),
197 p
= subprocess
.Popen(
201 stdin
=subprocess
.PIPE
,
202 stdout
=subprocess
.PIPE
204 js_decode_script
= ("""
205 const vm = require('vm');
207 const fakeGlobal = {};
208 fakeGlobal.window = fakeGlobal;
209 fakeGlobal.location = {
211 host: 'www.youtube.com',
212 hostname: 'www.youtube.com',
213 href: 'https://www.youtube.com',
214 origin: 'https://www.youtube.com',
218 fakeGlobal.history = {
219 pushState: function(){}
221 fakeGlobal.document = {
222 location: fakeGlobal.location
224 fakeGlobal.document = {};
225 fakeGlobal.navigator = {
228 fakeGlobal.XMLHttpRequest = class XMLHttpRequest {};
229 fakeGlobal.matchMedia = () => ({matches: () => {}, media: ''});
230 fakeGlobal.result_url = null;
231 fakeGlobal.g = function(){}; // this is _yt_player
233 const code_string = %(code)s + ';';
234 const exec_string = 'result_url = %(url_func_name)s(%(cipher_func_name)s(...%(args)s));';
235 vm.runInNewContext(code_string + exec_string, fakeGlobal);
237 console.log(fakeGlobal.result_url);
240 p
.stdin
.write(js_decode_script
.encode("utf-8"))
243 result_url
= p
.stdout
.read().decode("utf-8").strip()
245 raise Exception("js failed to execute: %d" % p
.returncode
)
249 def get_best_video(player_config
):
250 player_args
= player_config
["args"]
251 player_response
= json
.loads(player_args
["player_response"])
252 formats
= player_response
["streamingData"]["formats"]
256 best_extension
= None
257 for format_data
in formats
:
258 mimetype
= format_data
["mimeType"].split(";")[0]
259 quality
= format_data
["quality"]
261 if quality
not in QUALITIES
:
263 if mimetype
not in MIMETYPES
:
266 extension
= MIMETYPES
[mimetype
]
267 quality
= QUALITIES
.get(quality
, -1)
269 if best_quality
is not None and quality
< best_quality
:
272 if "signatureCipher" in format_data
:
273 js_url
= player_config
["PLAYER_JS_URL"]
274 video_url
= decode_cipher_url(js_url
, format_data
["signatureCipher"])
276 video_url
= format_data
["url"]
279 best_quality
= quality
280 best_extension
= extension
282 return best_url
, best_extension
284 def sanitize_filename(filename
):
286 re
.sub("\s+", " ", filename
.strip())
292 def get_video_url(page
):
293 player_config
= get_player_config(page
.scripts
)
294 if not player_config
:
295 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
297 video_url
, extension
= get_best_video(player_config
)
301 title
= player_config
["args"].get("title", None)
303 title
= json
.loads(player_config
["args"]["player_response"])["videoDetails"]["title"]
305 title
= "Unknown title"
307 filename
= sanitize_filename(title
) + "." + extension
309 return video_url
, filename
311 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
314 self
.unavailable_message
= None
317 def handle_starttag(self
, tag
, attrs
):
319 self
._handle
_unavailable
_message
(tag
, attrs
)
320 self
._handle
_script
(tag
, attrs
)
322 def handle_endtag(self
, tag
):
323 self
.handle_data
= self
._ignore
_data
325 def _ignore_data(self
, _
):
328 def _handle_unavailable_message(self
, tag
, attrs
):
329 if attrs
.get("id", None) == "unavailable-message":
330 self
.handle_data
= self
._handle
_unavailable
_message
_data
332 def _handle_unavailable_message_data(self
, data
):
333 self
.unavailable_message
= data
.strip()
335 def _handle_script(self
, tag
, attrs
):
337 self
.handle_data
= self
._handle
_script
_data
339 def _handle_script_data(self
, data
):
341 self
.scripts
.append(data
)
343 def write_video(filename
, video_data
):
344 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
345 sys
.stdout
.buffer.write(
346 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
347 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
349 sys
.stdout
.buffer.write(
350 b
"Content-Length: {0}\r\n"
351 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
353 sys
.stdout
.buffer.write(b
"\r\n")
354 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
362 print_form(url
="https://www.youtube.com/watch?v=FOOBAR")
366 page
= YouTubeVideoPageParser()
369 video_url
, filename
= get_video_url(page
)
370 video_data
= urlopen(video_url
)
371 except VideoUnavailable
as e
:
374 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
379 msg
="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
381 except Exception as e
:
384 msg
="<p class='error'>Sorry, there was an unknown error.</p>"
388 write_video(filename
, video_data
)
391 suffixes
= ["", "KiB", "MiB", "GiB"]
392 for i
, suffix
in enumerate(suffixes
):
396 return "%.2f %s" % (size
, suffix
)
398 def copy_with_progress(content_length
, infile
, outfile
):
402 rate
= last_bytes_read
/ (now
- last_ts
)
403 sys
.stdout
.write("\33[2K\r")
404 sys
.stdout
.write("%s / %s (%s/sec)" % (
406 pp_size(content_length
),
416 if now
- last_ts
> 0.5:
421 buf
= infile
.read(32768)
425 last_bytes_read
+= len(buf
)
426 bytes_read
+= len(buf
)
436 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
439 page
= YouTubeVideoPageParser()
441 video_url
, filename
= get_video_url(page
)
442 print("Downloading", filename
)
444 outfile
= open(filename
, "ab")
445 offset
= outfile
.tell()
447 print("Resuming download from", pp_size(offset
))
452 video_data
= urlopen(video_url
, offset
)
453 except urllib
.error
.HTTPError
as e
:
455 print("File is complete!")
460 content_length
= int(video_data
.getheader("Content-Length"))
461 if total_size
is None:
462 total_size
= content_length
465 copy_with_progress(content_length
, video_data
, outfile
)
470 if outfile
.tell() != total_size
:
472 offset
= outfile
.tell()
473 if old_offset
== offset
:
475 print("Restarting download from", pp_size(offset
))
482 if __name__
== "__main__":
483 if "SCRIPT_NAME" in os
.environ
:
488 except KeyboardInterrupt:
489 print("\nExiting...")