]>
code.delx.au - youtube-cgi/blob - youtube.cgi
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"
36 class VideoUnavailable(Exception):
39 class NotYouTube(Exception):
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")
49 <title>delx.net.au - YouTube Scraper</title>
50 <link rel="stylesheet" type="text/css" href="/style.css">
51 <style type="text/css">
61 <h1>delx.net.au - YouTube Scraper</h1>
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>
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>
75 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
77 cookiejar
= http
.cookiejar
.CookieJar()
78 urlopener
= urllib
.request
.build_opener(urllib
.request
.HTTPCookieProcessor(cookiejar
))
82 def urlopen(url
, offset
=None):
85 page
= MozillaReleasesPageParser()
86 with urllib
.request
.urlopen(MOZILLA_RELEASE_URL
) as f
:
87 page
.feed(f
.read().decode("utf-8"))
89 user_agent
= USER_AGENT_TEMPLATE
% page
.latest_release
91 if url
.startswith("//"):
93 if not url
.startswith("http://") and not url
.startswith("https://"):
94 url
= "https://www.youtube.com" + url
97 req
= urllib
.request
.Request(url
)
101 req
.add_header("Referer", referrer
)
103 req
.add_header("User-Agent", user_agent
)
106 req
.add_header("Range", "bytes=%d-" % offset
)
108 res
= urlopener
.open(req
)
110 content_range
= res
.getheader("Content-Range")
112 tokens
= content_range
.split()
113 assert tokens
[0] == "bytes"
114 start
= int(tokens
[1].split("-")[0])
115 assert start
== offset
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"]
124 if scheme_ok
and host_ok
:
129 def load_parse_url(url
, parser
):
131 parser
.feed(f
.read().decode("utf-8"))
135 def append_to_qs(url
, params
):
136 r
= list(urllib
.parse
.urlsplit(url
))
137 qs
= urllib
.parse
.parse_qs(r
[3])
139 r
[3] = urllib
.parse
.urlencode(qs
, True)
140 url
= urllib
.parse
.urlunsplit(r
)
143 def get_player_config(scripts
):
145 ("ytplayer.config = {", 1, "};", 1),
146 ("ytcfg.set({\"", 2, "});", 1),
149 for script
in scripts
:
150 for line
in script
.split("\n"):
151 for s1
, off1
, s2
, off2
in config_strings
:
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
]))
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
)
165 return script
[len(PREFIX
):-len(SUFFIX
)]
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
174 match
= re
.search(PATTERN
, script
)
175 func_name
= match
.groups()[0]
178 def find_url_func(script
):
179 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
180 PATTERN
= R
"this\.url\s*=\s*" + FUNC_NAME
+ R
"\s*\(\s*this\s*\)"
182 match
= re
.search(PATTERN
, script
)
183 func_name
= match
.groups()[0]
186 def decode_cipher_url(js_url
, cipher
):
187 cipher
= urllib
.parse
.parse_qs(cipher
)
195 script
= f
.read().decode("utf-8")
198 cipher_func_name
= find_cipher_func(script
)
199 url_func_name
= find_url_func(script
)
202 "cipher_func_name": cipher_func_name
,
203 "url_func_name": url_func_name
,
204 "args": json
.dumps(args
),
205 "code": json
.dumps(extract_js(script
)),
207 p
= subprocess
.Popen(
211 stdin
=subprocess
.PIPE
,
212 stdout
=subprocess
.PIPE
214 js_decode_script
= ("""
215 const vm = require('vm');
217 const fakeGlobal = {};
218 fakeGlobal.window = fakeGlobal;
219 fakeGlobal.location = {
221 host: 'www.youtube.com',
222 hostname: 'www.youtube.com',
223 href: 'https://www.youtube.com',
224 origin: 'https://www.youtube.com',
228 fakeGlobal.history = {
229 pushState: function(){}
231 fakeGlobal.document = {
232 location: fakeGlobal.location
234 fakeGlobal.document = {};
235 fakeGlobal.navigator = {
238 fakeGlobal.XMLHttpRequest = class XMLHttpRequest {};
239 fakeGlobal.matchMedia = () => ({matches: () => {}, media: ''});
240 fakeGlobal.result_url = null;
241 fakeGlobal.g = function(){}; // this is _yt_player
242 fakeGlobal.TimeRanges = function(){};
244 const code_string = %(code)s + ';';
245 const exec_string = 'result_url = %(url_func_name)s(%(cipher_func_name)s(...%(args)s));';
246 vm.runInNewContext(code_string + exec_string, fakeGlobal);
248 console.log(fakeGlobal.result_url);
251 p
.stdin
.write(js_decode_script
.encode("utf-8"))
254 result_url
= p
.stdout
.read().decode("utf-8").strip()
256 raise Exception("js failed to execute: %d" % p
.returncode
)
260 def get_best_video(player_config
):
261 player_args
= player_config
["args"]
262 player_response
= json
.loads(player_args
["player_response"])
263 formats
= player_response
["streamingData"]["formats"]
267 best_extension
= None
268 for format_data
in formats
:
269 mimetype
= format_data
["mimeType"].split(";")[0]
270 quality
= format_data
["quality"]
272 if quality
not in QUALITIES
:
274 if mimetype
not in MIMETYPES
:
277 extension
= MIMETYPES
[mimetype
]
278 quality
= QUALITIES
.get(quality
, -1)
280 if best_quality
is not None and quality
< best_quality
:
283 if "signatureCipher" in format_data
:
284 js_url
= player_config
["PLAYER_JS_URL"]
285 video_url
= decode_cipher_url(js_url
, format_data
["signatureCipher"])
287 video_url
= format_data
["url"]
290 best_quality
= quality
291 best_extension
= extension
293 return best_url
, best_extension
295 def sanitize_filename(filename
):
297 re
.sub("\s+", " ", filename
.strip())
303 def get_video_url(page
):
304 player_config
= get_player_config(page
.scripts
)
305 if not player_config
:
306 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
308 video_url
, extension
= get_best_video(player_config
)
312 title
= player_config
["args"].get("title", None)
314 title
= json
.loads(player_config
["args"]["player_response"])["videoDetails"]["title"]
316 title
= "Unknown title"
318 filename
= sanitize_filename(title
) + "." + extension
320 return video_url
, filename
322 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
325 self
.unavailable_message
= None
328 def handle_starttag(self
, tag
, attrs
):
330 self
._handle
_unavailable
_message
(tag
, attrs
)
331 self
._handle
_script
(tag
, attrs
)
333 def handle_endtag(self
, tag
):
334 self
.handle_data
= self
._ignore
_data
336 def _ignore_data(self
, _
):
339 def _handle_unavailable_message(self
, tag
, attrs
):
340 if attrs
.get("id", None) == "unavailable-message":
341 self
.handle_data
= self
._handle
_unavailable
_message
_data
343 def _handle_unavailable_message_data(self
, data
):
344 self
.unavailable_message
= data
.strip()
346 def _handle_script(self
, tag
, attrs
):
348 self
.handle_data
= self
._handle
_script
_data
350 def _handle_script_data(self
, data
):
352 self
.scripts
.append(data
)
354 class MozillaReleasesPageParser(html
.parser
.HTMLParser
):
357 self
.latest_release
= "1.0"
359 def handle_starttag(self
, tag
, attrs
):
361 if attrs
.get("data-latest-firefox", None):
362 self
.latest_release
= attrs
.get("data-latest-firefox", None)
364 def write_video(filename
, video_data
):
365 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
366 sys
.stdout
.buffer.write(
367 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
368 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
370 sys
.stdout
.buffer.write(
371 b
"Content-Length: {0}\r\n"
372 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
374 sys
.stdout
.buffer.write(b
"\r\n")
375 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
383 print_form(url
="https://www.youtube.com/watch?v=FOOBAR")
387 page
= YouTubeVideoPageParser()
389 with
urlopen(url
) as f
:
390 page
.feed(f
.read().decode("utf-8"))
392 video_url
, filename
= get_video_url(page
)
393 video_data
= urlopen(video_url
)
394 except VideoUnavailable
as e
:
397 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
402 msg
="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
404 except Exception as e
:
407 msg
="<p class='error'>Sorry, there was an unknown error.</p>"
411 write_video(filename
, video_data
)
414 suffixes
= ["", "KiB", "MiB", "GiB"]
415 for i
, suffix
in enumerate(suffixes
):
419 return "%.2f %s" % (size
, suffix
)
421 def copy_with_progress(content_length
, infile
, outfile
):
425 rate
= last_bytes_read
/ (now
- last_ts
)
426 sys
.stdout
.write("\33[2K\r")
427 sys
.stdout
.write("%s / %s (%s/sec)" % (
429 pp_size(content_length
),
439 if now
- last_ts
> 0.5:
444 buf
= infile
.read(32768)
448 last_bytes_read
+= len(buf
)
449 bytes_read
+= len(buf
)
459 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
462 page
= YouTubeVideoPageParser()
463 with
urlopen(url
) as f
:
464 page
.feed(f
.read().decode("utf-8"))
466 video_url
, filename
= get_video_url(page
)
467 print("Downloading", filename
)
469 outfile
= open(filename
, "ab")
470 offset
= outfile
.tell()
472 print("Resuming download from", pp_size(offset
))
477 video_data
= urlopen(video_url
, offset
)
478 except urllib
.error
.HTTPError
as e
:
480 print("File is complete!")
485 content_length
= int(video_data
.getheader("Content-Length"))
486 if total_size
is None:
487 total_size
= content_length
490 copy_with_progress(content_length
, video_data
, outfile
)
495 if outfile
.tell() != total_size
:
497 offset
= outfile
.tell()
498 if old_offset
== offset
:
500 print("Restarting download from", pp_size(offset
))
507 if __name__
== "__main__":
508 if "SCRIPT_NAME" in os
.environ
:
513 except KeyboardInterrupt:
514 print("\nExiting...")