]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/youtube.py
[youtube] Correct description in test case
[yt-dlp.git] / youtube_dl / extractor / youtube.py
CommitLineData
c5e8d7af 1# coding: utf-8
c5e8d7af 2
0ca96d48 3import itertools
c5e8d7af 4import json
c4417ddb 5import os.path
c5e8d7af 6import re
e0df6211 7import traceback
c5e8d7af 8
b05654f0 9from .common import InfoExtractor, SearchInfoExtractor
54d39d8b 10from .subtitles import SubtitlesInfoExtractor
2b25cb5d 11from ..jsinterp import JSInterpreter
54256267 12from ..swfinterp import SWFInterpreter
c5e8d7af 13from ..utils import (
edf3e38e 14 compat_chr,
c5e8d7af 15 compat_parse_qs,
c5e8d7af
PH
16 compat_urllib_parse,
17 compat_urllib_request,
7c61bd36 18 compat_urlparse,
c5e8d7af
PH
19 compat_str,
20
21 clean_html,
22 get_element_by_id,
652cdaa2 23 get_element_by_attribute,
c5e8d7af 24 ExtractorError,
dd27fd17 25 int_or_none,
b7ab0590 26 PagedList,
c5e8d7af
PH
27 unescapeHTML,
28 unified_strdate,
04cc9617 29 orderedSet,
81c2f20b 30 uppercase_escape,
c5e8d7af
PH
31)
32
de7f3446 33class YoutubeBaseInfoExtractor(InfoExtractor):
b2e8bc1b
JMF
34 """Provide base functions for Youtube extractors"""
35 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
83317f69 36 _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
b2e8bc1b 37 _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
38c2e5b8 38 _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
b2e8bc1b
JMF
39 _NETRC_MACHINE = 'youtube'
40 # If True it will raise an error if no login info is provided
41 _LOGIN_REQUIRED = False
42
b2e8bc1b 43 def _set_language(self):
7cc3570e
PH
44 return bool(self._download_webpage(
45 self._LANG_URL, None,
46 note=u'Setting language', errnote='unable to set language',
47 fatal=False))
b2e8bc1b
JMF
48
49 def _login(self):
83317f69 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 """
b2e8bc1b
JMF
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)
83317f69 62 return True
b2e8bc1b 63
7cc3570e
PH
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
b2e8bc1b 70
795f28f8
PH
71 galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
72 login_page, u'Login GALX parameter')
c5e8d7af 73
b2e8bc1b
JMF
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,
83317f69 80
b2e8bc1b
JMF
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'',
b2e8bc1b
JMF
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 }
83317f69 96
b2e8bc1b
JMF
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')
7cc3570e
PH
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
83317f69 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
7cc3570e
PH
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')
b2e8bc1b
JMF
172 return False
173 return True
174
175 def _confirm_age(self):
176 age_form = {
7cc3570e
PH
177 'next_url': '/',
178 'action_confirm': 'Confirm',
179 }
5700e779
JMF
180 req = compat_urllib_request.Request(self._AGE_URL,
181 compat_urllib_parse.urlencode(age_form).encode('ascii'))
7cc3570e
PH
182
183 self._download_webpage(
184 req, None,
185 note=u'Confirming age', errnote=u'Unable to confirm age')
b2e8bc1b
JMF
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()
c5e8d7af 196
8377574c 197
de7f3446 198class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
0f818663 199 IE_DESC = u'YouTube.com'
cb7dfeea 200 _VALID_URL = r"""(?x)^
c5e8d7af 201 (
edb53e2d 202 (?:https?://|//) # http(s):// or protocol-independent URL
cb7dfeea 203 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
484aaeb2 204 (?:www\.)?deturl\.com/www\.youtube\.com/|
e70dc1d1 205 (?:www\.)?pwnyoutube\.com/|
f7000f3a 206 (?:www\.)?yourepeat\.com/|
e69ae5b9
JMF
207 tube\.majestyc\.net/|
208 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
c5e8d7af
PH
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
f7000f3a 213 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
c5e8d7af
PH
214 (?:\?|\#!?) # the params delimiter ? or # or #!
215 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
216 v=
217 )
f4b05232
JMF
218 ))
219 |youtu\.be/ # just youtu.be/xxxx
edb53e2d 220 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
f4b05232 221 )
c5e8d7af 222 )? # all until now is optional -> you can pass the naked ID
8963d9c2 223 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
9291475f 224 (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
c5e8d7af
PH
225 (?(1).+)? # if we found the ID, everything can follow
226 $"""
c5e8d7af 227 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
2c62dc26
PH
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
1d043b93 245
86fe61c8 246 # 3d videos
43b81eb9
PH
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},
836a086c 254
96fb5605 255 # Apple HTTP Live Streaming
43b81eb9
PH
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},
2c62dc26
PH
263
264 # DASH mp4 video
43b81eb9
PH
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},
836a086c 273
f6f1fc92 274 # Dash mp4 audio
2c62dc26
PH
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},
836a086c
AZ
278
279 # Dash webm
e75cafe9
A
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},
3c80377b 293 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
18061bba 294 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
2c62dc26
PH
295
296 # Dash webm audio
55db73ef 297 '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
e75cafe9 298 '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
ce6b9a2d
PH
299
300 # RTMP (unnamed)
301 '_rtmp': {'protocol': 'rtmp'},
c5e8d7af 302 }
836a086c 303
c5e8d7af 304 IE_NAME = u'youtube'
2eb88d95
PH
305 _TESTS = [
306 {
0e853ca4
PH
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",
ad3bc6ac
PH
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'],
3e7c1224
PH
316 'like_count': int,
317 'dislike_count': int,
2eb88d95 318 }
0e853ca4 319 },
0e853ca4
PH
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]",
ba60a3eb 327 u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f",
45ed795c 328 u"uploader": u"Icona Pop",
0e853ca4 329 u"uploader_id": u"IconaPop"
2eb88d95 330 }
c108eb73
JMF
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 },
fccd3771 344 {
83aa5293 345 u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
fccd3771
PH
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 },
dd27fd17
PH
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",
dd27fd17
PH
360 u"info_dict": {
361 u"upload_date": "20121002",
362 u"uploader_id": "8KVIDEO",
310d75d1 363 u"description": '',
dd27fd17
PH
364 u"uploader": "8KVIDEO",
365 u"title": "UHDTV TEST 8K VIDEO.mp4"
4919603f
PH
366 },
367 u"params": {
368 u"youtube_include_dash_manifest": True,
369 u"format": "141",
370 },
dd27fd17 371 },
3489b7d2
JMF
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',
e00c9cf5 379 u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8',
3489b7d2
JMF
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 },
2eb88d95
PH
389 ]
390
e0df6211
PH
391 def __init__(self, *args, **kwargs):
392 super(YoutubeIE, self).__init__(*args, **kwargs)
83799698 393 self._player_cache = {}
e0df6211 394
c5e8d7af
PH
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
c5e8d7af
PH
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
60064c53
PH
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):
cf010131 416 id_m = re.match(
c081b35c 417 r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
cf010131 418 player_url)
c081b35c
PH
419 if not id_m:
420 raise ExtractorError('Cannot identify player %r' % player_url)
e0df6211
PH
421 player_type = id_m.group('ext')
422 player_id = id_m.group('id')
423
c4417ddb 424 # Read from filesystem cache
60064c53
PH
425 func_id = '%s_%s_%s' % (
426 player_type, player_id, self._signature_cache_id(example_sig))
c4417ddb 427 assert os.path.basename(func_id) == func_id
a0e07d31
PH
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)
83799698 432
e0df6211
PH
433 if player_type == 'js':
434 code = self._download_webpage(
435 player_url, video_id,
83799698 436 note=u'Downloading %s player %s' % (player_type, player_id),
e0df6211 437 errnote=u'Download of %s failed' % player_url)
83799698 438 res = self._parse_sig_js(code)
c4417ddb 439 elif player_type == 'swf':
e0df6211
PH
440 urlh = self._request_webpage(
441 player_url, video_id,
83799698 442 note=u'Downloading %s player %s' % (player_type, player_id),
e0df6211
PH
443 errnote=u'Download of %s failed' % player_url)
444 code = urlh.read()
83799698 445 res = self._parse_sig_swf(code)
e0df6211
PH
446 else:
447 assert False, 'Invalid player type %r' % player_type
448
a0e07d31
PH
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]
83799698 453
a0e07d31 454 self._downloader.cache.store(u'youtube-sigfuncs', func_id, cache_spec)
83799698
PH
455 return res
456
60064c53 457 def _print_sig_code(self, func, example_sig):
edf3e38e
PH
458 def gen_sig_code(idxs):
459 def _genslice(start, end, step):
460 starts = u'' if start == 0 else str(start)
e35e4ddc
PH
461 ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
462 steps = u'' if step == 1 else (u':%d' % step)
edf3e38e
PH
463 return u's[%s%s%s]' % (starts, ends, steps)
464
465 step = None
0ca96d48
PH
466 start = '(Never used)' # Quelch pyflakes warnings - start will be
467 # set as soon as step is set
edf3e38e
PH
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
60064c53 486 test_string = u''.join(map(compat_chr, range(len(example_sig))))
c705320f 487 cache_res = func(test_string)
edf3e38e
PH
488 cache_spec = [ord(c) for c in cache_res]
489 expr_code = u' + '.join(gen_sig_code(cache_spec))
60064c53
PH
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)
f8061589 494 self.to_screen(u'Extracted signature function:\n' + code)
edf3e38e 495
e0df6211
PH
496 def _parse_sig_js(self, jscode):
497 funcname = self._search_regex(
c26e9ac4 498 r'signature=([$a-zA-Z]+)', jscode,
2b25cb5d
PH
499 u'Initial JS player signature function name')
500
501 jsi = JSInterpreter(jscode)
502 initial_function = jsi.extract_function(funcname)
e0df6211
PH
503 return lambda s: initial_function([s])
504
505 def _parse_sig_swf(self, file_contents):
54256267 506 swfi = SWFInterpreter(file_contents)
5dc3552d 507 TARGET_CLASSNAME = u'SignatureDecipher'
54256267
PH
508 searched_class = swfi.extract_class(TARGET_CLASSNAME)
509 initial_function = swfi.extract_function(searched_class, u'decipher')
e0df6211
PH
510 return lambda s: initial_function([s])
511
83799698 512 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
257a2501 513 """Turn the encrypted s field into a working signature"""
6b37f0be 514
c8bf86d5
PH
515 if player_url is None:
516 raise ExtractorError(u'Cannot decrypt signature without player_url')
920de7a2 517
c8bf86d5
PH
518 if player_url.startswith(u'//'):
519 player_url = u'https:' + player_url
520 try:
62af3a0e 521 player_id = (player_url, self._signature_cache_id(s))
c8bf86d5
PH
522 if player_id not in self._player_cache:
523 func = self._extract_signature_function(
60064c53 524 video_id, player_url, s
c8bf86d5
PH
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'):
60064c53 529 self._print_sig_code(func, s)
c8bf86d5
PH
530 return func(s)
531 except Exception as e:
532 tb = traceback.format_exc()
533 raise ExtractorError(
60064c53 534 u'Signature extraction failed: ' + tb, cause=e)
e0df6211 535
1f343eaa 536 def _get_available_subtitles(self, video_id, webpage):
de7f3446 537 try:
7fad1c63 538 sub_list = self._download_webpage(
38c2e5b8 539 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
7fad1c63
JMF
540 video_id, note=False)
541 except ExtractorError as err:
de7f3446
JMF
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]
7e660ac1
LD
549 if lang in sub_lang_list:
550 continue
de7f3446
JMF
551 params = compat_urllib_parse.urlencode({
552 'lang': lang,
553 'v': video_id,
ca715127 554 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
c3197e3e 555 'name': unescapeHTML(l[0]).encode('utf-8'),
de7f3446 556 })
38c2e5b8 557 url = u'https://www.youtube.com/api/timedtext?' + params
de7f3446
JMF
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
055e6f36 564 def _get_available_automatic_caption(self, video_id, webpage):
de7f3446
JMF
565 """We need the webpage for getting the captions url, pass it as an
566 argument to speed up the process."""
ca715127 567 sub_format = self._downloader.params.get('subtitlesformat', 'srt')
de7f3446
JMF
568 self.to_screen(u'%s: Looking for automatic captions' % video_id)
569 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
055e6f36 570 err_msg = u'Couldn\'t find automatic captions for %s' % video_id
de7f3446
JMF
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']
055e6f36
JMF
579 # We get the available subtitles
580 list_params = compat_urllib_parse.urlencode({
581 'type': 'list',
582 'tlangs': 1,
583 'asrs': 1,
de7f3446 584 })
055e6f36 585 list_url = caption_url + '&' + list_params
e26f8712 586 caption_list = self._download_xml(list_url, video_id)
e3dc22ca 587 original_lang_node = caption_list.find('track')
f6a54188 588 if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
e3dc22ca
JMF
589 self._downloader.report_warning(u'Video doesn\'t have automatic captions')
590 return {}
591 original_lang = original_lang_node.attrib['lang_code']
055e6f36
JMF
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
de7f3446
JMF
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
97665381
PH
611 @classmethod
612 def extract_id(cls, url):
613 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
c5e8d7af
PH
614 if mobj is None:
615 raise ExtractorError(u'Invalid URL: %s' % url)
616 video_id = mobj.group(2)
617 return video_id
618
1d043b93
JMF
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:
890f62e8 629 itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
1d043b93
JMF
630 url_map[itag] = format_url
631 return url_map
632
1fb07d10
JG
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
c5e8d7af 637 def _real_extract(self, url):
7e8c0af0
PH
638 proto = (
639 u'http' if self._downloader.params.get('prefer_insecure', False)
640 else u'https')
641
c5e8d7af
PH
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:
7e8c0af0 645 url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
97665381 646 video_id = self.extract_id(url)
c5e8d7af
PH
647
648 # Get video webpage
7e8c0af0 649 url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
336c3a69 650 video_webpage = self._download_webpage(url, video_id)
c5e8d7af
PH
651
652 # Attempt to extract SWF player URL
e0df6211 653 mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
c5e8d7af
PH
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)
c108eb73
JMF
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
2c57c7fa
JMF
666 data = compat_urllib_parse.urlencode({
667 'video_id': video_id,
668 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
c084c934
JMF
669 'sts': self._search_regex(
670 r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
2c57c7fa 671 })
7e8c0af0 672 video_info_url = proto + '://www.youtube.com/get_video_info?' + data
c5e8d7af
PH
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)
c108eb73
JMF
677 else:
678 age_gate = False
679 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
7e8c0af0 680 video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
c108eb73
JMF
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
c5e8d7af
PH
688 if 'token' not in video_info:
689 if 'reason' in video_info:
d11271dd
PH
690 raise ExtractorError(
691 u'YouTube said: %s' % video_info['reason'][0],
692 expected=True, video_id=video_id)
c5e8d7af 693 else:
d11271dd
PH
694 raise ExtractorError(
695 u'"token" parameter not in video info for unknown reason',
696 video_id=video_id)
c5e8d7af 697
1d699755
PH
698 if 'view_count' in video_info:
699 view_count = int(video_info['view_count'][0])
700 else:
701 view_count = None
702
c5e8d7af
PH
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
a8c6b241 724 if 'title' in video_info:
aa92f063 725 video_title = video_info['title'][0]
a8c6b241
PH
726 else:
727 self._downloader.report_warning(u'Unable to extract video title')
728 video_title = u'_'
c5e8d7af
PH
729
730 # thumbnail image
7763b04e
JMF
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:
c5e8d7af 737 self._downloader.report_warning(u'unable to extract video thumbnail')
f490e77e 738 video_thumbnail = None
c5e8d7af
PH
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
ad3bc6ac 744 mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
beee53de
PH
745 if mobj is None:
746 mobj = re.search(
263bd4ec 747 r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
beee53de 748 video_webpage)
c5e8d7af
PH
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
55f7bd2d
PH
753 m_cat_container = self._search_regex(
754 r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
755 video_webpage, 'categories', fatal=False)
ec8deefc 756 if m_cat_container:
ad3bc6ac 757 category = self._html_search_regex(
01ed5c9b 758 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
ad3bc6ac
PH
759 default=None)
760 video_categories = None if category is None else [category]
761 else:
762 video_categories = None
ec8deefc 763
c5e8d7af
PH
764 # description
765 video_description = get_element_by_id("eow-description", video_webpage)
766 if video_description:
27dcce19
PH
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)
c5e8d7af
PH
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
f30a38be 784 def _extract_count(count_name):
46374a56 785 count = self._search_regex(
f30a38be
JMF
786 r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
787 video_webpage, count_name, default=None)
336c3a69
JMF
788 if count is not None:
789 return int(count.replace(',', ''))
790 return None
f30a38be
JMF
791 like_count = _extract_count(u'like')
792 dislike_count = _extract_count(u'dislike')
336c3a69 793
c5e8d7af 794 # subtitles
d82134c3 795 video_subtitles = self.extract_subtitles(video_id, video_webpage)
c5e8d7af 796
c5e8d7af 797 if self._downloader.params.get('listsubtitles', False):
d665f8d3 798 self._list_available_subtitles(video_id, video_webpage)
c5e8d7af
PH
799 return
800
801 if 'length_seconds' not in video_info:
802 self._downloader.report_warning(u'unable to extract video duration')
b466b702 803 video_duration = None
c5e8d7af 804 else:
b466b702 805 video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
c5e8d7af 806
1fb07d10
JG
807 # annotations
808 video_annotations = None
809 if self._downloader.params.get('writeannotations', False):
810 video_annotations = self._extract_annotations(video_id)
811
c5e8d7af 812 # Decide which formats to download
c5e8d7af 813 try:
ae7ed920 814 mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
50be92c1
PH
815 if not mobj:
816 raise ValueError('Could not find vevo ID')
ae7ed920
PH
817 json_code = uppercase_escape(mobj.group(1))
818 ytplayer_config = json.loads(json_code)
3489b7d2 819 args = ytplayer_config['args']
7ce7e394
JMF
820 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
821 # this signatures are encrypted
44d46655 822 if 'url_encoded_fmt_stream_map' not in args:
f10503db 823 raise ValueError(u'No stream_map present') # caught below
00fe14fc
JMF
824 re_signature = re.compile(r'[&,]s=')
825 m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
7ce7e394
JMF
826 if m_s is not None:
827 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
c5e8d7af 828 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
00fe14fc 829 m_s = re_signature.search(args.get('adaptive_fmts', u''))
b7a68384 830 if m_s is not None:
00fe14fc
JMF
831 if 'adaptive_fmts' in video_info:
832 video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
37b6d5f6 833 else:
00fe14fc 834 video_info['adaptive_fmts'] = [args['adaptive_fmts']]
c5e8d7af
PH
835 except ValueError:
836 pass
837
dd27fd17
PH
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 }
0b65e5d4
PH
846 if itag in self._formats:
847 dct.update(self._formats[itag])
dd27fd17
PH
848 formats.append(dct)
849 return formats
850
c5e8d7af
PH
851 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
852 self.report_rtmp_download()
dd27fd17
PH
853 formats = [{
854 'format_id': '_rtmp',
855 'protocol': 'rtmp',
856 'url': video_info['conn'][0],
857 'player_url': player_url,
858 }]
00fe14fc
JMF
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:
a7055eb9 862 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
c5e8d7af 863 url_map = {}
00fe14fc 864 for url_data_str in encoded_url_map.split(','):
c5e8d7af 865 url_data = compat_parse_qs(url_data_str)
201e9eaa
PH
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'):
cf010131 888 if player_url is None:
201e9eaa
PH
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
cf010131 897 else:
201e9eaa
PH
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
60064c53 904 parts_sizes = self._signature_cache_id(encrypted_sig)
98eb1c3f
PH
905 self.to_screen(u'{%s} signature length %s, %s' %
906 (format_id, parts_sizes, player_desc))
201e9eaa
PH
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
dd27fd17 914 formats = _map_to_format_list(url_map)
1d043b93
JMF
915 elif video_info.get('hlsvp'):
916 manifest_url = video_info['hlsvp'][0]
917 url_map = self._extract_from_m3u8(manifest_url, video_id)
dd27fd17 918 formats = _map_to_format_list(url_map)
c5e8d7af 919 else:
9abb3204 920 raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
c5e8d7af 921
dd27fd17 922 # Look for the DASH manifest
d68f0cdb 923 if (self._downloader.params.get('youtube_include_dash_manifest', False)):
dd27fd17 924 try:
d68f0cdb 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:
3489b7d2 931 dash_manifest_url = video_info.get('dashmpd')[0]
d68f0cdb 932 else:
3489b7d2 933 dash_manifest_url = ytplayer_config['args']['dashmpd']
d68f0cdb 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)
dd27fd17 939 dash_doc = self._download_xml(
d68f0cdb 940 dash_manifest_url, video_id,
dd27fd17
PH
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)
d80044c2 970
4bcc7bd1 971 self._sort_formats(formats)
4ea3be0a 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,
ec8deefc 981 'categories': video_categories,
4ea3be0a 982 'subtitles': video_subtitles,
983 'duration': video_duration,
984 'age_limit': 18 if age_gate else 0,
985 'annotations': video_annotations,
7e8c0af0 986 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
4ea3be0a 987 'view_count': view_count,
988 'like_count': like_count,
989 'dislike_count': dislike_count,
990 'formats': formats,
991 }
c5e8d7af 992
880e1c52 993class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
0f818663 994 IE_DESC = u'YouTube.com playlists'
d67cc9fa 995 _VALID_URL = r"""(?x)(?:
c5e8d7af
PH
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 )
d67cc9fa 1004 (
7d568f5a 1005 (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
d67cc9fa
JMF
1006 # Top tracks, they can also include dots
1007 |(?:MC)[\w\.]*
1008 )
c5e8d7af
PH
1009 .*
1010 |
7d568f5a 1011 ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
c5e8d7af 1012 )"""
dbb94fb0 1013 _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
dcbb4580 1014 _MORE_PAGES_INDICATOR = r'data-link-type="next"'
dbb94fb0 1015 _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
c5e8d7af 1016 IE_NAME = u'youtube:playlist'
81127aa5
PH
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,
9291475f
PH
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,
81127aa5 1056 }]
c5e8d7af 1057
880e1c52
JMF
1058 def _real_initialize(self):
1059 self._login()
1060
652cdaa2 1061 def _ids_to_results(self, ids):
c9cc0bf5
PH
1062 return [
1063 self.url_result(vid_id, 'Youtube', video_id=vid_id)
1064 for vid_id in ids]
652cdaa2
JMF
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
7d4afc55 1069 url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
c9cc0bf5
PH
1070 webpage = self._download_webpage(
1071 url, playlist_id, u'Downloading Youtube mix')
bc2f773b 1072 search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
c9cc0bf5
PH
1073 title_span = (
1074 search_title('playlist-title') or
1075 search_title('title long-title') or
1076 search_title('title'))
76d1700b 1077 title = clean_html(title_span)
c9cc0bf5
PH
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))
652cdaa2
JMF
1082 url_results = self._ids_to_results(ids)
1083
1084 return self.playlist_result(url_results, playlist_id, title)
1085
c5e8d7af
PH
1086 def _real_extract(self, url):
1087 # Extract playlist id
d67cc9fa 1088 mobj = re.match(self._VALID_URL, url)
c5e8d7af
PH
1089 if mobj is None:
1090 raise ExtractorError(u'Invalid URL: %s' % url)
47192f92
FV
1091 playlist_id = mobj.group(1) or mobj.group(2)
1092
1093 # Check if it's a video-specific URL
7c61bd36 1094 query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
47192f92
FV
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)
7012b23c 1099 return self.url_result(video_id, 'Youtube', video_id=video_id)
47192f92 1100 else:
1db26669 1101 self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
c5e8d7af 1102
7d4afc55 1103 if playlist_id.startswith('RD'):
652cdaa2
JMF
1104 # Mixes require a custom extraction process
1105 return self._extract_mix(playlist_id)
0a688bc0
JMF
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)
652cdaa2 1109
dbb94fb0
S
1110 url = self._TEMPLATE_URL % playlist_id
1111 page = self._download_webpage(url, playlist_id)
1112 more_widget_html = content_html = page
1113
10c0e2d8 1114 # Check if the playlist exists or is private
e399853d 1115 if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
10c0e2d8
JMF
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
dcbb4580
JMF
1121 # Extract the video ids from the playlist pages
1122 ids = []
c5e8d7af 1123
755eb032 1124 for page_num in itertools.count(1):
dbb94fb0 1125 matches = re.finditer(self._VIDEO_RE, content_html)
6e47b51e
JMF
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')
dcbb4580 1129 ids.extend(new_ids)
c5e8d7af 1130
dbb94fb0
S
1131 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
1132 if not mobj:
c5e8d7af
PH
1133 break
1134
dbb94fb0 1135 more = self._download_json(
5912c639
PH
1136 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
1137 'Downloading page #%s' % page_num,
1138 transform_source=uppercase_escape)
dbb94fb0
S
1139 content_html = more['content_html']
1140 more_widget_html = more['load_more_widget_html']
1141
1142 playlist_title = self._html_search_regex(
68eb8e90
PH
1143 r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
1144 page, u'title')
c5e8d7af 1145
652cdaa2 1146 url_results = self._ids_to_results(ids)
dcbb4580 1147 return self.playlist_result(url_results, playlist_id, playlist_title)
c5e8d7af
PH
1148
1149
0a688bc0
JMF
1150class 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>.*?)$'
81127aa5 1155 _TESTS = []
0a688bc0
JMF
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})
beddbc2a 1162 playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query)
0a688bc0
JMF
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
c9cc0bf5 1175
0a688bc0
JMF
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
c5e8d7af 1184class YoutubeChannelIE(InfoExtractor):
0f818663 1185 IE_DESC = u'YouTube.com channels'
c5e8d7af 1186 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
c5e8d7af 1187 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
38c2e5b8 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'
c5e8d7af
PH
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 = []
b9643eed
JMF
1207 url = 'https://www.youtube.com/channel/%s/videos' % channel_id
1208 channel_page = self._download_webpage(url, channel_id)
31812a9e
PH
1209 autogenerated = re.search(r'''(?x)
1210 class="[^"]*?(?:
1211 channel-header-autogenerated-label|
1212 yt-channel-title-autogenerated
1213 )[^"]*"''', channel_page) is not None
c5e8d7af 1214
b9643eed
JMF
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)
81c2f20b
PH
1223 page = self._download_json(
1224 url, channel_id, note=u'Downloading page #%s' % pagenum,
1225 transform_source=uppercase_escape)
1226
b9643eed
JMF
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
c5e8d7af
PH
1232
1233 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1234
7012b23c
PH
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)
c5e8d7af
PH
1238
1239
1240class YoutubeUserIE(InfoExtractor):
0f818663 1241 IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
c9ae7b95 1242 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
38c2e5b8 1243 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
c5e8d7af 1244 _GDATA_PAGE_SIZE = 50
38c2e5b8 1245 _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
c5e8d7af
PH
1246 IE_NAME = u'youtube:user'
1247
e3ea4790 1248 @classmethod
f4b05232 1249 def suitable(cls, url):
e3ea4790
JMF
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
f4b05232
JMF
1254 else: return super(YoutubeUserIE, cls).suitable(url)
1255
c5e8d7af
PH
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
b7ab0590 1269 def download_page(pagenum):
c5e8d7af
PH
1270 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1271
1272 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
b7ab0590
PH
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))
c5e8d7af 1277
fd9cf738
JMF
1278 try:
1279 response = json.loads(page)
1280 except ValueError as err:
1281 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
71c82637 1282 if 'entry' not in response['feed']:
b7ab0590 1283 return
fd9cf738 1284
c5e8d7af 1285 # Extract video identifiers
e302f9ce
PH
1286 entries = response['feed']['entry']
1287 for entry in entries:
1288 title = entry['title']['$t']
1289 video_id = entry['id']['$t'].split('/')[-1]
b7ab0590 1290 yield {
e302f9ce
PH
1291 '_type': 'url',
1292 'url': video_id,
1293 'ie_key': 'Youtube',
b11cec41 1294 'id': video_id,
e302f9ce 1295 'title': title,
b7ab0590
PH
1296 }
1297 url_results = PagedList(download_page, self._GDATA_PAGE_SIZE)
c5e8d7af 1298
7012b23c
PH
1299 return self.playlist_result(url_results, playlist_title=username)
1300
b05654f0
PH
1301
1302class YoutubeSearchIE(SearchInfoExtractor):
0f818663 1303 IE_DESC = u'YouTube.com searches'
83d548ef 1304 _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
b05654f0
PH
1305 _MAX_RESULTS = 1000
1306 IE_NAME = u'youtube:search'
1307 _SEARCH_KEY = 'ytsearch'
1308
b05654f0
PH
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
83d548ef 1315 PAGE_SIZE = 50
b05654f0 1316
83d548ef
PH
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)
7cc3570e
PH
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:
07ad22b8
PH
1329 raise ExtractorError(
1330 u'[youtube] No video results', expected=True)
b05654f0
PH
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]
7012b23c
PH
1340 videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
1341 for video_id in video_ids]
b05654f0 1342 return self.playlist_result(videos, query)
75dff0ee 1343
c9ae7b95 1344
a3dd9248 1345class YoutubeSearchDateIE(YoutubeSearchIE):
cb7fb546 1346 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
a3dd9248
CM
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'
08fb86c4 1349 IE_DESC = u'YouTube.com searches, newest videos first'
75dff0ee 1350
c9ae7b95
PH
1351
1352class 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(
6feb2d5e 1363 r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML')
c9ae7b95
PH
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(
6feb2d5e 1370 [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
c9ae7b95
PH
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
75dff0ee 1388class YoutubeShowIE(InfoExtractor):
0f818663 1389 IE_DESC = u'YouTube.com (multi-season) shows'
75dff0ee
JMF
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]
04cc9617
JMF
1401
1402
b2e8bc1b 1403class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
d7ae0639
JMF
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 """
b2e8bc1b 1409 _LOGIN_REQUIRED = True
43ba5456
JMF
1410 # use action_load_personal_feed instead of action_load_system_feed
1411 _PERSONAL_FEED = False
04cc9617 1412
d7ae0639
JMF
1413 @property
1414 def _FEED_TEMPLATE(self):
43ba5456
JMF
1415 action = 'action_load_system_feed'
1416 if self._PERSONAL_FEED:
1417 action = 'action_load_personal_feed'
38c2e5b8 1418 return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
d7ae0639
JMF
1419
1420 @property
1421 def IE_NAME(self):
1422 return u'youtube:%s' % self._FEED_NAME
04cc9617 1423
81f0259b 1424 def _real_initialize(self):
b2e8bc1b 1425 self._login()
81f0259b 1426
04cc9617
JMF
1427 def _real_extract(self, url):
1428 feed_entries = []
0e44d838
JMF
1429 paging = 0
1430 for i in itertools.count(1):
f6177462 1431 info = self._download_json(self._FEED_TEMPLATE % paging,
d7ae0639 1432 u'%s feed' % self._FEED_NAME,
04cc9617 1433 u'Downloading page %s' % i)
f6177462 1434 feed_html = info.get('feed_html') or info.get('content_html')
1a9b9649 1435 load_more_widget_html = info.get('load_more_widget_html') or feed_html
43ba5456 1436 m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
04cc9617 1437 ids = orderedSet(m.group(1) for m in m_ids)
7012b23c
PH
1438 feed_entries.extend(
1439 self.url_result(video_id, 'Youtube', video_id=video_id)
1440 for video_id in ids)
05ee2b6d
JMF
1441 mobj = re.search(
1442 r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
1a9b9649 1443 load_more_widget_html)
05ee2b6d 1444 if mobj is None:
04cc9617 1445 break
05ee2b6d 1446 paging = mobj.group('paging')
d7ae0639
JMF
1447 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1448
d7ae0639
JMF
1449class 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'
c626a3d9 1454
43ba5456
JMF
1455class 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'
43ba5456 1460 _PERSONAL_FEED = True
c626a3d9 1461
f459d170
JMF
1462class 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
c626a3d9
JMF
1469class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1470 IE_NAME = u'youtube:favorites'
1471 IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
c7a7750d 1472 _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
c626a3d9
JMF
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')
15870e90
PH
1479
1480
1ed5b5c9
JMF
1481class 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)?'
81127aa5 1485 _TESTS = []
1ed5b5c9
JMF
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
15870e90
PH
1519class YoutubeTruncatedURLIE(InfoExtractor):
1520 IE_NAME = 'youtube:truncated_url'
1521 IE_DESC = False # Do not list
975d35db 1522 _VALID_URL = r'''(?x)
c4808c60
PH
1523 (?:https?://)?[^/]+/watch\?(?:
1524 feature=[a-z_]+|
1525 annotation_id=annotation_[^&]+
1526 )?$|
975d35db
PH
1527 (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
1528 '''
15870e90 1529
c4808c60
PH
1530 _TESTS = [{
1531 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
1532 'only_matching': True,
dc2fc736
PH
1533 }, {
1534 'url': 'http://www.youtube.com/watch?',
1535 'only_matching': True,
c4808c60
PH
1536 }]
1537
15870e90
PH
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 '
b4622a32
PH
1543 u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
1544 u' or simply youtube-dl BaW_jenozKc .',
15870e90 1545 expected=True)