]>
code.delx.au - youtube-cgi/blob - youtube.cgi
ef7b6084433884ec75d0402a823d19c5278d35a7
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 FUNC_PARAMS
= R
"(\([a-zA-Z,\.]+\.s\))"
154 TERMINATOR
= R
"[,;\)]"
155 PATTERN
= FUNC_NAME
+ FUNC_PARAMS
+ TERMINATOR
157 match
= re
.search(PATTERN
, script
)
158 func_name
= match
.groups()[0]
161 def decode_signature(js_url
, signature
):
163 script
= f
.read().decode("utf-8")
166 func_name
= find_func_name(script
)
169 "func_name": func_name
,
170 "signature": json
.dumps(signature
),
171 "code": json
.dumps(extract_js(script
)),
173 p
= subprocess
.Popen(
177 stdin
=subprocess
.PIPE
,
178 stdout
=subprocess
.PIPE
180 js_decode_script
= ("""
181 const vm = require('vm');
190 pushState: function(){}
196 XMLHttpRequest: class XMLHttpRequest {},
197 matchMedia: () => ({matches: () => {}, media: ''}),
198 signature: %(signature)s,
199 transformed_signature: null,
200 g: function(){} // this is _yt_player
202 sandbox.window = sandbox;
204 const code_string = %(code)s + ';';
205 const exec_string = 'transformed_signature = %(func_name)s("", "MARKER", signature);';
206 vm.runInNewContext(code_string + exec_string, sandbox);
208 function findSignature(obj) {
209 if (typeof obj !== 'object') {
212 for (const [key, value] of Object.entries(obj)) {
213 if (key === 'MARKER') {
216 const result = findSignature(value);
222 console.log(findSignature(sandbox.transformed_signature));
225 p
.stdin
.write(js_decode_script
.encode("utf-8"))
228 transformed_signature
= p
.stdout
.read().decode("utf-8").strip()
229 transformed_signature
= urllib
.parse
.unquote(transformed_signature
)
231 raise Exception("js failed to execute: %d" % p
.returncode
)
233 return transformed_signature
235 def get_best_video(player_config
):
236 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
237 js_url
= player_config
["assets"]["js"]
241 best_extension
= None
242 for url_data
in url_data_list
:
243 url_data
= urllib
.parse
.parse_qs(url_data
)
244 mimetype
= url_data
["type"][0].split(";")[0]
245 quality
= url_data
["quality"][0]
247 if "stereo3d" in url_data
:
249 if quality
not in QUALITIES
:
251 if mimetype
not in MIMETYPES
:
254 extension
= MIMETYPES
[mimetype
]
255 quality
= QUALITIES
.get(quality
, -1)
257 if best_quality
is not None and quality
< best_quality
:
260 video_url
= url_data
["url"][0]
261 if "sig" in url_data
:
262 signature
= url_data
["sig"][0]
263 elif "s" in url_data
:
264 signature
= decode_signature(js_url
, url_data
["s"][0])
269 sp
= url_data
.get("sp", ["signature"])[0]
270 video_url
= append_to_qs(video_url
, {sp
: signature
})
273 best_quality
= quality
274 best_extension
= extension
276 return best_url
, best_extension
278 def sanitize_filename(filename
):
280 re
.sub("\s+", " ", filename
.strip())
286 def get_video_url(page
):
287 player_config
= get_player_config(page
.scripts
)
288 if not player_config
:
289 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
291 video_url
, extension
= get_best_video(player_config
)
295 title
= player_config
["args"].get("title", None)
297 title
= json
.loads(player_config
["args"]["player_response"])["videoDetails"]["title"]
299 title
= "Unknown title"
301 filename
= sanitize_filename(title
) + "." + extension
303 return video_url
, filename
305 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
308 self
.unavailable_message
= None
311 def handle_starttag(self
, tag
, attrs
):
313 self
._handle
_unavailable
_message
(tag
, attrs
)
314 self
._handle
_script
(tag
, attrs
)
316 def handle_endtag(self
, tag
):
317 self
.handle_data
= self
._ignore
_data
319 def _ignore_data(self
, _
):
322 def _handle_unavailable_message(self
, tag
, attrs
):
323 if attrs
.get("id", None) == "unavailable-message":
324 self
.handle_data
= self
._handle
_unavailable
_message
_data
326 def _handle_unavailable_message_data(self
, data
):
327 self
.unavailable_message
= data
.strip()
329 def _handle_script(self
, tag
, attrs
):
331 self
.handle_data
= self
._handle
_script
_data
333 def _handle_script_data(self
, data
):
335 self
.scripts
.append(data
)
337 def write_video(filename
, video_data
):
338 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
339 sys
.stdout
.buffer.write(
340 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
341 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
343 sys
.stdout
.buffer.write(
344 b
"Content-Length: {0}\r\n"
345 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
347 sys
.stdout
.buffer.write(b
"\r\n")
348 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
356 print_form(url
="https://www.youtube.com/watch?v=FOOBAR")
360 page
= YouTubeVideoPageParser()
363 video_url
, filename
= get_video_url(page
)
364 video_data
= urlopen(video_url
)
365 except VideoUnavailable
as e
:
368 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
373 msg
="<p class='error'>Sorry, that does not look like a YouTube page!</p>"
375 except Exception as e
:
378 msg
="<p class='error'>Sorry, there was an unknown error.</p>"
382 write_video(filename
, video_data
)
385 suffixes
= ["", "KiB", "MiB", "GiB"]
386 for i
, suffix
in enumerate(suffixes
):
390 return "%.2f %s" % (size
, suffix
)
392 def copy_with_progress(content_length
, infile
, outfile
):
396 rate
= last_bytes_read
/ (now
- last_ts
)
397 sys
.stdout
.write("\33[2K\r")
398 sys
.stdout
.write("%s / %s (%s/sec)" % (
400 pp_size(content_length
),
410 if now
- last_ts
> 0.5:
415 buf
= infile
.read(32768)
419 last_bytes_read
+= len(buf
)
420 bytes_read
+= len(buf
)
430 print("Usage: %s https://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
433 page
= YouTubeVideoPageParser()
435 video_url
, filename
= get_video_url(page
)
436 print("Downloading", filename
)
438 outfile
= open(filename
, "ab")
439 offset
= outfile
.tell()
441 print("Resuming download from", pp_size(offset
))
446 video_data
= urlopen(video_url
, offset
)
447 except urllib
.error
.HTTPError
as e
:
449 print("File is complete!")
454 content_length
= int(video_data
.getheader("Content-Length"))
455 if total_size
is None:
456 total_size
= content_length
459 copy_with_progress(content_length
, video_data
, outfile
)
464 if outfile
.tell() != total_size
:
466 offset
= outfile
.tell()
467 if old_offset
== offset
:
469 print("Restarting download from", pp_size(offset
))
476 if __name__
== "__main__":
477 if "SCRIPT_NAME" in os
.environ
:
482 except KeyboardInterrupt:
483 print("\nExiting...")