9 from .common import InfoExtractor, SearchInfoExtractor
15 compat_urllib_request,
27 class YoutubeIE(InfoExtractor):
28 IE_DESC = u'YouTube.com'
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|movie(?:_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)
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
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']
87 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
88 u"file": u"BaW_jenozKc.mp4",
90 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
91 u"uploader": u"Philipp Hagemeister",
92 u"uploader_id": u"phihag",
93 u"upload_date": u"20121002",
94 u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
98 u"url": u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
99 u"file": u"1ltcDfZMA3U.flv",
100 u"note": u"Test VEVO video (#897)",
102 u"upload_date": u"20070518",
103 u"title": u"Maps - It Will Find You",
104 u"description": u"Music video by Maps performing It Will Find You.",
105 u"uploader": u"MuteUSA",
106 u"uploader_id": u"MuteUSA"
110 u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
111 u"file": u"UxxajLWwzqY.mp4",
112 u"note": u"Test generic use_cipher_signature video (#897)",
114 u"upload_date": u"20120506",
115 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
116 u"description": u"md5:b085c9804f5ab69f4adea963a2dceb3c",
117 u"uploader": u"IconaPop",
118 u"uploader_id": u"IconaPop"
122 u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
123 u"file": u"07FYdnEawAQ.mp4",
124 u"note": u"Test VEVO video with age protection (#956)",
126 u"upload_date": u"20130703",
127 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
128 u"description": u"md5:64249768eec3bc4276236606ea996373",
129 u"uploader": u"justintimberlakeVEVO",
130 u"uploader_id": u"justintimberlakeVEVO"
137 def suitable(cls, url):
138 """Receives a URL and returns True if suitable for this IE."""
139 if YoutubePlaylistIE.suitable(url) or YoutubeSubscriptionsIE.suitable(url): return False
140 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
142 def report_lang(self):
143 """Report attempt to set language."""
144 self.to_screen(u'Setting language')
146 def report_video_webpage_download(self, video_id):
147 """Report attempt to download video webpage."""
148 self.to_screen(u'%s: Downloading video webpage' % video_id)
150 def report_video_info_webpage_download(self, video_id):
151 """Report attempt to download video info webpage."""
152 self.to_screen(u'%s: Downloading video info webpage' % video_id)
154 def report_video_subtitles_download(self, video_id):
155 """Report attempt to download video info webpage."""
156 self.to_screen(u'%s: Checking available subtitles' % video_id)
158 def report_video_subtitles_request(self, video_id, sub_lang, format):
159 """Report attempt to download video info webpage."""
160 self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
162 def report_video_subtitles_available(self, video_id, sub_lang_list):
163 """Report available subtitles."""
164 sub_lang = ",".join(list(sub_lang_list.keys()))
165 self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
167 def report_information_extraction(self, video_id):
168 """Report attempt to extract video information."""
169 self.to_screen(u'%s: Extracting video information' % video_id)
171 def report_unavailable_format(self, video_id, format):
172 """Report extracted video URL."""
173 self.to_screen(u'%s: Format %s not available' % (video_id, format))
175 def report_rtmp_download(self):
176 """Indicate the download will use the RTMP protocol."""
177 self.to_screen(u'RTMP download detected')
179 def _decrypt_signature(self, s):
180 """Turn the encrypted s field into a working signature"""
184 a[0] = a[b % len(a)];
201 def _get_available_subtitles(self, video_id):
202 self.report_video_subtitles_download(video_id)
203 request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
205 sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
206 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
207 return (u'unable to download video subtitles: %s' % compat_str(err), None)
208 sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
209 sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
210 if not sub_lang_list:
211 return (u'video doesn\'t have subtitles', None)
214 def _list_available_subtitles(self, video_id):
215 sub_lang_list = self._get_available_subtitles(video_id)
216 self.report_video_subtitles_available(video_id, sub_lang_list)
218 def _request_subtitle(self, sub_lang, sub_name, video_id, format):
221 (error_message, sub_lang, sub)
223 self.report_video_subtitles_request(video_id, sub_lang, format)
224 params = compat_urllib_parse.urlencode({
230 url = 'http://www.youtube.com/api/timedtext?' + params
232 sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
233 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
234 return (u'unable to download video subtitles: %s' % compat_str(err), None, None)
236 return (u'Did not fetch video subtitles', None, None)
237 return (None, sub_lang, sub)
239 def _request_automatic_caption(self, video_id, webpage):
240 """We need the webpage for getting the captions url, pass it as an
241 argument to speed up the process."""
242 sub_lang = self._downloader.params.get('subtitleslang') or 'en'
243 sub_format = self._downloader.params.get('subtitlesformat')
244 self.to_screen(u'%s: Looking for automatic captions' % video_id)
245 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
246 err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
248 return [(err_msg, None, None)]
249 player_config = json.loads(mobj.group(1))
251 args = player_config[u'args']
252 caption_url = args[u'ttsurl']
253 timestamp = args[u'timestamp']
254 params = compat_urllib_parse.urlencode({
261 subtitles_url = caption_url + '&' + params
262 sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
263 return [(None, sub_lang, sub)]
265 return [(err_msg, None, None)]
267 def _extract_subtitle(self, video_id):
269 Return a list with a tuple:
270 [(error_message, sub_lang, sub)]
272 sub_lang_list = self._get_available_subtitles(video_id)
273 sub_format = self._downloader.params.get('subtitlesformat')
274 if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
275 return [(sub_lang_list[0], None, None)]
276 if self._downloader.params.get('subtitleslang', False):
277 sub_lang = self._downloader.params.get('subtitleslang')
278 elif 'en' in sub_lang_list:
281 sub_lang = list(sub_lang_list.keys())[0]
282 if not sub_lang in sub_lang_list:
283 return [(u'no closed captions found in the specified language "%s"' % sub_lang, None, None)]
285 subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
288 def _extract_all_subtitles(self, video_id):
289 sub_lang_list = self._get_available_subtitles(video_id)
290 sub_format = self._downloader.params.get('subtitlesformat')
291 if isinstance(sub_lang_list,tuple): #There was some error, it didn't get the available subtitles
292 return [(sub_lang_list[0], None, None)]
294 for sub_lang in sub_lang_list:
295 subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
296 subtitles.append(subtitle)
299 def _print_formats(self, formats):
300 print('Available formats:')
302 print('%s\t:\t%s\t[%s]' %(x, self._video_extensions.get(x, 'flv'), self._video_dimensions.get(x, '???')))
304 def _real_initialize(self):
305 if self._downloader is None:
309 request = compat_urllib_request.Request(self._LANG_URL)
312 compat_urllib_request.urlopen(request).read()
313 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
314 self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
317 (username, password) = self._get_login_info()
319 # No authentication to be performed
323 request = compat_urllib_request.Request(self._LOGIN_URL)
325 login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
326 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
327 self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
332 match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
334 galx = match.group(1)
336 match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
342 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
346 u'PersistentCookie': u'yes',
348 u'bgresponse': u'js_disabled',
349 u'checkConnection': u'',
350 u'checkedDomains': u'youtube',
356 u'signIn': u'Sign in',
358 u'service': u'youtube',
362 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
364 login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
365 login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
366 request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
369 login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
370 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
371 self._downloader.report_warning(u'unable to log in: bad username or password')
373 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
374 self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
380 'action_confirm': 'Confirm',
382 request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
384 self.report_age_confirmation()
385 compat_urllib_request.urlopen(request).read().decode('utf-8')
386 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
387 raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
389 def _extract_id(self, url):
390 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
392 raise ExtractorError(u'Invalid URL: %s' % url)
393 video_id = mobj.group(2)
396 def _real_extract(self, url):
397 if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
398 self._downloader.report_warning(u'Did you forget to quote the URL? Remember that & is a meta-character in most shells, so you want to put the URL in quotes, like youtube-dl \'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\' (or simply youtube-dl BaW_jenozKc ).')
400 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
401 mobj = re.search(self._NEXT_URL_RE, url)
403 url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
404 video_id = self._extract_id(url)
407 self.report_video_webpage_download(video_id)
408 url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
409 request = compat_urllib_request.Request(url)
411 video_webpage_bytes = compat_urllib_request.urlopen(request).read()
412 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
413 raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
415 video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
417 # Attempt to extract SWF player URL
418 mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
420 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
425 self.report_video_info_webpage_download(video_id)
426 if re.search(r'player-age-gate-content">', video_webpage) is not None:
427 self.report_age_confirmation()
429 # We simulate the access to the video from www.youtube.com/v/{video_id}
430 # this can be viewed without login into Youtube
431 data = compat_urllib_parse.urlencode({'video_id': video_id,
435 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
439 video_info_url = 'https://www.youtube.com/get_video_info?' + data
440 video_info_webpage = self._download_webpage(video_info_url, video_id,
442 errnote='unable to download video info webpage')
443 video_info = compat_parse_qs(video_info_webpage)
446 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
447 video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
448 % (video_id, el_type))
449 video_info_webpage = self._download_webpage(video_info_url, video_id,
451 errnote='unable to download video info webpage')
452 video_info = compat_parse_qs(video_info_webpage)
453 if 'token' in video_info:
455 if 'token' not in video_info:
456 if 'reason' in video_info:
457 raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
459 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
461 # Check for "rental" videos
462 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
463 raise ExtractorError(u'"rental" videos not supported')
465 # Start extracting information
466 self.report_information_extraction(video_id)
469 if 'author' not in video_info:
470 raise ExtractorError(u'Unable to extract uploader name')
471 video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
474 video_uploader_id = None
475 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
477 video_uploader_id = mobj.group(1)
479 self._downloader.report_warning(u'unable to extract uploader nickname')
482 if 'title' not in video_info:
483 raise ExtractorError(u'Unable to extract video title')
484 video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
487 # We try first to get a high quality image:
488 m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
489 video_webpage, re.DOTALL)
490 if m_thumb is not None:
491 video_thumbnail = m_thumb.group(1)
492 elif 'thumbnail_url' not in video_info:
493 self._downloader.report_warning(u'unable to extract video thumbnail')
495 else: # don't panic if we can't find it
496 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
500 mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
502 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
503 upload_date = unified_strdate(upload_date)
506 video_description = get_element_by_id("eow-description", video_webpage)
507 if video_description:
508 video_description = clean_html(video_description)
510 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
512 video_description = unescapeHTML(fd_mobj.group(1))
514 video_description = u''
517 video_subtitles = None
519 if self._downloader.params.get('writesubtitles', False):
520 video_subtitles = self._extract_subtitle(video_id)
522 (sub_error, sub_lang, sub) = video_subtitles[0]
524 self._downloader.report_warning(sub_error)
526 if self._downloader.params.get('writeautomaticsub', False):
527 video_subtitles = self._request_automatic_caption(video_id, video_webpage)
528 (sub_error, sub_lang, sub) = video_subtitles[0]
530 self._downloader.report_warning(sub_error)
532 if self._downloader.params.get('allsubtitles', False):
533 video_subtitles = self._extract_all_subtitles(video_id)
534 for video_subtitle in video_subtitles:
535 (sub_error, sub_lang, sub) = video_subtitle
537 self._downloader.report_warning(sub_error)
539 if self._downloader.params.get('listsubtitles', False):
540 self._list_available_subtitles(video_id)
543 if 'length_seconds' not in video_info:
544 self._downloader.report_warning(u'unable to extract video duration')
547 video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
549 # Decide which formats to download
550 req_format = self._downloader.params.get('format', None)
553 mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
555 raise ValueError('Could not find vevo ID')
556 info = json.loads(mobj.group(1))
558 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
559 # this signatures are encrypted
560 m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
562 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
563 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
567 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
568 self.report_rtmp_download()
569 video_url_list = [(None, video_info['conn'][0])]
570 elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
571 if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
572 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
574 for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
575 url_data = compat_parse_qs(url_data_str)
576 if 'itag' in url_data and 'url' in url_data:
577 url = url_data['url'][0]
578 if 'sig' in url_data:
579 url += '&signature=' + url_data['sig'][0]
580 elif 's' in url_data:
581 if self._downloader.params.get('verbose'):
584 player_version = self._search_regex(r'ad3-(.+?)\.swf',
585 video_info['ad3_module'][0], 'flash player',
587 player = 'flash player %s' % player_version
589 player = u'html5 player %s' % self._search_regex(r'html5player-(.+?)\.js', video_webpage,
590 'html5 player', fatal=False)
591 self.to_screen('encrypted signature length %d (%d.%d), itag %s, %s' %
592 (len(s), len(s.split('.')[0]), len(s.split('.')[1]), url_data['itag'][0], player))
593 signature = self._decrypt_signature(url_data['s'][0])
594 url += '&signature=' + signature
595 if 'ratebypass' not in url:
596 url += '&ratebypass=yes'
597 url_map[url_data['itag'][0]] = url
599 format_limit = self._downloader.params.get('format_limit', None)
600 available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
601 if format_limit is not None and format_limit in available_formats:
602 format_list = available_formats[available_formats.index(format_limit):]
604 format_list = available_formats
605 existing_formats = [x for x in format_list if x in url_map]
606 if len(existing_formats) == 0:
607 raise ExtractorError(u'no known formats available for video')
608 if self._downloader.params.get('listformats', None):
609 self._print_formats(existing_formats)
611 if req_format is None or req_format == 'best':
612 video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
613 elif req_format == 'worst':
614 video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
615 elif req_format in ('-1', 'all'):
616 video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
618 # Specific formats. We pick the first in a slash-delimeted sequence.
619 # For example, if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
620 req_formats = req_format.split('/')
621 video_url_list = None
622 for rf in req_formats:
624 video_url_list = [(rf, url_map[rf])]
626 if video_url_list is None:
627 raise ExtractorError(u'requested format not available')
629 raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
632 for format_param, video_real_url in video_url_list:
634 video_extension = self._video_extensions.get(format_param, 'flv')
636 video_format = '{0} - {1}'.format(format_param if format_param else video_extension,
637 self._video_dimensions.get(format_param, '???'))
641 'url': video_real_url,
642 'uploader': video_uploader,
643 'uploader_id': video_uploader_id,
644 'upload_date': upload_date,
645 'title': video_title,
646 'ext': video_extension,
647 'format': video_format,
648 'thumbnail': video_thumbnail,
649 'description': video_description,
650 'player_url': player_url,
651 'subtitles': video_subtitles,
652 'duration': video_duration
656 class YoutubePlaylistIE(InfoExtractor):
657 IE_DESC = u'YouTube.com playlists'
663 (?:course|view_play_list|my_playlists|artist|playlist|watch)
664 \? (?:.*?&)*? (?:p|a|list)=
667 ((?:PL|EC|UU)?[0-9A-Za-z-_]{10,})
670 ((?:PL|EC|UU)[0-9A-Za-z-_]{10,})
672 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
674 IE_NAME = u'youtube:playlist'
677 def suitable(cls, url):
678 """Receives a URL and returns True if suitable for this IE."""
679 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
681 def _real_extract(self, url):
682 # Extract playlist id
683 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
685 raise ExtractorError(u'Invalid URL: %s' % url)
687 # Download playlist videos from API
688 playlist_id = mobj.group(1) or mobj.group(2)
693 url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, self._MAX_RESULTS * (page_num - 1) + 1)
694 page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
697 response = json.loads(page)
698 except ValueError as err:
699 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
701 if 'feed' not in response:
702 raise ExtractorError(u'Got a malformed response from YouTube API')
703 playlist_title = response['feed']['title']['$t']
704 if 'entry' not in response['feed']:
705 # Number of videos is a multiple of self._MAX_RESULTS
708 for entry in response['feed']['entry']:
709 index = entry['yt$position']['$t']
710 if 'media$group' in entry and 'media$player' in entry['media$group']:
711 videos.append((index, entry['media$group']['media$player']['url']))
713 if len(response['feed']['entry']) < self._MAX_RESULTS:
717 videos = [v[1] for v in sorted(videos)]
719 url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
720 return [self.playlist_result(url_results, playlist_id, playlist_title)]
723 class YoutubeChannelIE(InfoExtractor):
724 IE_DESC = u'YouTube.com channels'
725 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
726 _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
727 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
728 _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'
729 IE_NAME = u'youtube:channel'
731 def extract_videos_from_page(self, page):
733 for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
734 if mobj.group(1) not in ids_in_page:
735 ids_in_page.append(mobj.group(1))
738 def _real_extract(self, url):
740 mobj = re.match(self._VALID_URL, url)
742 raise ExtractorError(u'Invalid URL: %s' % url)
744 # Download channel page
745 channel_id = mobj.group(1)
749 url = self._TEMPLATE_URL % (channel_id, pagenum)
750 page = self._download_webpage(url, channel_id,
751 u'Downloading page #%s' % pagenum)
753 # Extract video identifiers
754 ids_in_page = self.extract_videos_from_page(page)
755 video_ids.extend(ids_in_page)
757 # Download any subsequent channel pages using the json-based channel_ajax query
758 if self._MORE_PAGES_INDICATOR in page:
760 pagenum = pagenum + 1
762 url = self._MORE_PAGES_URL % (pagenum, channel_id)
763 page = self._download_webpage(url, channel_id,
764 u'Downloading page #%s' % pagenum)
766 page = json.loads(page)
768 ids_in_page = self.extract_videos_from_page(page['content_html'])
769 video_ids.extend(ids_in_page)
771 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
774 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
776 urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
777 url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
778 return [self.playlist_result(url_entries, channel_id)]
781 class YoutubeUserIE(InfoExtractor):
782 IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
783 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
784 _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
785 _GDATA_PAGE_SIZE = 50
786 _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
787 _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
788 IE_NAME = u'youtube:user'
790 def _real_extract(self, url):
792 mobj = re.match(self._VALID_URL, url)
794 raise ExtractorError(u'Invalid URL: %s' % url)
796 username = mobj.group(1)
798 # Download video ids using YouTube Data API. Result size per
799 # query is limited (currently to 50 videos) so we need to query
800 # page by page until there are no video ids - it means we got
807 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
809 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
810 page = self._download_webpage(gdata_url, username,
811 u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
813 # Extract video identifiers
816 for mobj in re.finditer(self._VIDEO_INDICATOR, page):
817 if mobj.group(1) not in ids_in_page:
818 ids_in_page.append(mobj.group(1))
820 video_ids.extend(ids_in_page)
822 # A little optimization - if current page is not
823 # "full", ie. does not contain PAGE_SIZE video ids then
824 # we can assume that this page is the last one - there
825 # are no more ids on further pages - no need to query
828 if len(ids_in_page) < self._GDATA_PAGE_SIZE:
833 urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
834 url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
835 return [self.playlist_result(url_results, playlist_title = username)]
837 class YoutubeSearchIE(SearchInfoExtractor):
838 IE_DESC = u'YouTube.com searches'
839 _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
841 IE_NAME = u'youtube:search'
842 _SEARCH_KEY = 'ytsearch'
844 def report_download_page(self, query, pagenum):
845 """Report attempt to download search page with given number."""
846 self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
848 def _get_n_results(self, query, n):
849 """Get a specified number of results for a query"""
855 while (50 * pagenum) < limit:
856 self.report_download_page(query, pagenum+1)
857 result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
858 request = compat_urllib_request.Request(result_url)
860 data = compat_urllib_request.urlopen(request).read().decode('utf-8')
861 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
862 raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
863 api_response = json.loads(data)['data']
865 if not 'items' in api_response:
866 raise ExtractorError(u'[youtube] No video results')
868 new_ids = list(video['id'] for video in api_response['items'])
871 limit = min(n, api_response['totalItems'])
874 if len(video_ids) > n:
875 video_ids = video_ids[:n]
876 videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
877 return self.playlist_result(videos, query)
880 class YoutubeShowIE(InfoExtractor):
881 IE_DESC = u'YouTube.com (multi-season) shows'
882 _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
883 IE_NAME = u'youtube:show'
885 def _real_extract(self, url):
886 mobj = re.match(self._VALID_URL, url)
887 show_name = mobj.group(1)
888 webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
889 # There's one playlist for each season of the show
890 m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
891 self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
892 return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
895 class YoutubeSubscriptionsIE(YoutubeIE):
896 """It's a subclass of YoutubeIE because we need to login"""
897 IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
898 _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
899 IE_NAME = u'youtube:subscriptions'
900 _FEED_TEMPLATE = 'http://www.youtube.com/feed_ajax?action_load_system_feed=1&feed_name=subscriptions&paging=%s'
903 # Overwrite YoutubeIE properties we don't want
906 def suitable(cls, url):
907 return re.match(cls._VALID_URL, url) is not None
909 def _real_initialize(self):
910 (username, password) = self._get_login_info()
912 raise ExtractorError(u'No login info available, needed for downloading the Youtube subscriptions.', expected=True)
913 super(YoutubeSubscriptionsIE, self)._real_initialize()
915 def _real_extract(self, url):
917 # The step argument is available only in 2.7 or higher
918 for i in itertools.count(0):
919 paging = i*self._PAGING_STEP
920 info = self._download_webpage(self._FEED_TEMPLATE % paging, 'feed',
921 u'Downloading page %s' % i)
922 info = json.loads(info)
923 feed_html = info['feed_html']
924 m_ids = re.finditer(r'"/watch\?v=(.*?)"', feed_html)
925 ids = orderedSet(m.group(1) for m in m_ids)
926 feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
927 if info['paging'] is None:
929 return self.playlist_result(feed_entries, playlist_title='Youtube Subscriptions')