Merge branch 'youtube-dash-manifest'
[youtube-dl] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 import collections
4 import errno
5 import io
6 import itertools
7 import json
8 import os.path
9 import re
10 import string
11 import struct
12 import traceback
13 import zlib
14
15 from .common import InfoExtractor, SearchInfoExtractor
16 from .subtitles import SubtitlesInfoExtractor
17 from ..utils import (
18     compat_chr,
19     compat_parse_qs,
20     compat_urllib_parse,
21     compat_urllib_request,
22     compat_urlparse,
23     compat_str,
24
25     clean_html,
26     get_cachedir,
27     get_element_by_id,
28     get_element_by_attribute,
29     ExtractorError,
30     int_or_none,
31     RegexNotFoundError,
32     unescapeHTML,
33     unified_strdate,
34     orderedSet,
35     write_json_file,
36 )
37
38 class YoutubeBaseInfoExtractor(InfoExtractor):
39     """Provide base functions for Youtube extractors"""
40     _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
41     _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
42     _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
43     _NETRC_MACHINE = 'youtube'
44     # If True it will raise an error if no login info is provided
45     _LOGIN_REQUIRED = False
46
47     def _set_language(self):
48         return bool(self._download_webpage(
49             self._LANG_URL, None,
50             note=u'Setting language', errnote='unable to set language',
51             fatal=False))
52
53     def _login(self):
54         (username, password) = self._get_login_info()
55         # No authentication to be performed
56         if username is None:
57             if self._LOGIN_REQUIRED:
58                 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
59             return False
60
61         login_page = self._download_webpage(
62             self._LOGIN_URL, None,
63             note=u'Downloading login page',
64             errnote=u'unable to fetch login page', fatal=False)
65         if login_page is False:
66             return
67
68         galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
69                                   login_page, u'Login GALX parameter')
70
71         # Log in
72         login_form_strs = {
73                 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
74                 u'Email': username,
75                 u'GALX': galx,
76                 u'Passwd': password,
77                 u'PersistentCookie': u'yes',
78                 u'_utf8': u'霱',
79                 u'bgresponse': u'js_disabled',
80                 u'checkConnection': u'',
81                 u'checkedDomains': u'youtube',
82                 u'dnConn': u'',
83                 u'pstMsg': u'0',
84                 u'rmShown': u'1',
85                 u'secTok': u'',
86                 u'signIn': u'Sign in',
87                 u'timeStmp': u'',
88                 u'service': u'youtube',
89                 u'uilel': u'3',
90                 u'hl': u'en_US',
91         }
92         # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
93         # chokes on unicode
94         login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
95         login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
96
97         req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
98         login_results = self._download_webpage(
99             req, None,
100             note=u'Logging in', errnote=u'unable to log in', fatal=False)
101         if login_results is False:
102             return False
103         if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
104             self._downloader.report_warning(u'unable to log in: bad username or password')
105             return False
106         return True
107
108     def _confirm_age(self):
109         age_form = {
110             'next_url': '/',
111             'action_confirm': 'Confirm',
112         }
113         req = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
114
115         self._download_webpage(
116             req, None,
117             note=u'Confirming age', errnote=u'Unable to confirm age')
118         return True
119
120     def _real_initialize(self):
121         if self._downloader is None:
122             return
123         if not self._set_language():
124             return
125         if not self._login():
126             return
127         self._confirm_age()
128
129
130 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
131     IE_DESC = u'YouTube.com'
132     _VALID_URL = r"""(?x)^
133                      (
134                          (?:https?://|//)?                                    # http(s):// or protocol-independent URL (optional)
135                          (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
136                             (?:www\.)?deturl\.com/www\.youtube\.com/|
137                             (?:www\.)?pwnyoutube\.com|
138                             tube\.majestyc\.net/|
139                             youtube\.googleapis\.com/)                        # the various hostnames, with wildcard subdomains
140                          (?:.*?\#/)?                                          # handle anchor (#/) redirect urls
141                          (?:                                                  # the various things that can precede the ID:
142                              (?:(?:v|embed|e)/)                               # v/ or embed/ or e/
143                              |(?:                                             # or the v= param in all its forms
144                                  (?:(?:watch|movie)(?:_popup)?(?:\.php)?)?    # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
145                                  (?:\?|\#!?)                                  # the params delimiter ? or # or #!
146                                  (?:.*?&)?                                    # any other preceding param (like /?s=tuff&v=xxxx)
147                                  v=
148                              )
149                          ))
150                          |youtu\.be/                                          # just youtu.be/xxxx
151                          )
152                      )?                                                       # all until now is optional -> you can pass the naked ID
153                      ([0-9A-Za-z_-]{11})                                      # here is it! the YouTube video ID
154                      (?(1).+)?                                                # if we found the ID, everything can follow
155                      $"""
156     _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
157     _formats = {
158         '5': {'ext': 'flv', 'width': 400, 'height': 240},
159         '6': {'ext': 'flv', 'width': 450, 'height': 270},
160         '13': {'ext': '3gp'},
161         '17': {'ext': '3gp', 'width': 176, 'height': 144},
162         '18': {'ext': 'mp4', 'width': 640, 'height': 360},
163         '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
164         '34': {'ext': 'flv', 'width': 640, 'height': 360},
165         '35': {'ext': 'flv', 'width': 854, 'height': 480},
166         '36': {'ext': '3gp', 'width': 320, 'height': 240},
167         '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
168         '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
169         '43': {'ext': 'webm', 'width': 640, 'height': 360},
170         '44': {'ext': 'webm', 'width': 854, 'height': 480},
171         '45': {'ext': 'webm', 'width': 1280, 'height': 720},
172         '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
173
174
175         # 3d videos
176         '82': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': '3D', 'preference': -20},
177         '83': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': '3D', 'preference': -20},
178         '84': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': '3D', 'preference': -20},
179         '85': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': '3D', 'preference': -20},
180         '100': {'ext': 'webm', 'height': 360, 'resolution': '360p', 'format_note': '3D', 'preference': -20},
181         '101': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': '3D', 'preference': -20},
182         '102': {'ext': 'webm', 'height': 720, 'resolution': '720p', 'format_note': '3D', 'preference': -20},
183
184         # Apple HTTP Live Streaming
185         '92': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'HLS', 'preference': -10},
186         '93': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': 'HLS', 'preference': -10},
187         '94': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': 'HLS', 'preference': -10},
188         '95': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': 'HLS', 'preference': -10},
189         '96': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'HLS', 'preference': -10},
190         '132': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'HLS', 'preference': -10},
191         '151': {'ext': 'mp4', 'height': 72, 'resolution': '72p', 'format_note': 'HLS', 'preference': -10},
192
193         # DASH mp4 video
194         '133': {'ext': 'mp4', 'height': 240, 'resolution': '240p', 'format_note': 'DASH video', 'preference': -40},
195         '134': {'ext': 'mp4', 'height': 360, 'resolution': '360p', 'format_note': 'DASH video', 'preference': -40},
196         '135': {'ext': 'mp4', 'height': 480, 'resolution': '480p', 'format_note': 'DASH video', 'preference': -40},
197         '136': {'ext': 'mp4', 'height': 720, 'resolution': '720p', 'format_note': 'DASH video', 'preference': -40},
198         '137': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH video', 'preference': -40},
199         '138': {'ext': 'mp4', 'height': 1081, 'resolution': '>1080p', 'format_note': 'DASH video', 'preference': -40},
200         '160': {'ext': 'mp4', 'height': 192, 'resolution': '192p', 'format_note': 'DASH video', 'preference': -40},
201         '264': {'ext': 'mp4', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH video', 'preference': -40},
202
203         # Dash mp4 audio
204         '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
205         '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
206         '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
207
208         # Dash webm
209         '242': {'ext': 'webm', 'height': 240, 'resolution': '240p', 'format_note': 'DASH webm', 'preference': -40},
210         '243': {'ext': 'webm', 'height': 360, 'resolution': '360p', 'format_note': 'DASH webm', 'preference': -40},
211         '244': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
212         '245': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
213         '246': {'ext': 'webm', 'height': 480, 'resolution': '480p', 'format_note': 'DASH webm', 'preference': -40},
214         '247': {'ext': 'webm', 'height': 720, 'resolution': '720p', 'format_note': 'DASH webm', 'preference': -40},
215         '248': {'ext': 'webm', 'height': 1080, 'resolution': '1080p', 'format_note': 'DASH webm', 'preference': -40},
216
217         # Dash webm audio
218         '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH webm audio', 'abr': 48, 'preference': -50},
219         '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH webm audio', 'abr': 256, 'preference': -50},
220
221         # RTMP (unnamed)
222         '_rtmp': {'protocol': 'rtmp'},
223     }
224
225     IE_NAME = u'youtube'
226     _TESTS = [
227         {
228             u"url":  u"http://www.youtube.com/watch?v=BaW_jenozKc",
229             u"file":  u"BaW_jenozKc.mp4",
230             u"info_dict": {
231                 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
232                 u"uploader": u"Philipp Hagemeister",
233                 u"uploader_id": u"phihag",
234                 u"upload_date": u"20121002",
235                 u"description": u"test chars:  \"'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
236             }
237         },
238         {
239             u"url":  u"http://www.youtube.com/watch?v=UxxajLWwzqY",
240             u"file":  u"UxxajLWwzqY.mp4",
241             u"note": u"Test generic use_cipher_signature video (#897)",
242             u"info_dict": {
243                 u"upload_date": u"20120506",
244                 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
245                 u"description": u"md5:5b292926389560516e384ac437c0ec07",
246                 u"uploader": u"Icona Pop",
247                 u"uploader_id": u"IconaPop"
248             }
249         },
250         {
251             u"url":  u"https://www.youtube.com/watch?v=07FYdnEawAQ",
252             u"file":  u"07FYdnEawAQ.mp4",
253             u"note": u"Test VEVO video with age protection (#956)",
254             u"info_dict": {
255                 u"upload_date": u"20130703",
256                 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
257                 u"description": u"md5:64249768eec3bc4276236606ea996373",
258                 u"uploader": u"justintimberlakeVEVO",
259                 u"uploader_id": u"justintimberlakeVEVO"
260             }
261         },
262         {
263             u"url":  u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
264             u"file":  u"yZIXLfi8CZQ.mp4",
265             u"note": u"Embed-only video (#1746)",
266             u"info_dict": {
267                 u"upload_date": u"20120608",
268                 u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
269                 u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
270                 u"uploader": u"SET India",
271                 u"uploader_id": u"setindia"
272             }
273         },
274         {
275             u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
276             u"file": u"a9LDPn-MO4I.m4a",
277             u"note": u"256k DASH audio (format 141) via DASH manifest",
278             u"params": {
279                 u"format": "141"
280             },
281             u"info_dict": {
282                 u"upload_date": "20121002",
283                 u"uploader_id": "8KVIDEO",
284                 u"description": "No description available.",
285                 u"uploader": "8KVIDEO",
286                 u"title": "UHDTV TEST 8K VIDEO.mp4"
287             }
288         },
289     ]
290
291
292     @classmethod
293     def suitable(cls, url):
294         """Receives a URL and returns True if suitable for this IE."""
295         if YoutubePlaylistIE.suitable(url): return False
296         return re.match(cls._VALID_URL, url) is not None
297
298     def __init__(self, *args, **kwargs):
299         super(YoutubeIE, self).__init__(*args, **kwargs)
300         self._player_cache = {}
301
302     def report_video_info_webpage_download(self, video_id):
303         """Report attempt to download video info webpage."""
304         self.to_screen(u'%s: Downloading video info webpage' % video_id)
305
306     def report_information_extraction(self, video_id):
307         """Report attempt to extract video information."""
308         self.to_screen(u'%s: Extracting video information' % video_id)
309
310     def report_unavailable_format(self, video_id, format):
311         """Report extracted video URL."""
312         self.to_screen(u'%s: Format %s not available' % (video_id, format))
313
314     def report_rtmp_download(self):
315         """Indicate the download will use the RTMP protocol."""
316         self.to_screen(u'RTMP download detected')
317
318     def _extract_signature_function(self, video_id, player_url, slen):
319         id_m = re.match(r'.*-(?P<id>[a-zA-Z0-9_-]+)\.(?P<ext>[a-z]+)$',
320                         player_url)
321         player_type = id_m.group('ext')
322         player_id = id_m.group('id')
323
324         # Read from filesystem cache
325         func_id = '%s_%s_%d' % (player_type, player_id, slen)
326         assert os.path.basename(func_id) == func_id
327         cache_dir = get_cachedir(self._downloader.params)
328
329         cache_enabled = cache_dir is not None
330         if cache_enabled:
331             cache_fn = os.path.join(os.path.expanduser(cache_dir),
332                                     u'youtube-sigfuncs',
333                                     func_id + '.json')
334             try:
335                 with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
336                     cache_spec = json.load(cachef)
337                 return lambda s: u''.join(s[i] for i in cache_spec)
338             except IOError:
339                 pass  # No cache available
340
341         if player_type == 'js':
342             code = self._download_webpage(
343                 player_url, video_id,
344                 note=u'Downloading %s player %s' % (player_type, player_id),
345                 errnote=u'Download of %s failed' % player_url)
346             res = self._parse_sig_js(code)
347         elif player_type == 'swf':
348             urlh = self._request_webpage(
349                 player_url, video_id,
350                 note=u'Downloading %s player %s' % (player_type, player_id),
351                 errnote=u'Download of %s failed' % player_url)
352             code = urlh.read()
353             res = self._parse_sig_swf(code)
354         else:
355             assert False, 'Invalid player type %r' % player_type
356
357         if cache_enabled:
358             try:
359                 test_string = u''.join(map(compat_chr, range(slen)))
360                 cache_res = res(test_string)
361                 cache_spec = [ord(c) for c in cache_res]
362                 try:
363                     os.makedirs(os.path.dirname(cache_fn))
364                 except OSError as ose:
365                     if ose.errno != errno.EEXIST:
366                         raise
367                 write_json_file(cache_spec, cache_fn)
368             except Exception:
369                 tb = traceback.format_exc()
370                 self._downloader.report_warning(
371                     u'Writing cache to %r failed: %s' % (cache_fn, tb))
372
373         return res
374
375     def _print_sig_code(self, func, slen):
376         def gen_sig_code(idxs):
377             def _genslice(start, end, step):
378                 starts = u'' if start == 0 else str(start)
379                 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
380                 steps = u'' if step == 1 else (u':%d' % step)
381                 return u's[%s%s%s]' % (starts, ends, steps)
382
383             step = None
384             start = '(Never used)'  # Quelch pyflakes warnings - start will be
385                                     # set as soon as step is set
386             for i, prev in zip(idxs[1:], idxs[:-1]):
387                 if step is not None:
388                     if i - prev == step:
389                         continue
390                     yield _genslice(start, prev, step)
391                     step = None
392                     continue
393                 if i - prev in [-1, 1]:
394                     step = i - prev
395                     start = prev
396                     continue
397                 else:
398                     yield u's[%d]' % prev
399             if step is None:
400                 yield u's[%d]' % i
401             else:
402                 yield _genslice(start, i, step)
403
404         test_string = u''.join(map(compat_chr, range(slen)))
405         cache_res = func(test_string)
406         cache_spec = [ord(c) for c in cache_res]
407         expr_code = u' + '.join(gen_sig_code(cache_spec))
408         code = u'if len(s) == %d:\n    return %s\n' % (slen, expr_code)
409         self.to_screen(u'Extracted signature function:\n' + code)
410
411     def _parse_sig_js(self, jscode):
412         funcname = self._search_regex(
413             r'signature=([a-zA-Z]+)', jscode,
414             u'Initial JS player signature function name')
415
416         functions = {}
417
418         def argidx(varname):
419             return string.lowercase.index(varname)
420
421         def interpret_statement(stmt, local_vars, allow_recursion=20):
422             if allow_recursion < 0:
423                 raise ExtractorError(u'Recursion limit reached')
424
425             if stmt.startswith(u'var '):
426                 stmt = stmt[len(u'var '):]
427             ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
428                              r'=(?P<expr>.*)$', stmt)
429             if ass_m:
430                 if ass_m.groupdict().get('index'):
431                     def assign(val):
432                         lvar = local_vars[ass_m.group('out')]
433                         idx = interpret_expression(ass_m.group('index'),
434                                                    local_vars, allow_recursion)
435                         assert isinstance(idx, int)
436                         lvar[idx] = val
437                         return val
438                     expr = ass_m.group('expr')
439                 else:
440                     def assign(val):
441                         local_vars[ass_m.group('out')] = val
442                         return val
443                     expr = ass_m.group('expr')
444             elif stmt.startswith(u'return '):
445                 assign = lambda v: v
446                 expr = stmt[len(u'return '):]
447             else:
448                 raise ExtractorError(
449                     u'Cannot determine left side of statement in %r' % stmt)
450
451             v = interpret_expression(expr, local_vars, allow_recursion)
452             return assign(v)
453
454         def interpret_expression(expr, local_vars, allow_recursion):
455             if expr.isdigit():
456                 return int(expr)
457
458             if expr.isalpha():
459                 return local_vars[expr]
460
461             m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
462             if m:
463                 member = m.group('member')
464                 val = local_vars[m.group('in')]
465                 if member == 'split("")':
466                     return list(val)
467                 if member == 'join("")':
468                     return u''.join(val)
469                 if member == 'length':
470                     return len(val)
471                 if member == 'reverse()':
472                     return val[::-1]
473                 slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
474                 if slice_m:
475                     idx = interpret_expression(
476                         slice_m.group('idx'), local_vars, allow_recursion-1)
477                     return val[idx:]
478
479             m = re.match(
480                 r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
481             if m:
482                 val = local_vars[m.group('in')]
483                 idx = interpret_expression(m.group('idx'), local_vars,
484                                            allow_recursion-1)
485                 return val[idx]
486
487             m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
488             if m:
489                 a = interpret_expression(m.group('a'),
490                                          local_vars, allow_recursion)
491                 b = interpret_expression(m.group('b'),
492                                          local_vars, allow_recursion)
493                 return a % b
494
495             m = re.match(
496                 r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
497             if m:
498                 fname = m.group('func')
499                 if fname not in functions:
500                     functions[fname] = extract_function(fname)
501                 argvals = [int(v) if v.isdigit() else local_vars[v]
502                            for v in m.group('args').split(',')]
503                 return functions[fname](argvals)
504             raise ExtractorError(u'Unsupported JS expression %r' % expr)
505
506         def extract_function(funcname):
507             func_m = re.search(
508                 r'function ' + re.escape(funcname) +
509                 r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
510                 jscode)
511             argnames = func_m.group('args').split(',')
512
513             def resf(args):
514                 local_vars = dict(zip(argnames, args))
515                 for stmt in func_m.group('code').split(';'):
516                     res = interpret_statement(stmt, local_vars)
517                 return res
518             return resf
519
520         initial_function = extract_function(funcname)
521         return lambda s: initial_function([s])
522
523     def _parse_sig_swf(self, file_contents):
524         if file_contents[1:3] != b'WS':
525             raise ExtractorError(
526                 u'Not an SWF file; header is %r' % file_contents[:3])
527         if file_contents[:1] == b'C':
528             content = zlib.decompress(file_contents[8:])
529         else:
530             raise NotImplementedError(u'Unsupported compression format %r' %
531                                       file_contents[:1])
532
533         def extract_tags(content):
534             pos = 0
535             while pos < len(content):
536                 header16 = struct.unpack('<H', content[pos:pos+2])[0]
537                 pos += 2
538                 tag_code = header16 >> 6
539                 tag_len = header16 & 0x3f
540                 if tag_len == 0x3f:
541                     tag_len = struct.unpack('<I', content[pos:pos+4])[0]
542                     pos += 4
543                 assert pos+tag_len <= len(content)
544                 yield (tag_code, content[pos:pos+tag_len])
545                 pos += tag_len
546
547         code_tag = next(tag
548                         for tag_code, tag in extract_tags(content)
549                         if tag_code == 82)
550         p = code_tag.index(b'\0', 4) + 1
551         code_reader = io.BytesIO(code_tag[p:])
552
553         # Parse ABC (AVM2 ByteCode)
554         def read_int(reader=None):
555             if reader is None:
556                 reader = code_reader
557             res = 0
558             shift = 0
559             for _ in range(5):
560                 buf = reader.read(1)
561                 assert len(buf) == 1
562                 b = struct.unpack('<B', buf)[0]
563                 res = res | ((b & 0x7f) << shift)
564                 if b & 0x80 == 0:
565                     break
566                 shift += 7
567             return res
568
569         def u30(reader=None):
570             res = read_int(reader)
571             assert res & 0xf0000000 == 0
572             return res
573         u32 = read_int
574
575         def s32(reader=None):
576             v = read_int(reader)
577             if v & 0x80000000 != 0:
578                 v = - ((v ^ 0xffffffff) + 1)
579             return v
580
581         def read_string(reader=None):
582             if reader is None:
583                 reader = code_reader
584             slen = u30(reader)
585             resb = reader.read(slen)
586             assert len(resb) == slen
587             return resb.decode('utf-8')
588
589         def read_bytes(count, reader=None):
590             if reader is None:
591                 reader = code_reader
592             resb = reader.read(count)
593             assert len(resb) == count
594             return resb
595
596         def read_byte(reader=None):
597             resb = read_bytes(1, reader=reader)
598             res = struct.unpack('<B', resb)[0]
599             return res
600
601         # minor_version + major_version
602         read_bytes(2 + 2)
603
604         # Constant pool
605         int_count = u30()
606         for _c in range(1, int_count):
607             s32()
608         uint_count = u30()
609         for _c in range(1, uint_count):
610             u32()
611         double_count = u30()
612         read_bytes((double_count-1) * 8)
613         string_count = u30()
614         constant_strings = [u'']
615         for _c in range(1, string_count):
616             s = read_string()
617             constant_strings.append(s)
618         namespace_count = u30()
619         for _c in range(1, namespace_count):
620             read_bytes(1)  # kind
621             u30()  # name
622         ns_set_count = u30()
623         for _c in range(1, ns_set_count):
624             count = u30()
625             for _c2 in range(count):
626                 u30()
627         multiname_count = u30()
628         MULTINAME_SIZES = {
629             0x07: 2,  # QName
630             0x0d: 2,  # QNameA
631             0x0f: 1,  # RTQName
632             0x10: 1,  # RTQNameA
633             0x11: 0,  # RTQNameL
634             0x12: 0,  # RTQNameLA
635             0x09: 2,  # Multiname
636             0x0e: 2,  # MultinameA
637             0x1b: 1,  # MultinameL
638             0x1c: 1,  # MultinameLA
639         }
640         multinames = [u'']
641         for _c in range(1, multiname_count):
642             kind = u30()
643             assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
644             if kind == 0x07:
645                 u30()  # namespace_idx
646                 name_idx = u30()
647                 multinames.append(constant_strings[name_idx])
648             else:
649                 multinames.append('[MULTINAME kind: %d]' % kind)
650                 for _c2 in range(MULTINAME_SIZES[kind]):
651                     u30()
652
653         # Methods
654         method_count = u30()
655         MethodInfo = collections.namedtuple(
656             'MethodInfo',
657             ['NEED_ARGUMENTS', 'NEED_REST'])
658         method_infos = []
659         for method_id in range(method_count):
660             param_count = u30()
661             u30()  # return type
662             for _ in range(param_count):
663                 u30()  # param type
664             u30()  # name index (always 0 for youtube)
665             flags = read_byte()
666             if flags & 0x08 != 0:
667                 # Options present
668                 option_count = u30()
669                 for c in range(option_count):
670                     u30()  # val
671                     read_bytes(1)  # kind
672             if flags & 0x80 != 0:
673                 # Param names present
674                 for _ in range(param_count):
675                     u30()  # param name
676             mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
677             method_infos.append(mi)
678
679         # Metadata
680         metadata_count = u30()
681         for _c in range(metadata_count):
682             u30()  # name
683             item_count = u30()
684             for _c2 in range(item_count):
685                 u30()  # key
686                 u30()  # value
687
688         def parse_traits_info():
689             trait_name_idx = u30()
690             kind_full = read_byte()
691             kind = kind_full & 0x0f
692             attrs = kind_full >> 4
693             methods = {}
694             if kind in [0x00, 0x06]:  # Slot or Const
695                 u30()  # Slot id
696                 u30()  # type_name_idx
697                 vindex = u30()
698                 if vindex != 0:
699                     read_byte()  # vkind
700             elif kind in [0x01, 0x02, 0x03]:  # Method / Getter / Setter
701                 u30()  # disp_id
702                 method_idx = u30()
703                 methods[multinames[trait_name_idx]] = method_idx
704             elif kind == 0x04:  # Class
705                 u30()  # slot_id
706                 u30()  # classi
707             elif kind == 0x05:  # Function
708                 u30()  # slot_id
709                 function_idx = u30()
710                 methods[function_idx] = multinames[trait_name_idx]
711             else:
712                 raise ExtractorError(u'Unsupported trait kind %d' % kind)
713
714             if attrs & 0x4 != 0:  # Metadata present
715                 metadata_count = u30()
716                 for _c3 in range(metadata_count):
717                     u30()  # metadata index
718
719             return methods
720
721         # Classes
722         TARGET_CLASSNAME = u'SignatureDecipher'
723         searched_idx = multinames.index(TARGET_CLASSNAME)
724         searched_class_id = None
725         class_count = u30()
726         for class_id in range(class_count):
727             name_idx = u30()
728             if name_idx == searched_idx:
729                 # We found the class we're looking for!
730                 searched_class_id = class_id
731             u30()  # super_name idx
732             flags = read_byte()
733             if flags & 0x08 != 0:  # Protected namespace is present
734                 u30()  # protected_ns_idx
735             intrf_count = u30()
736             for _c2 in range(intrf_count):
737                 u30()
738             u30()  # iinit
739             trait_count = u30()
740             for _c2 in range(trait_count):
741                 parse_traits_info()
742
743         if searched_class_id is None:
744             raise ExtractorError(u'Target class %r not found' %
745                                  TARGET_CLASSNAME)
746
747         method_names = {}
748         method_idxs = {}
749         for class_id in range(class_count):
750             u30()  # cinit
751             trait_count = u30()
752             for _c2 in range(trait_count):
753                 trait_methods = parse_traits_info()
754                 if class_id == searched_class_id:
755                     method_names.update(trait_methods.items())
756                     method_idxs.update(dict(
757                         (idx, name)
758                         for name, idx in trait_methods.items()))
759
760         # Scripts
761         script_count = u30()
762         for _c in range(script_count):
763             u30()  # init
764             trait_count = u30()
765             for _c2 in range(trait_count):
766                 parse_traits_info()
767
768         # Method bodies
769         method_body_count = u30()
770         Method = collections.namedtuple('Method', ['code', 'local_count'])
771         methods = {}
772         for _c in range(method_body_count):
773             method_idx = u30()
774             u30()  # max_stack
775             local_count = u30()
776             u30()  # init_scope_depth
777             u30()  # max_scope_depth
778             code_length = u30()
779             code = read_bytes(code_length)
780             if method_idx in method_idxs:
781                 m = Method(code, local_count)
782                 methods[method_idxs[method_idx]] = m
783             exception_count = u30()
784             for _c2 in range(exception_count):
785                 u30()  # from
786                 u30()  # to
787                 u30()  # target
788                 u30()  # exc_type
789                 u30()  # var_name
790             trait_count = u30()
791             for _c2 in range(trait_count):
792                 parse_traits_info()
793
794         assert p + code_reader.tell() == len(code_tag)
795         assert len(methods) == len(method_idxs)
796
797         method_pyfunctions = {}
798
799         def extract_function(func_name):
800             if func_name in method_pyfunctions:
801                 return method_pyfunctions[func_name]
802             if func_name not in methods:
803                 raise ExtractorError(u'Cannot find function %r' % func_name)
804             m = methods[func_name]
805
806             def resfunc(args):
807                 registers = ['(this)'] + list(args) + [None] * m.local_count
808                 stack = []
809                 coder = io.BytesIO(m.code)
810                 while True:
811                     opcode = struct.unpack('!B', coder.read(1))[0]
812                     if opcode == 36:  # pushbyte
813                         v = struct.unpack('!B', coder.read(1))[0]
814                         stack.append(v)
815                     elif opcode == 44:  # pushstring
816                         idx = u30(coder)
817                         stack.append(constant_strings[idx])
818                     elif opcode == 48:  # pushscope
819                         # We don't implement the scope register, so we'll just
820                         # ignore the popped value
821                         stack.pop()
822                     elif opcode == 70:  # callproperty
823                         index = u30(coder)
824                         mname = multinames[index]
825                         arg_count = u30(coder)
826                         args = list(reversed(
827                             [stack.pop() for _ in range(arg_count)]))
828                         obj = stack.pop()
829                         if mname == u'split':
830                             assert len(args) == 1
831                             assert isinstance(args[0], compat_str)
832                             assert isinstance(obj, compat_str)
833                             if args[0] == u'':
834                                 res = list(obj)
835                             else:
836                                 res = obj.split(args[0])
837                             stack.append(res)
838                         elif mname == u'slice':
839                             assert len(args) == 1
840                             assert isinstance(args[0], int)
841                             assert isinstance(obj, list)
842                             res = obj[args[0]:]
843                             stack.append(res)
844                         elif mname == u'join':
845                             assert len(args) == 1
846                             assert isinstance(args[0], compat_str)
847                             assert isinstance(obj, list)
848                             res = args[0].join(obj)
849                             stack.append(res)
850                         elif mname in method_pyfunctions:
851                             stack.append(method_pyfunctions[mname](args))
852                         else:
853                             raise NotImplementedError(
854                                 u'Unsupported property %r on %r'
855                                 % (mname, obj))
856                     elif opcode == 72:  # returnvalue
857                         res = stack.pop()
858                         return res
859                     elif opcode == 79:  # callpropvoid
860                         index = u30(coder)
861                         mname = multinames[index]
862                         arg_count = u30(coder)
863                         args = list(reversed(
864                             [stack.pop() for _ in range(arg_count)]))
865                         obj = stack.pop()
866                         if mname == u'reverse':
867                             assert isinstance(obj, list)
868                             obj.reverse()
869                         else:
870                             raise NotImplementedError(
871                                 u'Unsupported (void) property %r on %r'
872                                 % (mname, obj))
873                     elif opcode == 93:  # findpropstrict
874                         index = u30(coder)
875                         mname = multinames[index]
876                         res = extract_function(mname)
877                         stack.append(res)
878                     elif opcode == 97:  # setproperty
879                         index = u30(coder)
880                         value = stack.pop()
881                         idx = stack.pop()
882                         obj = stack.pop()
883                         assert isinstance(obj, list)
884                         assert isinstance(idx, int)
885                         obj[idx] = value
886                     elif opcode == 98:  # getlocal
887                         index = u30(coder)
888                         stack.append(registers[index])
889                     elif opcode == 99:  # setlocal
890                         index = u30(coder)
891                         value = stack.pop()
892                         registers[index] = value
893                     elif opcode == 102:  # getproperty
894                         index = u30(coder)
895                         pname = multinames[index]
896                         if pname == u'length':
897                             obj = stack.pop()
898                             assert isinstance(obj, list)
899                             stack.append(len(obj))
900                         else:  # Assume attribute access
901                             idx = stack.pop()
902                             assert isinstance(idx, int)
903                             obj = stack.pop()
904                             assert isinstance(obj, list)
905                             stack.append(obj[idx])
906                     elif opcode == 128:  # coerce
907                         u30(coder)
908                     elif opcode == 133:  # coerce_s
909                         assert isinstance(stack[-1], (type(None), compat_str))
910                     elif opcode == 164:  # modulo
911                         value2 = stack.pop()
912                         value1 = stack.pop()
913                         res = value1 % value2
914                         stack.append(res)
915                     elif opcode == 208:  # getlocal_0
916                         stack.append(registers[0])
917                     elif opcode == 209:  # getlocal_1
918                         stack.append(registers[1])
919                     elif opcode == 210:  # getlocal_2
920                         stack.append(registers[2])
921                     elif opcode == 211:  # getlocal_3
922                         stack.append(registers[3])
923                     elif opcode == 214:  # setlocal_2
924                         registers[2] = stack.pop()
925                     elif opcode == 215:  # setlocal_3
926                         registers[3] = stack.pop()
927                     else:
928                         raise NotImplementedError(
929                             u'Unsupported opcode %d' % opcode)
930
931             method_pyfunctions[func_name] = resfunc
932             return resfunc
933
934         initial_function = extract_function(u'decipher')
935         return lambda s: initial_function([s])
936
937     def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
938         """Turn the encrypted s field into a working signature"""
939
940         if player_url is not None:
941             if player_url.startswith(u'//'):
942                 player_url = u'https:' + player_url
943             try:
944                 player_id = (player_url, len(s))
945                 if player_id not in self._player_cache:
946                     func = self._extract_signature_function(
947                         video_id, player_url, len(s)
948                     )
949                     self._player_cache[player_id] = func
950                 func = self._player_cache[player_id]
951                 if self._downloader.params.get('youtube_print_sig_code'):
952                     self._print_sig_code(func, len(s))
953                 return func(s)
954             except Exception:
955                 tb = traceback.format_exc()
956                 self._downloader.report_warning(
957                     u'Automatic signature extraction failed: ' + tb)
958
959             self._downloader.report_warning(
960                 u'Warning: Falling back to static signature algorithm')
961
962         return self._static_decrypt_signature(
963             s, video_id, player_url, age_gate)
964
965     def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
966         if age_gate:
967             # The videos with age protection use another player, so the
968             # algorithms can be different.
969             if len(s) == 86:
970                 return s[2:63] + s[82] + s[64:82] + s[63]
971
972         if len(s) == 93:
973             return s[86:29:-1] + s[88] + s[28:5:-1]
974         elif len(s) == 92:
975             return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
976         elif len(s) == 91:
977             return s[84:27:-1] + s[86] + s[26:5:-1]
978         elif len(s) == 90:
979             return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
980         elif len(s) == 89:
981             return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
982         elif len(s) == 88:
983             return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
984         elif len(s) == 87:
985             return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
986         elif len(s) == 86:
987             return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
988         elif len(s) == 85:
989             return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
990         elif len(s) == 84:
991             return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
992         elif len(s) == 83:
993             return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
994         elif len(s) == 82:
995             return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
996         elif len(s) == 81:
997             return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
998         elif len(s) == 80:
999             return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
1000         elif len(s) == 79:
1001             return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
1002
1003         else:
1004             raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
1005
1006     def _get_available_subtitles(self, video_id, webpage):
1007         try:
1008             sub_list = self._download_webpage(
1009                 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
1010                 video_id, note=False)
1011         except ExtractorError as err:
1012             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
1013             return {}
1014         lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
1015
1016         sub_lang_list = {}
1017         for l in lang_list:
1018             lang = l[1]
1019             params = compat_urllib_parse.urlencode({
1020                 'lang': lang,
1021                 'v': video_id,
1022                 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
1023                 'name': unescapeHTML(l[0]).encode('utf-8'),
1024             })
1025             url = u'http://www.youtube.com/api/timedtext?' + params
1026             sub_lang_list[lang] = url
1027         if not sub_lang_list:
1028             self._downloader.report_warning(u'video doesn\'t have subtitles')
1029             return {}
1030         return sub_lang_list
1031
1032     def _get_available_automatic_caption(self, video_id, webpage):
1033         """We need the webpage for getting the captions url, pass it as an
1034            argument to speed up the process."""
1035         sub_format = self._downloader.params.get('subtitlesformat', 'srt')
1036         self.to_screen(u'%s: Looking for automatic captions' % video_id)
1037         mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
1038         err_msg = u'Couldn\'t find automatic captions for %s' % video_id
1039         if mobj is None:
1040             self._downloader.report_warning(err_msg)
1041             return {}
1042         player_config = json.loads(mobj.group(1))
1043         try:
1044             args = player_config[u'args']
1045             caption_url = args[u'ttsurl']
1046             timestamp = args[u'timestamp']
1047             # We get the available subtitles
1048             list_params = compat_urllib_parse.urlencode({
1049                 'type': 'list',
1050                 'tlangs': 1,
1051                 'asrs': 1,
1052             })
1053             list_url = caption_url + '&' + list_params
1054             caption_list = self._download_xml(list_url, video_id)
1055             original_lang_node = caption_list.find('track')
1056             if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
1057                 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
1058                 return {}
1059             original_lang = original_lang_node.attrib['lang_code']
1060
1061             sub_lang_list = {}
1062             for lang_node in caption_list.findall('target'):
1063                 sub_lang = lang_node.attrib['lang_code']
1064                 params = compat_urllib_parse.urlencode({
1065                     'lang': original_lang,
1066                     'tlang': sub_lang,
1067                     'fmt': sub_format,
1068                     'ts': timestamp,
1069                     'kind': 'asr',
1070                 })
1071                 sub_lang_list[sub_lang] = caption_url + '&' + params
1072             return sub_lang_list
1073         # An extractor error can be raise by the download process if there are
1074         # no automatic captions but there are subtitles
1075         except (KeyError, ExtractorError):
1076             self._downloader.report_warning(err_msg)
1077             return {}
1078
1079     def _extract_id(self, url):
1080         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
1081         if mobj is None:
1082             raise ExtractorError(u'Invalid URL: %s' % url)
1083         video_id = mobj.group(2)
1084         return video_id
1085
1086     def _extract_from_m3u8(self, manifest_url, video_id):
1087         url_map = {}
1088         def _get_urls(_manifest):
1089             lines = _manifest.split('\n')
1090             urls = filter(lambda l: l and not l.startswith('#'),
1091                             lines)
1092             return urls
1093         manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
1094         formats_urls = _get_urls(manifest)
1095         for format_url in formats_urls:
1096             itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
1097             url_map[itag] = format_url
1098         return url_map
1099
1100     def _extract_annotations(self, video_id):
1101         url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
1102         return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
1103
1104     def _real_extract(self, url):
1105         # Extract original video URL from URL with redirection, like age verification, using next_url parameter
1106         mobj = re.search(self._NEXT_URL_RE, url)
1107         if mobj:
1108             url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
1109         video_id = self._extract_id(url)
1110
1111         # Get video webpage
1112         url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
1113         video_webpage = self._download_webpage(url, video_id)
1114
1115         # Attempt to extract SWF player URL
1116         mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
1117         if mobj is not None:
1118             player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
1119         else:
1120             player_url = None
1121
1122         # Get video info
1123         self.report_video_info_webpage_download(video_id)
1124         if re.search(r'player-age-gate-content">', video_webpage) is not None:
1125             self.report_age_confirmation()
1126             age_gate = True
1127             # We simulate the access to the video from www.youtube.com/v/{video_id}
1128             # this can be viewed without login into Youtube
1129             data = compat_urllib_parse.urlencode({'video_id': video_id,
1130                                                   'el': 'player_embedded',
1131                                                   'gl': 'US',
1132                                                   'hl': 'en',
1133                                                   'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1134                                                   'asv': 3,
1135                                                   'sts':'1588',
1136                                                   })
1137             video_info_url = 'https://www.youtube.com/get_video_info?' + data
1138             video_info_webpage = self._download_webpage(video_info_url, video_id,
1139                                     note=False,
1140                                     errnote='unable to download video info webpage')
1141             video_info = compat_parse_qs(video_info_webpage)
1142         else:
1143             age_gate = False
1144             for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
1145                 video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
1146                         % (video_id, el_type))
1147                 video_info_webpage = self._download_webpage(video_info_url, video_id,
1148                                         note=False,
1149                                         errnote='unable to download video info webpage')
1150                 video_info = compat_parse_qs(video_info_webpage)
1151                 if 'token' in video_info:
1152                     break
1153         if 'token' not in video_info:
1154             if 'reason' in video_info:
1155                 raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
1156             else:
1157                 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
1158
1159         if 'view_count' in video_info:
1160             view_count = int(video_info['view_count'][0])
1161         else:
1162             view_count = None
1163
1164         # Check for "rental" videos
1165         if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
1166             raise ExtractorError(u'"rental" videos not supported')
1167
1168         # Start extracting information
1169         self.report_information_extraction(video_id)
1170
1171         # uploader
1172         if 'author' not in video_info:
1173             raise ExtractorError(u'Unable to extract uploader name')
1174         video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
1175
1176         # uploader_id
1177         video_uploader_id = None
1178         mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
1179         if mobj is not None:
1180             video_uploader_id = mobj.group(1)
1181         else:
1182             self._downloader.report_warning(u'unable to extract uploader nickname')
1183
1184         # title
1185         if 'title' in video_info:
1186             video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
1187         else:
1188             self._downloader.report_warning(u'Unable to extract video title')
1189             video_title = u'_'
1190
1191         # thumbnail image
1192         # We try first to get a high quality image:
1193         m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
1194                             video_webpage, re.DOTALL)
1195         if m_thumb is not None:
1196             video_thumbnail = m_thumb.group(1)
1197         elif 'thumbnail_url' not in video_info:
1198             self._downloader.report_warning(u'unable to extract video thumbnail')
1199             video_thumbnail = None
1200         else:   # don't panic if we can't find it
1201             video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
1202
1203         # upload date
1204         upload_date = None
1205         mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
1206         if mobj is not None:
1207             upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
1208             upload_date = unified_strdate(upload_date)
1209
1210         # description
1211         video_description = get_element_by_id("eow-description", video_webpage)
1212         if video_description:
1213             video_description = re.sub(r'''(?x)
1214                 <a\s+
1215                     (?:[a-zA-Z-]+="[^"]+"\s+)*?
1216                     title="([^"]+)"\s+
1217                     (?:[a-zA-Z-]+="[^"]+"\s+)*?
1218                     class="yt-uix-redirect-link"\s*>
1219                 [^<]+
1220                 </a>
1221             ''', r'\1', video_description)
1222             video_description = clean_html(video_description)
1223         else:
1224             fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
1225             if fd_mobj:
1226                 video_description = unescapeHTML(fd_mobj.group(1))
1227             else:
1228                 video_description = u''
1229
1230         def _extract_count(klass):
1231             count = self._search_regex(
1232                 r'class="%s">([\d,]+)</span>' % re.escape(klass),
1233                 video_webpage, klass, default=None)
1234             if count is not None:
1235                 return int(count.replace(',', ''))
1236             return None
1237         like_count = _extract_count(u'likes-count')
1238         dislike_count = _extract_count(u'dislikes-count')
1239
1240         # subtitles
1241         video_subtitles = self.extract_subtitles(video_id, video_webpage)
1242
1243         if self._downloader.params.get('listsubtitles', False):
1244             self._list_available_subtitles(video_id, video_webpage)
1245             return
1246
1247         if 'length_seconds' not in video_info:
1248             self._downloader.report_warning(u'unable to extract video duration')
1249             video_duration = None
1250         else:
1251             video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
1252
1253         # annotations
1254         video_annotations = None
1255         if self._downloader.params.get('writeannotations', False):
1256                 video_annotations = self._extract_annotations(video_id)
1257
1258         # Decide which formats to download
1259         try:
1260             mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
1261             if not mobj:
1262                 raise ValueError('Could not find vevo ID')
1263             info = json.loads(mobj.group(1))
1264             args = info['args']
1265             # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
1266             # this signatures are encrypted
1267             if 'url_encoded_fmt_stream_map' not in args:
1268                 raise ValueError(u'No stream_map present')  # caught below
1269             re_signature = re.compile(r'[&,]s=')
1270             m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
1271             if m_s is not None:
1272                 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
1273                 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
1274             m_s = re_signature.search(args.get('adaptive_fmts', u''))
1275             if m_s is not None:
1276                 if 'adaptive_fmts' in video_info:
1277                     video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
1278                 else:
1279                     video_info['adaptive_fmts'] = [args['adaptive_fmts']]
1280         except ValueError:
1281             pass
1282
1283         def _map_to_format_list(urlmap):
1284             formats = []
1285             for itag, video_real_url in urlmap.items():
1286                 dct = {
1287                     'format_id': itag,
1288                     'url': video_real_url,
1289                     'player_url': player_url,
1290                 }
1291                 dct.update(self._formats[itag])
1292                 formats.append(dct)
1293             return formats
1294
1295         if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
1296             self.report_rtmp_download()
1297             formats = [{
1298                 'format_id': '_rtmp',
1299                 'protocol': 'rtmp',
1300                 'url': video_info['conn'][0],
1301                 'player_url': player_url,
1302             }]
1303         elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
1304             encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
1305             if 'rtmpe%3Dyes' in encoded_url_map:
1306                 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
1307             url_map = {}
1308             for url_data_str in encoded_url_map.split(','):
1309                 url_data = compat_parse_qs(url_data_str)
1310                 if 'itag' in url_data and 'url' in url_data:
1311                     url = url_data['url'][0]
1312                     if 'sig' in url_data:
1313                         url += '&signature=' + url_data['sig'][0]
1314                     elif 's' in url_data:
1315                         encrypted_sig = url_data['s'][0]
1316                         if self._downloader.params.get('verbose'):
1317                             if age_gate:
1318                                 if player_url is None:
1319                                     player_version = 'unknown'
1320                                 else:
1321                                     player_version = self._search_regex(
1322                                         r'-(.+)\.swf$', player_url,
1323                                         u'flash player', fatal=False)
1324                                 player_desc = 'flash player %s' % player_version
1325                             else:
1326                                 player_version = self._search_regex(
1327                                     r'html5player-(.+?)\.js', video_webpage,
1328                                     'html5 player', fatal=False)
1329                                 player_desc = u'html5 player %s' % player_version
1330
1331                             parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
1332                             self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
1333                                 (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
1334
1335                         if not age_gate:
1336                             jsplayer_url_json = self._search_regex(
1337                                 r'"assets":.+?"js":\s*("[^"]+")',
1338                                 video_webpage, u'JS player URL')
1339                             player_url = json.loads(jsplayer_url_json)
1340
1341                         signature = self._decrypt_signature(
1342                             encrypted_sig, video_id, player_url, age_gate)
1343                         url += '&signature=' + signature
1344                     if 'ratebypass' not in url:
1345                         url += '&ratebypass=yes'
1346                     url_map[url_data['itag'][0]] = url
1347             formats = _map_to_format_list(url_map)
1348         elif video_info.get('hlsvp'):
1349             manifest_url = video_info['hlsvp'][0]
1350             url_map = self._extract_from_m3u8(manifest_url, video_id)
1351             formats = _map_to_format_list(url_map)
1352         else:
1353             raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
1354
1355         # Look for the DASH manifest
1356         dash_manifest_url_lst = video_info.get('dashmpd')
1357         if dash_manifest_url_lst and dash_manifest_url_lst[0]:
1358             try:
1359                 dash_doc = self._download_xml(
1360                     dash_manifest_url_lst[0], video_id,
1361                     note=u'Downloading DASH manifest',
1362                     errnote=u'Could not download DASH manifest')
1363                 for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
1364                     url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
1365                     if url_el is None:
1366                         continue
1367                     format_id = r.attrib['id']
1368                     video_url = url_el.text
1369                     filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
1370                     f = {
1371                         'format_id': format_id,
1372                         'url': video_url,
1373                         'width': int_or_none(r.attrib.get('width')),
1374                         'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
1375                         'asr': int_or_none(r.attrib.get('audioSamplingRate')),
1376                         'filesize': filesize,
1377                     }
1378                     try:
1379                         existing_format = next(
1380                             fo for fo in formats
1381                             if fo['format_id'] == format_id)
1382                     except StopIteration:
1383                         f.update(self._formats.get(format_id, {}))
1384                         formats.append(f)
1385                     else:
1386                         existing_format.update(f)
1387
1388             except (ExtractorError, KeyError) as e:
1389                 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
1390
1391         self._sort_formats(formats)
1392
1393         return {
1394             'id':           video_id,
1395             'uploader':     video_uploader,
1396             'uploader_id':  video_uploader_id,
1397             'upload_date':  upload_date,
1398             'title':        video_title,
1399             'thumbnail':    video_thumbnail,
1400             'description':  video_description,
1401             'subtitles':    video_subtitles,
1402             'duration':     video_duration,
1403             'age_limit':    18 if age_gate else 0,
1404             'annotations':  video_annotations,
1405             'webpage_url': 'https://www.youtube.com/watch?v=%s' % video_id,
1406             'view_count':   view_count,
1407             'like_count': like_count,
1408             'dislike_count': dislike_count,
1409             'formats':      formats,
1410         }
1411
1412 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
1413     IE_DESC = u'YouTube.com playlists'
1414     _VALID_URL = r"""(?:
1415                         (?:https?://)?
1416                         (?:\w+\.)?
1417                         youtube\.com/
1418                         (?:
1419                            (?:course|view_play_list|my_playlists|artist|playlist|watch)
1420                            \? (?:.*?&)*? (?:p|a|list)=
1421                         |  p/
1422                         )
1423                         ((?:PL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,})
1424                         .*
1425                      |
1426                         ((?:PL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
1427                      )"""
1428     _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&page=%s'
1429     _MORE_PAGES_INDICATOR = r'data-link-type="next"'
1430     _VIDEO_RE = r'href="/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
1431     IE_NAME = u'youtube:playlist'
1432
1433     @classmethod
1434     def suitable(cls, url):
1435         """Receives a URL and returns True if suitable for this IE."""
1436         return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
1437
1438     def _real_initialize(self):
1439         self._login()
1440
1441     def _ids_to_results(self, ids):
1442         return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
1443                        for vid_id in ids]
1444
1445     def _extract_mix(self, playlist_id):
1446         # The mixes are generated from a a single video
1447         # the id of the playlist is just 'RD' + video_id
1448         url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
1449         webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
1450         title_span = (get_element_by_attribute('class', 'title long-title', webpage) or
1451             get_element_by_attribute('class', 'title ', webpage))
1452         title = clean_html(title_span)
1453         video_re = r'data-index="\d+".*?href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s' % re.escape(playlist_id)
1454         ids = orderedSet(re.findall(video_re, webpage))
1455         url_results = self._ids_to_results(ids)
1456
1457         return self.playlist_result(url_results, playlist_id, title)
1458
1459     def _real_extract(self, url):
1460         # Extract playlist id
1461         mobj = re.match(self._VALID_URL, url, re.VERBOSE)
1462         if mobj is None:
1463             raise ExtractorError(u'Invalid URL: %s' % url)
1464         playlist_id = mobj.group(1) or mobj.group(2)
1465
1466         # Check if it's a video-specific URL
1467         query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
1468         if 'v' in query_dict:
1469             video_id = query_dict['v'][0]
1470             if self._downloader.params.get('noplaylist'):
1471                 self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
1472                 return self.url_result(video_id, 'Youtube', video_id=video_id)
1473             else:
1474                 self.to_screen(u'Downloading playlist PL%s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1475
1476         if playlist_id.startswith('RD'):
1477             # Mixes require a custom extraction process
1478             return self._extract_mix(playlist_id)
1479         if playlist_id.startswith('TL'):
1480             raise ExtractorError(u'For downloading YouTube.com top lists, use '
1481                 u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
1482
1483         # Extract the video ids from the playlist pages
1484         ids = []
1485
1486         for page_num in itertools.count(1):
1487             url = self._TEMPLATE_URL % (playlist_id, page_num)
1488             page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
1489             matches = re.finditer(self._VIDEO_RE, page)
1490             # We remove the duplicates and the link with index 0
1491             # (it's not the first video of the playlist)
1492             new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
1493             ids.extend(new_ids)
1494
1495             if re.search(self._MORE_PAGES_INDICATOR, page) is None:
1496                 break
1497
1498         try:
1499             playlist_title = self._og_search_title(page)
1500         except RegexNotFoundError:
1501             self.report_warning(
1502                 u'Playlist page is missing OpenGraph title, falling back ...',
1503                 playlist_id)
1504             playlist_title = self._html_search_regex(
1505                 r'<h1 class="pl-header-title">(.*?)</h1>', page, u'title')
1506
1507         url_results = self._ids_to_results(ids)
1508         return self.playlist_result(url_results, playlist_id, playlist_title)
1509
1510
1511 class YoutubeTopListIE(YoutubePlaylistIE):
1512     IE_NAME = u'youtube:toplist'
1513     IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1514         u' (Example: "yttoplist:music:Top Tracks")')
1515     _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1516
1517     def _real_extract(self, url):
1518         mobj = re.match(self._VALID_URL, url)
1519         channel = mobj.group('chann')
1520         title = mobj.group('title')
1521         query = compat_urllib_parse.urlencode({'title': title})
1522         playlist_re = 'href="([^"]+?%s[^"]+?)"' % re.escape(query)
1523         channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title)
1524         link = self._html_search_regex(playlist_re, channel_page, u'list')
1525         url = compat_urlparse.urljoin('https://www.youtube.com/', link)
1526         
1527         video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1528         ids = []
1529         # sometimes the webpage doesn't contain the videos
1530         # retry until we get them
1531         for i in itertools.count(0):
1532             msg = u'Downloading Youtube mix'
1533             if i > 0:
1534                 msg += ', retry #%d' % i
1535             webpage = self._download_webpage(url, title, msg)
1536             ids = orderedSet(re.findall(video_re, webpage))
1537             if ids:
1538                 break
1539         url_results = self._ids_to_results(ids)
1540         return self.playlist_result(url_results, playlist_title=title)
1541
1542
1543 class YoutubeChannelIE(InfoExtractor):
1544     IE_DESC = u'YouTube.com channels'
1545     _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1546     _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
1547     _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
1548     IE_NAME = u'youtube:channel'
1549
1550     def extract_videos_from_page(self, page):
1551         ids_in_page = []
1552         for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
1553             if mobj.group(1) not in ids_in_page:
1554                 ids_in_page.append(mobj.group(1))
1555         return ids_in_page
1556
1557     def _real_extract(self, url):
1558         # Extract channel id
1559         mobj = re.match(self._VALID_URL, url)
1560         if mobj is None:
1561             raise ExtractorError(u'Invalid URL: %s' % url)
1562
1563         # Download channel page
1564         channel_id = mobj.group(1)
1565         video_ids = []
1566         url = 'https://www.youtube.com/channel/%s/videos' % channel_id
1567         channel_page = self._download_webpage(url, channel_id)
1568         autogenerated = re.search(r'''(?x)
1569                 class="[^"]*?(?:
1570                     channel-header-autogenerated-label|
1571                     yt-channel-title-autogenerated
1572                 )[^"]*"''', channel_page) is not None
1573
1574         if autogenerated:
1575             # The videos are contained in a single page
1576             # the ajax pages can't be used, they are empty
1577             video_ids = self.extract_videos_from_page(channel_page)
1578         else:
1579             # Download all channel pages using the json-based channel_ajax query
1580             for pagenum in itertools.count(1):
1581                 url = self._MORE_PAGES_URL % (pagenum, channel_id)
1582                 page = self._download_webpage(url, channel_id,
1583                                               u'Downloading page #%s' % pagenum)
1584     
1585                 page = json.loads(page)
1586     
1587                 ids_in_page = self.extract_videos_from_page(page['content_html'])
1588                 video_ids.extend(ids_in_page)
1589     
1590                 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1591                     break
1592
1593         self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1594
1595         url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
1596                        for video_id in video_ids]
1597         return self.playlist_result(url_entries, channel_id)
1598
1599
1600 class YoutubeUserIE(InfoExtractor):
1601     IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
1602     _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1603     _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
1604     _GDATA_PAGE_SIZE = 50
1605     _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1606     IE_NAME = u'youtube:user'
1607
1608     @classmethod
1609     def suitable(cls, url):
1610         # Don't return True if the url can be extracted with other youtube
1611         # extractor, the regex would is too permissive and it would match.
1612         other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
1613         if any(ie.suitable(url) for ie in other_ies): return False
1614         else: return super(YoutubeUserIE, cls).suitable(url)
1615
1616     def _real_extract(self, url):
1617         # Extract username
1618         mobj = re.match(self._VALID_URL, url)
1619         if mobj is None:
1620             raise ExtractorError(u'Invalid URL: %s' % url)
1621
1622         username = mobj.group(1)
1623
1624         # Download video ids using YouTube Data API. Result size per
1625         # query is limited (currently to 50 videos) so we need to query
1626         # page by page until there are no video ids - it means we got
1627         # all of them.
1628
1629         url_results = []
1630
1631         for pagenum in itertools.count(0):
1632             start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1633
1634             gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
1635             page = self._download_webpage(gdata_url, username,
1636                                           u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
1637
1638             try:
1639                 response = json.loads(page)
1640             except ValueError as err:
1641                 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
1642             if 'entry' not in response['feed']:
1643                 # Number of videos is a multiple of self._MAX_RESULTS
1644                 break
1645
1646             # Extract video identifiers
1647             entries = response['feed']['entry']
1648             for entry in entries:
1649                 title = entry['title']['$t']
1650                 video_id = entry['id']['$t'].split('/')[-1]
1651                 url_results.append({
1652                     '_type': 'url',
1653                     'url': video_id,
1654                     'ie_key': 'Youtube',
1655                     'id': 'video_id',
1656                     'title': title,
1657                 })
1658
1659             # A little optimization - if current page is not
1660             # "full", ie. does not contain PAGE_SIZE video ids then
1661             # we can assume that this page is the last one - there
1662             # are no more ids on further pages - no need to query
1663             # again.
1664
1665             if len(entries) < self._GDATA_PAGE_SIZE:
1666                 break
1667
1668         return self.playlist_result(url_results, playlist_title=username)
1669
1670
1671 class YoutubeSearchIE(SearchInfoExtractor):
1672     IE_DESC = u'YouTube.com searches'
1673     _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1674     _MAX_RESULTS = 1000
1675     IE_NAME = u'youtube:search'
1676     _SEARCH_KEY = 'ytsearch'
1677
1678     def _get_n_results(self, query, n):
1679         """Get a specified number of results for a query"""
1680
1681         video_ids = []
1682         pagenum = 0
1683         limit = n
1684
1685         while (50 * pagenum) < limit:
1686             result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
1687             data_json = self._download_webpage(
1688                 result_url, video_id=u'query "%s"' % query,
1689                 note=u'Downloading page %s' % (pagenum + 1),
1690                 errnote=u'Unable to download API page')
1691             data = json.loads(data_json)
1692             api_response = data['data']
1693
1694             if 'items' not in api_response:
1695                 raise ExtractorError(u'[youtube] No video results')
1696
1697             new_ids = list(video['id'] for video in api_response['items'])
1698             video_ids += new_ids
1699
1700             limit = min(n, api_response['totalItems'])
1701             pagenum += 1
1702
1703         if len(video_ids) > n:
1704             video_ids = video_ids[:n]
1705         videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
1706                   for video_id in video_ids]
1707         return self.playlist_result(videos, query)
1708
1709 class YoutubeSearchDateIE(YoutubeSearchIE):
1710     IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
1711     _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1712     _SEARCH_KEY = 'ytsearchdate'
1713     IE_DESC = u'YouTube.com searches, newest videos first'
1714
1715 class YoutubeShowIE(InfoExtractor):
1716     IE_DESC = u'YouTube.com (multi-season) shows'
1717     _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
1718     IE_NAME = u'youtube:show'
1719
1720     def _real_extract(self, url):
1721         mobj = re.match(self._VALID_URL, url)
1722         show_name = mobj.group(1)
1723         webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
1724         # There's one playlist for each season of the show
1725         m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
1726         self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
1727         return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
1728
1729
1730 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
1731     """
1732     Base class for extractors that fetch info from
1733     http://www.youtube.com/feed_ajax
1734     Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1735     """
1736     _LOGIN_REQUIRED = True
1737     # use action_load_personal_feed instead of action_load_system_feed
1738     _PERSONAL_FEED = False
1739
1740     @property
1741     def _FEED_TEMPLATE(self):
1742         action = 'action_load_system_feed'
1743         if self._PERSONAL_FEED:
1744             action = 'action_load_personal_feed'
1745         return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
1746
1747     @property
1748     def IE_NAME(self):
1749         return u'youtube:%s' % self._FEED_NAME
1750
1751     def _real_initialize(self):
1752         self._login()
1753
1754     def _real_extract(self, url):
1755         feed_entries = []
1756         paging = 0
1757         for i in itertools.count(1):
1758             info = self._download_webpage(self._FEED_TEMPLATE % paging,
1759                                           u'%s feed' % self._FEED_NAME,
1760                                           u'Downloading page %s' % i)
1761             info = json.loads(info)
1762             feed_html = info['feed_html']
1763             m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
1764             ids = orderedSet(m.group(1) for m in m_ids)
1765             feed_entries.extend(
1766                 self.url_result(video_id, 'Youtube', video_id=video_id)
1767                 for video_id in ids)
1768             if info['paging'] is None:
1769                 break
1770             paging = info['paging']
1771         return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1772
1773 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
1774     IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
1775     _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1776     _FEED_NAME = 'subscriptions'
1777     _PLAYLIST_TITLE = u'Youtube Subscriptions'
1778
1779 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
1780     IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1781     _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1782     _FEED_NAME = 'recommended'
1783     _PLAYLIST_TITLE = u'Youtube Recommended videos'
1784
1785 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
1786     IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1787     _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1788     _FEED_NAME = 'watch_later'
1789     _PLAYLIST_TITLE = u'Youtube Watch Later'
1790     _PERSONAL_FEED = True
1791
1792 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
1793     IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
1794     _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
1795     _FEED_NAME = 'history'
1796     _PERSONAL_FEED = True
1797     _PLAYLIST_TITLE = u'Youtube Watch History'
1798
1799 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1800     IE_NAME = u'youtube:favorites'
1801     IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1802     _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1803     _LOGIN_REQUIRED = True
1804
1805     def _real_extract(self, url):
1806         webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1807         playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
1808         return self.url_result(playlist_id, 'YoutubePlaylist')
1809
1810
1811 class YoutubeTruncatedURLIE(InfoExtractor):
1812     IE_NAME = 'youtube:truncated_url'
1813     IE_DESC = False  # Do not list
1814     _VALID_URL = r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$'
1815
1816     def _real_extract(self, url):
1817         raise ExtractorError(
1818             u'Did you forget to quote the URL? Remember that & is a meta '
1819             u'character in most shells, so you want to put the URL in quotes, '
1820             u'like  youtube-dl '
1821             u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1822             u' or simply  youtube-dl BaW_jenozKc  .',
1823             expected=True)