]>
code.delx.au - youtube-cgi/blob - youtube.cgi
b94febfdfb4f549f411477bced8349183961eb5f
18 MAX_MEMORY_BYTES
= 128 * 1024*1024
19 USER_AGENT
= "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"
36 class VideoUnavailable(Exception):
39 def print_form(url
="", msg
=""):
40 script_url
= "http://%s%s" % (os
.environ
["HTTP_HOST"], os
.environ
["REQUEST_URI"])
41 sys
.stdout
.write("Content-Type: text/html\r\n\r\n")
46 <title>delx.net.au - YouTube Scraper</title>
47 <link rel="stylesheet" type="text/css" href="/style.css">
48 <style type="text/css">
58 <h1>delx.net.au - YouTube Scraper</h1>
60 <form action="" method="get">
61 <p>This page will let you easily download YouTube videos to watch offline. It
62 will automatically grab the highest quality version.</p>
63 <div><input type="text" name="url" value="{1}"/></div>
64 <div><input type="submit" value="Download!"/></div>
66 <p>Tip! Use this bookmarklet: <a href="javascript:(function(){window.location='{2}?url='+escape(location);})()">YouTube Download</a>
67 to easily download videos. Right-click the link and add it to bookmarks,
68 then when you're looking at a YouTube page select that bookmark from your
69 browser's bookmarks menu to download the video straight away.</p>
72 """.replace("{0}", msg
).replace("{1}", url
).replace("{2}", script_url
))
74 cookiejar
= http
.cookiejar
.CookieJar()
75 urlopener
= urllib
.request
.build_opener(urllib
.request
.HTTPCookieProcessor(cookiejar
))
78 def urlopen(url
, offset
=None):
79 if url
.startswith("//"):
81 if not url
.startswith("http://") and not url
.startswith("https://"):
82 url
= "https://www.youtube.com" + url
85 req
= urllib
.request
.Request(url
)
89 req
.add_header("Referer", referrer
)
91 req
.add_header("User-Agent", USER_AGENT
)
94 req
.add_header("Range", "bytes=%d-" % offset
)
96 res
= urlopener
.open(req
)
98 content_range
= res
.getheader("Content-Range")
100 tokens
= content_range
.split()
101 assert tokens
[0] == "bytes"
102 start
= int(tokens
[1].split("-")[0])
103 assert start
== offset
106 def parse_url(url
, parser
):
108 parser
.feed(f
.read().decode("utf-8"))
112 def append_to_qs(url
, params
):
113 r
= list(urllib
.parse
.urlsplit(url
))
114 qs
= urllib
.parse
.parse_qs(r
[3])
116 r
[3] = urllib
.parse
.urlencode(qs
, True)
117 url
= urllib
.parse
.urlunsplit(r
)
120 def get_player_config(scripts
):
122 for script
in scripts
:
123 for line
in script
.split("\n"):
124 s
= "ytplayer.config = {"
126 p1
= line
.find(s
) + len(s
) - 1
127 p2
= line
.find("};", p1
) + 1
128 if p1
>= 0 and p2
> 0:
129 return json
.loads(line
[p1
:p2
])
131 def extract_js(script
):
132 PREFIX
= "var _yt_player={};(function(g){var window=this;"
133 SUFFIX
= ";})(_yt_player);\n"
134 assert script
.startswith(PREFIX
)
135 assert script
.endswith(SUFFIX
)
137 return script
[len(PREFIX
):-len(SUFFIX
)]
139 def find_func_name(script
):
140 FUNC_NAME
= R
"([a-zA-Z0-9$]+)"
141 FUNC_PARAMS
= R
"(\([a-zA-Z,\.]+\.s\))"
142 TERMINATOR
= R
"[,;\)]"
143 PATTERN
= FUNC_NAME
+ FUNC_PARAMS
+ TERMINATOR
145 match
= re
.search(PATTERN
, script
)
146 func_name
= match
.groups()[0]
149 def decode_signature(js_url
, signature
):
151 script
= f
.read().decode("utf-8")
154 func_name
= find_func_name(script
)
157 "func_name": func_name
,
158 "signature": json
.dumps(signature
),
159 "code": json
.dumps(extract_js(script
)),
161 p
= subprocess
.Popen(
165 stdin
=subprocess
.PIPE
,
166 stdout
=subprocess
.PIPE
168 js_decode_script
= ("""
169 const vm = require('vm');
178 pushState: function(){}
184 XMLHttpRequest: class XMLHttpRequest {},
185 matchMedia: () => ({matches: () => {}, media: ''}),
186 signature: %(signature)s,
187 transformed_signature: null,
188 g: function(){} // this is _yt_player
190 sandbox.window = sandbox;
192 const code_string = %(code)s + ';';
193 const exec_string = 'transformed_signature = %(func_name)s("", "MARKER", signature);';
194 vm.runInNewContext(code_string + exec_string, sandbox);
196 function findSignature(obj) {
197 if (typeof obj !== 'object') {
200 for (const [key, value] of Object.entries(obj)) {
201 if (key === 'MARKER') {
204 const result = findSignature(value);
210 console.log(findSignature(sandbox.transformed_signature));
213 p
.stdin
.write(js_decode_script
.encode("utf-8"))
216 transformed_signature
= p
.stdout
.read().decode("utf-8").strip()
218 raise Exception("js failed to execute: %d" % p
.returncode
)
220 return transformed_signature
222 def get_best_video(player_config
):
223 url_data_list
= player_config
["args"]["url_encoded_fmt_stream_map"].split(",")
224 js_url
= player_config
["assets"]["js"]
228 best_extension
= None
229 for url_data
in url_data_list
:
230 url_data
= urllib
.parse
.parse_qs(url_data
)
231 mimetype
= url_data
["type"][0].split(";")[0]
232 quality
= url_data
["quality"][0]
234 if "stereo3d" in url_data
:
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 video_url
= url_data
["url"][0]
248 if "sig" in url_data
:
249 signature
= url_data
["sig"][0]
250 elif "s" in url_data
:
251 signature
= decode_signature(js_url
, url_data
["s"][0])
256 video_url
= append_to_qs(video_url
, {"signature": signature
})
259 best_quality
= quality
260 best_extension
= extension
262 return best_url
, best_extension
264 def sanitize_filename(filename
):
266 re
.sub("\s+", " ", filename
.strip())
272 def get_video_url(page
):
273 player_config
= get_player_config(page
.scripts
)
274 if not player_config
:
275 raise VideoUnavailable(page
.unavailable_message
or "Could not find video URL")
277 video_url
, extension
= get_best_video(player_config
)
281 filename
= sanitize_filename(page
.title
)
282 filename
+= "." + extension
284 return video_url
, filename
286 class YouTubeVideoPageParser(html
.parser
.HTMLParser
):
290 self
.unavailable_message
= None
293 def handle_starttag(self
, tag
, attrs
):
295 self
._handle
_title
(tag
, attrs
)
296 self
._handle
_unavailable
_message
(tag
, attrs
)
297 self
._handle
_script
(tag
, attrs
)
299 def handle_endtag(self
, tag
):
300 self
.handle_data
= self
._ignore
_data
302 def _ignore_data(self
, _
):
305 def _handle_title(self
, tag
, attrs
):
307 self
.handle_data
= self
._handle
_title
_data
309 def _handle_title_data(self
, data
):
310 self
.title
= data
.strip()
312 def _handle_unavailable_message(self
, tag
, attrs
):
313 if attrs
.get("id", None) == "unavailable-message":
314 self
.handle_data
= self
._handle
_unavailable
_message
_data
316 def _handle_unavailable_message_data(self
, data
):
317 self
.unavailable_message
= data
.strip()
319 def _handle_script(self
, tag
, attrs
):
321 self
.handle_data
= self
._handle
_script
_data
323 def _handle_script_data(self
, data
):
325 self
.scripts
.append(data
)
327 def write_video(filename
, video_data
):
328 quoted_filename
= urllib
.parse
.quote(filename
.encode("utf-8"))
329 sys
.stdout
.buffer.write(
330 b
"Content-Disposition: attachment; filename*=UTF-8''{0}\r\n"
331 .replace(b
"{0}", quoted_filename
.encode("utf-8"))
333 sys
.stdout
.buffer.write(
334 b
"Content-Length: {0}\r\n"
335 .replace(b
"{0}", video_data
.getheader("Content-Length").encode("utf-8"))
337 sys
.stdout
.buffer.write(b
"\r\n")
338 shutil
.copyfileobj(video_data
, sys
.stdout
.buffer)
346 print_form(url
="http://www.youtube.com/watch?v=FOOBAR")
350 page
= YouTubeVideoPageParser()
352 video_url
, filename
= get_video_url(page
)
353 video_data
= urlopen(video_url
)
354 except VideoUnavailable
as e
:
357 msg
="<p class='error'>Sorry, there was an error: %s</p>" % cgi
.escape(e
.args
[0])
359 except Exception as e
:
362 msg
="<p class='error'>Sorry, there was an error. Check your URL?</p>"
366 write_video(filename
, video_data
)
369 suffixes
= ["", "KiB", "MiB", "GiB"]
370 for i
, suffix
in enumerate(suffixes
):
374 return "%.2f %s" % (size
, suffix
)
376 def copy_with_progress(content_length
, infile
, outfile
):
380 rate
= last_bytes_read
/ (now
- last_ts
)
381 sys
.stdout
.write("\33[2K\r")
382 sys
.stdout
.write("%s / %s (%s/sec)" % (
384 pp_size(content_length
),
394 if now
- last_ts
> 0.5:
399 buf
= infile
.read(32768)
403 last_bytes_read
+= len(buf
)
404 bytes_read
+= len(buf
)
414 print("Usage: %s http://youtube.com/watch?v=FOOBAR" % sys
.argv
[0], file=sys
.stderr
)
417 page
= YouTubeVideoPageParser()
419 video_url
, filename
= get_video_url(page
)
420 print("Downloading", filename
)
422 outfile
= open(filename
, "ab")
423 offset
= outfile
.tell()
425 print("Resuming download from", pp_size(offset
))
430 video_data
= urlopen(video_url
, offset
)
431 except urllib
.error
.HTTPError
as e
:
433 print("File is complete!")
438 content_length
= int(video_data
.getheader("Content-Length"))
439 if total_size
is None:
440 total_size
= content_length
443 copy_with_progress(content_length
, video_data
, outfile
)
448 if outfile
.tell() != total_size
:
450 offset
= outfile
.tell()
451 if old_offset
== offset
:
453 print("Restarting download from", pp_size(offset
))
460 if __name__
== "__main__":
461 if "SCRIPT_NAME" in os
.environ
:
466 except KeyboardInterrupt:
467 print("\nExiting...")