]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/youtube.py
[youtube] Correct description in test case
[yt-dlp.git] / youtube_dl / extractor / youtube.py
1 # coding: utf-8
2
3 import itertools
4 import json
5 import os.path
6 import re
7 import traceback
8
9 from .common import InfoExtractor, SearchInfoExtractor
10 from .subtitles import SubtitlesInfoExtractor
11 from ..jsinterp import JSInterpreter
12 from ..swfinterp import SWFInterpreter
13 from ..utils import (
14 compat_chr,
15 compat_parse_qs,
16 compat_urllib_parse,
17 compat_urllib_request,
18 compat_urlparse,
19 compat_str,
20
21 clean_html,
22 get_element_by_id,
23 get_element_by_attribute,
24 ExtractorError,
25 int_or_none,
26 PagedList,
27 unescapeHTML,
28 unified_strdate,
29 orderedSet,
30 uppercase_escape,
31 )
32
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
42
43 def _set_language(self):
44 return bool(self._download_webpage(
45 self._LANG_URL, None,
46 note=u'Setting language', errnote='unable to set language',
47 fatal=False))
48
49 def _login(self):
50 """
51 Attempt to log in to YouTube.
52 True is returned if successful or skipped.
53 False is returned if login failed.
54
55 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
56 """
57 (username, password) = self._get_login_info()
58 # No authentication to be performed
59 if username is None:
60 if self._LOGIN_REQUIRED:
61 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
62 return True
63
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:
69 return
70
71 galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
72 login_page, u'Login GALX parameter')
73
74 # Log in
75 login_form_strs = {
76 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
77 u'Email': username,
78 u'GALX': galx,
79 u'Passwd': password,
80
81 u'PersistentCookie': u'yes',
82 u'_utf8': u'霱',
83 u'bgresponse': u'js_disabled',
84 u'checkConnection': u'',
85 u'checkedDomains': u'youtube',
86 u'dnConn': u'',
87 u'pstMsg': u'0',
88 u'rmShown': u'1',
89 u'secTok': u'',
90 u'signIn': u'Sign in',
91 u'timeStmp': u'',
92 u'service': u'youtube',
93 u'uilel': u'3',
94 u'hl': u'en_US',
95 }
96
97 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
98 # chokes on unicode
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')
101
102 req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
103 login_results = self._download_webpage(
104 req, None,
105 note=u'Logging in', errnote=u'unable to log in', fatal=False)
106 if login_results is False:
107 return False
108
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)
111
112 # Two-Factor
113 # TODO add SMS and phone call support - these require making a request and then prompting the user
114
115 if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
116 tfa_code = self._get_tfa_info()
117
118 if tfa_code is None:
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.)')
121 return False
122
123 # Unlike the first login form, secTok and timeStmp are both required for the TFA form
124
125 match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
126 if match is None:
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)
130 if match is None:
131 self._downloader.report_warning(u'Failed to get timeStmp - did the page structure change?')
132 timeStmp = match.group(1)
133
134 tfa_form_strs = {
135 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
136 u'smsToken': u'',
137 u'smsUserPin': tfa_code,
138 u'smsVerifyPin': u'Verify',
139
140 u'PersistentCookie': u'yes',
141 u'checkConnection': u'',
142 u'checkedDomains': u'youtube',
143 u'pstMsg': u'1',
144 u'secTok': secTok,
145 u'timeStmp': timeStmp,
146 u'service': u'youtube',
147 u'hl': u'en_US',
148 }
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')
151
152 tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
153 tfa_results = self._download_webpage(
154 tfa_req, None,
155 note=u'Submitting TFA code', errnote=u'unable to submit tfa', fatal=False)
156
157 if tfa_results is False:
158 return False
159
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.')
162 return False
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?')
165 return False
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.')
168 return False
169
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')
172 return False
173 return True
174
175 def _confirm_age(self):
176 age_form = {
177 'next_url': '/',
178 'action_confirm': 'Confirm',
179 }
180 req = compat_urllib_request.Request(self._AGE_URL,
181 compat_urllib_parse.urlencode(age_form).encode('ascii'))
182
183 self._download_webpage(
184 req, None,
185 note=u'Confirming age', errnote=u'Unable to confirm age')
186 return True
187
188 def _real_initialize(self):
189 if self._downloader is None:
190 return
191 if not self._set_language():
192 return
193 if not self._login():
194 return
195 self._confirm_age()
196
197
198 class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
199 IE_DESC = u'YouTube.com'
200 _VALID_URL = r"""(?x)^
201 (
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)
216 v=
217 )
218 ))
219 |youtu\.be/ # just youtu.be/xxxx
220 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
221 )
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
226 $"""
227 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
228 _formats = {
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},
244
245
246 # 3d videos
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},
254
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},
263
264 # DASH mp4 video
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},
273
274 # Dash mp4 audio
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},
278
279 # Dash webm
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},
295
296 # Dash webm audio
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},
299
300 # RTMP (unnamed)
301 '_rtmp': {'protocol': 'rtmp'},
302 }
303
304 IE_NAME = u'youtube'
305 _TESTS = [
306 {
307 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
308 u"file": u"BaW_jenozKc.mp4",
309 u"info_dict": {
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'],
316 'like_count': int,
317 'dislike_count': int,
318 }
319 },
320 {
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)",
324 u"info_dict": {
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"
330 }
331 },
332 {
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)",
336 u"info_dict": {
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"
342 }
343 },
344 {
345 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
346 u"file": u"yZIXLfi8CZQ.mp4",
347 u"note": u"Embed-only video (#1746)",
348 u"info_dict": {
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"
354 }
355 },
356 {
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",
360 u"info_dict": {
361 u"upload_date": "20121002",
362 u"uploader_id": "8KVIDEO",
363 u"description": '',
364 u"uploader": "8KVIDEO",
365 u"title": "UHDTV TEST 8K VIDEO.mp4"
366 },
367 u"params": {
368 u"youtube_include_dash_manifest": True,
369 u"format": "141",
370 },
371 },
372 # DASH manifest with encrypted signature
373 {
374 u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA',
375 u'info_dict': {
376 u'id': u'IB3lcPjvWLA',
377 u'ext': u'm4a',
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',
383 },
384 u"params": {
385 u'youtube_include_dash_manifest': True,
386 u'format': '141',
387 },
388 },
389 ]
390
391 def __init__(self, *args, **kwargs):
392 super(YoutubeIE, self).__init__(*args, **kwargs)
393 self._player_cache = {}
394
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)
398
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)
402
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))
406
407 def report_rtmp_download(self):
408 """Indicate the download will use the RTMP protocol."""
409 self.to_screen(u'RTMP download detected')
410
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('.'))
414
415 def _extract_signature_function(self, video_id, player_url, example_sig):
416 id_m = re.match(
417 r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
418 player_url)
419 if not id_m:
420 raise ExtractorError('Cannot identify player %r' % player_url)
421 player_type = id_m.group('ext')
422 player_id = id_m.group('id')
423
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
428
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)
432
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)
444 code = urlh.read()
445 res = self._parse_sig_swf(code)
446 else:
447 assert False, 'Invalid player type %r' % player_type
448
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]
453
454 self._downloader.cache.store(u'youtube-sigfuncs', func_id, cache_spec)
455 return res
456
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)
464
465 step = None
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]):
469 if step is not None:
470 if i - prev == step:
471 continue
472 yield _genslice(start, prev, step)
473 step = None
474 continue
475 if i - prev in [-1, 1]:
476 step = i - prev
477 start = prev
478 continue
479 else:
480 yield u's[%d]' % prev
481 if step is None:
482 yield u's[%d]' % i
483 else:
484 yield _genslice(start, i, step)
485
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)
495
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')
500
501 jsi = JSInterpreter(jscode)
502 initial_function = jsi.extract_function(funcname)
503 return lambda s: initial_function([s])
504
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])
511
512 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
513 """Turn the encrypted s field into a working signature"""
514
515 if player_url is None:
516 raise ExtractorError(u'Cannot decrypt signature without player_url')
517
518 if player_url.startswith(u'//'):
519 player_url = u'https:' + player_url
520 try:
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
525 )
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)
530 return func(s)
531 except Exception as e:
532 tb = traceback.format_exc()
533 raise ExtractorError(
534 u'Signature extraction failed: ' + tb, cause=e)
535
536 def _get_available_subtitles(self, video_id, webpage):
537 try:
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))
543 return {}
544 lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
545
546 sub_lang_list = {}
547 for l in lang_list:
548 lang = l[1]
549 if lang in sub_lang_list:
550 continue
551 params = compat_urllib_parse.urlencode({
552 'lang': lang,
553 'v': video_id,
554 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
555 'name': unescapeHTML(l[0]).encode('utf-8'),
556 })
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')
561 return {}
562 return sub_lang_list
563
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
571 if mobj is None:
572 self._downloader.report_warning(err_msg)
573 return {}
574 player_config = json.loads(mobj.group(1))
575 try:
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({
581 'type': 'list',
582 'tlangs': 1,
583 'asrs': 1,
584 })
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')
590 return {}
591 original_lang = original_lang_node.attrib['lang_code']
592
593 sub_lang_list = {}
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,
598 'tlang': sub_lang,
599 'fmt': sub_format,
600 'ts': timestamp,
601 'kind': 'asr',
602 })
603 sub_lang_list[sub_lang] = caption_url + '&' + params
604 return sub_lang_list
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)
609 return {}
610
611 @classmethod
612 def extract_id(cls, url):
613 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
614 if mobj is None:
615 raise ExtractorError(u'Invalid URL: %s' % url)
616 video_id = mobj.group(2)
617 return video_id
618
619 def _extract_from_m3u8(self, manifest_url, video_id):
620 url_map = {}
621 def _get_urls(_manifest):
622 lines = _manifest.split('\n')
623 urls = filter(lambda l: l and not l.startswith('#'),
624 lines)
625 return urls
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
631 return url_map
632
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.')
636
637 def _real_extract(self, url):
638 proto = (
639 u'http' if self._downloader.params.get('prefer_insecure', False)
640 else u'https')
641
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)
644 if mobj:
645 url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
646 video_id = self.extract_id(url)
647
648 # Get video webpage
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)
651
652 # Attempt to extract SWF player URL
653 mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
654 if mobj is not None:
655 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
656 else:
657 player_url = None
658
659 # Get video info
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()
663 age_gate = True
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'),
671 })
672 video_info_url = proto + '://www.youtube.com/get_video_info?' + data
673 video_info_webpage = self._download_webpage(video_info_url, video_id,
674 note=False,
675 errnote='unable to download video info webpage')
676 video_info = compat_parse_qs(video_info_webpage)
677 else:
678 age_gate = False
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,
683 note=False,
684 errnote='unable to download video info webpage')
685 video_info = compat_parse_qs(video_info_webpage)
686 if 'token' in video_info:
687 break
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)
693 else:
694 raise ExtractorError(
695 u'"token" parameter not in video info for unknown reason',
696 video_id=video_id)
697
698 if 'view_count' in video_info:
699 view_count = int(video_info['view_count'][0])
700 else:
701 view_count = None
702
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')
706
707 # Start extracting information
708 self.report_information_extraction(video_id)
709
710 # uploader
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])
714
715 # uploader_id
716 video_uploader_id = None
717 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
718 if mobj is not None:
719 video_uploader_id = mobj.group(1)
720 else:
721 self._downloader.report_warning(u'unable to extract uploader nickname')
722
723 # title
724 if 'title' in video_info:
725 video_title = video_info['title'][0]
726 else:
727 self._downloader.report_warning(u'Unable to extract video title')
728 video_title = u'_'
729
730 # thumbnail image
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])
741
742 # upload date
743 upload_date = None
744 mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
745 if mobj is None:
746 mobj = re.search(
747 r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
748 video_webpage)
749 if mobj is not None:
750 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
751 upload_date = unified_strdate(upload_date)
752
753 m_cat_container = self._search_regex(
754 r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
755 video_webpage, 'categories', fatal=False)
756 if m_cat_container:
757 category = self._html_search_regex(
758 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
759 default=None)
760 video_categories = None if category is None else [category]
761 else:
762 video_categories = None
763
764 # description
765 video_description = get_element_by_id("eow-description", video_webpage)
766 if video_description:
767 video_description = re.sub(r'''(?x)
768 <a\s+
769 (?:[a-zA-Z-]+="[^"]+"\s+)*?
770 title="([^"]+)"\s+
771 (?:[a-zA-Z-]+="[^"]+"\s+)*?
772 class="yt-uix-redirect-link"\s*>
773 [^<]+
774 </a>
775 ''', r'\1', video_description)
776 video_description = clean_html(video_description)
777 else:
778 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
779 if fd_mobj:
780 video_description = unescapeHTML(fd_mobj.group(1))
781 else:
782 video_description = u''
783
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(',', ''))
790 return None
791 like_count = _extract_count(u'like')
792 dislike_count = _extract_count(u'dislike')
793
794 # subtitles
795 video_subtitles = self.extract_subtitles(video_id, video_webpage)
796
797 if self._downloader.params.get('listsubtitles', False):
798 self._list_available_subtitles(video_id, video_webpage)
799 return
800
801 if 'length_seconds' not in video_info:
802 self._downloader.report_warning(u'unable to extract video duration')
803 video_duration = None
804 else:
805 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
806
807 # annotations
808 video_annotations = None
809 if self._downloader.params.get('writeannotations', False):
810 video_annotations = self._extract_annotations(video_id)
811
812 # Decide which formats to download
813 try:
814 mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
815 if not mobj:
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'])
826 if m_s is not None:
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''))
830 if m_s is not None:
831 if 'adaptive_fmts' in video_info:
832 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
833 else:
834 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
835 except ValueError:
836 pass
837
838 def _map_to_format_list(urlmap):
839 formats = []
840 for itag, video_real_url in urlmap.items():
841 dct = {
842 'format_id': itag,
843 'url': video_real_url,
844 'player_url': player_url,
845 }
846 if itag in self._formats:
847 dct.update(self._formats[itag])
848 formats.append(dct)
849 return formats
850
851 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
852 self.report_rtmp_download()
853 formats = [{
854 'format_id': '_rtmp',
855 'protocol': 'rtmp',
856 'url': video_info['conn'][0],
857 'player_url': player_url,
858 }]
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)
863 url_map = {}
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:
867 continue
868 format_id = url_data['itag'][0]
869 url = url_data['url'][0]
870
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]
875
876 if not age_gate:
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)
886
887 if self._downloader.params.get('verbose'):
888 if player_url is None:
889 player_version = 'unknown'
890 player_desc = 'unknown'
891 else:
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
897 else:
898 player_version = self._search_regex(
899 r'html5player-([^/]+?)(?:/html5player)?\.js',
900 player_url,
901 'html5 player', fatal=False)
902 player_desc = u'html5 player %s' % player_version
903
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))
907
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)
919 else:
920 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
921
922 # Look for the DASH manifest
923 if (self._downloader.params.get('youtube_include_dash_manifest', False)):
924 try:
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.
930 if age_gate:
931 dash_manifest_url = video_info.get('dashmpd')[0]
932 else:
933 dash_manifest_url = ytplayer_config['args']['dashmpd']
934 def decrypt_sig(mobj):
935 s = mobj.group(1)
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')
945 if url_el is None:
946 continue
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'))
950 f = {
951 'format_id': format_id,
952 'url': video_url,
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,
957 }
958 try:
959 existing_format = next(
960 fo for fo in formats
961 if fo['format_id'] == format_id)
962 except StopIteration:
963 f.update(self._formats.get(format_id, {}))
964 formats.append(f)
965 else:
966 existing_format.update(f)
967
968 except (ExtractorError, KeyError) as e:
969 self.report_warning(u'Skipping DASH manifest: %s' % e, video_id)
970
971 self._sort_formats(formats)
972
973 return {
974 'id': video_id,
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,
990 'formats': formats,
991 }
992
993 class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
994 IE_DESC = u'YouTube.com playlists'
995 _VALID_URL = r"""(?x)(?:
996 (?:https?://)?
997 (?:\w+\.)?
998 youtube\.com/
999 (?:
1000 (?:course|view_play_list|my_playlists|artist|playlist|watch)
1001 \? (?:.*?&)*? (?:p|a|list)=
1002 | p/
1003 )
1004 (
1005 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
1006 # Top tracks, they can also include dots
1007 |(?:MC)[\w\.]*
1008 )
1009 .*
1010 |
1011 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
1012 )"""
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})&amp;[^"]*?index=(?P<index>\d+)'
1016 IE_NAME = u'youtube:playlist'
1017 _TESTS = [{
1018 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
1019 'info_dict': {
1020 'title': 'ytdl test PL',
1021 },
1022 'playlist_count': 3,
1023 }, {
1024 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
1025 'info_dict': {
1026 'title': 'YDL_Empty_List',
1027 },
1028 'playlist_count': 0,
1029 }, {
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',
1032 'info_dict': {
1033 'title': '29C3: Not my department',
1034 },
1035 'playlist_count': 95,
1036 }, {
1037 'note': 'issue #673',
1038 'url': 'PLBB231211A4F62143',
1039 'info_dict': {
1040 'title': 'Team Fortress 2 (Class-based LP)',
1041 },
1042 'playlist_mincount': 26,
1043 }, {
1044 'note': 'Large playlist',
1045 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
1046 'info_dict': {
1047 'title': 'Uploads from Cauchemar',
1048 },
1049 'playlist_mincount': 799,
1050 }, {
1051 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
1052 'info_dict': {
1053 'title': 'YDL_safe_search',
1054 },
1055 'playlist_count': 2,
1056 }]
1057
1058 def _real_initialize(self):
1059 self._login()
1060
1061 def _ids_to_results(self, ids):
1062 return [
1063 self.url_result(vid_id, 'Youtube', video_id=vid_id)
1064 for vid_id in ids]
1065
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)
1073 title_span = (
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})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
1081 webpage))
1082 url_results = self._ids_to_results(ids)
1083
1084 return self.playlist_result(url_results, playlist_id, title)
1085
1086 def _real_extract(self, url):
1087 # Extract playlist id
1088 mobj = re.match(self._VALID_URL, url)
1089 if mobj is None:
1090 raise ExtractorError(u'Invalid URL: %s' % url)
1091 playlist_id = mobj.group(1) or mobj.group(2)
1092
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)
1100 else:
1101 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
1102
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)
1109
1110 url = self._TEMPLATE_URL % playlist_id
1111 page = self._download_webpage(url, playlist_id)
1112 more_widget_html = content_html = page
1113
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.',
1119 expected=True)
1120
1121 # Extract the video ids from the playlist pages
1122 ids = []
1123
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')
1129 ids.extend(new_ids)
1130
1131 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1132 if not mobj:
1133 break
1134
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']
1141
1142 playlist_title = self._html_search_regex(
1143 r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1144 page, u'title')
1145
1146 url_results = self._ids_to_results(ids)
1147 return self.playlist_result(url_results, playlist_id, playlist_title)
1148
1149
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>.*?)$'
1155 _TESTS = []
1156
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)
1166
1167 video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
1168 ids = []
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'
1173 if i > 0:
1174 msg += ', retry #%d' % i
1175
1176 webpage = self._download_webpage(url, title, msg)
1177 ids = orderedSet(re.findall(video_re, webpage))
1178 if ids:
1179 break
1180 url_results = self._ids_to_results(ids)
1181 return self.playlist_result(url_results, playlist_title=title)
1182
1183
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'
1190
1191 def extract_videos_from_page(self, page):
1192 ids_in_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))
1196 return ids_in_page
1197
1198 def _real_extract(self, url):
1199 # Extract channel id
1200 mobj = re.match(self._VALID_URL, url)
1201 if mobj is None:
1202 raise ExtractorError(u'Invalid URL: %s' % url)
1203
1204 # Download channel page
1205 channel_id = mobj.group(1)
1206 video_ids = []
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)
1210 class="[^"]*?(?:
1211 channel-header-autogenerated-label|
1212 yt-channel-title-autogenerated
1213 )[^"]*"''', channel_page) is not None
1214
1215 if autogenerated:
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)
1219 else:
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)
1226
1227 ids_in_page = self.extract_videos_from_page(page['content_html'])
1228 video_ids.extend(ids_in_page)
1229
1230 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1231 break
1232
1233 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1234
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)
1238
1239
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'
1247
1248 @classmethod
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)
1255
1256 def _real_extract(self, url):
1257 # Extract username
1258 mobj = re.match(self._VALID_URL, url)
1259 if mobj is None:
1260 raise ExtractorError(u'Invalid URL: %s' % url)
1261
1262 username = mobj.group(1)
1263
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
1267 # all of them.
1268
1269 def download_page(pagenum):
1270 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1271
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))
1277
1278 try:
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']:
1283 return
1284
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]
1290 yield {
1291 '_type': 'url',
1292 'url': video_id,
1293 'ie_key': 'Youtube',
1294 'id': video_id,
1295 'title': title,
1296 }
1297 url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
1298
1299 return self.playlist_result(url_results, playlist_title=username)
1300
1301
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'
1305 _MAX_RESULTS = 1000
1306 IE_NAME = u'youtube:search'
1307 _SEARCH_KEY = 'ytsearch'
1308
1309 def _get_n_results(self, query, n):
1310 """Get a specified number of results for a query"""
1311
1312 video_ids = []
1313 pagenum = 0
1314 limit = n
1315 PAGE_SIZE = 50
1316
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']
1327
1328 if 'items' not in api_response:
1329 raise ExtractorError(
1330 u'[youtube] No video results', expected=True)
1331
1332 new_ids = list(video['id'] for video in api_response['items'])
1333 video_ids += new_ids
1334
1335 limit = min(n, api_response['totalItems'])
1336 pagenum += 1
1337
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)
1343
1344
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'
1350
1351
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>[^&]+)(?:[&]|$)'
1356
1357 def _real_extract(self, url):
1358 mobj = re.match(self._VALID_URL, url)
1359 query = compat_urllib_parse.unquote_plus(mobj.group('query'))
1360
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')
1364
1365 part_codes = re.findall(
1366 r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
1367 entries = []
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)
1375 entries.append({
1376 '_type': 'url',
1377 'url': part_url,
1378 'title': part_title,
1379 })
1380
1381 return {
1382 '_type': 'playlist',
1383 'entries': entries,
1384 'title': query,
1385 }
1386
1387
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'
1392
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]
1401
1402
1403 class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
1404 """
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.
1408 """
1409 _LOGIN_REQUIRED = True
1410 # use action_load_personal_feed instead of action_load_system_feed
1411 _PERSONAL_FEED = False
1412
1413 @property
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)
1419
1420 @property
1421 def IE_NAME(self):
1422 return u'youtube:%s' % self._FEED_NAME
1423
1424 def _real_initialize(self):
1425 self._login()
1426
1427 def _real_extract(self, url):
1428 feed_entries = []
1429 paging = 0
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)
1441 mobj = re.search(
1442 r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1443 load_more_widget_html)
1444 if mobj is None:
1445 break
1446 paging = mobj.group('paging')
1447 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1448
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'
1454
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
1461
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'
1468
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
1474
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')
1479
1480
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)?'
1485 _TESTS = []
1486
1487 def _real_extract(self, url):
1488 title = u'Youtube Subscriptions'
1489 page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title)
1490
1491 # The extraction process is the same as for playlists, but the regex
1492 # for the video ids doesn't contain an index
1493 ids = []
1494 more_widget_html = content_html = page
1495
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)
1499 ids.extend(new_ids)
1500
1501 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1502 if not mobj:
1503 break
1504
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']
1511
1512 return {
1513 '_type': 'playlist',
1514 'title': title,
1515 'entries': self._ids_to_results(ids),
1516 }
1517
1518
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\?(?:
1524 feature=[a-z_]+|
1525 annotation_id=annotation_[^&]+
1526 )?$|
1527 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1528 '''
1529
1530 _TESTS = [{
1531 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1532 'only_matching': True,
1533 }, {
1534 'url': 'http://www.youtube.com/watch?',
1535 'only_matching': True,
1536 }]
1537
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, '
1542 u'like youtube-dl '
1543 u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1544 u' or simply youtube-dl BaW_jenozKc .',
1545 expected=True)