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