11 from .common
import InfoExtractor
, SearchInfoExtractor
12 from .subtitles
import SubtitlesInfoExtractor
13 from ..jsinterp
import JSInterpreter
14 from ..swfinterp
import SWFInterpreter
19 compat_urllib_request
,
26 get_element_by_attribute
,
37 class YoutubeBaseInfoExtractor(InfoExtractor
):
38 """Provide base functions for Youtube extractors"""
39 _LOGIN_URL
= 'https://accounts.google.com/ServiceLogin'
40 _LANG_URL
= r
'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
41 _AGE_URL
= 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
42 _NETRC_MACHINE
= 'youtube'
43 # If True it will raise an error if no login info is provided
44 _LOGIN_REQUIRED
= False
46 def _set_language(self
):
47 return bool(self
._download
_webpage
(
49 note
=u
'Setting language', errnote
='unable to set language',
53 (username
, password
) = self
._get
_login
_info
()
54 # No authentication to be performed
56 if self
._LOGIN
_REQUIRED
:
57 raise ExtractorError(u
'No login info available, needed for using %s.' % self
.IE_NAME
, expected
=True)
60 login_page
= self
._download
_webpage
(
61 self
._LOGIN
_URL
, None,
62 note
=u
'Downloading login page',
63 errnote
=u
'unable to fetch login page', fatal
=False)
64 if login_page
is False:
67 galx
= self
._search
_regex
(r
'(?s)<input.+?name="GALX".+?value="(.+?)"',
68 login_page
, u
'Login GALX parameter')
72 u
'continue': u
'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
76 u
'PersistentCookie': u
'yes',
78 u
'bgresponse': u
'js_disabled',
79 u
'checkConnection': u
'',
80 u
'checkedDomains': u
'youtube',
85 u
'signIn': u
'Sign in',
87 u
'service': u
'youtube',
91 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
93 login_form
= dict((k
.encode('utf-8'), v
.encode('utf-8')) for k
,v
in login_form_strs
.items())
94 login_data
= compat_urllib_parse
.urlencode(login_form
).encode('ascii')
96 req
= compat_urllib_request
.Request(self
._LOGIN
_URL
, login_data
)
97 login_results
= self
._download
_webpage
(
99 note
=u
'Logging in', errnote
=u
'unable to log in', fatal
=False)
100 if login_results
is False:
102 if re
.search(r
'(?i)<form[^>]* id="gaia_loginform"', login_results
) is not None:
103 self
._downloader
.report_warning(u
'unable to log in: bad username or password')
107 def _confirm_age(self
):
110 'action_confirm': 'Confirm',
112 req
= compat_urllib_request
.Request(self
._AGE
_URL
,
113 compat_urllib_parse
.urlencode(age_form
).encode('ascii'))
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 (?:www\.)?yourepeat\.com/|
139 tube\.majestyc\.net/|
140 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
141 (?:.*?\#/)? # handle anchor (#/) redirect urls
142 (?: # the various things that can precede the ID:
143 (?:(?:v|embed|e)/) # v/ or embed/ or e/
144 |(?: # or the v= param in all its forms
145 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
146 (?:\?|\#!?) # the params delimiter ? or # or #!
147 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
151 |youtu\.be/ # just youtu.be/xxxx
152 |https?://(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
154 )? # all until now is optional -> you can pass the naked ID
155 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
156 (?(1).+)? # if we found the ID, everything can follow
158 _NEXT_URL_RE
= r
'[\?&]next_url=([^&]+)'
160 '5': {'ext': 'flv', 'width': 400, 'height': 240}
,
161 '6': {'ext': 'flv', 'width': 450, 'height': 270}
,
162 '13': {'ext': '3gp'}
,
163 '17': {'ext': '3gp', 'width': 176, 'height': 144}
,
164 '18': {'ext': 'mp4', 'width': 640, 'height': 360}
,
165 '22': {'ext': 'mp4', 'width': 1280, 'height': 720}
,
166 '34': {'ext': 'flv', 'width': 640, 'height': 360}
,
167 '35': {'ext': 'flv', 'width': 854, 'height': 480}
,
168 '36': {'ext': '3gp', 'width': 320, 'height': 240}
,
169 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080}
,
170 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072}
,
171 '43': {'ext': 'webm', 'width': 640, 'height': 360}
,
172 '44': {'ext': 'webm', 'width': 854, 'height': 480}
,
173 '45': {'ext': 'webm', 'width': 1280, 'height': 720}
,
174 '46': {'ext': 'webm', 'width': 1920, 'height': 1080}
,
178 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20}
,
179 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20}
,
180 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20}
,
181 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20}
,
182 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20}
,
183 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20}
,
184 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20}
,
186 # Apple HTTP Live Streaming
187 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10}
,
188 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10}
,
189 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10}
,
190 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10}
,
191 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10}
,
192 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10}
,
193 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10}
,
196 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
197 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
198 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
199 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
200 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
201 '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
202 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
203 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
206 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50}
,
207 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50}
,
208 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50}
,
211 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
212 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
213 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
214 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
215 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
216 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}
,
217 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
218 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
219 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
220 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
221 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
222 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
223 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
224 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
225 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}
,
228 '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 48, 'preference': -50}
,
229 '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50}
,
232 '_rtmp': {'protocol': 'rtmp'}
,
238 u
"url": u
"http://www.youtube.com/watch?v=BaW_jenozKc",
239 u
"file": u
"BaW_jenozKc.mp4",
241 u
"title": u
"youtube-dl test video \"'/\\ä↭𝕐",
242 u
"uploader": u
"Philipp Hagemeister",
243 u
"uploader_id": u
"phihag",
244 u
"upload_date": u
"20121002",
245 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 .",
246 u
"categories": [u
'Science & Technology'],
250 u
"url": u
"http://www.youtube.com/watch?v=UxxajLWwzqY",
251 u
"file": u
"UxxajLWwzqY.mp4",
252 u
"note": u
"Test generic use_cipher_signature video (#897)",
254 u
"upload_date": u
"20120506",
255 u
"title": u
"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
256 u
"description": u
"md5:fea86fda2d5a5784273df5c7cc994d9f",
257 u
"uploader": u
"Icona Pop",
258 u
"uploader_id": u
"IconaPop"
262 u
"url": u
"https://www.youtube.com/watch?v=07FYdnEawAQ",
263 u
"file": u
"07FYdnEawAQ.mp4",
264 u
"note": u
"Test VEVO video with age protection (#956)",
266 u
"upload_date": u
"20130703",
267 u
"title": u
"Justin Timberlake - Tunnel Vision (Explicit)",
268 u
"description": u
"md5:64249768eec3bc4276236606ea996373",
269 u
"uploader": u
"justintimberlakeVEVO",
270 u
"uploader_id": u
"justintimberlakeVEVO"
274 u
"url": u
"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
275 u
"file": u
"yZIXLfi8CZQ.mp4",
276 u
"note": u
"Embed-only video (#1746)",
278 u
"upload_date": u
"20120608",
279 u
"title": u
"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
280 u
"description": u
"md5:09b78bd971f1e3e289601dfba15ca4f7",
281 u
"uploader": u
"SET India",
282 u
"uploader_id": u
"setindia"
286 u
"url": u
"http://www.youtube.com/watch?v=a9LDPn-MO4I",
287 u
"file": u
"a9LDPn-MO4I.m4a",
288 u
"note": u
"256k DASH audio (format 141) via DASH manifest",
290 u
"upload_date": "20121002",
291 u
"uploader_id": "8KVIDEO",
292 u
"description": "No description available.",
293 u
"uploader": "8KVIDEO",
294 u
"title": "UHDTV TEST 8K VIDEO.mp4"
297 u
"youtube_include_dash_manifest": True,
301 # DASH manifest with encrypted signature
303 u
'url': u
'https://www.youtube.com/watch?v=IB3lcPjvWLA',
305 u
'id': u
'IB3lcPjvWLA',
307 u
'title': u
'Afrojack - The Spark ft. Spree Wilson',
308 u
'description': u
'md5:9717375db5a9a3992be4668bbf3bc0a8',
309 u
'uploader': u
'AfrojackVEVO',
310 u
'uploader_id': u
'AfrojackVEVO',
311 u
'upload_date': u
'20131011',
314 u
'youtube_include_dash_manifest': True,
322 def suitable(cls
, url
):
323 """Receives a URL and returns True if suitable for this IE."""
324 if YoutubePlaylistIE
.suitable(url
): return False
325 return re
.match(cls
._VALID
_URL
, url
) is not None
327 def __init__(self
, *args
, **kwargs
):
328 super(YoutubeIE
, self
).__init
__(*args
, **kwargs
)
329 self
._player
_cache
= {}
331 def report_video_info_webpage_download(self
, video_id
):
332 """Report attempt to download video info webpage."""
333 self
.to_screen(u
'%s: Downloading video info webpage' % video_id
)
335 def report_information_extraction(self
, video_id
):
336 """Report attempt to extract video information."""
337 self
.to_screen(u
'%s: Extracting video information' % video_id
)
339 def report_unavailable_format(self
, video_id
, format
):
340 """Report extracted video URL."""
341 self
.to_screen(u
'%s: Format %s not available' % (video_id
, format
))
343 def report_rtmp_download(self
):
344 """Indicate the download will use the RTMP protocol."""
345 self
.to_screen(u
'RTMP download detected')
347 def _extract_signature_function(self
, video_id
, player_url
, slen
):
349 r
'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
352 raise ExtractorError('Cannot identify player %r' % player_url
)
353 player_type
= id_m
.group('ext')
354 player_id
= id_m
.group('id')
356 # Read from filesystem cache
357 func_id
= '%s_%s_%d' % (player_type
, player_id
, slen
)
358 assert os
.path
.basename(func_id
) == func_id
359 cache_dir
= get_cachedir(self
._downloader
.params
)
361 cache_enabled
= cache_dir
is not None
363 cache_fn
= os
.path
.join(os
.path
.expanduser(cache_dir
),
367 with io
.open(cache_fn
, 'r', encoding
='utf-8') as cachef
:
368 cache_spec
= json
.load(cachef
)
369 return lambda s
: u
''.join(s
[i
] for i
in cache_spec
)
371 pass # No cache available
373 if player_type
== 'js':
374 code
= self
._download
_webpage
(
375 player_url
, video_id
,
376 note
=u
'Downloading %s player %s' % (player_type
, player_id
),
377 errnote
=u
'Download of %s failed' % player_url
)
378 res
= self
._parse
_sig
_js
(code
)
379 elif player_type
== 'swf':
380 urlh
= self
._request
_webpage
(
381 player_url
, video_id
,
382 note
=u
'Downloading %s player %s' % (player_type
, player_id
),
383 errnote
=u
'Download of %s failed' % player_url
)
385 res
= self
._parse
_sig
_swf
(code
)
387 assert False, 'Invalid player type %r' % player_type
391 test_string
= u
''.join(map(compat_chr
, range(slen
)))
392 cache_res
= res(test_string
)
393 cache_spec
= [ord(c
) for c
in cache_res
]
395 os
.makedirs(os
.path
.dirname(cache_fn
))
396 except OSError as ose
:
397 if ose
.errno
!= errno
.EEXIST
:
399 write_json_file(cache_spec
, cache_fn
)
401 tb
= traceback
.format_exc()
402 self
._downloader
.report_warning(
403 u
'Writing cache to %r failed: %s' % (cache_fn
, tb
))
407 def _print_sig_code(self
, func
, slen
):
408 def gen_sig_code(idxs
):
409 def _genslice(start
, end
, step
):
410 starts
= u
'' if start
== 0 else str(start
)
411 ends
= (u
':%d' % (end
+step
)) if end
+ step
>= 0 else u
':'
412 steps
= u
'' if step
== 1 else (u
':%d' % step
)
413 return u
's[%s%s%s]' % (starts
, ends
, steps
)
416 start
= '(Never used)' # Quelch pyflakes warnings - start will be
417 # set as soon as step is set
418 for i
, prev
in zip(idxs
[1:], idxs
[:-1]):
422 yield _genslice(start
, prev
, step
)
425 if i
- prev
in [-1, 1]:
430 yield u
's[%d]' % prev
434 yield _genslice(start
, i
, step
)
436 test_string
= u
''.join(map(compat_chr
, range(slen
)))
437 cache_res
= func(test_string
)
438 cache_spec
= [ord(c
) for c
in cache_res
]
439 expr_code
= u
' + '.join(gen_sig_code(cache_spec
))
440 code
= u
'if len(s) == %d:\n return %s\n' % (slen
, expr_code
)
441 self
.to_screen(u
'Extracted signature function:\n' + code
)
443 def _parse_sig_js(self
, jscode
):
444 funcname
= self
._search
_regex
(
445 r
'signature=([$a-zA-Z]+)', jscode
,
446 u
'Initial JS player signature function name')
448 jsi
= JSInterpreter(jscode
)
449 initial_function
= jsi
.extract_function(funcname
)
450 return lambda s
: initial_function([s
])
452 def _parse_sig_swf(self
, file_contents
):
453 swfi
= SWFInterpreter(file_contents
)
454 TARGET_CLASSNAME
= u
'SignatureDecipher'
455 searched_class
= swfi
.extract_class(TARGET_CLASSNAME
)
456 initial_function
= swfi
.extract_function(searched_class
, u
'decipher')
457 return lambda s
: initial_function([s
])
459 def _decrypt_signature(self
, s
, video_id
, player_url
, age_gate
=False):
460 """Turn the encrypted s field into a working signature"""
462 if player_url
is None:
463 raise ExtractorError(u
'Cannot decrypt signature without player_url')
465 if player_url
.startswith(u
'//'):
466 player_url
= u
'https:' + player_url
468 player_id
= (player_url
, len(s
))
469 if player_id
not in self
._player
_cache
:
470 func
= self
._extract
_signature
_function
(
471 video_id
, player_url
, len(s
)
473 self
._player
_cache
[player_id
] = func
474 func
= self
._player
_cache
[player_id
]
475 if self
._downloader
.params
.get('youtube_print_sig_code'):
476 self
._print
_sig
_code
(func
, len(s
))
478 except Exception as e
:
479 tb
= traceback
.format_exc()
480 raise ExtractorError(
481 u
'Automatic signature extraction failed: ' + tb
, cause
=e
)
483 def _get_available_subtitles(self
, video_id
, webpage
):
485 sub_list
= self
._download
_webpage
(
486 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id
,
487 video_id
, note
=False)
488 except ExtractorError
as err
:
489 self
._downloader
.report_warning(u
'unable to download video subtitles: %s' % compat_str(err
))
491 lang_list
= re
.findall(r
'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list
)
496 params
= compat_urllib_parse
.urlencode({
499 'fmt': self
._downloader
.params
.get('subtitlesformat', 'srt'),
500 'name': unescapeHTML(l
[0]).encode('utf-8'),
502 url
= u
'https://www.youtube.com/api/timedtext?' + params
503 sub_lang_list
[lang
] = url
504 if not sub_lang_list
:
505 self
._downloader
.report_warning(u
'video doesn\'t have subtitles')
509 def _get_available_automatic_caption(self
, video_id
, webpage
):
510 """We need the webpage for getting the captions url, pass it as an
511 argument to speed up the process."""
512 sub_format
= self
._downloader
.params
.get('subtitlesformat', 'srt')
513 self
.to_screen(u
'%s: Looking for automatic captions' % video_id
)
514 mobj
= re
.search(r
';ytplayer.config = ({.*?});', webpage
)
515 err_msg
= u
'Couldn\'t find automatic captions for %s' % video_id
517 self
._downloader
.report_warning(err_msg
)
519 player_config
= json
.loads(mobj
.group(1))
521 args
= player_config
[u
'args']
522 caption_url
= args
[u
'ttsurl']
523 timestamp
= args
[u
'timestamp']
524 # We get the available subtitles
525 list_params
= compat_urllib_parse
.urlencode({
530 list_url
= caption_url
+ '&' + list_params
531 caption_list
= self
._download
_xml
(list_url
, video_id
)
532 original_lang_node
= caption_list
.find('track')
533 if original_lang_node
is None or original_lang_node
.attrib
.get('kind') != 'asr' :
534 self
._downloader
.report_warning(u
'Video doesn\'t have automatic captions')
536 original_lang
= original_lang_node
.attrib
['lang_code']
539 for lang_node
in caption_list
.findall('target'):
540 sub_lang
= lang_node
.attrib
['lang_code']
541 params
= compat_urllib_parse
.urlencode({
542 'lang': original_lang
,
548 sub_lang_list
[sub_lang
] = caption_url
+ '&' + params
550 # An extractor error can be raise by the download process if there are
551 # no automatic captions but there are subtitles
552 except (KeyError, ExtractorError
):
553 self
._downloader
.report_warning(err_msg
)
557 def extract_id(cls
, url
):
558 mobj
= re
.match(cls
._VALID
_URL
, url
, re
.VERBOSE
)
560 raise ExtractorError(u
'Invalid URL: %s' % url
)
561 video_id
= mobj
.group(2)
564 def _extract_from_m3u8(self
, manifest_url
, video_id
):
566 def _get_urls(_manifest
):
567 lines
= _manifest
.split('\n')
568 urls
= filter(lambda l
: l
and not l
.startswith('#'),
571 manifest
= self
._download
_webpage
(manifest_url
, video_id
, u
'Downloading formats manifest')
572 formats_urls
= _get_urls(manifest
)
573 for format_url
in formats_urls
:
574 itag
= self
._search
_regex
(r
'itag/(\d+?)/', format_url
, 'itag')
575 url_map
[itag
] = format_url
578 def _extract_annotations(self
, video_id
):
579 url
= 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
580 return self
._download
_webpage
(url
, video_id
, note
=u
'Searching for annotations.', errnote
=u
'Unable to download video annotations.')
582 def _real_extract(self
, url
):
584 u
'http' if self
._downloader
.params
.get('prefer_insecure', False)
587 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
588 mobj
= re
.search(self
._NEXT
_URL
_RE
, url
)
590 url
= proto
+ '://www.youtube.com/' + compat_urllib_parse
.unquote(mobj
.group(1)).lstrip('/')
591 video_id
= self
.extract_id(url
)
594 url
= proto
+ '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
595 video_webpage
= self
._download
_webpage
(url
, video_id
)
597 # Attempt to extract SWF player URL
598 mobj
= re
.search(r
'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage
)
600 player_url
= re
.sub(r
'\\(.)', r
'\1', mobj
.group(1))
605 self
.report_video_info_webpage_download(video_id
)
606 if re
.search(r
'player-age-gate-content">', video_webpage
) is not None:
607 self
.report_age_confirmation()
609 # We simulate the access to the video from www.youtube.com/v/{video_id}
610 # this can be viewed without login into Youtube
611 data
= compat_urllib_parse
.urlencode({
612 'video_id': video_id
,
613 'eurl': 'https://youtube.googleapis.com/v/' + video_id
,
614 'sts': self
._search
_regex
(
615 r
'"sts"\s*:\s*(\d+)', video_webpage
, 'sts'),
617 video_info_url
= proto
+ '://www.youtube.com/get_video_info?' + data
618 video_info_webpage
= self
._download
_webpage
(video_info_url
, video_id
,
620 errnote
='unable to download video info webpage')
621 video_info
= compat_parse_qs(video_info_webpage
)
624 for el_type
in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
625 video_info_url
= (proto
+ '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
626 % (video_id
, el_type
))
627 video_info_webpage
= self
._download
_webpage
(video_info_url
, video_id
,
629 errnote
='unable to download video info webpage')
630 video_info
= compat_parse_qs(video_info_webpage
)
631 if 'token' in video_info
:
633 if 'token' not in video_info
:
634 if 'reason' in video_info
:
635 raise ExtractorError(
636 u
'YouTube said: %s' % video_info
['reason'][0],
637 expected
=True, video_id
=video_id
)
639 raise ExtractorError(
640 u
'"token" parameter not in video info for unknown reason',
643 if 'view_count' in video_info
:
644 view_count
= int(video_info
['view_count'][0])
648 # Check for "rental" videos
649 if 'ypc_video_rental_bar_text' in video_info
and 'author' not in video_info
:
650 raise ExtractorError(u
'"rental" videos not supported')
652 # Start extracting information
653 self
.report_information_extraction(video_id
)
656 if 'author' not in video_info
:
657 raise ExtractorError(u
'Unable to extract uploader name')
658 video_uploader
= compat_urllib_parse
.unquote_plus(video_info
['author'][0])
661 video_uploader_id
= None
662 mobj
= re
.search(r
'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage
)
664 video_uploader_id
= mobj
.group(1)
666 self
._downloader
.report_warning(u
'unable to extract uploader nickname')
669 if 'title' in video_info
:
670 video_title
= video_info
['title'][0]
672 self
._downloader
.report_warning(u
'Unable to extract video title')
676 # We try first to get a high quality image:
677 m_thumb
= re
.search(r
'<span itemprop="thumbnail".*?href="(.*?)">',
678 video_webpage
, re
.DOTALL
)
679 if m_thumb
is not None:
680 video_thumbnail
= m_thumb
.group(1)
681 elif 'thumbnail_url' not in video_info
:
682 self
._downloader
.report_warning(u
'unable to extract video thumbnail')
683 video_thumbnail
= None
684 else: # don't panic if we can't find it
685 video_thumbnail
= compat_urllib_parse
.unquote_plus(video_info
['thumbnail_url'][0])
689 mobj
= re
.search(r
'(?s)id="eow-date.*?>(.*?)</span>', video_webpage
)
692 r
'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
695 upload_date
= ' '.join(re
.sub(r
'[/,-]', r
' ', mobj
.group(1)).split())
696 upload_date
= unified_strdate(upload_date
)
698 m_cat_container
= get_element_by_id("eow-category", video_webpage
)
700 category
= self
._html
_search
_regex
(
701 r
'(?s)<a[^<]+>(.*?)</a>', m_cat_container
, 'category',
703 video_categories
= None if category
is None else [category
]
705 video_categories
= None
708 video_description
= get_element_by_id("eow-description", video_webpage
)
709 if video_description
:
710 video_description
= re
.sub(r
'''(?x)
712 (?:[a-zA-Z-]+="[^"]+"\s+)*?
714 (?:[a-zA-Z-]+="[^"]+"\s+)*?
715 class="yt-uix-redirect-link"\s*>
718 ''', r
'\1', video_description
)
719 video_description
= clean_html(video_description
)
721 fd_mobj
= re
.search(r
'<meta name="description" content="([^"]+)"', video_webpage
)
723 video_description
= unescapeHTML(fd_mobj
.group(1))
725 video_description
= u
''
727 def _extract_count(klass
):
728 count
= self
._search
_regex
(
729 r
'class="%s">([\d,]+)</span>' % re
.escape(klass
),
730 video_webpage
, klass
, default
=None)
731 if count
is not None:
732 return int(count
.replace(',', ''))
734 like_count
= _extract_count(u
'likes-count')
735 dislike_count
= _extract_count(u
'dislikes-count')
738 video_subtitles
= self
.extract_subtitles(video_id
, video_webpage
)
740 if self
._downloader
.params
.get('listsubtitles', False):
741 self
._list
_available
_subtitles
(video_id
, video_webpage
)
744 if 'length_seconds' not in video_info
:
745 self
._downloader
.report_warning(u
'unable to extract video duration')
746 video_duration
= None
748 video_duration
= int(compat_urllib_parse
.unquote_plus(video_info
['length_seconds'][0]))
751 video_annotations
= None
752 if self
._downloader
.params
.get('writeannotations', False):
753 video_annotations
= self
._extract
_annotations
(video_id
)
755 # Decide which formats to download
757 mobj
= re
.search(r
';ytplayer\.config\s*=\s*({.*?});', video_webpage
)
759 raise ValueError('Could not find vevo ID')
760 json_code
= uppercase_escape(mobj
.group(1))
761 ytplayer_config
= json
.loads(json_code
)
762 args
= ytplayer_config
['args']
763 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
764 # this signatures are encrypted
765 if 'url_encoded_fmt_stream_map' not in args
:
766 raise ValueError(u
'No stream_map present') # caught below
767 re_signature
= re
.compile(r
'[&,]s=')
768 m_s
= re_signature
.search(args
['url_encoded_fmt_stream_map'])
770 self
.to_screen(u
'%s: Encrypted signatures detected.' % video_id
)
771 video_info
['url_encoded_fmt_stream_map'] = [args
['url_encoded_fmt_stream_map']]
772 m_s
= re_signature
.search(args
.get('adaptive_fmts', u
''))
774 if 'adaptive_fmts' in video_info
:
775 video_info
['adaptive_fmts'][0] += ',' + args
['adaptive_fmts']
777 video_info
['adaptive_fmts'] = [args
['adaptive_fmts']]
781 def _map_to_format_list(urlmap
):
783 for itag
, video_real_url
in urlmap
.items():
786 'url': video_real_url
,
787 'player_url': player_url
,
789 if itag
in self
._formats
:
790 dct
.update(self
._formats
[itag
])
794 if 'conn' in video_info
and video_info
['conn'][0].startswith('rtmp'):
795 self
.report_rtmp_download()
797 'format_id': '_rtmp',
799 'url': video_info
['conn'][0],
800 'player_url': player_url
,
802 elif len(video_info
.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info
.get('adaptive_fmts', [])) >= 1:
803 encoded_url_map
= video_info
.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info
.get('adaptive_fmts',[''])[0]
804 if 'rtmpe%3Dyes' in encoded_url_map
:
805 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected
=True)
807 for url_data_str
in encoded_url_map
.split(','):
808 url_data
= compat_parse_qs(url_data_str
)
809 if 'itag' not in url_data
or 'url' not in url_data
:
811 format_id
= url_data
['itag'][0]
812 url
= url_data
['url'][0]
814 if 'sig' in url_data
:
815 url
+= '&signature=' + url_data
['sig'][0]
816 elif 's' in url_data
:
817 encrypted_sig
= url_data
['s'][0]
820 jsplayer_url_json
= self
._search
_regex
(
821 r
'"assets":.+?"js":\s*("[^"]+")',
822 video_webpage
, u
'JS player URL')
823 player_url
= json
.loads(jsplayer_url_json
)
824 if player_url
is None:
825 player_url_json
= self
._search
_regex
(
826 r
'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
827 video_webpage
, u
'age gate player URL')
828 player_url
= json
.loads(player_url_json
)
830 if self
._downloader
.params
.get('verbose'):
831 if player_url
is None:
832 player_version
= 'unknown'
833 player_desc
= 'unknown'
835 if player_url
.endswith('swf'):
836 player_version
= self
._search
_regex
(
837 r
'-(.+?)(?:/watch_as3)?\.swf$', player_url
,
838 u
'flash player', fatal
=False)
839 player_desc
= 'flash player %s' % player_version
841 player_version
= self
._search
_regex
(
842 r
'html5player-([^/]+?)(?:/html5player)?\.js',
844 'html5 player', fatal
=False)
845 player_desc
= u
'html5 player %s' % player_version
847 parts_sizes
= u
'.'.join(compat_str(len(part
)) for part
in encrypted_sig
.split('.'))
848 self
.to_screen(u
'{%s} signature length %s, %s' %
849 (format_id
, parts_sizes
, player_desc
))
851 signature
= self
._decrypt
_signature
(
852 encrypted_sig
, video_id
, player_url
, age_gate
)
853 url
+= '&signature=' + signature
854 if 'ratebypass' not in url
:
855 url
+= '&ratebypass=yes'
856 url_map
[format_id
] = url
857 formats
= _map_to_format_list(url_map
)
858 elif video_info
.get('hlsvp'):
859 manifest_url
= video_info
['hlsvp'][0]
860 url_map
= self
._extract
_from
_m
3u8(manifest_url
, video_id
)
861 formats
= _map_to_format_list(url_map
)
863 raise ExtractorError(u
'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
865 # Look for the DASH manifest
866 if (self
._downloader
.params
.get('youtube_include_dash_manifest', False)):
868 # The DASH manifest used needs to be the one from the original video_webpage.
869 # The one found in get_video_info seems to be using different signatures.
870 # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
871 # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
872 # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
874 dash_manifest_url
= video_info
.get('dashmpd')[0]
876 dash_manifest_url
= ytplayer_config
['args']['dashmpd']
877 def decrypt_sig(mobj
):
879 dec_s
= self
._decrypt
_signature
(s
, video_id
, player_url
, age_gate
)
880 return '/signature/%s' % dec_s
881 dash_manifest_url
= re
.sub(r
'/s/([\w\.]+)', decrypt_sig
, dash_manifest_url
)
882 dash_doc
= self
._download
_xml
(
883 dash_manifest_url
, video_id
,
884 note
=u
'Downloading DASH manifest',
885 errnote
=u
'Could not download DASH manifest')
886 for r
in dash_doc
.findall(u
'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
887 url_el
= r
.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
890 format_id
= r
.attrib
['id']
891 video_url
= url_el
.text
892 filesize
= int_or_none(url_el
.attrib
.get('{http://youtube.com/yt/2012/10/10}contentLength'))
894 'format_id': format_id
,
896 'width': int_or_none(r
.attrib
.get('width')),
897 'tbr': int_or_none(r
.attrib
.get('bandwidth'), 1000),
898 'asr': int_or_none(r
.attrib
.get('audioSamplingRate')),
899 'filesize': filesize
,
902 existing_format
= next(
904 if fo
['format_id'] == format_id
)
905 except StopIteration:
906 f
.update(self
._formats
.get(format_id
, {}))
909 existing_format
.update(f
)
911 except (ExtractorError
, KeyError) as e
:
912 self
.report_warning(u
'Skipping DASH manifest: %s' % e
, video_id
)
914 self
._sort
_formats
(formats
)
918 'uploader': video_uploader
,
919 'uploader_id': video_uploader_id
,
920 'upload_date': upload_date
,
921 'title': video_title
,
922 'thumbnail': video_thumbnail
,
923 'description': video_description
,
924 'categories': video_categories
,
925 'subtitles': video_subtitles
,
926 'duration': video_duration
,
927 'age_limit': 18 if age_gate
else 0,
928 'annotations': video_annotations
,
929 'webpage_url': proto
+ '://www.youtube.com/watch?v=%s' % video_id
,
930 'view_count': view_count
,
931 'like_count': like_count
,
932 'dislike_count': dislike_count
,
936 class YoutubePlaylistIE(YoutubeBaseInfoExtractor
):
937 IE_DESC
= u
'YouTube.com playlists'
938 _VALID_URL
= r
"""(?x)(?:
943 (?:course|view_play_list|my_playlists|artist|playlist|watch)
944 \? (?:.*?&)*? (?:p|a|list)=
948 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
949 # Top tracks, they can also include dots
954 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
956 _TEMPLATE_URL
= 'https://www.youtube.com/playlist?list=%s'
957 _MORE_PAGES_INDICATOR
= r
'data-link-type="next"'
958 _VIDEO_RE
= r
'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&[^"]*?index=(?P<index>\d+)'
959 IE_NAME
= u
'youtube:playlist'
961 def _real_initialize(self
):
964 def _ids_to_results(self
, ids
):
965 return [self
.url_result(vid_id
, 'Youtube', video_id
=vid_id
)
968 def _extract_mix(self
, playlist_id
):
969 # The mixes are generated from a a single video
970 # the id of the playlist is just 'RD' + video_id
971 url
= 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id
[-11:], playlist_id
)
972 webpage
= self
._download
_webpage
(url
, playlist_id
, u
'Downloading Youtube mix')
973 search_title
= lambda class_name
: get_element_by_attribute('class', class_name
, webpage
)
974 title_span
= (search_title('playlist-title') or
975 search_title('title long-title') or search_title('title'))
976 title
= clean_html(title_span
)
977 video_re
= r
'''(?x)data-video-username=".*?".*?
978 href="/watch\?v=([0-9A-Za-z_-]{11})&[^"]*?list=%s''' % re
.escape(playlist_id
)
979 ids
= orderedSet(re
.findall(video_re
, webpage
, flags
=re
.DOTALL
))
980 url_results
= self
._ids
_to
_results
(ids
)
982 return self
.playlist_result(url_results
, playlist_id
, title
)
984 def _real_extract(self
, url
):
985 # Extract playlist id
986 mobj
= re
.match(self
._VALID
_URL
, url
)
988 raise ExtractorError(u
'Invalid URL: %s' % url
)
989 playlist_id
= mobj
.group(1) or mobj
.group(2)
991 # Check if it's a video-specific URL
992 query_dict
= compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
993 if 'v' in query_dict
:
994 video_id
= query_dict
['v'][0]
995 if self
._downloader
.params
.get('noplaylist'):
996 self
.to_screen(u
'Downloading just video %s because of --no-playlist' % video_id
)
997 return self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
999 self
.to_screen(u
'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id
, video_id
))
1001 if playlist_id
.startswith('RD'):
1002 # Mixes require a custom extraction process
1003 return self
._extract
_mix
(playlist_id
)
1004 if playlist_id
.startswith('TL'):
1005 raise ExtractorError(u
'For downloading YouTube.com top lists, use '
1006 u
'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected
=True)
1008 url
= self
._TEMPLATE
_URL
% playlist_id
1009 page
= self
._download
_webpage
(url
, playlist_id
)
1010 more_widget_html
= content_html
= page
1012 # Check if the playlist exists or is private
1013 if re
.search(r
'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page
) is not None:
1014 raise ExtractorError(
1015 u
'The playlist doesn\'t exist or is private, use --username or '
1016 '--netrc to access it.',
1019 # Extract the video ids from the playlist pages
1022 for page_num
in itertools
.count(1):
1023 matches
= re
.finditer(self
._VIDEO
_RE
, content_html
)
1024 # We remove the duplicates and the link with index 0
1025 # (it's not the first video of the playlist)
1026 new_ids
= orderedSet(m
.group('id') for m
in matches
if m
.group('index') != '0')
1029 mobj
= re
.search(r
'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html
)
1033 more
= self
._download
_json
(
1034 'https://youtube.com/%s' % mobj
.group('more'), playlist_id
,
1035 'Downloading page #%s' % page_num
,
1036 transform_source
=uppercase_escape
)
1037 content_html
= more
['content_html']
1038 more_widget_html
= more
['load_more_widget_html']
1040 playlist_title
= self
._html
_search
_regex
(
1041 r
'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1044 url_results
= self
._ids
_to
_results
(ids
)
1045 return self
.playlist_result(url_results
, playlist_id
, playlist_title
)
1048 class YoutubeTopListIE(YoutubePlaylistIE
):
1049 IE_NAME
= u
'youtube:toplist'
1050 IE_DESC
= (u
'YouTube.com top lists, "yttoplist:{channel}:{list title}"'
1051 u
' (Example: "yttoplist:music:Top Tracks")')
1052 _VALID_URL
= r
'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
1054 def _real_extract(self
, url
):
1055 mobj
= re
.match(self
._VALID
_URL
, url
)
1056 channel
= mobj
.group('chann')
1057 title
= mobj
.group('title')
1058 query
= compat_urllib_parse
.urlencode({'title': title}
)
1059 playlist_re
= 'href="([^"]+?%s.*?)"' % re
.escape(query
)
1060 channel_page
= self
._download
_webpage
('https://www.youtube.com/%s' % channel
, title
)
1061 link
= self
._html
_search
_regex
(playlist_re
, channel_page
, u
'list')
1062 url
= compat_urlparse
.urljoin('https://www.youtube.com/', link
)
1064 video_re
= r
'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1066 # sometimes the webpage doesn't contain the videos
1067 # retry until we get them
1068 for i
in itertools
.count(0):
1069 msg
= u
'Downloading Youtube mix'
1071 msg
+= ', retry #%d' % i
1072 webpage
= self
._download
_webpage
(url
, title
, msg
)
1073 ids
= orderedSet(re
.findall(video_re
, webpage
))
1076 url_results
= self
._ids
_to
_results
(ids
)
1077 return self
.playlist_result(url_results
, playlist_title
=title
)
1080 class YoutubeChannelIE(InfoExtractor
):
1081 IE_DESC
= u
'YouTube.com channels'
1082 _VALID_URL
= r
"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
1083 _MORE_PAGES_INDICATOR
= 'yt-uix-load-more'
1084 _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'
1085 IE_NAME
= u
'youtube:channel'
1087 def extract_videos_from_page(self
, page
):
1089 for mobj
in re
.finditer(r
'href="/watch\?v=([0-9A-Za-z_-]+)&?', page
):
1090 if mobj
.group(1) not in ids_in_page
:
1091 ids_in_page
.append(mobj
.group(1))
1094 def _real_extract(self
, url
):
1095 # Extract channel id
1096 mobj
= re
.match(self
._VALID
_URL
, url
)
1098 raise ExtractorError(u
'Invalid URL: %s' % url
)
1100 # Download channel page
1101 channel_id
= mobj
.group(1)
1103 url
= 'https://www.youtube.com/channel/%s/videos' % channel_id
1104 channel_page
= self
._download
_webpage
(url
, channel_id
)
1105 autogenerated
= re
.search(r
'''(?x)
1107 channel-header-autogenerated-label|
1108 yt-channel-title-autogenerated
1109 )[^"]*"''', channel_page
) is not None
1112 # The videos are contained in a single page
1113 # the ajax pages can't be used, they are empty
1114 video_ids
= self
.extract_videos_from_page(channel_page
)
1116 # Download all channel pages using the json-based channel_ajax query
1117 for pagenum
in itertools
.count(1):
1118 url
= self
._MORE
_PAGES
_URL
% (pagenum
, channel_id
)
1119 page
= self
._download
_json
(
1120 url
, channel_id
, note
=u
'Downloading page #%s' % pagenum
,
1121 transform_source
=uppercase_escape
)
1123 ids_in_page
= self
.extract_videos_from_page(page
['content_html'])
1124 video_ids
.extend(ids_in_page
)
1126 if self
._MORE
_PAGES
_INDICATOR
not in page
['load_more_widget_html']:
1129 self
._downloader
.to_screen(u
'[youtube] Channel %s: Found %i videos' % (channel_id
, len(video_ids
)))
1131 url_entries
= [self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1132 for video_id
in video_ids
]
1133 return self
.playlist_result(url_entries
, channel_id
)
1136 class YoutubeUserIE(InfoExtractor
):
1137 IE_DESC
= u
'YouTube.com user videos (URL or "ytuser" keyword)'
1138 _VALID_URL
= r
'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
1139 _TEMPLATE_URL
= 'https://gdata.youtube.com/feeds/api/users/%s'
1140 _GDATA_PAGE_SIZE
= 50
1141 _GDATA_URL
= 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
1142 IE_NAME
= u
'youtube:user'
1145 def suitable(cls
, url
):
1146 # Don't return True if the url can be extracted with other youtube
1147 # extractor, the regex would is too permissive and it would match.
1148 other_ies
= iter(klass
for (name
, klass
) in globals().items() if name
.endswith('IE') and klass
is not cls
)
1149 if any(ie
.suitable(url
) for ie
in other_ies
): return False
1150 else: return super(YoutubeUserIE
, cls
).suitable(url
)
1152 def _real_extract(self
, url
):
1154 mobj
= re
.match(self
._VALID
_URL
, url
)
1156 raise ExtractorError(u
'Invalid URL: %s' % url
)
1158 username
= mobj
.group(1)
1160 # Download video ids using YouTube Data API. Result size per
1161 # query is limited (currently to 50 videos) so we need to query
1162 # page by page until there are no video ids - it means we got
1165 def download_page(pagenum
):
1166 start_index
= pagenum
* self
._GDATA
_PAGE
_SIZE
+ 1
1168 gdata_url
= self
._GDATA
_URL
% (username
, self
._GDATA
_PAGE
_SIZE
, start_index
)
1169 page
= self
._download
_webpage
(
1170 gdata_url
, username
,
1171 u
'Downloading video ids from %d to %d' % (
1172 start_index
, start_index
+ self
._GDATA
_PAGE
_SIZE
))
1175 response
= json
.loads(page
)
1176 except ValueError as err
:
1177 raise ExtractorError(u
'Invalid JSON in API response: ' + compat_str(err
))
1178 if 'entry' not in response
['feed']:
1181 # Extract video identifiers
1182 entries
= response
['feed']['entry']
1183 for entry
in entries
:
1184 title
= entry
['title']['$t']
1185 video_id
= entry
['id']['$t'].split('/')[-1]
1189 'ie_key': 'Youtube',
1193 url_results
= PagedList(download_page
, self
._GDATA
_PAGE
_SIZE
)
1195 return self
.playlist_result(url_results
, playlist_title
=username
)
1198 class YoutubeSearchIE(SearchInfoExtractor
):
1199 IE_DESC
= u
'YouTube.com searches'
1200 _API_URL
= u
'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1202 IE_NAME
= u
'youtube:search'
1203 _SEARCH_KEY
= 'ytsearch'
1205 def _get_n_results(self
, query
, n
):
1206 """Get a specified number of results for a query"""
1213 while (PAGE_SIZE
* pagenum
) < limit
:
1214 result_url
= self
._API
_URL
% (
1215 compat_urllib_parse
.quote_plus(query
.encode('utf-8')),
1216 (PAGE_SIZE
* pagenum
) + 1)
1217 data_json
= self
._download
_webpage
(
1218 result_url
, video_id
=u
'query "%s"' % query
,
1219 note
=u
'Downloading page %s' % (pagenum
+ 1),
1220 errnote
=u
'Unable to download API page')
1221 data
= json
.loads(data_json
)
1222 api_response
= data
['data']
1224 if 'items' not in api_response
:
1225 raise ExtractorError(
1226 u
'[youtube] No video results', expected
=True)
1228 new_ids
= list(video
['id'] for video
in api_response
['items'])
1229 video_ids
+= new_ids
1231 limit
= min(n
, api_response
['totalItems'])
1234 if len(video_ids
) > n
:
1235 video_ids
= video_ids
[:n
]
1236 videos
= [self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1237 for video_id
in video_ids
]
1238 return self
.playlist_result(videos
, query
)
1241 class YoutubeSearchDateIE(YoutubeSearchIE
):
1242 IE_NAME
= YoutubeSearchIE
.IE_NAME
+ ':date'
1243 _API_URL
= 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
1244 _SEARCH_KEY
= 'ytsearchdate'
1245 IE_DESC
= u
'YouTube.com searches, newest videos first'
1248 class YoutubeSearchURLIE(InfoExtractor
):
1249 IE_DESC
= u
'YouTube.com search URLs'
1250 IE_NAME
= u
'youtube:search_url'
1251 _VALID_URL
= r
'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
1253 def _real_extract(self
, url
):
1254 mobj
= re
.match(self
._VALID
_URL
, url
)
1255 query
= compat_urllib_parse
.unquote_plus(mobj
.group('query'))
1257 webpage
= self
._download
_webpage
(url
, query
)
1258 result_code
= self
._search
_regex
(
1259 r
'(?s)<ol class="item-section"(.*?)</ol>', webpage
, u
'result HTML')
1261 part_codes
= re
.findall(
1262 r
'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code
)
1264 for part_code
in part_codes
:
1265 part_title
= self
._html
_search
_regex
(
1266 [r
'(?s)title="([^"]+)"', r
'>([^<]+)</a>'], part_code
, 'item title', fatal
=False)
1267 part_url_snippet
= self
._html
_search
_regex
(
1268 r
'(?s)href="([^"]+)"', part_code
, 'item URL')
1269 part_url
= compat_urlparse
.urljoin(
1270 'https://www.youtube.com/', part_url_snippet
)
1274 'title': part_title
,
1278 '_type': 'playlist',
1284 class YoutubeShowIE(InfoExtractor
):
1285 IE_DESC
= u
'YouTube.com (multi-season) shows'
1286 _VALID_URL
= r
'https?://www\.youtube\.com/show/(.*)'
1287 IE_NAME
= u
'youtube:show'
1289 def _real_extract(self
, url
):
1290 mobj
= re
.match(self
._VALID
_URL
, url
)
1291 show_name
= mobj
.group(1)
1292 webpage
= self
._download
_webpage
(url
, show_name
, u
'Downloading show webpage')
1293 # There's one playlist for each season of the show
1294 m_seasons
= list(re
.finditer(r
'href="(/playlist\?list=.*?)"', webpage
))
1295 self
.to_screen(u
'%s: Found %s seasons' % (show_name
, len(m_seasons
)))
1296 return [self
.url_result('https://www.youtube.com' + season
.group(1), 'YoutubePlaylist') for season
in m_seasons
]
1299 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor
):
1301 Base class for extractors that fetch info from
1302 http://www.youtube.com/feed_ajax
1303 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1305 _LOGIN_REQUIRED
= True
1306 # use action_load_personal_feed instead of action_load_system_feed
1307 _PERSONAL_FEED
= False
1310 def _FEED_TEMPLATE(self
):
1311 action
= 'action_load_system_feed'
1312 if self
._PERSONAL
_FEED
:
1313 action
= 'action_load_personal_feed'
1314 return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action
, self
._FEED
_NAME
)
1318 return u
'youtube:%s' % self
._FEED
_NAME
1320 def _real_initialize(self
):
1323 def _real_extract(self
, url
):
1326 for i
in itertools
.count(1):
1327 info
= self
._download
_json
(self
._FEED
_TEMPLATE
% paging
,
1328 u
'%s feed' % self
._FEED
_NAME
,
1329 u
'Downloading page %s' % i
)
1330 feed_html
= info
.get('feed_html') or info
.get('content_html')
1331 m_ids
= re
.finditer(r
'"/watch\?v=(.*?)["&]', feed_html
)
1332 ids
= orderedSet(m
.group(1) for m
in m_ids
)
1333 feed_entries
.extend(
1334 self
.url_result(video_id
, 'Youtube', video_id
=video_id
)
1335 for video_id
in ids
)
1337 r
'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1341 paging
= mobj
.group('paging')
1342 return self
.playlist_result(feed_entries
, playlist_title
=self
._PLAYLIST
_TITLE
)
1344 class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor
):
1345 IE_DESC
= u
'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
1346 _VALID_URL
= r
'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1347 _FEED_NAME
= 'subscriptions'
1348 _PLAYLIST_TITLE
= u
'Youtube Subscriptions'
1350 class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor
):
1351 IE_DESC
= u
'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1352 _VALID_URL
= r
'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1353 _FEED_NAME
= 'recommended'
1354 _PLAYLIST_TITLE
= u
'Youtube Recommended videos'
1356 class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor
):
1357 IE_DESC
= u
'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1358 _VALID_URL
= r
'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1359 _FEED_NAME
= 'watch_later'
1360 _PLAYLIST_TITLE
= u
'Youtube Watch Later'
1361 _PERSONAL_FEED
= True
1363 class YoutubeHistoryIE(YoutubeFeedsInfoExtractor
):
1364 IE_DESC
= u
'Youtube watch history, "ythistory" keyword (requires authentication)'
1365 _VALID_URL
= u
'https?://www\.youtube\.com/feed/history|:ythistory'
1366 _FEED_NAME
= 'history'
1367 _PERSONAL_FEED
= True
1368 _PLAYLIST_TITLE
= u
'Youtube Watch History'
1370 class YoutubeFavouritesIE(YoutubeBaseInfoExtractor
):
1371 IE_NAME
= u
'youtube:favorites'
1372 IE_DESC
= u
'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
1373 _VALID_URL
= r
'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
1374 _LOGIN_REQUIRED
= True
1376 def _real_extract(self
, url
):
1377 webpage
= self
._download
_webpage
('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1378 playlist_id
= self
._search
_regex
(r
'list=(.+?)["&]', webpage
, u
'favourites playlist id')
1379 return self
.url_result(playlist_id
, 'YoutubePlaylist')
1382 class YoutubeTruncatedURLIE(InfoExtractor
):
1383 IE_NAME
= 'youtube:truncated_url'
1384 IE_DESC
= False # Do not list
1385 _VALID_URL
= r
'''(?x)
1386 (?:https?://)?[^/]+/watch\?(?:
1388 annotation_id=annotation_[^&]+
1390 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1394 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1395 'only_matching': True,
1397 'url': 'http://www.youtube.com/watch?',
1398 'only_matching': True,
1401 def _real_extract(self
, url
):
1402 raise ExtractorError(
1403 u
'Did you forget to quote the URL? Remember that & is a meta '
1404 u
'character in most shells, so you want to put the URL in quotes, '
1406 u
'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1407 u
' or simply youtube-dl BaW_jenozKc .',