15 from .common import InfoExtractor, SearchInfoExtractor
16 from .subtitles import SubtitlesInfoExtractor
21 compat_urllib_request,
28 get_element_by_attribute,
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
47 def _set_language(self):
48 return bool(self._download_webpage(
50 note=u'Setting language', errnote='unable to set language',
54 (username, password) = self._get_login_info()
55 # No authentication to be performed
57 if self._LOGIN_REQUIRED:
58 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
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:
68 galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
69 login_page, u'Login GALX parameter')
73 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
77 u'PersistentCookie': u'yes',
79 u'bgresponse': u'js_disabled',
80 u'checkConnection': u'',
81 u'checkedDomains': u'youtube',
86 u'signIn': u'Sign in',
88 u'service': u'youtube',
92 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
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')
97 req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
98 login_results = self._download_webpage(
100 note=u'Logging in', errnote=u'unable to log in', fatal=False)
101 if login_results is 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')
108 def _confirm_age(self):
111 'action_confirm': 'Confirm',
113 req = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
115 self._download_webpage(
117 note=u'Confirming age', errnote=u'Unable to confirm age')
120 def _real_initialize(self):
121 if self._downloader is None:
123 if not self._set_language():
125 if not self._login():
130 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
131 IE_DESC = u'YouTube.com'
132 _VALID_URL = r"""(?x)^
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)
150 |youtu\.be/ # just youtu.be/xxxx
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
156 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
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},
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},
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},
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},
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},
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},
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},
222 '_rtmp': {'protocol': 'rtmp'},
228 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
229 u"file": u"BaW_jenozKc.mp4",
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 ."
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)",
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"
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)",
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"
263 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
264 u"file": u"yZIXLfi8CZQ.mp4",
265 u"note": u"Embed-only video (#1746)",
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"
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",
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"
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
298 def __init__(self, *args, **kwargs):
299 super(YoutubeIE, self).__init__(*args, **kwargs)
300 self._player_cache = {}
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)
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)
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))
314 def report_rtmp_download(self):
315 """Indicate the download will use the RTMP protocol."""
316 self.to_screen(u'RTMP download detected')
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]+)$',
321 player_type = id_m.group('ext')
322 player_id = id_m.group('id')
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)
329 cache_enabled = cache_dir is not None
331 cache_fn = os.path.join(os.path.expanduser(cache_dir),
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)
339 pass # No cache available
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)
353 res = self._parse_sig_swf(code)
355 assert False, 'Invalid player type %r' % player_type
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]
363 os.makedirs(os.path.dirname(cache_fn))
364 except OSError as ose:
365 if ose.errno != errno.EEXIST:
367 write_json_file(cache_spec, cache_fn)
369 tb = traceback.format_exc()
370 self._downloader.report_warning(
371 u'Writing cache to %r failed: %s' % (cache_fn, tb))
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)
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]):
390 yield _genslice(start, prev, step)
393 if i - prev in [-1, 1]:
398 yield u's[%d]' % prev
402 yield _genslice(start, i, step)
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)
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')
419 return string.lowercase.index(varname)
421 def interpret_statement(stmt, local_vars, allow_recursion=20):
422 if allow_recursion < 0:
423 raise ExtractorError(u'Recursion limit reached')
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)
430 if ass_m.groupdict().get('index'):
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)
438 expr = ass_m.group('expr')
441 local_vars[ass_m.group('out')] = val
443 expr = ass_m.group('expr')
444 elif stmt.startswith(u'return '):
446 expr = stmt[len(u'return '):]
448 raise ExtractorError(
449 u'Cannot determine left side of statement in %r' % stmt)
451 v = interpret_expression(expr, local_vars, allow_recursion)
454 def interpret_expression(expr, local_vars, allow_recursion):
459 return local_vars[expr]
461 m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
463 member = m.group('member')
464 val = local_vars[m.group('in')]
465 if member == 'split("")':
467 if member == 'join("")':
469 if member == 'length':
471 if member == 'reverse()':
473 slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
475 idx = interpret_expression(
476 slice_m.group('idx'), local_vars, allow_recursion-1)
480 r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
482 val = local_vars[m.group('in')]
483 idx = interpret_expression(m.group('idx'), local_vars,
487 m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
489 a = interpret_expression(m.group('a'),
490 local_vars, allow_recursion)
491 b = interpret_expression(m.group('b'),
492 local_vars, allow_recursion)
496 r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
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)
506 def extract_function(funcname):
508 r'function ' + re.escape(funcname) +
509 r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
511 argnames = func_m.group('args').split(',')
514 local_vars = dict(zip(argnames, args))
515 for stmt in func_m.group('code').split(';'):
516 res = interpret_statement(stmt, local_vars)
520 initial_function = extract_function(funcname)
521 return lambda s: initial_function([s])
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:])
530 raise NotImplementedError(u'Unsupported compression format %r' %
533 def extract_tags(content):
535 while pos < len(content):
536 header16 = struct.unpack('<H', content[pos:pos+2])[0]
538 tag_code = header16 >> 6
539 tag_len = header16 & 0x3f
541 tag_len = struct.unpack('<I', content[pos:pos+4])[0]
543 assert pos+tag_len <= len(content)
544 yield (tag_code, content[pos:pos+tag_len])
548 for tag_code, tag in extract_tags(content)
550 p = code_tag.index(b'\0', 4) + 1
551 code_reader = io.BytesIO(code_tag[p:])
553 # Parse ABC (AVM2 ByteCode)
554 def read_int(reader=None):
562 b = struct.unpack('<B', buf)[0]
563 res = res | ((b & 0x7f) << shift)
569 def u30(reader=None):
570 res = read_int(reader)
571 assert res & 0xf0000000 == 0
575 def s32(reader=None):
577 if v & 0x80000000 != 0:
578 v = - ((v ^ 0xffffffff) + 1)
581 def read_string(reader=None):
585 resb = reader.read(slen)
586 assert len(resb) == slen
587 return resb.decode('utf-8')
589 def read_bytes(count, reader=None):
592 resb = reader.read(count)
593 assert len(resb) == count
596 def read_byte(reader=None):
597 resb = read_bytes(1, reader=reader)
598 res = struct.unpack('<B', resb)[0]
601 # minor_version + major_version
606 for _c in range(1, int_count):
609 for _c in range(1, uint_count):
612 read_bytes((double_count-1) * 8)
614 constant_strings = [u'']
615 for _c in range(1, string_count):
617 constant_strings.append(s)
618 namespace_count = u30()
619 for _c in range(1, namespace_count):
623 for _c in range(1, ns_set_count):
625 for _c2 in range(count):
627 multiname_count = u30()
636 0x0e: 2, # MultinameA
637 0x1b: 1, # MultinameL
638 0x1c: 1, # MultinameLA
641 for _c in range(1, multiname_count):
643 assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
645 u30() # namespace_idx
647 multinames.append(constant_strings[name_idx])
649 multinames.append('[MULTINAME kind: %d]' % kind)
650 for _c2 in range(MULTINAME_SIZES[kind]):
655 MethodInfo = collections.namedtuple(
657 ['NEED_ARGUMENTS', 'NEED_REST'])
659 for method_id in range(method_count):
662 for _ in range(param_count):
664 u30() # name index (always 0 for youtube)
666 if flags & 0x08 != 0:
669 for c in range(option_count):
672 if flags & 0x80 != 0:
673 # Param names present
674 for _ in range(param_count):
676 mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
677 method_infos.append(mi)
680 metadata_count = u30()
681 for _c in range(metadata_count):
684 for _c2 in range(item_count):
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
694 if kind in [0x00, 0x06]: # Slot or Const
696 u30() # type_name_idx
700 elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
703 methods[multinames[trait_name_idx]] = method_idx
704 elif kind == 0x04: # Class
707 elif kind == 0x05: # Function
710 methods[function_idx] = multinames[trait_name_idx]
712 raise ExtractorError(u'Unsupported trait kind %d' % kind)
714 if attrs & 0x4 != 0: # Metadata present
715 metadata_count = u30()
716 for _c3 in range(metadata_count):
717 u30() # metadata index
722 TARGET_CLASSNAME = u'SignatureDecipher'
723 searched_idx = multinames.index(TARGET_CLASSNAME)
724 searched_class_id = None
726 for class_id in range(class_count):
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
733 if flags & 0x08 != 0: # Protected namespace is present
734 u30() # protected_ns_idx
736 for _c2 in range(intrf_count):
740 for _c2 in range(trait_count):
743 if searched_class_id is None:
744 raise ExtractorError(u'Target class %r not found' %
749 for class_id in range(class_count):
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(
758 for name, idx in trait_methods.items()))
762 for _c in range(script_count):
765 for _c2 in range(trait_count):
769 method_body_count = u30()
770 Method = collections.namedtuple('Method', ['code', 'local_count'])
772 for _c in range(method_body_count):
776 u30() # init_scope_depth
777 u30() # max_scope_depth
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):
791 for _c2 in range(trait_count):
794 assert p + code_reader.tell() == len(code_tag)
795 assert len(methods) == len(method_idxs)
797 method_pyfunctions = {}
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]
807 registers = ['(this)'] + list(args) + [None] * m.local_count
809 coder = io.BytesIO(m.code)
811 opcode = struct.unpack('!B', coder.read(1))[0]
812 if opcode == 36: # pushbyte
813 v = struct.unpack('!B', coder.read(1))[0]
815 elif opcode == 44: # pushstring
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
822 elif opcode == 70: # callproperty
824 mname = multinames[index]
825 arg_count = u30(coder)
826 args = list(reversed(
827 [stack.pop() for _ in range(arg_count)]))
829 if mname == u'split':
830 assert len(args) == 1
831 assert isinstance(args[0], compat_str)
832 assert isinstance(obj, compat_str)
836 res = obj.split(args[0])
838 elif mname == u'slice':
839 assert len(args) == 1
840 assert isinstance(args[0], int)
841 assert isinstance(obj, list)
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)
850 elif mname in method_pyfunctions:
851 stack.append(method_pyfunctions[mname](args))
853 raise NotImplementedError(
854 u'Unsupported property %r on %r'
856 elif opcode == 72: # returnvalue
859 elif opcode == 79: # callpropvoid
861 mname = multinames[index]
862 arg_count = u30(coder)
863 args = list(reversed(
864 [stack.pop() for _ in range(arg_count)]))
866 if mname == u'reverse':
867 assert isinstance(obj, list)
870 raise NotImplementedError(
871 u'Unsupported (void) property %r on %r'
873 elif opcode == 93: # findpropstrict
875 mname = multinames[index]
876 res = extract_function(mname)
878 elif opcode == 97: # setproperty
883 assert isinstance(obj, list)
884 assert isinstance(idx, int)
886 elif opcode == 98: # getlocal
888 stack.append(registers[index])
889 elif opcode == 99: # setlocal
892 registers[index] = value
893 elif opcode == 102: # getproperty
895 pname = multinames[index]
896 if pname == u'length':
898 assert isinstance(obj, list)
899 stack.append(len(obj))
900 else: # Assume attribute access
902 assert isinstance(idx, int)
904 assert isinstance(obj, list)
905 stack.append(obj[idx])
906 elif opcode == 128: # coerce
908 elif opcode == 133: # coerce_s
909 assert isinstance(stack[-1], (type(None), compat_str))
910 elif opcode == 164: # modulo
913 res = value1 % value2
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()
928 raise NotImplementedError(
929 u'Unsupported opcode %d' % opcode)
931 method_pyfunctions[func_name] = resfunc
934 initial_function = extract_function(u'decipher')
935 return lambda s: initial_function([s])
937 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
938 """Turn the encrypted s field into a working signature"""
940 if player_url is not None:
941 if player_url.startswith(u'//'):
942 player_url = u'https:' + player_url
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)
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))
955 tb = traceback.format_exc()
956 self._downloader.report_warning(
957 u'Automatic signature extraction failed: ' + tb)
959 self._downloader.report_warning(
960 u'Warning: Falling back to static signature algorithm')
962 return self._static_decrypt_signature(
963 s, video_id, player_url, age_gate)
965 def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
967 # The videos with age protection use another player, so the
968 # algorithms can be different.
970 return s[2:63] + s[82] + s[64:82] + s[63]
973 return s[86:29:-1] + s[88] + s[28:5:-1]
975 return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
977 return s[84:27:-1] + s[86] + s[26:5:-1]
979 return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
981 return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
983 return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
985 return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
987 return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
989 return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
991 return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
993 return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
995 return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
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]
999 return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
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]
1004 raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
1006 def _get_available_subtitles(self, video_id, webpage):
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))
1014 lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
1019 params = compat_urllib_parse.urlencode({
1022 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
1023 'name': unescapeHTML(l[0]).encode('utf-8'),
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')
1030 return sub_lang_list
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
1040 self._downloader.report_warning(err_msg)
1042 player_config = json.loads(mobj.group(1))
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({
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')
1059 original_lang = original_lang_node.attrib['lang_code']
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,
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)
1079 def _extract_id(self, url):
1080 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
1082 raise ExtractorError(u'Invalid URL: %s' % url)
1083 video_id = mobj.group(2)
1086 def _extract_from_m3u8(self, manifest_url, video_id):
1088 def _get_urls(_manifest):
1089 lines = _manifest.split('\n')
1090 urls = filter(lambda l: l and not l.startswith('#'),
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
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.')
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)
1108 url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
1109 video_id = self._extract_id(url)
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)
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))
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()
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',
1133 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
1137 video_info_url = 'https://www.youtube.com/get_video_info?' + data
1138 video_info_webpage = self._download_webpage(video_info_url, video_id,
1140 errnote='unable to download video info webpage')
1141 video_info = compat_parse_qs(video_info_webpage)
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,
1149 errnote='unable to download video info webpage')
1150 video_info = compat_parse_qs(video_info_webpage)
1151 if 'token' in video_info:
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)
1157 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
1159 if 'view_count' in video_info:
1160 view_count = int(video_info['view_count'][0])
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')
1168 # Start extracting information
1169 self.report_information_extraction(video_id)
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])
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)
1182 self._downloader.report_warning(u'unable to extract uploader nickname')
1185 if 'title' in video_info:
1186 video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
1188 self._downloader.report_warning(u'Unable to extract video title')
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])
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)
1211 video_description = get_element_by_id("eow-description", video_webpage)
1212 if video_description:
1213 video_description = re.sub(r'''(?x)
1215 (?:[a-zA-Z-]+="[^"]+"\s+)*?
1217 (?:[a-zA-Z-]+="[^"]+"\s+)*?
1218 class="yt-uix-redirect-link"\s*>
1221 ''', r'\1', video_description)
1222 video_description = clean_html(video_description)
1224 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
1226 video_description = unescapeHTML(fd_mobj.group(1))
1228 video_description = u''
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(',', ''))
1237 like_count = _extract_count(u'likes-count')
1238 dislike_count = _extract_count(u'dislikes-count')
1241 video_subtitles = self.extract_subtitles(video_id, video_webpage)
1243 if self._downloader.params.get('listsubtitles', False):
1244 self._list_available_subtitles(video_id, video_webpage)
1247 if 'length_seconds' not in video_info:
1248 self._downloader.report_warning(u'unable to extract video duration')
1249 video_duration = None
1251 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
1254 video_annotations = None
1255 if self._downloader.params.get('writeannotations', False):
1256 video_annotations = self._extract_annotations(video_id)
1258 # Decide which formats to download
1260 mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
1262 raise ValueError('Could not find vevo ID')
1263 info = json.loads(mobj.group(1))
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'])
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''))
1276 if 'adaptive_fmts' in video_info:
1277 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
1279 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
1283 def _map_to_format_list(urlmap):
1285 for itag, video_real_url in urlmap.items():
1288 'url': video_real_url,
1289 'player_url': player_url,
1291 dct.update(self._formats[itag])
1295 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
1296 self.report_rtmp_download()
1298 'format_id': '_rtmp',
1300 'url': video_info['conn'][0],
1301 'player_url': player_url,
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)
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'):
1318 if player_url is None:
1319 player_version = 'unknown'
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
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
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))
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)
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)
1353 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
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]:
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')
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'))
1371 'format_id': format_id,
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,
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, {}))
1386 existing_format.update(f)
1388 except (ExtractorError, KeyError) as e:
1389 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
1391 self._sort_formats(formats)
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,
1412 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
1413 IE_DESC = u'YouTube.com playlists'
1414 _VALID_URL = r"""(?:
1419 (?:course|view_play_list|my_playlists|artist|playlist|watch)
1420 \? (?:.*?&)*? (?:p|a|list)=
1423 ((?:PL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,})
1426 ((?:PL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
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})&[^"]*?index=(?P<index>\d+)'
1431 IE_NAME = u'youtube:playlist'
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
1438 def _real_initialize(self):
1441 def _ids_to_results(self, ids):
1442 return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
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})&[^"]*?list=%s' % re.escape(playlist_id)
1454 ids = orderedSet(re.findall(video_re, webpage))
1455 url_results = self._ids_to_results(ids)
1457 return self.playlist_result(url_results, playlist_id, title)
1459 def _real_extract(self, url):
1460 # Extract playlist id
1461 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
1463 raise ExtractorError(u'Invalid URL: %s' % url)
1464 playlist_id = mobj.group(1) or mobj.group(2)
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)
1474 self.to_screen(u'Downloading playlist PL%s - add --no-playlist to just download video %s' % (playlist_id, video_id))
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)
1483 # Extract the video ids from the playlist pages
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')
1495 if re.search(self._MORE_PAGES_INDICATOR, page) is None:
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 ...',
1504 playlist_title = self._html_search_regex(
1505 r'<h1 class="pl-header-title">(.*?)</h1>', page, u'title')
1507 url_results = self._ids_to_results(ids)
1508 return self.playlist_result(url_results, playlist_id, playlist_title)
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>.*?)$'
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)
1527 video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
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'
1534 msg += ', retry #%d' % i
1535 webpage = self._download_webpage(url, title, msg)
1536 ids = orderedSet(re.findall(video_re, webpage))
1539 url_results = self._ids_to_results(ids)
1540 return self.playlist_result(url_results, playlist_title=title)
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'
1550 def extract_videos_from_page(self, 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))
1557 def _real_extract(self, url):
1558 # Extract channel id
1559 mobj = re.match(self._VALID_URL, url)
1561 raise ExtractorError(u'Invalid URL: %s' % url)
1563 # Download channel page
1564 channel_id = mobj.group(1)
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)
1570 channel-header-autogenerated-label|
1571 yt-channel-title-autogenerated
1572 )[^"]*"''', channel_page) is not None
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)
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)
1585 page = json.loads(page)
1587 ids_in_page = self.extract_videos_from_page(page['content_html'])
1588 video_ids.extend(ids_in_page)
1590 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1593 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
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)
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'
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)
1616 def _real_extract(self, url):
1618 mobj = re.match(self._VALID_URL, url)
1620 raise ExtractorError(u'Invalid URL: %s' % url)
1622 username = mobj.group(1)
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
1631 for pagenum in itertools.count(0):
1632 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
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))
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
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({
1654 'ie_key': 'Youtube',
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
1665 if len(entries) < self._GDATA_PAGE_SIZE:
1668 return self.playlist_result(url_results, playlist_title=username)
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'
1675 IE_NAME = u'youtube:search'
1676 _SEARCH_KEY = 'ytsearch'
1678 def _get_n_results(self, query, n):
1679 """Get a specified number of results for a query"""
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']
1694 if 'items' not in api_response:
1695 raise ExtractorError(u'[youtube] No video results')
1697 new_ids = list(video['id'] for video in api_response['items'])
1698 video_ids += new_ids
1700 limit = min(n, api_response['totalItems'])
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)
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'
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'
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]
1730 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
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.
1736 _LOGIN_REQUIRED = True
1737 # use action_load_personal_feed instead of action_load_system_feed
1738 _PERSONAL_FEED = False
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)
1749 return u'youtube:%s' % self._FEED_NAME
1751 def _real_initialize(self):
1754 def _real_extract(self, url):
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:
1770 paging = info['paging']
1771 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
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'
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'
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
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'
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
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')
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_]+$'
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, '
1821 u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1822 u' or simply youtube-dl BaW_jenozKc .',