]>
Commit | Line | Data |
---|---|---|
c5e8d7af PH |
1 | # coding: utf-8 |
2 | from __future__ import absolute_import | |
3 | ||
4 | import json | |
5 | import netrc | |
6 | import re | |
7 | import socket | |
8 | ||
9 | from .common import InfoExtractor | |
10 | from ..utils import ( | |
11 | compat_http_client, | |
12 | compat_parse_qs, | |
13 | compat_urllib_error, | |
14 | compat_urllib_parse, | |
15 | compat_urllib_request, | |
16 | compat_str, | |
17 | ||
18 | clean_html, | |
19 | get_element_by_id, | |
20 | ExtractorError, | |
21 | unescapeHTML, | |
22 | unified_strdate, | |
23 | ) | |
24 | ||
25 | ||
26 | class YoutubeIE(InfoExtractor): | |
27 | """Information extractor for youtube.com.""" | |
28 | ||
29 | _VALID_URL = r"""^ | |
30 | ( | |
31 | (?:https?://)? # http(s):// (optional) | |
32 | (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/| | |
33 | tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains | |
34 | (?:.*?\#/)? # handle anchor (#/) redirect urls | |
35 | (?: # the various things that can precede the ID: | |
36 | (?:(?:v|embed|e)/) # v/ or embed/ or e/ | |
37 | |(?: # or the v= param in all its forms | |
38 | (?:watch(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx) | |
39 | (?:\?|\#!?) # the params delimiter ? or # or #! | |
40 | (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx) | |
41 | v= | |
42 | ) | |
43 | )? # optional -> youtube.com/xxxx is OK | |
44 | )? # all until now is optional -> you can pass the naked ID | |
45 | ([0-9A-Za-z_-]+) # here is it! the YouTube video ID | |
46 | (?(1).+)? # if we found the ID, everything can follow | |
47 | $""" | |
48 | _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1' | |
49 | _LOGIN_URL = 'https://accounts.google.com/ServiceLogin' | |
50 | _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en' | |
51 | _NEXT_URL_RE = r'[\?&]next_url=([^&]+)' | |
52 | _NETRC_MACHINE = 'youtube' | |
53 | # Listed in order of quality | |
54 | _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '17', '13'] | |
55 | _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '17', '13'] | |
56 | _video_extensions = { | |
57 | '13': '3gp', | |
58 | '17': 'mp4', | |
59 | '18': 'mp4', | |
60 | '22': 'mp4', | |
61 | '37': 'mp4', | |
62 | '38': 'video', # You actually don't know if this will be MOV, AVI or whatever | |
63 | '43': 'webm', | |
64 | '44': 'webm', | |
65 | '45': 'webm', | |
66 | '46': 'webm', | |
67 | } | |
68 | _video_dimensions = { | |
69 | '5': '240x400', | |
70 | '6': '???', | |
71 | '13': '???', | |
72 | '17': '144x176', | |
73 | '18': '360x640', | |
74 | '22': '720x1280', | |
75 | '34': '360x640', | |
76 | '35': '480x854', | |
77 | '37': '1080x1920', | |
78 | '38': '3072x4096', | |
79 | '43': '360x640', | |
80 | '44': '480x854', | |
81 | '45': '720x1280', | |
82 | '46': '1080x1920', | |
83 | } | |
84 | IE_NAME = u'youtube' | |
85 | ||
86 | @classmethod | |
87 | def suitable(cls, url): | |
88 | """Receives a URL and returns True if suitable for this IE.""" | |
89 | if YoutubePlaylistIE.suitable(url): return False | |
90 | return re.match(cls._VALID_URL, url, re.VERBOSE) is not None | |
91 | ||
92 | def report_lang(self): | |
93 | """Report attempt to set language.""" | |
94 | self.to_screen(u'Setting language') | |
95 | ||
96 | def report_login(self): | |
97 | """Report attempt to log in.""" | |
98 | self.to_screen(u'Logging in') | |
99 | ||
100 | def report_video_webpage_download(self, video_id): | |
101 | """Report attempt to download video webpage.""" | |
102 | self.to_screen(u'%s: Downloading video webpage' % video_id) | |
103 | ||
104 | def report_video_info_webpage_download(self, video_id): | |
105 | """Report attempt to download video info webpage.""" | |
106 | self.to_screen(u'%s: Downloading video info webpage' % video_id) | |
107 | ||
108 | def report_video_subtitles_download(self, video_id): | |
109 | """Report attempt to download video info webpage.""" | |
110 | self.to_screen(u'%s: Checking available subtitles' % video_id) | |
111 | ||
112 | def report_video_subtitles_request(self, video_id, sub_lang, format): | |
113 | """Report attempt to download video info webpage.""" | |
114 | self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format)) | |
115 | ||
116 | def report_video_subtitles_available(self, video_id, sub_lang_list): | |
117 | """Report available subtitles.""" | |
118 | sub_lang = ",".join(list(sub_lang_list.keys())) | |
119 | self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang)) | |
120 | ||
121 | def report_information_extraction(self, video_id): | |
122 | """Report attempt to extract video information.""" | |
123 | self.to_screen(u'%s: Extracting video information' % video_id) | |
124 | ||
125 | def report_unavailable_format(self, video_id, format): | |
126 | """Report extracted video URL.""" | |
127 | self.to_screen(u'%s: Format %s not available' % (video_id, format)) | |
128 | ||
129 | def report_rtmp_download(self): | |
130 | """Indicate the download will use the RTMP protocol.""" | |
131 | self.to_screen(u'RTMP download detected') | |
132 | ||
133 | @staticmethod | |
134 | def _decrypt_signature(s): | |
135 | """Decrypt the key the two subkeys must have a length of 43""" | |
136 | (a,b) = s.split('.') | |
137 | if len(a) != 43 or len(b) != 43: | |
138 | raise ExtractorError(u'Unable to decrypt signature, subkeys lengths not valid') | |
139 | b = ''.join([b[:8],a[0],b[9:18],b[-4],b[19:39], b[18]])[0:40] | |
140 | a = a[-40:] | |
141 | s_dec = '.'.join((a,b))[::-1] | |
142 | return s_dec | |
143 | ||
144 | def _get_available_subtitles(self, video_id): | |
145 | self.report_video_subtitles_download(video_id) | |
146 | request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id) | |
147 | try: | |
148 | sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8') | |
149 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
150 | return (u'unable to download video subtitles: %s' % compat_str(err), None) | |
151 | sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list) | |
152 | sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list) | |
153 | if not sub_lang_list: | |
154 | return (u'video doesn\'t have subtitles', None) | |
155 | return sub_lang_list | |
156 | ||
157 | def _list_available_subtitles(self, video_id): | |
158 | sub_lang_list = self._get_available_subtitles(video_id) | |
159 | self.report_video_subtitles_available(video_id, sub_lang_list) | |
160 | ||
161 | def _request_subtitle(self, sub_lang, sub_name, video_id, format): | |
162 | """ | |
163 | Return tuple: | |
164 | (error_message, sub_lang, sub) | |
165 | """ | |
166 | self.report_video_subtitles_request(video_id, sub_lang, format) | |
167 | params = compat_urllib_parse.urlencode({ | |
168 | 'lang': sub_lang, | |
169 | 'name': sub_name, | |
170 | 'v': video_id, | |
171 | 'fmt': format, | |
172 | }) | |
173 | url = 'http://www.youtube.com/api/timedtext?' + params | |
174 | try: | |
175 | sub = compat_urllib_request.urlopen(url).read().decode('utf-8') | |
176 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
177 | return (u'unable to download video subtitles: %s' % compat_str(err), None, None) | |
178 | if not sub: | |
179 | return (u'Did not fetch video subtitles', None, None) | |
180 | return (None, sub_lang, sub) | |
181 | ||
182 | def _request_automatic_caption(self, video_id, webpage): | |
183 | """We need the webpage for getting the captions url, pass it as an | |
184 | argument to speed up the process.""" | |
185 | sub_lang = self._downloader.params.get('subtitleslang') or 'en' | |
186 | sub_format = self._downloader.params.get('subtitlesformat') | |
187 | self.to_screen(u'%s: Looking for automatic captions' % video_id) | |
188 | mobj = re.search(r';ytplayer.config = ({.*?});', webpage) | |
189 | err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang | |
190 | if mobj is None: | |
191 | return [(err_msg, None, None)] | |
192 | player_config = json.loads(mobj.group(1)) | |
193 | try: | |
194 | args = player_config[u'args'] | |
195 | caption_url = args[u'ttsurl'] | |
196 | timestamp = args[u'timestamp'] | |
197 | params = compat_urllib_parse.urlencode({ | |
198 | 'lang': 'en', | |
199 | 'tlang': sub_lang, | |
200 | 'fmt': sub_format, | |
201 | 'ts': timestamp, | |
202 | 'kind': 'asr', | |
203 | }) | |
204 | subtitles_url = caption_url + '&' + params | |
205 | sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions') | |
206 | return [(None, sub_lang, sub)] | |
207 | except KeyError: | |
208 | return [(err_msg, None, None)] | |
209 | ||
210 | def _extract_subtitle(self, video_id): | |
211 | """ | |
212 | Return a list with a tuple: | |
213 | [(error_message, sub_lang, sub)] | |
214 | """ | |
215 | sub_lang_list = self._get_available_subtitles(video_id) | |
216 | sub_format = self._downloader.params.get('subtitlesformat') | |
217 | if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles | |
218 | return [(sub_lang_list[0], None, None)] | |
219 | if self._downloader.params.get('subtitleslang', False): | |
220 | sub_lang = self._downloader.params.get('subtitleslang') | |
221 | elif 'en' in sub_lang_list: | |
222 | sub_lang = 'en' | |
223 | else: | |
224 | sub_lang = list(sub_lang_list.keys())[0] | |
225 | if not sub_lang in sub_lang_list: | |
226 | return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)] | |
227 | ||
228 | subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format) | |
229 | return [subtitle] | |
230 | ||
231 | def _extract_all_subtitles(self, video_id): | |
232 | sub_lang_list = self._get_available_subtitles(video_id) | |
233 | sub_format = self._downloader.params.get('subtitlesformat') | |
234 | if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles | |
235 | return [(sub_lang_list[0], None, None)] | |
236 | subtitles = [] | |
237 | for sub_lang in sub_lang_list: | |
238 | subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format) | |
239 | subtitles.append(subtitle) | |
240 | return subtitles | |
241 | ||
242 | def _print_formats(self, formats): | |
243 | print('Available formats:') | |
244 | for x in formats: | |
245 | print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???'))) | |
246 | ||
247 | def _real_initialize(self): | |
248 | if self._downloader is None: | |
249 | return | |
250 | ||
251 | username = None | |
252 | password = None | |
253 | downloader_params = self._downloader.params | |
254 | ||
255 | # Attempt to use provided username and password or .netrc data | |
256 | if downloader_params.get('username', None) is not None: | |
257 | username = downloader_params['username'] | |
258 | password = downloader_params['password'] | |
259 | elif downloader_params.get('usenetrc', False): | |
260 | try: | |
261 | info = netrc.netrc().authenticators(self._NETRC_MACHINE) | |
262 | if info is not None: | |
263 | username = info[0] | |
264 | password = info[2] | |
265 | else: | |
266 | raise netrc.NetrcParseError('No authenticators for %s' % self._NETRC_MACHINE) | |
267 | except (IOError, netrc.NetrcParseError) as err: | |
268 | self._downloader.report_warning(u'parsing .netrc: %s' % compat_str(err)) | |
269 | return | |
270 | ||
271 | # Set language | |
272 | request = compat_urllib_request.Request(self._LANG_URL) | |
273 | try: | |
274 | self.report_lang() | |
275 | compat_urllib_request.urlopen(request).read() | |
276 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
277 | self._downloader.report_warning(u'unable to set language: %s' % compat_str(err)) | |
278 | return | |
279 | ||
280 | # No authentication to be performed | |
281 | if username is None: | |
282 | return | |
283 | ||
284 | request = compat_urllib_request.Request(self._LOGIN_URL) | |
285 | try: | |
286 | login_page = compat_urllib_request.urlopen(request).read().decode('utf-8') | |
287 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
288 | self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err)) | |
289 | return | |
290 | ||
291 | galx = None | |
292 | dsh = None | |
293 | match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page) | |
294 | if match: | |
295 | galx = match.group(1) | |
296 | ||
297 | match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page) | |
298 | if match: | |
299 | dsh = match.group(1) | |
300 | ||
301 | # Log in | |
302 | login_form_strs = { | |
303 | u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1', | |
304 | u'Email': username, | |
305 | u'GALX': galx, | |
306 | u'Passwd': password, | |
307 | u'PersistentCookie': u'yes', | |
308 | u'_utf8': u'霱', | |
309 | u'bgresponse': u'js_disabled', | |
310 | u'checkConnection': u'', | |
311 | u'checkedDomains': u'youtube', | |
312 | u'dnConn': u'', | |
313 | u'dsh': dsh, | |
314 | u'pstMsg': u'0', | |
315 | u'rmShown': u'1', | |
316 | u'secTok': u'', | |
317 | u'signIn': u'Sign in', | |
318 | u'timeStmp': u'', | |
319 | u'service': u'youtube', | |
320 | u'uilel': u'3', | |
321 | u'hl': u'en_US', | |
322 | } | |
323 | # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode | |
324 | # chokes on unicode | |
325 | login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items()) | |
326 | login_data = compat_urllib_parse.urlencode(login_form).encode('ascii') | |
327 | request = compat_urllib_request.Request(self._LOGIN_URL, login_data) | |
328 | try: | |
329 | self.report_login() | |
330 | login_results = compat_urllib_request.urlopen(request).read().decode('utf-8') | |
331 | if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None: | |
332 | self._downloader.report_warning(u'unable to log in: bad username or password') | |
333 | return | |
334 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
335 | self._downloader.report_warning(u'unable to log in: %s' % compat_str(err)) | |
336 | return | |
337 | ||
338 | # Confirm age | |
339 | age_form = { | |
340 | 'next_url': '/', | |
341 | 'action_confirm': 'Confirm', | |
342 | } | |
343 | request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form)) | |
344 | try: | |
345 | self.report_age_confirmation() | |
346 | age_results = compat_urllib_request.urlopen(request).read().decode('utf-8') | |
347 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
348 | raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err)) | |
349 | ||
350 | def _extract_id(self, url): | |
351 | mobj = re.match(self._VALID_URL, url, re.VERBOSE) | |
352 | if mobj is None: | |
353 | raise ExtractorError(u'Invalid URL: %s' % url) | |
354 | video_id = mobj.group(2) | |
355 | return video_id | |
356 | ||
357 | def _real_extract(self, url): | |
358 | # Extract original video URL from URL with redirection, like age verification, using next_url parameter | |
359 | mobj = re.search(self._NEXT_URL_RE, url) | |
360 | if mobj: | |
361 | url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/') | |
362 | video_id = self._extract_id(url) | |
363 | ||
364 | # Get video webpage | |
365 | self.report_video_webpage_download(video_id) | |
366 | url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id | |
367 | request = compat_urllib_request.Request(url) | |
368 | try: | |
369 | video_webpage_bytes = compat_urllib_request.urlopen(request).read() | |
370 | except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err: | |
371 | raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err)) | |
372 | ||
373 | video_webpage = video_webpage_bytes.decode('utf-8', 'ignore') | |
374 | ||
375 | # Attempt to extract SWF player URL | |
376 | mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage) | |
377 | if mobj is not None: | |
378 | player_url = re.sub(r'\\(.)', r'\1', mobj.group(1)) | |
379 | else: | |
380 | player_url = None | |
381 | ||
382 | # Get video info | |
383 | self.report_video_info_webpage_download(video_id) | |
384 | for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']: | |
385 | video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en' | |
386 | % (video_id, el_type)) | |
387 | video_info_webpage = self._download_webpage(video_info_url, video_id, | |
388 | note=False, | |
389 | errnote='unable to download video info webpage') | |
390 | video_info = compat_parse_qs(video_info_webpage) | |
391 | if 'token' in video_info: | |
392 | break | |
393 | if 'token' not in video_info: | |
394 | if 'reason' in video_info: | |
395 | raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0]) | |
396 | else: | |
397 | raise ExtractorError(u'"token" parameter not in video info for unknown reason') | |
398 | ||
399 | # Check for "rental" videos | |
400 | if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info: | |
401 | raise ExtractorError(u'"rental" videos not supported') | |
402 | ||
403 | # Start extracting information | |
404 | self.report_information_extraction(video_id) | |
405 | ||
406 | # uploader | |
407 | if 'author' not in video_info: | |
408 | raise ExtractorError(u'Unable to extract uploader name') | |
409 | video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0]) | |
410 | ||
411 | # uploader_id | |
412 | video_uploader_id = None | |
413 | mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage) | |
414 | if mobj is not None: | |
415 | video_uploader_id = mobj.group(1) | |
416 | else: | |
417 | self._downloader.report_warning(u'unable to extract uploader nickname') | |
418 | ||
419 | # title | |
420 | if 'title' not in video_info: | |
421 | raise ExtractorError(u'Unable to extract video title') | |
422 | video_title = compat_urllib_parse.unquote_plus(video_info['title'][0]) | |
423 | ||
424 | # thumbnail image | |
425 | if 'thumbnail_url' not in video_info: | |
426 | self._downloader.report_warning(u'unable to extract video thumbnail') | |
427 | video_thumbnail = '' | |
428 | else: # don't panic if we can't find it | |
429 | video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0]) | |
430 | ||
431 | # upload date | |
432 | upload_date = None | |
433 | mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL) | |
434 | if mobj is not None: | |
435 | upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split()) | |
436 | upload_date = unified_strdate(upload_date) | |
437 | ||
438 | # description | |
439 | video_description = get_element_by_id("eow-description", video_webpage) | |
440 | if video_description: | |
441 | video_description = clean_html(video_description) | |
442 | else: | |
443 | fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage) | |
444 | if fd_mobj: | |
445 | video_description = unescapeHTML(fd_mobj.group(1)) | |
446 | else: | |
447 | video_description = u'' | |
448 | ||
449 | # subtitles | |
450 | video_subtitles = None | |
451 | ||
452 | if self._downloader.params.get('writesubtitles', False): | |
453 | video_subtitles = self._extract_subtitle(video_id) | |
454 | if video_subtitles: | |
455 | (sub_error, sub_lang, sub) = video_subtitles[0] | |
456 | if sub_error: | |
457 | # We try with the automatic captions | |
458 | video_subtitles = self._request_automatic_caption(video_id, video_webpage) | |
459 | (sub_error_auto, sub_lang, sub) = video_subtitles[0] | |
460 | if sub is not None: | |
461 | pass | |
462 | else: | |
463 | # We report the original error | |
464 | self._downloader.report_warning(sub_error) | |
465 | ||
466 | if self._downloader.params.get('allsubtitles', False): | |
467 | video_subtitles = self._extract_all_subtitles(video_id) | |
468 | for video_subtitle in video_subtitles: | |
469 | (sub_error, sub_lang, sub) = video_subtitle | |
470 | if sub_error: | |
471 | self._downloader.report_warning(sub_error) | |
472 | ||
473 | if self._downloader.params.get('listsubtitles', False): | |
474 | sub_lang_list = self._list_available_subtitles(video_id) | |
475 | return | |
476 | ||
477 | if 'length_seconds' not in video_info: | |
478 | self._downloader.report_warning(u'unable to extract video duration') | |
479 | video_duration = '' | |
480 | else: | |
481 | video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]) | |
482 | ||
483 | # token | |
484 | video_token = compat_urllib_parse.unquote_plus(video_info['token'][0]) | |
485 | ||
486 | # Decide which formats to download | |
487 | req_format = self._downloader.params.get('format', None) | |
488 | ||
489 | try: | |
490 | mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage) | |
491 | info = json.loads(mobj.group(1)) | |
492 | args = info['args'] | |
493 | if args.get('ptk','') == 'vevo' or 'dashmpd': | |
494 | # Vevo videos with encrypted signatures | |
495 | self.to_screen(u'%s: Vevo video detected.' % video_id) | |
496 | video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']] | |
497 | except ValueError: | |
498 | pass | |
499 | ||
500 | if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'): | |
501 | self.report_rtmp_download() | |
502 | video_url_list = [(None, video_info['conn'][0])] | |
503 | elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1: | |
504 | url_map = {} | |
505 | for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','): | |
506 | url_data = compat_parse_qs(url_data_str) | |
507 | if 'itag' in url_data and 'url' in url_data: | |
508 | url = url_data['url'][0] | |
509 | if 'sig' in url_data: | |
510 | url += '&signature=' + url_data['sig'][0] | |
511 | elif 's' in url_data: | |
512 | signature = self._decrypt_signature(url_data['s'][0]) | |
513 | url += '&signature=' + signature | |
514 | if 'ratebypass' not in url: | |
515 | url += '&ratebypass=yes' | |
516 | url_map[url_data['itag'][0]] = url | |
517 | ||
518 | format_limit = self._downloader.params.get('format_limit', None) | |
519 | available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats | |
520 | if format_limit is not None and format_limit in available_formats: | |
521 | format_list = available_formats[available_formats.index(format_limit):] | |
522 | else: | |
523 | format_list = available_formats | |
524 | existing_formats = [x for x in format_list if x in url_map] | |
525 | if len(existing_formats) == 0: | |
526 | raise ExtractorError(u'no known formats available for video') | |
527 | if self._downloader.params.get('listformats', None): | |
528 | self._print_formats(existing_formats) | |
529 | return | |
530 | if req_format is None or req_format == 'best': | |
531 | video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality | |
532 | elif req_format == 'worst': | |
533 | video_url_list = [(existing_formats[len(existing_formats)-1], url_map[existing_formats[len(existing_formats)-1]])] # worst quality | |
534 | elif req_format in ('-1', 'all'): | |
535 | video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats | |
536 | else: | |
537 | # Specific formats. We pick the first in a slash-delimeted sequence. | |
538 | # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'. | |
539 | req_formats = req_format.split('/') | |
540 | video_url_list = None | |
541 | for rf in req_formats: | |
542 | if rf in url_map: | |
543 | video_url_list = [(rf, url_map[rf])] | |
544 | break | |
545 | if video_url_list is None: | |
546 | raise ExtractorError(u'requested format not available') | |
547 | else: | |
548 | raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info') | |
549 | ||
550 | results = [] | |
551 | for format_param, video_real_url in video_url_list: | |
552 | # Extension | |
553 | video_extension = self._video_extensions.get(format_param, 'flv') | |
554 | ||
555 | video_format = '{0} - {1}'.format(format_param if format_param else video_extension, | |
556 | self._video_dimensions.get(format_param, '???')) | |
557 | ||
558 | results.append({ | |
559 | 'id': video_id, | |
560 | 'url': video_real_url, | |
561 | 'uploader': video_uploader, | |
562 | 'uploader_id': video_uploader_id, | |
563 | 'upload_date': upload_date, | |
564 | 'title': video_title, | |
565 | 'ext': video_extension, | |
566 | 'format': video_format, | |
567 | 'thumbnail': video_thumbnail, | |
568 | 'description': video_description, | |
569 | 'player_url': player_url, | |
570 | 'subtitles': video_subtitles, | |
571 | 'duration': video_duration | |
572 | }) | |
573 | return results | |
574 | ||
575 | class YoutubePlaylistIE(InfoExtractor): | |
576 | """Information Extractor for YouTube playlists.""" | |
577 | ||
578 | _VALID_URL = r"""(?: | |
579 | (?:https?://)? | |
580 | (?:\w+\.)? | |
581 | youtube\.com/ | |
582 | (?: | |
583 | (?:course|view_play_list|my_playlists|artist|playlist|watch) | |
584 | \? (?:.*?&)*? (?:p|a|list)= | |
585 | | p/ | |
586 | ) | |
587 | ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,}) | |
588 | .* | |
589 | | | |
590 | ((?:PL|EC|UU)[0-9A-Za-z-_]{10,}) | |
591 | )""" | |
592 | _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none' | |
593 | _MAX_RESULTS = 50 | |
594 | IE_NAME = u'youtube:playlist' | |
595 | ||
596 | @classmethod | |
597 | def suitable(cls, url): | |
598 | """Receives a URL and returns True if suitable for this IE.""" | |
599 | return re.match(cls._VALID_URL, url, re.VERBOSE) is not None | |
600 | ||
601 | def _real_extract(self, url): | |
602 | # Extract playlist id | |
603 | mobj = re.match(self._VALID_URL, url, re.VERBOSE) | |
604 | if mobj is None: | |
605 | raise ExtractorError(u'Invalid URL: %s' % url) | |
606 | ||
607 | # Download playlist videos from API | |
608 | playlist_id = mobj.group(1) or mobj.group(2) | |
609 | page_num = 1 | |
610 | videos = [] | |
611 | ||
612 | while True: | |
613 | url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1) | |
614 | page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num) | |
615 | ||
616 | try: | |
617 | response = json.loads(page) | |
618 | except ValueError as err: | |
619 | raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err)) | |
620 | ||
621 | if 'feed' not in response: | |
622 | raise ExtractorError(u'Got a malformed response from YouTube API') | |
623 | playlist_title = response['feed']['title']['$t'] | |
624 | if 'entry' not in response['feed']: | |
625 | # Number of videos is a multiple of self._MAX_RESULTS | |
626 | break | |
627 | ||
628 | for entry in response['feed']['entry']: | |
629 | index = entry['yt$position']['$t'] | |
630 | if 'media$group' in entry and 'media$player' in entry['media$group']: | |
631 | videos.append((index, entry['media$group']['media$player']['url'])) | |
632 | ||
633 | if len(response['feed']['entry']) < self._MAX_RESULTS: | |
634 | break | |
635 | page_num += 1 | |
636 | ||
637 | videos = [v[1] for v in sorted(videos)] | |
638 | ||
639 | url_results = [self.url_result(url, 'Youtube') for url in videos] | |
640 | return [self.playlist_result(url_results, playlist_id, playlist_title)] | |
641 | ||
642 | ||
643 | class YoutubeChannelIE(InfoExtractor): | |
644 | """Information Extractor for YouTube channels.""" | |
645 | ||
646 | _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)" | |
647 | _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en' | |
648 | _MORE_PAGES_INDICATOR = 'yt-uix-load-more' | |
649 | _MORE_PAGES_URL = 'http://www.youtube.com/channel_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s' | |
650 | IE_NAME = u'youtube:channel' | |
651 | ||
652 | def extract_videos_from_page(self, page): | |
653 | ids_in_page = [] | |
654 | for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page): | |
655 | if mobj.group(1) not in ids_in_page: | |
656 | ids_in_page.append(mobj.group(1)) | |
657 | return ids_in_page | |
658 | ||
659 | def _real_extract(self, url): | |
660 | # Extract channel id | |
661 | mobj = re.match(self._VALID_URL, url) | |
662 | if mobj is None: | |
663 | raise ExtractorError(u'Invalid URL: %s' % url) | |
664 | ||
665 | # Download channel page | |
666 | channel_id = mobj.group(1) | |
667 | video_ids = [] | |
668 | pagenum = 1 | |
669 | ||
670 | url = self._TEMPLATE_URL % (channel_id, pagenum) | |
671 | page = self._download_webpage(url, channel_id, | |
672 | u'Downloading page #%s' % pagenum) | |
673 | ||
674 | # Extract video identifiers | |
675 | ids_in_page = self.extract_videos_from_page(page) | |
676 | video_ids.extend(ids_in_page) | |
677 | ||
678 | # Download any subsequent channel pages using the json-based channel_ajax query | |
679 | if self._MORE_PAGES_INDICATOR in page: | |
680 | while True: | |
681 | pagenum = pagenum + 1 | |
682 | ||
683 | url = self._MORE_PAGES_URL % (pagenum, channel_id) | |
684 | page = self._download_webpage(url, channel_id, | |
685 | u'Downloading page #%s' % pagenum) | |
686 | ||
687 | page = json.loads(page) | |
688 | ||
689 | ids_in_page = self.extract_videos_from_page(page['content_html']) | |
690 | video_ids.extend(ids_in_page) | |
691 | ||
692 | if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']: | |
693 | break | |
694 | ||
695 | self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids))) | |
696 | ||
697 | urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids] | |
698 | url_entries = [self.url_result(url, 'Youtube') for url in urls] | |
699 | return [self.playlist_result(url_entries, channel_id)] | |
700 | ||
701 | ||
702 | class YoutubeUserIE(InfoExtractor): | |
703 | """Information Extractor for YouTube users.""" | |
704 | ||
705 | _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)' | |
706 | _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s' | |
707 | _GDATA_PAGE_SIZE = 50 | |
708 | _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d' | |
709 | _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]' | |
710 | IE_NAME = u'youtube:user' | |
711 | ||
712 | def _real_extract(self, url): | |
713 | # Extract username | |
714 | mobj = re.match(self._VALID_URL, url) | |
715 | if mobj is None: | |
716 | raise ExtractorError(u'Invalid URL: %s' % url) | |
717 | ||
718 | username = mobj.group(1) | |
719 | ||
720 | # Download video ids using YouTube Data API. Result size per | |
721 | # query is limited (currently to 50 videos) so we need to query | |
722 | # page by page until there are no video ids - it means we got | |
723 | # all of them. | |
724 | ||
725 | video_ids = [] | |
726 | pagenum = 0 | |
727 | ||
728 | while True: | |
729 | start_index = pagenum * self._GDATA_PAGE_SIZE + 1 | |
730 | ||
731 | gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index) | |
732 | page = self._download_webpage(gdata_url, username, | |
733 | u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE)) | |
734 | ||
735 | # Extract video identifiers | |
736 | ids_in_page = [] | |
737 | ||
738 | for mobj in re.finditer(self._VIDEO_INDICATOR, page): | |
739 | if mobj.group(1) not in ids_in_page: | |
740 | ids_in_page.append(mobj.group(1)) | |
741 | ||
742 | video_ids.extend(ids_in_page) | |
743 | ||
744 | # A little optimization - if current page is not | |
745 | # "full", ie. does not contain PAGE_SIZE video ids then | |
746 | # we can assume that this page is the last one - there | |
747 | # are no more ids on further pages - no need to query | |
748 | # again. | |
749 | ||
750 | if len(ids_in_page) < self._GDATA_PAGE_SIZE: | |
751 | break | |
752 | ||
753 | pagenum += 1 | |
754 | ||
755 | urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids] | |
756 | url_results = [self.url_result(url, 'Youtube') for url in urls] | |
757 | return [self.playlist_result(url_results, playlist_title = username)] |