]>
code.delx.au - youtube-cgi/blob - youtube.cgi
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 for script
in scripts
:
135 for line
in script
.split("\n"):
136 s
= "ytplayer.config = {"
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
])
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
)
149 return script
[len(PREFIX
):-len(SUFFIX
)]
151 def find_func_name(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
158 match
= re
.search(PATTERN
, script
)
159 func_name
= match
.groups()[0]
162 def decode_signature(js_url
, signature
):
164 script
= f
.read().decode("utf-8")
167 func_name
= find_func_name(script
)
170 "func_name": func_name
,
171 "signature": json
.dumps(signature
),
172 "code": json
.dumps(extract_js(script
)),
174 p
= subprocess
.Popen(
178 stdin
=subprocess
.PIPE
,
179 stdout
=subprocess
.PIPE
181 js_decode_script
= ("""
182 const vm = require('vm');
191 pushState: function(){}
197 XMLHttpRequest: class XMLHttpRequest {},
198 matchMedia: () => ({matches: () => {}, media: ''}),
199 signature: %(signature)s,
200 transformed_signature: null,
201 g: function(){} // this is _yt_player
203 sandbox.window = sandbox;
205 const code_string = %(code)s + ';';
206 const exec_string = 'transformed_signature = %(func_name)s(signature);';
207 vm.runInNewContext(code_string + exec_string, sandbox);
209 console.log(sandbox.transformed_signature);
212 p
.stdin
.write(js_decode_script
.encode("utf-8"))
215 transformed_signature
= p
.stdout
.read().decode("utf-8").strip()
216 transformed_signature
= urllib
.parse
.unquote(transformed_signature
)
218 raise Exception("js failed to execute: %d" % p
.returncode
)
220 return transformed_signature
222 def get_best_video(player_config
):
223 js_url
= player_config
["assets"]["js"]
225 player_args
= player_config
["args"]
226 player_response
= json
.loads(player_args
["player_response"])
227 formats
= player_response
["streamingData"]["formats"]
231 best_extension
= None
232 for format_data
in formats
:
233 mimetype
= format_data
["mimeType"].split(";")[0]
234 quality
= format_data
["quality"]
236 if quality
not in QUALITIES
:
238 if mimetype
not in MIMETYPES
:
241 extension
= MIMETYPES
[mimetype
]
242 quality
= QUALITIES
.get(quality
, -1)
244 if best_quality
is not None and quality
< best_quality
:
247 if "cipher" in format_data
:
248 cipher
= urllib
.parse
.parse_qs(format_data
["cipher"])
249 video_url
= cipher
["url"][0]
251 signature
= cipher
["sig"][0]
253 signature
= decode_signature(js_url
, cipher
["s"][0])
254 sp
= cipher
.get("sp", ["signature"])[0]
255 video_url
= append_to_qs(video_url
, {sp
: signature
})
257 video_url
= format_data
["url"]
260 best_quality
= quality
261 best_extension
= extension
263 return best_url
, best_extension
265 def sanitize_filename(filename
):
267 re
.sub("\s+", " ", filename
.strip())
273 def get_video_url(page
):
274 player_config
= get_player_config(page
.scripts
)
275 if not player_config
:
276 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
278 video_url
, extension
= get_best_video(player_config
)
282 title
= player_config
["args"].get("title", None)
284 title
= json
.loads(player_config
["args"]["player_response"])["videoDetails"]["title"]
286 title
= "Unknown title"
288 filename
= sanitize_filename(title
) + "." + extension
290 return video_url
, filename
292 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
295 self
.unavailable_message
= None
298 def handle_starttag(self
, tag
, attrs
):
300 self
._handle
_unavailable
_message
(tag
, attrs
)
301 self
._handle
_script
(tag
, attrs
)
303 def handle_endtag(self
, tag
):
304 self
.handle_data
= self
._ignore
_data
306 def _ignore_data(self
, _
):
309 def _handle_unavailable_message(self
, tag
, attrs
):
310 if attrs
.get("id", None) == "unavailable-message":
311 self
.handle_data
= self
._handle
_unavailable
_message
_data
313 def _handle_unavailable_message_data(self
, data
):
314 self
.unavailable_message
= data
.strip()
316 def _handle_script(self
, tag
, attrs
):
318 self
.handle_data
= self
._handle
_script
_data
320 def _handle_script_data(self
, data
):
322 self
.scripts
.append(data
)
324 def write_video(filename
, video_data
):
325 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
326 sys
.stdout
.buffer.write(
327 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
328 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
330 sys
.stdout
.buffer.write(
331 b
"Content-Length: {0}\r\n"
332 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
334 sys
.stdout
.buffer.write(b
"\r\n")
335 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
343 print_form(url
="https://www.youtube.com/watch?v=FOOBAR")
347 page
= YouTubeVideoPageParser()
350 video_url
, filename
= get_video_url(page
)
351 video_data
= urlopen(video_url
)
352 except VideoUnavailable
as e
:
355 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
360 msg
="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
362 except Exception as e
:
365 msg
="<p class='error'>Sorry, there was an unknown error.</p>"
369 write_video(filename
, video_data
)
372 suffixes
= ["", "KiB", "MiB", "GiB"]
373 for i
, suffix
in enumerate(suffixes
):
377 return "%.2f %s" % (size
, suffix
)
379 def copy_with_progress(content_length
, infile
, outfile
):
383 rate
= last_bytes_read
/ (now
- last_ts
)
384 sys
.stdout
.write("\33[2K\r")
385 sys
.stdout
.write("%s / %s (%s/sec)" % (
387 pp_size(content_length
),
397 if now
- last_ts
> 0.5:
402 buf
= infile
.read(32768)
406 last_bytes_read
+= len(buf
)
407 bytes_read
+= len(buf
)
417 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
420 page
= YouTubeVideoPageParser()
422 video_url
, filename
= get_video_url(page
)
423 print("Downloading", filename
)
425 outfile
= open(filename
, "ab")
426 offset
= outfile
.tell()
428 print("Resuming download from", pp_size(offset
))
433 video_data
= urlopen(video_url
, offset
)
434 except urllib
.error
.HTTPError
as e
:
436 print("File is complete!")
441 content_length
= int(video_data
.getheader("Content-Length"))
442 if total_size
is None:
443 total_size
= content_length
446 copy_with_progress(content_length
, video_data
, outfile
)
451 if outfile
.tell() != total_size
:
453 offset
= outfile
.tell()
454 if old_offset
== offset
:
456 print("Restarting download from", pp_size(offset
))
463 if __name__
== "__main__":
464 if "SCRIPT_NAME" in os
.environ
:
469 except KeyboardInterrupt:
470 print("\nExiting...")