]>
code.delx.au - youtube-cgi/blob - youtube.cgi
5c55feb3cdbb1abee93da8834685e7b76dd54193
18 USER_AGENT
= "Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.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_ok
= parsed_url
.netloc
.lstrip("www.") in ["youtube.com", "youtu.be"]
113 if scheme_ok
and host_ok
:
118 def parse_url(url
, parser
):
120 parser
.feed(f
.read().decode("utf-8"))
124 def append_to_qs(url
, params
):
125 r
= list(urllib
.parse
.urlsplit(url
))
126 qs
= urllib
.parse
.parse_qs(r
[3])
128 r
[3] = urllib
.parse
.urlencode(qs
, True)
129 url
= urllib
.parse
.urlunsplit(r
)
132 def get_player_config(scripts
):
134 ("ytplayer.config = {", 1, "};", 1),
135 ("ytcfg.set({\"", 2, "});", 1),
138 for script
in scripts
:
139 for line
in script
.split("\n"):
140 for s1
, off1
, s2
, off2
in config_strings
:
142 p1
= line
.find(s1
) + len(s1
) - off1
143 p2
= line
.find(s2
, p1
) + off2
144 if p1
>= 0 and p2
> 0:
145 player_config
.update(json
.loads(line
[p1
:p2
]))
148 def extract_js(script
):
149 PREFIX
= "var _yt_player={};(function(g){var window=this;"
150 SUFFIX
= ";})(_yt_player);\n"
151 assert script
.startswith(PREFIX
)
152 assert script
.endswith(SUFFIX
)
154 return script
[len(PREFIX
):-len(SUFFIX
)]
156 def find_cipher_func(script
):
157 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
158 DECODE_URI_COMPONENT
= R
"(\(decodeURIComponent)?"
159 FUNC_PARAMS
= R
"(\([a-zA-Z,\.]+\.s\))"
160 TERMINATOR
= R
"[,;\)]"
161 PATTERN
= FUNC_NAME
+ DECODE_URI_COMPONENT
+ FUNC_PARAMS
+ TERMINATOR
163 match
= re
.search(PATTERN
, script
)
164 func_name
= match
.groups()[0]
167 def find_url_func(script
):
168 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
169 PATTERN
= R
"this\.url\s*=\s*" + FUNC_NAME
+ R
"\s*\(\s*this\s*\)"
171 match
= re
.search(PATTERN
, script
)
172 func_name
= match
.groups()[0]
175 def decode_cipher_url(js_url
, cipher
):
176 cipher
= urllib
.parse
.parse_qs(cipher
)
184 script
= f
.read().decode("utf-8")
187 cipher_func_name
= find_cipher_func(script
)
188 url_func_name
= find_url_func(script
)
191 "cipher_func_name": cipher_func_name
,
192 "url_func_name": url_func_name
,
193 "args": json
.dumps(args
),
194 "code": json
.dumps(extract_js(script
)),
196 p
= subprocess
.Popen(
200 stdin
=subprocess
.PIPE
,
201 stdout
=subprocess
.PIPE
203 js_decode_script
= ("""
204 const vm = require('vm');
206 const fakeGlobal = {};
207 fakeGlobal.window = fakeGlobal;
208 fakeGlobal.location = {
210 host: 'www.youtube.com',
211 hostname: 'www.youtube.com',
212 href: 'https://www.youtube.com',
213 origin: 'https://www.youtube.com',
217 fakeGlobal.history = {
218 pushState: function(){}
220 fakeGlobal.document = {
221 location: fakeGlobal.location
223 fakeGlobal.document = {};
224 fakeGlobal.navigator = {
227 fakeGlobal.XMLHttpRequest = class XMLHttpRequest {};
228 fakeGlobal.matchMedia = () => ({matches: () => {}, media: ''});
229 fakeGlobal.result_url = null;
230 fakeGlobal.g = function(){}; // this is _yt_player
232 const code_string = %(code)s + ';';
233 const exec_string = 'result_url = %(url_func_name)s(%(cipher_func_name)s(...%(args)s));';
234 vm.runInNewContext(code_string + exec_string, fakeGlobal);
236 console.log(fakeGlobal.result_url);
239 p
.stdin
.write(js_decode_script
.encode("utf-8"))
242 result_url
= p
.stdout
.read().decode("utf-8").strip()
244 raise Exception("js failed to execute: %d" % p
.returncode
)
248 def get_best_video(player_config
):
249 player_args
= player_config
["args"]
250 player_response
= json
.loads(player_args
["player_response"])
251 formats
= player_response
["streamingData"]["formats"]
255 best_extension
= None
256 for format_data
in formats
:
257 mimetype
= format_data
["mimeType"].split(";")[0]
258 quality
= format_data
["quality"]
260 if quality
not in QUALITIES
:
262 if mimetype
not in MIMETYPES
:
265 extension
= MIMETYPES
[mimetype
]
266 quality
= QUALITIES
.get(quality
, -1)
268 if best_quality
is not None and quality
< best_quality
:
271 if "signatureCipher" in format_data
:
272 js_url
= player_config
["PLAYER_JS_URL"]
273 video_url
= decode_cipher_url(js_url
, format_data
["signatureCipher"])
275 video_url
= format_data
["url"]
278 best_quality
= quality
279 best_extension
= extension
281 return best_url
, best_extension
283 def sanitize_filename(filename
):
285 re
.sub("\s+", " ", filename
.strip())
291 def get_video_url(page
):
292 player_config
= get_player_config(page
.scripts
)
293 if not player_config
:
294 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
296 video_url
, extension
= get_best_video(player_config
)
300 title
= player_config
["args"].get("title", None)
302 title
= json
.loads(player_config
["args"]["player_response"])["videoDetails"]["title"]
304 title
= "Unknown title"
306 filename
= sanitize_filename(title
) + "." + extension
308 return video_url
, filename
310 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
313 self
.unavailable_message
= None
316 def handle_starttag(self
, tag
, attrs
):
318 self
._handle
_unavailable
_message
(tag
, attrs
)
319 self
._handle
_script
(tag
, attrs
)
321 def handle_endtag(self
, tag
):
322 self
.handle_data
= self
._ignore
_data
324 def _ignore_data(self
, _
):
327 def _handle_unavailable_message(self
, tag
, attrs
):
328 if attrs
.get("id", None) == "unavailable-message":
329 self
.handle_data
= self
._handle
_unavailable
_message
_data
331 def _handle_unavailable_message_data(self
, data
):
332 self
.unavailable_message
= data
.strip()
334 def _handle_script(self
, tag
, attrs
):
336 self
.handle_data
= self
._handle
_script
_data
338 def _handle_script_data(self
, data
):
340 self
.scripts
.append(data
)
342 def write_video(filename
, video_data
):
343 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
344 sys
.stdout
.buffer.write(
345 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
346 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
348 sys
.stdout
.buffer.write(
349 b
"Content-Length: {0}\r\n"
350 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
352 sys
.stdout
.buffer.write(b
"\r\n")
353 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
361 print_form(url
="https://www.youtube.com/watch?v=FOOBAR")
365 page
= YouTubeVideoPageParser()
368 video_url
, filename
= get_video_url(page
)
369 video_data
= urlopen(video_url
)
370 except VideoUnavailable
as e
:
373 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
378 msg
="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
380 except Exception as e
:
383 msg
="<p class='error'>Sorry, there was an unknown error.</p>"
387 write_video(filename
, video_data
)
390 suffixes
= ["", "KiB", "MiB", "GiB"]
391 for i
, suffix
in enumerate(suffixes
):
395 return "%.2f %s" % (size
, suffix
)
397 def copy_with_progress(content_length
, infile
, outfile
):
401 rate
= last_bytes_read
/ (now
- last_ts
)
402 sys
.stdout
.write("\33[2K\r")
403 sys
.stdout
.write("%s / %s (%s/sec)" % (
405 pp_size(content_length
),
415 if now
- last_ts
> 0.5:
420 buf
= infile
.read(32768)
424 last_bytes_read
+= len(buf
)
425 bytes_read
+= len(buf
)
435 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
438 page
= YouTubeVideoPageParser()
440 video_url
, filename
= get_video_url(page
)
441 print("Downloading", filename
)
443 outfile
= open(filename
, "ab")
444 offset
= outfile
.tell()
446 print("Resuming download from", pp_size(offset
))
451 video_data
= urlopen(video_url
, offset
)
452 except urllib
.error
.HTTPError
as e
:
454 print("File is complete!")
459 content_length
= int(video_data
.getheader("Content-Length"))
460 if total_size
is None:
461 total_size
= content_length
464 copy_with_progress(content_length
, video_data
, outfile
)
469 if outfile
.tell() != total_size
:
471 offset
= outfile
.tell()
472 if old_offset
== offset
:
474 print("Restarting download from", pp_size(offset
))
481 if __name__
== "__main__":
482 if "SCRIPT_NAME" in os
.environ
:
487 except KeyboardInterrupt:
488 print("\nExiting...")