9 from .common
import InfoExtractor
, SearchInfoExtractor
10 from .subtitles
import SubtitlesInfoExtractor
11 from ..jsinterp
import JSInterpreter
12 from ..swfinterp
import SWFInterpreter
17 compat_urllib_request
,
23 get_element_by_attribute
,
33 class YoutubeBaseInfoExtractor(InfoExtractor
):
34 """Provide base functions for Youtube extractors"""
35 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
36 _TWOFACTOR_URL
= 'https://accounts.google.com/SecondFactor'
37 _LANG_URL
= r
'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
38 _AGE_URL
= 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
39 _NETRC_MACHINE
= 'youtube'
40 # If True it will raise an error if no login info is provided
41 _LOGIN_REQUIRED
= False
43 def _set_language(self
):
44 return bool(self
._download
_webpage
(
46 note
=u
'Setting language', errnote
='unable to set language',
51 Attempt to log in to YouTube.
52 True is returned if successful or skipped.
53 False is returned if login failed.
55 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
57 (username
, password
) = self
._get
_login
_info
()
58 # No authentication to be performed
60 if self
._LOGIN
_REQUIRED
:
61 raise ExtractorError(u
'No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
64 login_page
= self
._download
_webpage
(
65 self
._LOGIN
_URL
, None,
66 note
=u
'Downloading login page',
67 errnote
=u
'unable to fetch login page', fatal
=False)
68 if login_page
is False:
71 galx
= self
._search
_regex
(r
'(?s)<input.+?name="GALX".+?value="(.+?)"',
72 login_page
, u
'Login GALX parameter')
76 u
'continue': u
'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
81 u
'PersistentCookie': u
'yes',
83 u
'bgresponse': u
'js_disabled',
84 u
'checkConnection': u
'',
85 u
'checkedDomains': u
'youtube',
90 u
'signIn': u
'Sign in',
92 u
'service': u
'youtube',
97 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
99 login_form
= dict((k
.encode('utf-8'), v
.encode('utf-8')) for k
,v
in login_form_strs
.items())
100 login_data
= compat_urllib_parse
.urlencode(login_form
).encode('ascii')
102 req
= compat_urllib_request
.Request(self
._LOGIN
_URL
, login_data
)
103 login_results
= self
._download
_webpage
(
105 note
=u
'Logging in', errnote
=u
'unable to log in', fatal
=False)
106 if login_results
is False:
109 if re
.search(r
'id="errormsg_0_Passwd"', login_results
) is not None:
110 raise ExtractorError(u
'Please use your account password and a two-factor code instead of an application-specific password.', expected
=True)
113 # TODO add SMS and phone call support - these require making a request and then prompting the user
115 if re
.search(r
'(?i)<form[^>]* id="gaia_secondfactorform"', login_results
) is not None:
116 tfa_code
= self
._get
_tfa
_info
()
119 self
._downloader
.report_warning(u
'Two-factor authentication required. Provide it with --twofactor <code>')
120 self
._downloader
.report_warning(u
'(Note that only TOTP (Google Authenticator App) codes work at this time.)')
123 # Unlike the first login form, secTok and timeStmp are both required for the TFA form
125 match
= re
.search(r
'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
127 self._downloader.report_warning(u'Failed to get secTok
- did the page structure change?
')
128 secTok = match.group(1)
129 match = re.search(r'id="timeStmp"\n\s
+value
=\'(.+)\'/>', login_results, re.M | re.U)
131 self._downloader.report_warning(u'Failed to get timeStmp
- did the page structure change?
')
132 timeStmp = match.group(1)
135 u'continue': u'https
://www
.youtube
.com
/signin?action_handle_signin
=true
&feature
=sign_in_button
&hl
=en_US
&nomobiletemp
=1',
137 u'smsUserPin
': tfa_code,
138 u'smsVerifyPin
': u'Verify
',
140 u'PersistentCookie
': u'yes
',
141 u'checkConnection
': u'',
142 u'checkedDomains
': u'youtube
',
145 u'timeStmp
': timeStmp,
146 u'service
': u'youtube
',
149 tfa_form = dict((k.encode('utf
-8'), v.encode('utf
-8')) for k,v in tfa_form_strs.items())
150 tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii
')
152 tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
153 tfa_results = self._download_webpage(
155 note=u'Submitting TFA code
', errnote=u'unable to submit tfa
', fatal=False)
157 if tfa_results is False:
160 if re.search(r'(?i
)<form
[^
>]* id="gaia_secondfactorform"', tfa_results) is not None:
161 self._downloader.report_warning(u'Two
-factor code expired
. Please
try again
, or use a one
-use backup code instead
.')
163 if re.search(r'(?i
)<form
[^
>]* id="gaia_loginform"', tfa_results) is not None:
164 self._downloader.report_warning(u'unable to log
in - did the page structure change?
')
166 if re.search(r'smsauth
-interstitial
-reviewsettings
', tfa_results) is not None:
167 self._downloader.report_warning(u'Your Google account has a security notice
. Please log
in on your web browser
, resolve the notice
, and try again
.')
170 if re.search(r'(?i
)<form
[^
>]* id="gaia_loginform"', login_results) is not None:
171 self._downloader.report_warning(u'unable to log
in: bad username
or password
')
175 def _confirm_age(self):
178 'action_confirm
': 'Confirm
',
180 req = compat_urllib_request.Request(self._AGE_URL,
181 compat_urllib_parse.urlencode(age_form).encode('ascii
'))
183 self._download_webpage(
185 note=u'Confirming age
', errnote=u'Unable to confirm age
')
188 def _real_initialize(self):
189 if self._downloader is None:
191 if not self._set_language():
193 if not self._login():
198 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
199 IE_DESC = u'YouTube
.com
'
200 _VALID_URL = r"""(?x)^
202 (?:https?://|//) # http(s):// or protocol-independent URL
203 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
204 (?:www\.)?deturl\.com/www\.youtube\.com/|
205 (?:www\.)?pwnyoutube\.com/|
206 (?:www\.)?yourepeat\.com/|
207 tube\.majestyc\.net/|
208 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
209 (?:.*?\#/)? # handle anchor (#/) redirect urls
210 (?: # the various things that can precede the ID:
211 (?:(?:v|embed|e)/) # v/ or embed/ or e/
212 |(?: # or the v= param in all its forms
213 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
214 (?:\?|\#!?) # the params delimiter ? or # or #!
215 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
219 |youtu\.be/ # just youtu.be/xxxx
220 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
222 )? # all until now is optional -> you can pass the naked ID
223 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
224 (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
225 (?(1).+)? # if we found the ID, everything can follow
227 _NEXT_URL_RE = r'[\?&]next_url
=([^
&]+)'
229 '5': {'ext': 'flv', 'width': 400, 'height': 240},
230 '6': {'ext': 'flv', 'width': 450, 'height': 270},
231 '13': {'ext': '3gp'},
232 '17': {'ext': '3gp', 'width': 176, 'height': 144},
233 '18': {'ext': 'mp4', 'width': 640, 'height': 360},
234 '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
235 '34': {'ext': 'flv', 'width': 640, 'height': 360},
236 '35': {'ext': 'flv', 'width': 854, 'height': 480},
237 '36': {'ext': '3gp', 'width': 320, 'height': 240},
238 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
239 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
240 '43': {'ext': 'webm', 'width': 640, 'height': 360},
241 '44': {'ext': 'webm', 'width': 854, 'height': 480},
242 '45': {'ext': 'webm', 'width': 1280, 'height': 720},
243 '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
247 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
248 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
249 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
250 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
251 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
252 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
253 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
255 # Apple HTTP Live Streaming
256 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
257 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
258 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
259 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
260 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
261 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
262 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
265 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
266 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
267 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
268 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
269 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
270 '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
271 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
272 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
275 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
276 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
277 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
280 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
281 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
282 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
283 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
284 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
285 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
286 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
287 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
288 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
289 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
290 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
291 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
292 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
293 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
294 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
297 '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
298 '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
301 '_rtmp
': {'protocol': 'rtmp'},
307 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
308 u"file": u"BaW_jenozKc.mp4",
310 u"title": u"youtube-dl test video \"'/\\ä↭𝕐
",
311 u"uploader
": u"Philipp Hagemeister
",
312 u"uploader_id
": u"phihag
",
313 u"upload_date
": u"20121002",
314 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 .",
315 u"categories": [u'Science
& Technology
'],
317 'dislike_count
': int,
321 u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
322 u"file": u"UxxajLWwzqY.mp4",
323 u"note": u"Test generic use_cipher_signature video (#897)",
325 u"upload_date": u"20120506",
326 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
327 u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
328 u"uploader": u"Icona Pop",
329 u"uploader_id": u"IconaPop"
333 u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
334 u"file": u"07FYdnEawAQ.mp4",
335 u"note": u"Test VEVO video with age protection (#956)",
337 u"upload_date": u"20130703",
338 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
339 u"description": u"md5:64249768eec3bc4276236606ea996373",
340 u"uploader": u"justintimberlakeVEVO",
341 u"uploader_id": u"justintimberlakeVEVO"
345 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
346 u"file": u"yZIXLfi8CZQ.mp4",
347 u"note": u"Embed-only video (#1746)",
349 u"upload_date": u"20120608",
350 u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
351 u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
352 u"uploader": u"SET India",
353 u"uploader_id": u"setindia"
357 u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I",
358 u"file": u"a9LDPn-MO4I.m4a",
359 u"note": u"256k DASH audio (format 141) via DASH manifest",
361 u"upload_date": "20121002",
362 u"uploader_id": "8KVIDEO",
363 u"description": "No description available.",
364 u"uploader": "8KVIDEO",
365 u"title": "UHDTV TEST 8K VIDEO.mp4"
368 u"youtube_include_dash_manifest": True,
372 # DASH manifest with encrypted signature
374 u'url
': u'https
://www
.youtube
.com
/watch?v
=IB3lcPjvWLA
',
376 u'id': u'IB3lcPjvWLA
',
378 u'title
': u'Afrojack
- The Spark ft
. Spree Wilson
',
379 u'description
': u'md5
:9717375db5a9a3992be4668bbf3bc0a8
',
380 u'uploader
': u'AfrojackVEVO
',
381 u'uploader_id
': u'AfrojackVEVO
',
382 u'upload_date
': u'20131011',
385 u'youtube_include_dash_manifest
': True,
391 def __init__(self, *args, **kwargs):
392 super(YoutubeIE, self).__init__(*args, **kwargs)
393 self._player_cache = {}
395 def report_video_info_webpage_download(self, video_id):
396 """Report attempt to download video info webpage."""
397 self.to_screen(u'%s: Downloading video info webpage
' % video_id)
399 def report_information_extraction(self, video_id):
400 """Report attempt to extract video information."""
401 self.to_screen(u'%s: Extracting video information
' % video_id)
403 def report_unavailable_format(self, video_id, format):
404 """Report extracted video URL."""
405 self.to_screen(u'%s: Format
%s not available
' % (video_id, format))
407 def report_rtmp_download(self):
408 """Indicate the download will use the RTMP protocol."""
409 self.to_screen(u'RTMP download detected
')
411 def _signature_cache_id(self, example_sig):
412 """ Return a string representation of a signature """
413 return u'.'.join(compat_str(len(part)) for part in example_sig.split('.'))
415 def _extract_signature_function(self, video_id, player_url, example_sig):
417 r'.*-(?P
<id>[a
-zA
-Z0
-9_-]+)(?
:/watch_as3|
/html5player
)?\
.(?P
<ext
>[a
-z
]+)$
',
420 raise ExtractorError('Cannot identify player
%r' % player_url)
421 player_type = id_m.group('ext
')
422 player_id = id_m.group('id')
424 # Read from filesystem cache
425 func_id = '%s_%s_%s' % (
426 player_type, player_id, self._signature_cache_id(example_sig))
427 assert os.path.basename(func_id) == func_id
429 cache_spec = self._downloader.cache.load(u'youtube
-sigfuncs
', func_id)
430 if cache_spec is not None:
431 return lambda s: u''.join(s[i] for i in cache_spec)
433 if player_type == 'js
':
434 code = self._download_webpage(
435 player_url, video_id,
436 note=u'Downloading
%s player
%s' % (player_type, player_id),
437 errnote=u'Download of
%s failed
' % player_url)
438 res = self._parse_sig_js(code)
439 elif player_type == 'swf
':
440 urlh = self._request_webpage(
441 player_url, video_id,
442 note=u'Downloading
%s player
%s' % (player_type, player_id),
443 errnote=u'Download of
%s failed
' % player_url)
445 res = self._parse_sig_swf(code)
447 assert False, 'Invalid player
type %r' % player_type
449 if cache_spec is None:
450 test_string = u''.join(map(compat_chr, range(len(example_sig))))
451 cache_res = res(test_string)
452 cache_spec = [ord(c) for c in cache_res]
454 self._downloader.cache.store(u'youtube
-sigfuncs
', func_id, cache_spec)
457 def _print_sig_code(self, func, example_sig):
458 def gen_sig_code(idxs):
459 def _genslice(start, end, step):
460 starts = u'' if start == 0 else str(start)
461 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
462 steps = u'' if step == 1 else (u':%d' % step)
463 return u's
[%s%s%s]' % (starts, ends, steps)
466 start = '(Never used
)' # Quelch pyflakes warnings - start will be
467 # set as soon as step is set
468 for i, prev in zip(idxs[1:], idxs[:-1]):
472 yield _genslice(start, prev, step)
475 if i - prev in [-1, 1]:
480 yield u's
[%d]' % prev
484 yield _genslice(start, i, step)
486 test_string = u''.join(map(compat_chr, range(len(example_sig))))
487 cache_res = func(test_string)
488 cache_spec = [ord(c) for c in cache_res]
489 expr_code = u' + '.join(gen_sig_code(cache_spec))
490 signature_id_tuple = '(%s)' % (
491 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
492 code = (u'if tuple(len(p
) for p
in s
.split(\'.\')) == %s:\n'
493 u' return %s\n') % (signature_id_tuple, expr_code)
494 self.to_screen(u'Extracted signature function
:\n' + code)
496 def _parse_sig_js(self, jscode):
497 funcname = self._search_regex(
498 r'signature
=([$a
-zA
-Z
]+)', jscode,
499 u'Initial JS player signature function name
')
501 jsi = JSInterpreter(jscode)
502 initial_function = jsi.extract_function(funcname)
503 return lambda s: initial_function([s])
505 def _parse_sig_swf(self, file_contents):
506 swfi = SWFInterpreter(file_contents)
507 TARGET_CLASSNAME = u'SignatureDecipher
'
508 searched_class = swfi.extract_class(TARGET_CLASSNAME)
509 initial_function = swfi.extract_function(searched_class, u'decipher
')
510 return lambda s: initial_function([s])
512 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
513 """Turn the encrypted s field into a working signature"""
515 if player_url is None:
516 raise ExtractorError(u'Cannot decrypt signature without player_url
')
518 if player_url.startswith(u'//'):
519 player_url = u'https
:' + player_url
521 player_id = (player_url, self._signature_cache_id(s))
522 if player_id not in self._player_cache:
523 func = self._extract_signature_function(
524 video_id, player_url, s
526 self._player_cache[player_id] = func
527 func = self._player_cache[player_id]
528 if self._downloader.params.get('youtube_print_sig_code
'):
529 self._print_sig_code(func, s)
531 except Exception as e:
532 tb = traceback.format_exc()
533 raise ExtractorError(
534 u'Signature extraction failed
: ' + tb, cause=e)
536 def _get_available_subtitles(self, video_id, webpage):
538 sub_list = self._download_webpage(
539 'https
://video
.google
.com
/timedtext?hl
=en
&type=list&v
=%s' % video_id,
540 video_id, note=False)
541 except ExtractorError as err:
542 self._downloader.report_warning(u'unable to download video subtitles
: %s' % compat_str(err))
544 lang_list = re.findall(r'name
="([^"]*)"[^>]+lang_code="([\w\
-]+)"', sub_list)
549 if lang in sub_lang_list:
551 params = compat_urllib_parse.urlencode({
554 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
555 'name': unescapeHTML(l[0]).encode('utf-8'),
557 url = u'https://www.youtube.com/api/timedtext?' + params
558 sub_lang_list[lang] = url
559 if not sub_lang_list:
560 self._downloader.report_warning(u'video doesn\'t have subtitles')
564 def _get_available_automatic_caption(self, video_id, webpage):
565 """We need the webpage for getting the captions url, pass it as an
566 argument to speed up the process."""
567 sub_format = self._downloader.params.get('subtitlesformat', 'srt')
568 self.to_screen(u'%s: Looking for automatic captions' % video_id)
569 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
570 err_msg = u'Couldn\'t find automatic captions for %s' % video_id
572 self._downloader.report_warning(err_msg)
574 player_config = json.loads(mobj.group(1))
576 args = player_config[u'args']
577 caption_url = args[u'ttsurl']
578 timestamp = args[u'timestamp']
579 # We get the available subtitles
580 list_params = compat_urllib_parse.urlencode({
585 list_url = caption_url + '&' + list_params
586 caption_list = self._download_xml(list_url, video_id)
587 original_lang_node = caption_list.find('track')
588 if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
589 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
591 original_lang = original_lang_node.attrib['lang_code']
594 for lang_node in caption_list.findall('target'):
595 sub_lang = lang_node.attrib['lang_code']
596 params = compat_urllib_parse.urlencode({
597 'lang': original_lang,
603 sub_lang_list[sub_lang] = caption_url + '&' + params
605 # An extractor error can be raise by the download process if there are
606 # no automatic captions but there are subtitles
607 except (KeyError, ExtractorError):
608 self._downloader.report_warning(err_msg)
612 def extract_id(cls, url):
613 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
615 raise ExtractorError(u'Invalid URL: %s' % url)
616 video_id = mobj.group(2)
619 def _extract_from_m3u8(self, manifest_url, video_id):
621 def _get_urls(_manifest):
622 lines = _manifest.split('\n')
623 urls = filter(lambda l: l and not l.startswith('#'),
626 manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
627 formats_urls = _get_urls(manifest)
628 for format_url in formats_urls:
629 itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
630 url_map[itag] = format_url
633 def _extract_annotations(self, video_id):
634 url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
635 return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
637 def _real_extract(self, url):
639 u'http' if self._downloader.params.get('prefer_insecure', False)
642 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
643 mobj = re.search(self._NEXT_URL_RE, url)
645 url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
646 video_id = self.extract_id(url)
649 url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
650 video_webpage = self._download_webpage(url, video_id)
652 # Attempt to extract SWF player URL
653 mobj = re.search(r'swfConfig.*?"(https?
:\\/\\/.*?watch
.*?
-.*?\
.swf
)"', video_webpage)
655 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
660 self.report_video_info_webpage_download(video_id)
661 if re.search(r'player-age-gate-content">', video_webpage) is not None:
662 self.report_age_confirmation()
664 # We simulate the access to the video from www.youtube.com/v/{video_id}
665 # this can be viewed without login into Youtube
666 data = compat_urllib_parse.urlencode({
667 'video_id
': video_id,
668 'eurl
': 'https
://youtube
.googleapis
.com
/v
/' + video_id,
669 'sts
': self._search_regex(
670 r'"sts"\s
*:\s
*(\d
+)', video_webpage, 'sts
'),
672 video_info_url = proto + '://www
.youtube
.com
/get_video_info?
' + data
673 video_info_webpage = self._download_webpage(video_info_url, video_id,
675 errnote='unable to download video info webpage
')
676 video_info = compat_parse_qs(video_info_webpage)
679 for el_type in ['&el
=embedded
', '&el
=detailpage
', '&el
=vevo
', '']:
680 video_info_url = (proto + '://www
.youtube
.com
/get_video_info?
&video_id
=%s%s&ps
=default
&eurl
=&gl
=US
&hl
=en
'
681 % (video_id, el_type))
682 video_info_webpage = self._download_webpage(video_info_url, video_id,
684 errnote='unable to download video info webpage
')
685 video_info = compat_parse_qs(video_info_webpage)
686 if 'token
' in video_info:
688 if 'token
' not in video_info:
689 if 'reason
' in video_info:
690 raise ExtractorError(
691 u'YouTube said
: %s' % video_info['reason
'][0],
692 expected=True, video_id=video_id)
694 raise ExtractorError(
695 u'"token" parameter
not in video info
for unknown reason
',
698 if 'view_count
' in video_info:
699 view_count = int(video_info['view_count
'][0])
703 # Check for "rental" videos
704 if 'ypc_video_rental_bar_text
' in video_info and 'author
' not in video_info:
705 raise ExtractorError(u'"rental" videos
not supported
')
707 # Start extracting information
708 self.report_information_extraction(video_id)
711 if 'author
' not in video_info:
712 raise ExtractorError(u'Unable to extract uploader name
')
713 video_uploader = compat_urllib_parse.unquote_plus(video_info['author
'][0])
716 video_uploader_id = None
717 mobj = re.search(r'<link itemprop
="url" href
="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
719 video_uploader_id = mobj.group(1)
721 self._downloader.report_warning(u'unable to extract uploader nickname')
724 if 'title' in video_info:
725 video_title = video_info['title'][0]
727 self._downloader.report_warning(u'Unable to extract video title')
731 # We try first to get a high quality image:
732 m_thumb = re.search(r'<span itemprop="thumbnail
".*?href="(.*?
)">',
733 video_webpage, re.DOTALL)
734 if m_thumb is not None:
735 video_thumbnail = m_thumb.group(1)
736 elif 'thumbnail_url' not in video_info:
737 self._downloader.report_warning(u'unable to extract video thumbnail')
738 video_thumbnail = None
739 else: # don't panic if we can't find it
740 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
744 mobj = re.search(r'(?s)id="eow
-date
.*?
>(.*?
)</span
>', video_webpage)
747 r'(?s
)id="watch-uploader-info".*?
>.*?
(?
:Published|Uploaded|Streamed live
) on (.*?
)</strong
>',
750 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
751 upload_date = unified_strdate(upload_date)
753 m_cat_container = self._search_regex(
754 r'(?s
)<h4
[^
>]*>\s
*Category\s
*</h4
>\s
*<ul
[^
>]*>(.*?
)</ul
>',
755 video_webpage, 'categories
', fatal=False)
757 category = self._html_search_regex(
758 r'(?s
)<a
[^
<]+>(.*?
)</a
>', m_cat_container, 'category
',
760 video_categories = None if category is None else [category]
762 video_categories = None
765 video_description = get_element_by_id("eow-description", video_webpage)
766 if video_description:
767 video_description = re.sub(r'''(?x)
769 (?:[a-zA-Z-]+="[^"]+"\s+)*?
771 (?:[a-zA-Z-]+="[^"]+"\s+)*?
772 class="yt-uix-redirect-link"\s*>
775 ''', r'\
1', video_description)
776 video_description = clean_html(video_description)
778 fd_mobj = re.search(r'<meta name
="description" content
="([^"]+)"', video_webpage)
780 video_description = unescapeHTML(fd_mobj.group(1))
782 video_description = u''
784 def _extract_count(count_name):
785 count = self._search_regex(
786 r'id="watch
-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
787 video_webpage, count_name, default=None)
788 if count is not None:
789 return int(count.replace(',', ''))
791 like_count = _extract_count(u'like')
792 dislike_count = _extract_count(u'dislike')
795 video_subtitles = self.extract_subtitles(video_id, video_webpage)
797 if self._downloader.params.get('listsubtitles', False):
798 self._list_available_subtitles(video_id, video_webpage)
801 if 'length_seconds' not in video_info:
802 self._downloader.report_warning(u'unable to extract video duration')
803 video_duration = None
805 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
808 video_annotations = None
809 if self._downloader.params.get('writeannotations', False):
810 video_annotations = self._extract_annotations(video_id)
812 # Decide which formats to download
814 mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
816 raise ValueError('Could not find vevo ID')
817 json_code = uppercase_escape(mobj.group(1))
818 ytplayer_config = json.loads(json_code)
819 args = ytplayer_config['args']
820 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
821 # this signatures are encrypted
822 if 'url_encoded_fmt_stream_map' not in args:
823 raise ValueError(u'No stream_map present') # caught below
824 re_signature = re.compile(r'[&,]s=')
825 m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
827 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
828 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
829 m_s = re_signature.search(args.get('adaptive_fmts', u''))
831 if 'adaptive_fmts' in video_info:
832 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
834 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
838 def _map_to_format_list(urlmap):
840 for itag, video_real_url in urlmap.items():
843 'url': video_real_url,
844 'player_url': player_url,
846 if itag in self._formats:
847 dct.update(self._formats[itag])
851 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
852 self.report_rtmp_download()
854 'format_id': '_rtmp',
856 'url': video_info['conn'][0],
857 'player_url': player_url,
859 elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
860 encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
861 if 'rtmpe%3Dyes' in encoded_url_map:
862 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
864 for url_data_str in encoded_url_map.split(','):
865 url_data = compat_parse_qs(url_data_str)
866 if 'itag' not in url_data or 'url' not in url_data:
868 format_id = url_data['itag'][0]
869 url = url_data['url'][0]
871 if 'sig' in url_data:
872 url += '&signature=' + url_data['sig'][0]
873 elif 's' in url_data:
874 encrypted_sig = url_data['s'][0]
877 jsplayer_url_json = self._search_regex(
878 r'"assets
":.+?"js
":\s*("[^
"]+")',
879 video_webpage, u'JS player URL
')
880 player_url = json.loads(jsplayer_url_json)
881 if player_url is None:
882 player_url_json = self._search_regex(
883 r'ytplayer\
.config
.*?
"url"\s
*:\s
*("[^"]+")',
884 video_webpage, u'age gate player URL')
885 player_url = json.loads(player_url_json)
887 if self._downloader.params.get('verbose'):
888 if player_url is None:
889 player_version = 'unknown'
890 player_desc = 'unknown'
892 if player_url.endswith('swf'):
893 player_version = self._search_regex(
894 r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
895 u'flash player', fatal=False)
896 player_desc = 'flash player %s' % player_version
898 player_version = self._search_regex(
899 r'html5player-([^/]+?)(?:/html5player)?\.js',
901 'html5 player', fatal=False)
902 player_desc = u'html5 player %s' % player_version
904 parts_sizes = self._signature_cache_id(encrypted_sig)
905 self.to_screen(u'{%s} signature length %s, %s' %
906 (format_id, parts_sizes, player_desc))
908 signature = self._decrypt_signature(
909 encrypted_sig, video_id, player_url, age_gate)
910 url += '&signature=' + signature
911 if 'ratebypass' not in url:
912 url += '&ratebypass=yes'
913 url_map[format_id] = url
914 formats = _map_to_format_list(url_map)
915 elif video_info.get('hlsvp'):
916 manifest_url = video_info['hlsvp'][0]
917 url_map = self._extract_from_m3u8(manifest_url, video_id)
918 formats = _map_to_format_list(url_map)
920 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
922 # Look for the DASH manifest
923 if (self._downloader.params.get('youtube_include_dash_manifest', False)):
925 # The DASH manifest used needs to be the one from the original video_webpage.
926 # The one found in get_video_info seems to be using different signatures.
927 # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
928 # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
929 # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
931 dash_manifest_url = video_info.get('dashmpd')[0]
933 dash_manifest_url = ytplayer_config['args']['dashmpd']
934 def decrypt_sig(mobj):
936 dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
937 return '/signature/%s' % dec_s
938 dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
939 dash_doc = self._download_xml(
940 dash_manifest_url, video_id,
941 note=u'Downloading DASH manifest',
942 errnote=u'Could not download DASH manifest')
943 for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
944 url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
947 format_id = r.attrib['id']
948 video_url = url_el.text
949 filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
951 'format_id': format_id,
953 'width': int_or_none(r.attrib.get('width')),
954 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
955 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
956 'filesize': filesize,
959 existing_format = next(
961 if fo['format_id'] == format_id)
962 except StopIteration:
963 f.update(self._formats.get(format_id, {}))
966 existing_format.update(f)
968 except (ExtractorError, KeyError) as e:
969 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
971 self._sort_formats(formats)
975 'uploader': video_uploader,
976 'uploader_id': video_uploader_id,
977 'upload_date': upload_date,
978 'title': video_title,
979 'thumbnail': video_thumbnail,
980 'description': video_description,
981 'categories': video_categories,
982 'subtitles': video_subtitles,
983 'duration': video_duration,
984 'age_limit': 18 if age_gate else 0,
985 'annotations': video_annotations,
986 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
987 'view_count': view_count,
988 'like_count': like_count,
989 'dislike_count': dislike_count,
993 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
994 IE_DESC = u'YouTube.com playlists'
995 _VALID_URL = r"""(?x)(?:
1000 (?:course|view_play_list|my_playlists|artist|playlist|watch)
1001 \? (?:.*?&)*? (?:p|a|list)=
1005 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
1006 # Top tracks, they can also include dots
1011 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
1013 _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
1014 _MORE_PAGES_INDICATOR = r'data-link-type="next
"'
1015 _VIDEO_RE = r'href="\s
*/watch
\?v
=(?P
<id>[0-9A
-Za
-z_
-]{11}
)&
;[^
"]*?index=(?P<index>\d+)'
1016 IE_NAME = u'youtube:playlist'
1018 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
1020 'title': 'ytdl test PL',
1022 'playlist_count': 3,
1024 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
1026 'title': 'YDL_Empty_List',
1028 'playlist_count': 0,
1030 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
1031 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
1033 'title': '29C3: Not my department',
1035 'playlist_count': 95,
1037 'note': 'issue #673',
1038 'url': 'PLBB231211A4F62143',
1040 'title': 'Team Fortress 2 (Class-based LP)',
1042 'playlist_mincount': 26,
1044 'note': 'Large playlist',
1045 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
1047 'title': 'Uploads from Cauchemar',
1049 'playlist_mincount': 799,
1051 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
1053 'title': 'YDL_safe_search',
1055 'playlist_count': 2,
1058 def _real_initialize(self):
1061 def _ids_to_results(self, ids):
1063 self.url_result(vid_id, 'Youtube', video_id=vid_id)
1066 def _extract_mix(self, playlist_id):
1067 # The mixes are generated from a a single video
1068 # the id of the playlist is just 'RD' + video_id
1069 url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
1070 webpage = self._download_webpage(
1071 url, playlist_id, u'Downloading Youtube mix')
1072 search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
1074 search_title('playlist-title') or
1075 search_title('title long-title') or
1076 search_title('title'))
1077 title = clean_html(title_span)
1078 ids = orderedSet(re.findall(
1079 r'''(?xs)data-video-username=".*?
".*?
1080 href="/watch
\?v
=([0-9A
-Za
-z_
-]{11}
)&
;[^
"]*?list=%s''' % re.escape(playlist_id),
1082 url_results = self._ids_to_results(ids)
1084 return self.playlist_result(url_results, playlist_id, title)
1086 def _real_extract(self, url):
1087 # Extract playlist id
1088 mobj = re.match(self._VALID_URL, url)
1090 raise ExtractorError(u'Invalid URL: %s' % url)
1091 playlist_id = mobj.group(1) or mobj.group(2)
1093 # Check if it's a video-specific URL
1094 query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
1095 if 'v' in query_dict:
1096 video_id = query_dict['v'][0]
1097 if self._downloader.params.get('noplaylist'):
1098 self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
1099 return self.url_result(video_id, 'Youtube', video_id=video_id)
1101 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1103 if playlist_id.startswith('RD'):
1104 # Mixes require a custom extraction process
1105 return self._extract_mix(playlist_id)
1106 if playlist_id.startswith('TL'):
1107 raise ExtractorError(u'For downloading YouTube.com top lists, use '
1108 u'the "yttoplist
" keyword, for example "youtube
-dl
\'yttoplist
:music
:Top Tracks
\'"', expected=True)
1110 url = self._TEMPLATE_URL % playlist_id
1111 page = self._download_webpage(url, playlist_id)
1112 more_widget_html = content_html = page
1114 # Check if the playlist exists or is private
1115 if re.search(r'<div class="yt
-alert
-message
">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
1116 raise ExtractorError(
1117 u'The playlist doesn\'t exist or is private, use --username or '
1118 '--netrc to access it.',
1121 # Extract the video ids from the playlist pages
1124 for page_num in itertools.count(1):
1125 matches = re.finditer(self._VIDEO_RE, content_html)
1126 # We remove the duplicates and the link with index 0
1127 # (it's not the first video of the playlist)
1128 new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
1131 mobj = re.search(r'data-uix-load-more-href="/?
(?P
<more
>[^
"]+)"', more_widget_html)
1135 more = self._download_json(
1136 'https
://youtube
.com
/%s' % mobj.group('more
'), playlist_id,
1137 'Downloading page
#%s' % page_num,
1138 transform_source
=uppercase_escape
)
1139 content_html
= more
['content_html']
1140 more_widget_html
= more
['load_more_widget_html']
1142 playlist_title
= self
._html
_search
_regex
(
1143 r
'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1146 url_results
= self
._ids
_to
_results
(ids
)
1147 return self
.playlist_result(url_results
, playlist_id
, playlist_title
)
1150 class YoutubeTopListIE(YoutubePlaylistIE
):
1151 IE_NAME
= u
'youtube:toplist'
1152 IE_DESC
= (u
'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1153 u
' (Example: "yttoplist:music:Top Tracks")')
1154 _VALID_URL
= r
'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1157 def _real_extract(self
, url
):
1158 mobj
= re
.match(self
._VALID
_URL
, url
)
1159 channel
= mobj
.group('chann')
1160 title
= mobj
.group('title')
1161 query
= compat_urllib_parse
.urlencode({'title': title}
)
1162 playlist_re
= 'href="([^"]+?%s.*?)"' % re
.escape(query
)
1163 channel_page
= self
._download
_webpage
('https://www.youtube.com/%s' % channel
, title
)
1164 link
= self
._html
_search
_regex
(playlist_re
, channel_page
, u
'list')
1165 url
= compat_urlparse
.urljoin('https://www.youtube.com/', link
)
1167 video_re
= r
'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1169 # sometimes the webpage doesn't contain the videos
1170 # retry until we get them
1171 for i
in itertools
.count(0):
1172 msg
= u
'Downloading Youtube mix'
1174 msg
+= ', retry #%d' % i
1176 webpage
= self
._download
_webpage
(url
, title
, msg
)
1177 ids
= orderedSet(re
.findall(video_re
, webpage
))
1180 url_results
= self
._ids
_to
_results
(ids
)
1181 return self
.playlist_result(url_results
, playlist_title
=title
)
1184 class YoutubeChannelIE(InfoExtractor
):
1185 IE_DESC
= u
'YouTube.com channels'
1186 _VALID_URL
= r
"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1187 _MORE_PAGES_INDICATOR
= 'yt-uix-load-more'
1188 _MORE_PAGES_URL
= 'https://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
1189 IE_NAME
= u
'youtube:channel'
1191 def extract_videos_from_page(self
, page
):
1193 for mobj
in re
.finditer(r
'href="/watch\?v=([0-9A-Za-z_-]+)&?', page
):
1194 if mobj
.group(1) not in ids_in_page
:
1195 ids_in_page
.append(mobj
.group(1))
1198 def _real_extract(self
, url
):
1199 # Extract channel id
1200 mobj
= re
.match(self
._VALID
_URL
, url
)
1202 raise ExtractorError(u
'Invalid URL: %s' % url
)
1204 # Download channel page
1205 channel_id
= mobj
.group(1)
1207 url
= 'https://www.youtube.com/channel/%s/videos' % channel_id
1208 channel_page
= self
._download
_webpage
(url
, channel_id
)
1209 autogenerated
= re
.search(r
'''(?x)
1211 channel-header-autogenerated-label|
1212 yt-channel-title-autogenerated
1213 )[^"]*"''', channel_page
) is not None
1216 # The videos are contained in a single page
1217 # the ajax pages can't be used, they are empty
1218 video_ids
= self
.extract_videos_from_page(channel_page
)
1220 # Download all channel pages using the json-based channel_ajax query
1221 for pagenum
in itertools
.count(1):
1222 url
= self
._MORE
_PAGES
_URL
% (pagenum
, channel_id
)
1223 page
= self
._download
_json
(
1224 url
, channel_id
, note
=u
'Downloading page #%s' % pagenum
,
1225 transform_source
=uppercase_escape
)
1227 ids_in_page
= self
.extract_videos_from_page(page
['content_html'])
1228 video_ids
.extend(ids_in_page
)
1230 if self
._MORE
_PAGES
_INDICATOR
not in page
['load_more_widget_html']:
1233 self
._downloader
.to_screen(u
'[youtube] Channel %s: Found %i videos' % (channel_id
, len(video_ids
)))
1235 url_entries
= [self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1236 for video_id
in video_ids
]
1237 return self
.playlist_result(url_entries
, channel_id
)
1240 class YoutubeUserIE(InfoExtractor
):
1241 IE_DESC
= u
'YouTube.com user videos (URL or "ytuser" keyword)'
1242 _VALID_URL
= r
'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1243 _TEMPLATE_URL
= 'https://gdata.youtube.com/feeds/api/users/%s'
1244 _GDATA_PAGE_SIZE
= 50
1245 _GDATA_URL
= 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1246 IE_NAME
= u
'youtube:user'
1249 def suitable(cls
, url
):
1250 # Don't return True if the url can be extracted with other youtube
1251 # extractor, the regex would is too permissive and it would match.
1252 other_ies
= iter(klass
for (name
, klass
) in globals().items() if name
.endswith('IE') and klass
is not cls
)
1253 if any(ie
.suitable(url
) for ie
in other_ies
): return False
1254 else: return super(YoutubeUserIE
, cls
).suitable(url
)
1256 def _real_extract(self
, url
):
1258 mobj
= re
.match(self
._VALID
_URL
, url
)
1260 raise ExtractorError(u
'Invalid URL: %s' % url
)
1262 username
= mobj
.group(1)
1264 # Download video ids using YouTube Data API. Result size per
1265 # query is limited (currently to 50 videos) so we need to query
1266 # page by page until there are no video ids - it means we got
1269 def download_page(pagenum
):
1270 start_index
= pagenum
* self
._GDATA
_PAGE
_SIZE
+ 1
1272 gdata_url
= self
._GDATA
_URL
% (username
, self
._GDATA
_PAGE
_SIZE
, start_index
)
1273 page
= self
._download
_webpage
(
1274 gdata_url
, username
,
1275 u
'Downloading video ids from %d to %d' % (
1276 start_index
, start_index
+ self
._GDATA
_PAGE
_SIZE
))
1279 response
= json
.loads(page
)
1280 except ValueError as err
:
1281 raise ExtractorError(u
'Invalid JSON in API response: ' + compat_str(err
))
1282 if 'entry' not in response
['feed']:
1285 # Extract video identifiers
1286 entries
= response
['feed']['entry']
1287 for entry
in entries
:
1288 title
= entry
['title']['$t']
1289 video_id
= entry
['id']['$t'].split('/')[-1]
1293 'ie_key': 'Youtube',
1297 url_results
= PagedList(download_page
, self
._GDATA
_PAGE
_SIZE
)
1299 return self
.playlist_result(url_results
, playlist_title
=username
)
1302 class YoutubeSearchIE(SearchInfoExtractor
):
1303 IE_DESC
= u
'YouTube.com searches'
1304 _API_URL
= u
'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1306 IE_NAME
= u
'youtube:search'
1307 _SEARCH_KEY
= 'ytsearch'
1309 def _get_n_results(self
, query
, n
):
1310 """Get a specified number of results for a query"""
1317 while (PAGE_SIZE
* pagenum
) < limit
:
1318 result_url
= self
._API
_URL
% (
1319 compat_urllib_parse
.quote_plus(query
.encode('utf-8')),
1320 (PAGE_SIZE
* pagenum
) + 1)
1321 data_json
= self
._download
_webpage
(
1322 result_url
, video_id
=u
'query "%s"' % query
,
1323 note
=u
'Downloading page %s' % (pagenum
+ 1),
1324 errnote
=u
'Unable to download API page')
1325 data
= json
.loads(data_json
)
1326 api_response
= data
['data']
1328 if 'items' not in api_response
:
1329 raise ExtractorError(
1330 u
'[youtube] No video results', expected
=True)
1332 new_ids
= list(video
['id'] for video
in api_response
['items'])
1333 video_ids
+= new_ids
1335 limit
= min(n
, api_response
['totalItems'])
1338 if len(video_ids
) > n
:
1339 video_ids
= video_ids
[:n
]
1340 videos
= [self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1341 for video_id
in video_ids
]
1342 return self
.playlist_result(videos
, query
)
1345 class YoutubeSearchDateIE(YoutubeSearchIE
):
1346 IE_NAME
= YoutubeSearchIE
.IE_NAME
+ ':date'
1347 _API_URL
= 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1348 _SEARCH_KEY
= 'ytsearchdate'
1349 IE_DESC
= u
'YouTube.com searches, newest videos first'
1352 class YoutubeSearchURLIE(InfoExtractor
):
1353 IE_DESC
= u
'YouTube.com search URLs'
1354 IE_NAME
= u
'youtube:search_url'
1355 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
1357 def _real_extract(self
, url
):
1358 mobj
= re
.match(self
._VALID
_URL
, url
)
1359 query
= compat_urllib_parse
.unquote_plus(mobj
.group('query'))
1361 webpage
= self
._download
_webpage
(url
, query
)
1362 result_code
= self
._search
_regex
(
1363 r
'(?s)<ol class="item-section"(.*?)</ol>', webpage
, u
'result HTML')
1365 part_codes
= re
.findall(
1366 r
'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code
)
1368 for part_code
in part_codes
:
1369 part_title
= self
._html
_search
_regex
(
1370 [r
'(?s)title="([^"]+)"', r
'>([^<]+)</a>'], part_code
, 'item title', fatal
=False)
1371 part_url_snippet
= self
._html
_search
_regex
(
1372 r
'(?s)href="([^"]+)"', part_code
, 'item URL')
1373 part_url
= compat_urlparse
.urljoin(
1374 'https://www.youtube.com/', part_url_snippet
)
1378 'title': part_title
,
1382 '_type': 'playlist',
1388 class YoutubeShowIE(InfoExtractor
):
1389 IE_DESC
= u
'YouTube.com (multi-season) shows'
1390 _VALID_URL
= r
'https?://www\.youtube\.com/show/(.*)'
1391 IE_NAME
= u
'youtube:show'
1393 def _real_extract(self
, url
):
1394 mobj
= re
.match(self
._VALID
_URL
, url
)
1395 show_name
= mobj
.group(1)
1396 webpage
= self
._download
_webpage
(url
, show_name
, u
'Downloading show webpage')
1397 # There's one playlist for each season of the show
1398 m_seasons
= list(re
.finditer(r
'href="(/playlist\?list=.*?)"', webpage
))
1399 self
.to_screen(u
'%s: Found %s seasons' % (show_name
, len(m_seasons
)))
1400 return [self
.url_result('https://www.youtube.com' + season
.group(1), 'YoutubePlaylist') for season
in m_seasons
]
1403 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor
):
1405 Base class for extractors that fetch info from
1406 http://www.youtube.com/feed_ajax
1407 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1409 _LOGIN_REQUIRED
= True
1410 # use action_load_personal_feed instead of action_load_system_feed
1411 _PERSONAL_FEED
= False
1414 def _FEED_TEMPLATE(self
):
1415 action
= 'action_load_system_feed'
1416 if self
._PERSONAL
_FEED
:
1417 action
= 'action_load_personal_feed'
1418 return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action
, self
._FEED
_NAME
)
1422 return u
'youtube:%s' % self
._FEED
_NAME
1424 def _real_initialize(self
):
1427 def _real_extract(self
, url
):
1430 for i
in itertools
.count(1):
1431 info
= self
._download
_json
(self
._FEED
_TEMPLATE
% paging
,
1432 u
'%s feed' % self
._FEED
_NAME
,
1433 u
'Downloading page %s' % i
)
1434 feed_html
= info
.get('feed_html') or info
.get('content_html')
1435 load_more_widget_html
= info
.get('load_more_widget_html') or feed_html
1436 m_ids
= re
.finditer(r
'"/watch\?v=(.*?)["&]', feed_html
)
1437 ids
= orderedSet(m
.group(1) for m
in m_ids
)
1438 feed_entries
.extend(
1439 self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1440 for video_id
in ids
)
1442 r
'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1443 load_more_widget_html
)
1446 paging
= mobj
.group('paging')
1447 return self
.playlist_result(feed_entries
, playlist_title
=self
._PLAYLIST
_TITLE
)
1449 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor
):
1450 IE_DESC
= u
'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1451 _VALID_URL
= r
'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1452 _FEED_NAME
= 'recommended'
1453 _PLAYLIST_TITLE
= u
'Youtube Recommended videos'
1455 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor
):
1456 IE_DESC
= u
'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1457 _VALID_URL
= r
'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1458 _FEED_NAME
= 'watch_later'
1459 _PLAYLIST_TITLE
= u
'Youtube Watch Later'
1460 _PERSONAL_FEED
= True
1462 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor
):
1463 IE_DESC
= u
'Youtube watch history, "ythistory" keyword (requires authentication)'
1464 _VALID_URL
= u
'https?://www\.youtube\.com/feed/history|:ythistory'
1465 _FEED_NAME
= 'history'
1466 _PERSONAL_FEED
= True
1467 _PLAYLIST_TITLE
= u
'Youtube Watch History'
1469 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor
):
1470 IE_NAME
= u
'youtube:favorites'
1471 IE_DESC
= u
'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1472 _VALID_URL
= r
'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1473 _LOGIN_REQUIRED
= True
1475 def _real_extract(self
, url
):
1476 webpage
= self
._download
_webpage
('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1477 playlist_id
= self
._search
_regex
(r
'list=(.+?)["&]', webpage
, u
'favourites playlist id')
1478 return self
.url_result(playlist_id
, 'YoutubePlaylist')
1481 class YoutubeSubscriptionsIE(YoutubePlaylistIE
):
1482 IE_NAME
= u
'youtube:subscriptions'
1483 IE_DESC
= u
'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
1484 _VALID_URL
= r
'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1487 def _real_extract(self
, url
):
1488 title
= u
'Youtube Subscriptions'
1489 page
= self
._download
_webpage
('https://www.youtube.com/feed/subscriptions', title
)
1491 # The extraction process is the same as for playlists, but the regex
1492 # for the video ids doesn't contain an index
1494 more_widget_html
= content_html
= page
1496 for page_num
in itertools
.count(1):
1497 matches
= re
.findall(r
'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html
)
1498 new_ids
= orderedSet(matches
)
1501 mobj
= re
.search(r
'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html
)
1505 more
= self
._download
_json
(
1506 'https://youtube.com/%s' % mobj
.group('more'), title
,
1507 'Downloading page #%s' % page_num
,
1508 transform_source
=uppercase_escape
)
1509 content_html
= more
['content_html']
1510 more_widget_html
= more
['load_more_widget_html']
1513 '_type': 'playlist',
1515 'entries': self
._ids
_to
_results
(ids
),
1519 class YoutubeTruncatedURLIE(InfoExtractor
):
1520 IE_NAME
= 'youtube:truncated_url'
1521 IE_DESC
= False # Do not list
1522 _VALID_URL
= r
'''(?x)
1523 (?:https?://)?[^/]+/watch\?(?:
1525 annotation_id=annotation_[^&]+
1527 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1531 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1532 'only_matching': True,
1534 'url': 'http://www.youtube.com/watch?',
1535 'only_matching': True,
1538 def _real_extract(self
, url
):
1539 raise ExtractorError(
1540 u
'Did you forget to quote the URL? Remember that & is a meta '
1541 u
'character in most shells, so you want to put the URL in quotes, '
1543 u
'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1544 u
' or simply youtube-dl BaW_jenozKc .',