]>
Commit | Line | Data |
---|---|---|
c5e8d7af | 1 | # coding: utf-8 |
c5e8d7af | 2 | |
0ca96d48 | 3 | import itertools |
c5e8d7af | 4 | import json |
c4417ddb | 5 | import os.path |
c5e8d7af | 6 | import re |
e0df6211 | 7 | import traceback |
c5e8d7af | 8 | |
b05654f0 | 9 | from .common import InfoExtractor, SearchInfoExtractor |
54d39d8b | 10 | from .subtitles import SubtitlesInfoExtractor |
2b25cb5d | 11 | from ..jsinterp import JSInterpreter |
54256267 | 12 | from ..swfinterp import SWFInterpreter |
c5e8d7af | 13 | from ..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 | 33 | class 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 | 198 | class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor): |
0f818663 | 199 | IE_DESC = u'YouTube.com' |
cb7dfeea | 200 | _VALID_URL = r"""(?x)^ |
c5e8d7af | 201 | ( |
83aa5293 | 202 | (?:https?://|//)? # http(s):// or protocol-independent URL (optional) |
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 | |
b9c76aa1 | 220 | |https?://(?: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 |
c5e8d7af PH |
224 | (?(1).+)? # if we found the ID, everything can follow |
225 | $""" | |
c5e8d7af | 226 | _NEXT_URL_RE = r'[\?&]next_url=([^&]+)' |
2c62dc26 PH |
227 | _formats = { |
228 | '5': {'ext': 'flv', 'width': 400, 'height': 240}, | |
229 | '6': {'ext': 'flv', 'width': 450, 'height': 270}, | |
230 | '13': {'ext': '3gp'}, | |
231 | '17': {'ext': '3gp', 'width': 176, 'height': 144}, | |
232 | '18': {'ext': 'mp4', 'width': 640, 'height': 360}, | |
233 | '22': {'ext': 'mp4', 'width': 1280, 'height': 720}, | |
234 | '34': {'ext': 'flv', 'width': 640, 'height': 360}, | |
235 | '35': {'ext': 'flv', 'width': 854, 'height': 480}, | |
236 | '36': {'ext': '3gp', 'width': 320, 'height': 240}, | |
237 | '37': {'ext': 'mp4', 'width': 1920, 'height': 1080}, | |
238 | '38': {'ext': 'mp4', 'width': 4096, 'height': 3072}, | |
239 | '43': {'ext': 'webm', 'width': 640, 'height': 360}, | |
240 | '44': {'ext': 'webm', 'width': 854, 'height': 480}, | |
241 | '45': {'ext': 'webm', 'width': 1280, 'height': 720}, | |
242 | '46': {'ext': 'webm', 'width': 1920, 'height': 1080}, | |
243 | ||
1d043b93 | 244 | |
86fe61c8 | 245 | # 3d videos |
43b81eb9 PH |
246 | '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20}, |
247 | '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20}, | |
248 | '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20}, | |
249 | '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20}, | |
250 | '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20}, | |
251 | '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20}, | |
252 | '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20}, | |
836a086c | 253 | |
96fb5605 | 254 | # Apple HTTP Live Streaming |
43b81eb9 PH |
255 | '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10}, |
256 | '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10}, | |
257 | '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10}, | |
258 | '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10}, | |
259 | '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10}, | |
260 | '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10}, | |
261 | '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10}, | |
2c62dc26 PH |
262 | |
263 | # DASH mp4 video | |
43b81eb9 PH |
264 | '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, |
265 | '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
266 | '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
267 | '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
268 | '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
269 | '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
270 | '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
271 | '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
836a086c | 272 | |
f6f1fc92 | 273 | # Dash mp4 audio |
2c62dc26 PH |
274 | '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50}, |
275 | '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50}, | |
276 | '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50}, | |
836a086c AZ |
277 | |
278 | # Dash webm | |
e75cafe9 A |
279 | '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, |
280 | '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, | |
281 | '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, | |
282 | '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, | |
283 | '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, | |
284 | '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40}, | |
285 | '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
286 | '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
287 | '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
288 | '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
289 | '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
290 | '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
291 | '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, | |
3c80377b | 292 | '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, |
18061bba | 293 | '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, |
2c62dc26 PH |
294 | |
295 | # Dash webm audio | |
55db73ef | 296 | '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50}, |
e75cafe9 | 297 | '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50}, |
ce6b9a2d PH |
298 | |
299 | # RTMP (unnamed) | |
300 | '_rtmp': {'protocol': 'rtmp'}, | |
c5e8d7af | 301 | } |
836a086c | 302 | |
c5e8d7af | 303 | IE_NAME = u'youtube' |
2eb88d95 PH |
304 | _TESTS = [ |
305 | { | |
0e853ca4 PH |
306 | u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc", |
307 | u"file": u"BaW_jenozKc.mp4", | |
308 | u"info_dict": { | |
309 | u"title": u"youtube-dl test video \"'/\\ä↭𝕐", | |
310 | u"uploader": u"Philipp Hagemeister", | |
311 | u"uploader_id": u"phihag", | |
312 | u"upload_date": u"20121002", | |
ad3bc6ac PH |
313 | 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 .", |
314 | u"categories": [u'Science & Technology'], | |
3e7c1224 PH |
315 | 'like_count': int, |
316 | 'dislike_count': int, | |
2eb88d95 | 317 | } |
0e853ca4 | 318 | }, |
0e853ca4 PH |
319 | { |
320 | u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY", | |
321 | u"file": u"UxxajLWwzqY.mp4", | |
322 | u"note": u"Test generic use_cipher_signature video (#897)", | |
323 | u"info_dict": { | |
324 | u"upload_date": u"20120506", | |
325 | u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]", | |
ba60a3eb | 326 | u"description": u"md5:fea86fda2d5a5784273df5c7cc994d9f", |
45ed795c | 327 | u"uploader": u"Icona Pop", |
0e853ca4 | 328 | u"uploader_id": u"IconaPop" |
2eb88d95 | 329 | } |
c108eb73 JMF |
330 | }, |
331 | { | |
332 | u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ", | |
333 | u"file": u"07FYdnEawAQ.mp4", | |
334 | u"note": u"Test VEVO video with age protection (#956)", | |
335 | u"info_dict": { | |
336 | u"upload_date": u"20130703", | |
337 | u"title": u"Justin Timberlake - Tunnel Vision (Explicit)", | |
338 | u"description": u"md5:64249768eec3bc4276236606ea996373", | |
339 | u"uploader": u"justintimberlakeVEVO", | |
340 | u"uploader_id": u"justintimberlakeVEVO" | |
341 | } | |
342 | }, | |
fccd3771 | 343 | { |
83aa5293 | 344 | u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ", |
fccd3771 PH |
345 | u"file": u"yZIXLfi8CZQ.mp4", |
346 | u"note": u"Embed-only video (#1746)", | |
347 | u"info_dict": { | |
348 | u"upload_date": u"20120608", | |
349 | u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012", | |
350 | u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7", | |
351 | u"uploader": u"SET India", | |
352 | u"uploader_id": u"setindia" | |
353 | } | |
354 | }, | |
dd27fd17 PH |
355 | { |
356 | u"url": u"http://www.youtube.com/watch?v=a9LDPn-MO4I", | |
357 | u"file": u"a9LDPn-MO4I.m4a", | |
358 | u"note": u"256k DASH audio (format 141) via DASH manifest", | |
dd27fd17 PH |
359 | u"info_dict": { |
360 | u"upload_date": "20121002", | |
361 | u"uploader_id": "8KVIDEO", | |
362 | u"description": "No description available.", | |
363 | u"uploader": "8KVIDEO", | |
364 | u"title": "UHDTV TEST 8K VIDEO.mp4" | |
4919603f PH |
365 | }, |
366 | u"params": { | |
367 | u"youtube_include_dash_manifest": True, | |
368 | u"format": "141", | |
369 | }, | |
dd27fd17 | 370 | }, |
3489b7d2 JMF |
371 | # DASH manifest with encrypted signature |
372 | { | |
373 | u'url': u'https://www.youtube.com/watch?v=IB3lcPjvWLA', | |
374 | u'info_dict': { | |
375 | u'id': u'IB3lcPjvWLA', | |
376 | u'ext': u'm4a', | |
377 | u'title': u'Afrojack - The Spark ft. Spree Wilson', | |
e00c9cf5 | 378 | u'description': u'md5:9717375db5a9a3992be4668bbf3bc0a8', |
3489b7d2 JMF |
379 | u'uploader': u'AfrojackVEVO', |
380 | u'uploader_id': u'AfrojackVEVO', | |
381 | u'upload_date': u'20131011', | |
382 | }, | |
383 | u"params": { | |
384 | u'youtube_include_dash_manifest': True, | |
385 | u'format': '141', | |
386 | }, | |
387 | }, | |
2eb88d95 PH |
388 | ] |
389 | ||
c5e8d7af PH |
390 | |
391 | @classmethod | |
392 | def suitable(cls, url): | |
393 | """Receives a URL and returns True if suitable for this IE.""" | |
e3ea4790 | 394 | if YoutubePlaylistIE.suitable(url): return False |
fccd3771 | 395 | return re.match(cls._VALID_URL, url) is not None |
c5e8d7af | 396 | |
e0df6211 PH |
397 | def __init__(self, *args, **kwargs): |
398 | super(YoutubeIE, self).__init__(*args, **kwargs) | |
83799698 | 399 | self._player_cache = {} |
e0df6211 | 400 | |
c5e8d7af PH |
401 | def report_video_info_webpage_download(self, video_id): |
402 | """Report attempt to download video info webpage.""" | |
403 | self.to_screen(u'%s: Downloading video info webpage' % video_id) | |
404 | ||
c5e8d7af PH |
405 | def report_information_extraction(self, video_id): |
406 | """Report attempt to extract video information.""" | |
407 | self.to_screen(u'%s: Extracting video information' % video_id) | |
408 | ||
409 | def report_unavailable_format(self, video_id, format): | |
410 | """Report extracted video URL.""" | |
411 | self.to_screen(u'%s: Format %s not available' % (video_id, format)) | |
412 | ||
413 | def report_rtmp_download(self): | |
414 | """Indicate the download will use the RTMP protocol.""" | |
415 | self.to_screen(u'RTMP download detected') | |
416 | ||
60064c53 PH |
417 | def _signature_cache_id(self, example_sig): |
418 | """ Return a string representation of a signature """ | |
419 | return u'.'.join(compat_str(len(part)) for part in example_sig.split('.')) | |
420 | ||
421 | def _extract_signature_function(self, video_id, player_url, example_sig): | |
cf010131 | 422 | id_m = re.match( |
c081b35c | 423 | r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$', |
cf010131 | 424 | player_url) |
c081b35c PH |
425 | if not id_m: |
426 | raise ExtractorError('Cannot identify player %r' % player_url) | |
e0df6211 PH |
427 | player_type = id_m.group('ext') |
428 | player_id = id_m.group('id') | |
429 | ||
c4417ddb | 430 | # Read from filesystem cache |
60064c53 PH |
431 | func_id = '%s_%s_%s' % ( |
432 | player_type, player_id, self._signature_cache_id(example_sig)) | |
c4417ddb | 433 | assert os.path.basename(func_id) == func_id |
a0e07d31 PH |
434 | |
435 | cache_spec = self._downloader.cache.load(u'youtube-sigfuncs', func_id) | |
436 | if cache_spec is not None: | |
437 | return lambda s: u''.join(s[i] for i in cache_spec) | |
83799698 | 438 | |
e0df6211 PH |
439 | if player_type == 'js': |
440 | code = self._download_webpage( | |
441 | player_url, video_id, | |
83799698 | 442 | note=u'Downloading %s player %s' % (player_type, player_id), |
e0df6211 | 443 | errnote=u'Download of %s failed' % player_url) |
83799698 | 444 | res = self._parse_sig_js(code) |
c4417ddb | 445 | elif player_type == 'swf': |
e0df6211 PH |
446 | urlh = self._request_webpage( |
447 | player_url, video_id, | |
83799698 | 448 | note=u'Downloading %s player %s' % (player_type, player_id), |
e0df6211 PH |
449 | errnote=u'Download of %s failed' % player_url) |
450 | code = urlh.read() | |
83799698 | 451 | res = self._parse_sig_swf(code) |
e0df6211 PH |
452 | else: |
453 | assert False, 'Invalid player type %r' % player_type | |
454 | ||
a0e07d31 PH |
455 | if cache_spec is None: |
456 | test_string = u''.join(map(compat_chr, range(len(example_sig)))) | |
457 | cache_res = res(test_string) | |
458 | cache_spec = [ord(c) for c in cache_res] | |
83799698 | 459 | |
a0e07d31 | 460 | self._downloader.cache.store(u'youtube-sigfuncs', func_id, cache_spec) |
83799698 PH |
461 | return res |
462 | ||
60064c53 | 463 | def _print_sig_code(self, func, example_sig): |
edf3e38e PH |
464 | def gen_sig_code(idxs): |
465 | def _genslice(start, end, step): | |
466 | starts = u'' if start == 0 else str(start) | |
e35e4ddc PH |
467 | ends = (u':%d' % (end+step)) if end + step >= 0 else u':' |
468 | steps = u'' if step == 1 else (u':%d' % step) | |
edf3e38e PH |
469 | return u's[%s%s%s]' % (starts, ends, steps) |
470 | ||
471 | step = None | |
0ca96d48 PH |
472 | start = '(Never used)' # Quelch pyflakes warnings - start will be |
473 | # set as soon as step is set | |
edf3e38e PH |
474 | for i, prev in zip(idxs[1:], idxs[:-1]): |
475 | if step is not None: | |
476 | if i - prev == step: | |
477 | continue | |
478 | yield _genslice(start, prev, step) | |
479 | step = None | |
480 | continue | |
481 | if i - prev in [-1, 1]: | |
482 | step = i - prev | |
483 | start = prev | |
484 | continue | |
485 | else: | |
486 | yield u's[%d]' % prev | |
487 | if step is None: | |
488 | yield u's[%d]' % i | |
489 | else: | |
490 | yield _genslice(start, i, step) | |
491 | ||
60064c53 | 492 | test_string = u''.join(map(compat_chr, range(len(example_sig)))) |
c705320f | 493 | cache_res = func(test_string) |
edf3e38e PH |
494 | cache_spec = [ord(c) for c in cache_res] |
495 | expr_code = u' + '.join(gen_sig_code(cache_spec)) | |
60064c53 PH |
496 | signature_id_tuple = '(%s)' % ( |
497 | ', '.join(compat_str(len(p)) for p in example_sig.split('.'))) | |
498 | code = (u'if tuple(len(p) for p in s.split(\'.\')) == %s:\n' | |
499 | u' return %s\n') % (signature_id_tuple, expr_code) | |
f8061589 | 500 | self.to_screen(u'Extracted signature function:\n' + code) |
edf3e38e | 501 | |
e0df6211 PH |
502 | def _parse_sig_js(self, jscode): |
503 | funcname = self._search_regex( | |
c26e9ac4 | 504 | r'signature=([$a-zA-Z]+)', jscode, |
2b25cb5d PH |
505 | u'Initial JS player signature function name') |
506 | ||
507 | jsi = JSInterpreter(jscode) | |
508 | initial_function = jsi.extract_function(funcname) | |
e0df6211 PH |
509 | return lambda s: initial_function([s]) |
510 | ||
511 | def _parse_sig_swf(self, file_contents): | |
54256267 | 512 | swfi = SWFInterpreter(file_contents) |
5dc3552d | 513 | TARGET_CLASSNAME = u'SignatureDecipher' |
54256267 PH |
514 | searched_class = swfi.extract_class(TARGET_CLASSNAME) |
515 | initial_function = swfi.extract_function(searched_class, u'decipher') | |
e0df6211 PH |
516 | return lambda s: initial_function([s]) |
517 | ||
83799698 | 518 | def _decrypt_signature(self, s, video_id, player_url, age_gate=False): |
257a2501 | 519 | """Turn the encrypted s field into a working signature""" |
6b37f0be | 520 | |
c8bf86d5 PH |
521 | if player_url is None: |
522 | raise ExtractorError(u'Cannot decrypt signature without player_url') | |
920de7a2 | 523 | |
c8bf86d5 PH |
524 | if player_url.startswith(u'//'): |
525 | player_url = u'https:' + player_url | |
526 | try: | |
62af3a0e | 527 | player_id = (player_url, self._signature_cache_id(s)) |
c8bf86d5 PH |
528 | if player_id not in self._player_cache: |
529 | func = self._extract_signature_function( | |
60064c53 | 530 | video_id, player_url, s |
c8bf86d5 PH |
531 | ) |
532 | self._player_cache[player_id] = func | |
533 | func = self._player_cache[player_id] | |
534 | if self._downloader.params.get('youtube_print_sig_code'): | |
60064c53 | 535 | self._print_sig_code(func, s) |
c8bf86d5 PH |
536 | return func(s) |
537 | except Exception as e: | |
538 | tb = traceback.format_exc() | |
539 | raise ExtractorError( | |
60064c53 | 540 | u'Signature extraction failed: ' + tb, cause=e) |
e0df6211 | 541 | |
1f343eaa | 542 | def _get_available_subtitles(self, video_id, webpage): |
de7f3446 | 543 | try: |
7fad1c63 | 544 | sub_list = self._download_webpage( |
38c2e5b8 | 545 | 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id, |
7fad1c63 JMF |
546 | video_id, note=False) |
547 | except ExtractorError as err: | |
de7f3446 JMF |
548 | self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err)) |
549 | return {} | |
550 | lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list) | |
551 | ||
552 | sub_lang_list = {} | |
553 | for l in lang_list: | |
554 | lang = l[1] | |
7e660ac1 LD |
555 | if lang in sub_lang_list: |
556 | continue | |
de7f3446 JMF |
557 | params = compat_urllib_parse.urlencode({ |
558 | 'lang': lang, | |
559 | 'v': video_id, | |
ca715127 | 560 | 'fmt': self._downloader.params.get('subtitlesformat', 'srt'), |
c3197e3e | 561 | 'name': unescapeHTML(l[0]).encode('utf-8'), |
de7f3446 | 562 | }) |
38c2e5b8 | 563 | url = u'https://www.youtube.com/api/timedtext?' + params |
de7f3446 JMF |
564 | sub_lang_list[lang] = url |
565 | if not sub_lang_list: | |
566 | self._downloader.report_warning(u'video doesn\'t have subtitles') | |
567 | return {} | |
568 | return sub_lang_list | |
569 | ||
055e6f36 | 570 | def _get_available_automatic_caption(self, video_id, webpage): |
de7f3446 JMF |
571 | """We need the webpage for getting the captions url, pass it as an |
572 | argument to speed up the process.""" | |
ca715127 | 573 | sub_format = self._downloader.params.get('subtitlesformat', 'srt') |
de7f3446 JMF |
574 | self.to_screen(u'%s: Looking for automatic captions' % video_id) |
575 | mobj = re.search(r';ytplayer.config = ({.*?});', webpage) | |
055e6f36 | 576 | err_msg = u'Couldn\'t find automatic captions for %s' % video_id |
de7f3446 JMF |
577 | if mobj is None: |
578 | self._downloader.report_warning(err_msg) | |
579 | return {} | |
580 | player_config = json.loads(mobj.group(1)) | |
581 | try: | |
582 | args = player_config[u'args'] | |
583 | caption_url = args[u'ttsurl'] | |
584 | timestamp = args[u'timestamp'] | |
055e6f36 JMF |
585 | # We get the available subtitles |
586 | list_params = compat_urllib_parse.urlencode({ | |
587 | 'type': 'list', | |
588 | 'tlangs': 1, | |
589 | 'asrs': 1, | |
de7f3446 | 590 | }) |
055e6f36 | 591 | list_url = caption_url + '&' + list_params |
e26f8712 | 592 | caption_list = self._download_xml(list_url, video_id) |
e3dc22ca | 593 | original_lang_node = caption_list.find('track') |
f6a54188 | 594 | if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' : |
e3dc22ca JMF |
595 | self._downloader.report_warning(u'Video doesn\'t have automatic captions') |
596 | return {} | |
597 | original_lang = original_lang_node.attrib['lang_code'] | |
055e6f36 JMF |
598 | |
599 | sub_lang_list = {} | |
600 | for lang_node in caption_list.findall('target'): | |
601 | sub_lang = lang_node.attrib['lang_code'] | |
602 | params = compat_urllib_parse.urlencode({ | |
603 | 'lang': original_lang, | |
604 | 'tlang': sub_lang, | |
605 | 'fmt': sub_format, | |
606 | 'ts': timestamp, | |
607 | 'kind': 'asr', | |
608 | }) | |
609 | sub_lang_list[sub_lang] = caption_url + '&' + params | |
610 | return sub_lang_list | |
de7f3446 JMF |
611 | # An extractor error can be raise by the download process if there are |
612 | # no automatic captions but there are subtitles | |
613 | except (KeyError, ExtractorError): | |
614 | self._downloader.report_warning(err_msg) | |
615 | return {} | |
616 | ||
97665381 PH |
617 | @classmethod |
618 | def extract_id(cls, url): | |
619 | mobj = re.match(cls._VALID_URL, url, re.VERBOSE) | |
c5e8d7af PH |
620 | if mobj is None: |
621 | raise ExtractorError(u'Invalid URL: %s' % url) | |
622 | video_id = mobj.group(2) | |
623 | return video_id | |
624 | ||
1d043b93 JMF |
625 | def _extract_from_m3u8(self, manifest_url, video_id): |
626 | url_map = {} | |
627 | def _get_urls(_manifest): | |
628 | lines = _manifest.split('\n') | |
629 | urls = filter(lambda l: l and not l.startswith('#'), | |
630 | lines) | |
631 | return urls | |
632 | manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest') | |
633 | formats_urls = _get_urls(manifest) | |
634 | for format_url in formats_urls: | |
890f62e8 | 635 | itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag') |
1d043b93 JMF |
636 | url_map[itag] = format_url |
637 | return url_map | |
638 | ||
1fb07d10 JG |
639 | def _extract_annotations(self, video_id): |
640 | url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id | |
641 | return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.') | |
642 | ||
c5e8d7af | 643 | def _real_extract(self, url): |
7e8c0af0 PH |
644 | proto = ( |
645 | u'http' if self._downloader.params.get('prefer_insecure', False) | |
646 | else u'https') | |
647 | ||
c5e8d7af PH |
648 | # Extract original video URL from URL with redirection, like age verification, using next_url parameter |
649 | mobj = re.search(self._NEXT_URL_RE, url) | |
650 | if mobj: | |
7e8c0af0 | 651 | url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/') |
97665381 | 652 | video_id = self.extract_id(url) |
c5e8d7af PH |
653 | |
654 | # Get video webpage | |
7e8c0af0 | 655 | url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id |
336c3a69 | 656 | video_webpage = self._download_webpage(url, video_id) |
c5e8d7af PH |
657 | |
658 | # Attempt to extract SWF player URL | |
e0df6211 | 659 | mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage) |
c5e8d7af PH |
660 | if mobj is not None: |
661 | player_url = re.sub(r'\\(.)', r'\1', mobj.group(1)) | |
662 | else: | |
663 | player_url = None | |
664 | ||
665 | # Get video info | |
666 | self.report_video_info_webpage_download(video_id) | |
c108eb73 JMF |
667 | if re.search(r'player-age-gate-content">', video_webpage) is not None: |
668 | self.report_age_confirmation() | |
669 | age_gate = True | |
670 | # We simulate the access to the video from www.youtube.com/v/{video_id} | |
671 | # this can be viewed without login into Youtube | |
2c57c7fa JMF |
672 | data = compat_urllib_parse.urlencode({ |
673 | 'video_id': video_id, | |
674 | 'eurl': 'https://youtube.googleapis.com/v/' + video_id, | |
c084c934 JMF |
675 | 'sts': self._search_regex( |
676 | r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'), | |
2c57c7fa | 677 | }) |
7e8c0af0 | 678 | video_info_url = proto + '://www.youtube.com/get_video_info?' + data |
c5e8d7af PH |
679 | video_info_webpage = self._download_webpage(video_info_url, video_id, |
680 | note=False, | |
681 | errnote='unable to download video info webpage') | |
682 | video_info = compat_parse_qs(video_info_webpage) | |
c108eb73 JMF |
683 | else: |
684 | age_gate = False | |
685 | for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']: | |
7e8c0af0 | 686 | video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en' |
c108eb73 JMF |
687 | % (video_id, el_type)) |
688 | video_info_webpage = self._download_webpage(video_info_url, video_id, | |
689 | note=False, | |
690 | errnote='unable to download video info webpage') | |
691 | video_info = compat_parse_qs(video_info_webpage) | |
692 | if 'token' in video_info: | |
693 | break | |
c5e8d7af PH |
694 | if 'token' not in video_info: |
695 | if 'reason' in video_info: | |
d11271dd PH |
696 | raise ExtractorError( |
697 | u'YouTube said: %s' % video_info['reason'][0], | |
698 | expected=True, video_id=video_id) | |
c5e8d7af | 699 | else: |
d11271dd PH |
700 | raise ExtractorError( |
701 | u'"token" parameter not in video info for unknown reason', | |
702 | video_id=video_id) | |
c5e8d7af | 703 | |
1d699755 PH |
704 | if 'view_count' in video_info: |
705 | view_count = int(video_info['view_count'][0]) | |
706 | else: | |
707 | view_count = None | |
708 | ||
c5e8d7af PH |
709 | # Check for "rental" videos |
710 | if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info: | |
711 | raise ExtractorError(u'"rental" videos not supported') | |
712 | ||
713 | # Start extracting information | |
714 | self.report_information_extraction(video_id) | |
715 | ||
716 | # uploader | |
717 | if 'author' not in video_info: | |
718 | raise ExtractorError(u'Unable to extract uploader name') | |
719 | video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0]) | |
720 | ||
721 | # uploader_id | |
722 | video_uploader_id = None | |
723 | mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage) | |
724 | if mobj is not None: | |
725 | video_uploader_id = mobj.group(1) | |
726 | else: | |
727 | self._downloader.report_warning(u'unable to extract uploader nickname') | |
728 | ||
729 | # title | |
a8c6b241 | 730 | if 'title' in video_info: |
aa92f063 | 731 | video_title = video_info['title'][0] |
a8c6b241 PH |
732 | else: |
733 | self._downloader.report_warning(u'Unable to extract video title') | |
734 | video_title = u'_' | |
c5e8d7af PH |
735 | |
736 | # thumbnail image | |
7763b04e JMF |
737 | # We try first to get a high quality image: |
738 | m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">', | |
739 | video_webpage, re.DOTALL) | |
740 | if m_thumb is not None: | |
741 | video_thumbnail = m_thumb.group(1) | |
742 | elif 'thumbnail_url' not in video_info: | |
c5e8d7af | 743 | self._downloader.report_warning(u'unable to extract video thumbnail') |
f490e77e | 744 | video_thumbnail = None |
c5e8d7af PH |
745 | else: # don't panic if we can't find it |
746 | video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0]) | |
747 | ||
748 | # upload date | |
749 | upload_date = None | |
ad3bc6ac | 750 | mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage) |
beee53de PH |
751 | if mobj is None: |
752 | mobj = re.search( | |
263bd4ec | 753 | r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>', |
beee53de | 754 | video_webpage) |
c5e8d7af PH |
755 | if mobj is not None: |
756 | upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split()) | |
757 | upload_date = unified_strdate(upload_date) | |
758 | ||
55f7bd2d PH |
759 | m_cat_container = self._search_regex( |
760 | r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>', | |
761 | video_webpage, 'categories', fatal=False) | |
ec8deefc | 762 | if m_cat_container: |
ad3bc6ac | 763 | category = self._html_search_regex( |
01ed5c9b | 764 | r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category', |
ad3bc6ac PH |
765 | default=None) |
766 | video_categories = None if category is None else [category] | |
767 | else: | |
768 | video_categories = None | |
ec8deefc | 769 | |
c5e8d7af PH |
770 | # description |
771 | video_description = get_element_by_id("eow-description", video_webpage) | |
772 | if video_description: | |
27dcce19 PH |
773 | video_description = re.sub(r'''(?x) |
774 | <a\s+ | |
775 | (?:[a-zA-Z-]+="[^"]+"\s+)*? | |
776 | title="([^"]+)"\s+ | |
777 | (?:[a-zA-Z-]+="[^"]+"\s+)*? | |
778 | class="yt-uix-redirect-link"\s*> | |
779 | [^<]+ | |
780 | </a> | |
781 | ''', r'\1', video_description) | |
c5e8d7af PH |
782 | video_description = clean_html(video_description) |
783 | else: | |
784 | fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage) | |
785 | if fd_mobj: | |
786 | video_description = unescapeHTML(fd_mobj.group(1)) | |
787 | else: | |
788 | video_description = u'' | |
789 | ||
f30a38be | 790 | def _extract_count(count_name): |
46374a56 | 791 | count = self._search_regex( |
f30a38be JMF |
792 | r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name), |
793 | video_webpage, count_name, default=None) | |
336c3a69 JMF |
794 | if count is not None: |
795 | return int(count.replace(',', '')) | |
796 | return None | |
f30a38be JMF |
797 | like_count = _extract_count(u'like') |
798 | dislike_count = _extract_count(u'dislike') | |
336c3a69 | 799 | |
c5e8d7af | 800 | # subtitles |
d82134c3 | 801 | video_subtitles = self.extract_subtitles(video_id, video_webpage) |
c5e8d7af | 802 | |
c5e8d7af | 803 | if self._downloader.params.get('listsubtitles', False): |
d665f8d3 | 804 | self._list_available_subtitles(video_id, video_webpage) |
c5e8d7af PH |
805 | return |
806 | ||
807 | if 'length_seconds' not in video_info: | |
808 | self._downloader.report_warning(u'unable to extract video duration') | |
b466b702 | 809 | video_duration = None |
c5e8d7af | 810 | else: |
b466b702 | 811 | video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])) |
c5e8d7af | 812 | |
1fb07d10 JG |
813 | # annotations |
814 | video_annotations = None | |
815 | if self._downloader.params.get('writeannotations', False): | |
816 | video_annotations = self._extract_annotations(video_id) | |
817 | ||
c5e8d7af | 818 | # Decide which formats to download |
c5e8d7af | 819 | try: |
ae7ed920 | 820 | mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage) |
50be92c1 PH |
821 | if not mobj: |
822 | raise ValueError('Could not find vevo ID') | |
ae7ed920 PH |
823 | json_code = uppercase_escape(mobj.group(1)) |
824 | ytplayer_config = json.loads(json_code) | |
3489b7d2 | 825 | args = ytplayer_config['args'] |
7ce7e394 JMF |
826 | # Easy way to know if the 's' value is in url_encoded_fmt_stream_map |
827 | # this signatures are encrypted | |
44d46655 | 828 | if 'url_encoded_fmt_stream_map' not in args: |
f10503db | 829 | raise ValueError(u'No stream_map present') # caught below |
00fe14fc JMF |
830 | re_signature = re.compile(r'[&,]s=') |
831 | m_s = re_signature.search(args['url_encoded_fmt_stream_map']) | |
7ce7e394 JMF |
832 | if m_s is not None: |
833 | self.to_screen(u'%s: Encrypted signatures detected.' % video_id) | |
c5e8d7af | 834 | video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']] |
00fe14fc | 835 | m_s = re_signature.search(args.get('adaptive_fmts', u'')) |
b7a68384 | 836 | if m_s is not None: |
00fe14fc JMF |
837 | if 'adaptive_fmts' in video_info: |
838 | video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts'] | |
37b6d5f6 | 839 | else: |
00fe14fc | 840 | video_info['adaptive_fmts'] = [args['adaptive_fmts']] |
c5e8d7af PH |
841 | except ValueError: |
842 | pass | |
843 | ||
dd27fd17 PH |
844 | def _map_to_format_list(urlmap): |
845 | formats = [] | |
846 | for itag, video_real_url in urlmap.items(): | |
847 | dct = { | |
848 | 'format_id': itag, | |
849 | 'url': video_real_url, | |
850 | 'player_url': player_url, | |
851 | } | |
0b65e5d4 PH |
852 | if itag in self._formats: |
853 | dct.update(self._formats[itag]) | |
dd27fd17 PH |
854 | formats.append(dct) |
855 | return formats | |
856 | ||
c5e8d7af PH |
857 | if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'): |
858 | self.report_rtmp_download() | |
dd27fd17 PH |
859 | formats = [{ |
860 | 'format_id': '_rtmp', | |
861 | 'protocol': 'rtmp', | |
862 | 'url': video_info['conn'][0], | |
863 | 'player_url': player_url, | |
864 | }] | |
00fe14fc JMF |
865 | elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1: |
866 | encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0] | |
867 | if 'rtmpe%3Dyes' in encoded_url_map: | |
a7055eb9 | 868 | raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True) |
c5e8d7af | 869 | url_map = {} |
00fe14fc | 870 | for url_data_str in encoded_url_map.split(','): |
c5e8d7af | 871 | url_data = compat_parse_qs(url_data_str) |
201e9eaa PH |
872 | if 'itag' not in url_data or 'url' not in url_data: |
873 | continue | |
874 | format_id = url_data['itag'][0] | |
875 | url = url_data['url'][0] | |
876 | ||
877 | if 'sig' in url_data: | |
878 | url += '&signature=' + url_data['sig'][0] | |
879 | elif 's' in url_data: | |
880 | encrypted_sig = url_data['s'][0] | |
881 | ||
882 | if not age_gate: | |
883 | jsplayer_url_json = self._search_regex( | |
884 | r'"assets":.+?"js":\s*("[^"]+")', | |
885 | video_webpage, u'JS player URL') | |
886 | player_url = json.loads(jsplayer_url_json) | |
887 | if player_url is None: | |
888 | player_url_json = self._search_regex( | |
889 | r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")', | |
890 | video_webpage, u'age gate player URL') | |
891 | player_url = json.loads(player_url_json) | |
892 | ||
893 | if self._downloader.params.get('verbose'): | |
cf010131 | 894 | if player_url is None: |
201e9eaa PH |
895 | player_version = 'unknown' |
896 | player_desc = 'unknown' | |
897 | else: | |
898 | if player_url.endswith('swf'): | |
899 | player_version = self._search_regex( | |
900 | r'-(.+?)(?:/watch_as3)?\.swf$', player_url, | |
901 | u'flash player', fatal=False) | |
902 | player_desc = 'flash player %s' % player_version | |
cf010131 | 903 | else: |
201e9eaa PH |
904 | player_version = self._search_regex( |
905 | r'html5player-([^/]+?)(?:/html5player)?\.js', | |
906 | player_url, | |
907 | 'html5 player', fatal=False) | |
908 | player_desc = u'html5 player %s' % player_version | |
909 | ||
60064c53 | 910 | parts_sizes = self._signature_cache_id(encrypted_sig) |
98eb1c3f PH |
911 | self.to_screen(u'{%s} signature length %s, %s' % |
912 | (format_id, parts_sizes, player_desc)) | |
201e9eaa PH |
913 | |
914 | signature = self._decrypt_signature( | |
915 | encrypted_sig, video_id, player_url, age_gate) | |
916 | url += '&signature=' + signature | |
917 | if 'ratebypass' not in url: | |
918 | url += '&ratebypass=yes' | |
919 | url_map[format_id] = url | |
dd27fd17 | 920 | formats = _map_to_format_list(url_map) |
1d043b93 JMF |
921 | elif video_info.get('hlsvp'): |
922 | manifest_url = video_info['hlsvp'][0] | |
923 | url_map = self._extract_from_m3u8(manifest_url, video_id) | |
dd27fd17 | 924 | formats = _map_to_format_list(url_map) |
c5e8d7af | 925 | else: |
9abb3204 | 926 | raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info') |
c5e8d7af | 927 | |
dd27fd17 | 928 | # Look for the DASH manifest |
d68f0cdb | 929 | if (self._downloader.params.get('youtube_include_dash_manifest', False)): |
dd27fd17 | 930 | try: |
d68f0cdb | 931 | # The DASH manifest used needs to be the one from the original video_webpage. |
932 | # The one found in get_video_info seems to be using different signatures. | |
933 | # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage. | |
934 | # Luckily, it seems, this case uses some kind of default signature (len == 86), so the | |
935 | # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here. | |
936 | if age_gate: | |
3489b7d2 | 937 | dash_manifest_url = video_info.get('dashmpd')[0] |
d68f0cdb | 938 | else: |
3489b7d2 | 939 | dash_manifest_url = ytplayer_config['args']['dashmpd'] |
d68f0cdb | 940 | def decrypt_sig(mobj): |
941 | s = mobj.group(1) | |
942 | dec_s = self._decrypt_signature(s, video_id, player_url, age_gate) | |
943 | return '/signature/%s' % dec_s | |
944 | dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url) | |
dd27fd17 | 945 | dash_doc = self._download_xml( |
d68f0cdb | 946 | dash_manifest_url, video_id, |
dd27fd17 PH |
947 | note=u'Downloading DASH manifest', |
948 | errnote=u'Could not download DASH manifest') | |
949 | for r in dash_doc.findall(u'.//{urn:mpeg:DASH:schema:MPD:2011}Representation'): | |
950 | url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL') | |
951 | if url_el is None: | |
952 | continue | |
953 | format_id = r.attrib['id'] | |
954 | video_url = url_el.text | |
955 | filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength')) | |
956 | f = { | |
957 | 'format_id': format_id, | |
958 | 'url': video_url, | |
959 | 'width': int_or_none(r.attrib.get('width')), | |
960 | 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000), | |
961 | 'asr': int_or_none(r.attrib.get('audioSamplingRate')), | |
962 | 'filesize': filesize, | |
963 | } | |
964 | try: | |
965 | existing_format = next( | |
966 | fo for fo in formats | |
967 | if fo['format_id'] == format_id) | |
968 | except StopIteration: | |
969 | f.update(self._formats.get(format_id, {})) | |
970 | formats.append(f) | |
971 | else: | |
972 | existing_format.update(f) | |
973 | ||
974 | except (ExtractorError, KeyError) as e: | |
975 | self.report_warning(u'Skipping DASH manifest: %s' % e, video_id) | |
d80044c2 | 976 | |
4bcc7bd1 | 977 | self._sort_formats(formats) |
4ea3be0a | 978 | |
979 | return { | |
980 | 'id': video_id, | |
981 | 'uploader': video_uploader, | |
982 | 'uploader_id': video_uploader_id, | |
983 | 'upload_date': upload_date, | |
984 | 'title': video_title, | |
985 | 'thumbnail': video_thumbnail, | |
986 | 'description': video_description, | |
ec8deefc | 987 | 'categories': video_categories, |
4ea3be0a | 988 | 'subtitles': video_subtitles, |
989 | 'duration': video_duration, | |
990 | 'age_limit': 18 if age_gate else 0, | |
991 | 'annotations': video_annotations, | |
7e8c0af0 | 992 | 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id, |
4ea3be0a | 993 | 'view_count': view_count, |
994 | 'like_count': like_count, | |
995 | 'dislike_count': dislike_count, | |
996 | 'formats': formats, | |
997 | } | |
c5e8d7af | 998 | |
880e1c52 | 999 | class YoutubePlaylistIE(YoutubeBaseInfoExtractor): |
0f818663 | 1000 | IE_DESC = u'YouTube.com playlists' |
d67cc9fa | 1001 | _VALID_URL = r"""(?x)(?: |
c5e8d7af PH |
1002 | (?:https?://)? |
1003 | (?:\w+\.)? | |
1004 | youtube\.com/ | |
1005 | (?: | |
1006 | (?:course|view_play_list|my_playlists|artist|playlist|watch) | |
1007 | \? (?:.*?&)*? (?:p|a|list)= | |
1008 | | p/ | |
1009 | ) | |
d67cc9fa | 1010 | ( |
7d568f5a | 1011 | (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,} |
d67cc9fa JMF |
1012 | # Top tracks, they can also include dots |
1013 | |(?:MC)[\w\.]* | |
1014 | ) | |
c5e8d7af PH |
1015 | .* |
1016 | | | |
7d568f5a | 1017 | ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,}) |
c5e8d7af | 1018 | )""" |
dbb94fb0 | 1019 | _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s' |
dcbb4580 | 1020 | _MORE_PAGES_INDICATOR = r'data-link-type="next"' |
dbb94fb0 | 1021 | _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&[^"]*?index=(?P<index>\d+)' |
c5e8d7af PH |
1022 | IE_NAME = u'youtube:playlist' |
1023 | ||
880e1c52 JMF |
1024 | def _real_initialize(self): |
1025 | self._login() | |
1026 | ||
652cdaa2 | 1027 | def _ids_to_results(self, ids): |
c9cc0bf5 PH |
1028 | return [ |
1029 | self.url_result(vid_id, 'Youtube', video_id=vid_id) | |
1030 | for vid_id in ids] | |
652cdaa2 JMF |
1031 | |
1032 | def _extract_mix(self, playlist_id): | |
1033 | # The mixes are generated from a a single video | |
1034 | # the id of the playlist is just 'RD' + video_id | |
7d4afc55 | 1035 | url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id) |
c9cc0bf5 PH |
1036 | webpage = self._download_webpage( |
1037 | url, playlist_id, u'Downloading Youtube mix') | |
bc2f773b | 1038 | search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage) |
c9cc0bf5 PH |
1039 | title_span = ( |
1040 | search_title('playlist-title') or | |
1041 | search_title('title long-title') or | |
1042 | search_title('title')) | |
76d1700b | 1043 | title = clean_html(title_span) |
c9cc0bf5 PH |
1044 | ids = orderedSet(re.findall( |
1045 | r'''(?xs)data-video-username=".*?".*? | |
1046 | href="/watch\?v=([0-9A-Za-z_-]{11})&[^"]*?list=%s''' % re.escape(playlist_id), | |
1047 | webpage)) | |
652cdaa2 JMF |
1048 | url_results = self._ids_to_results(ids) |
1049 | ||
1050 | return self.playlist_result(url_results, playlist_id, title) | |
1051 | ||
c5e8d7af PH |
1052 | def _real_extract(self, url): |
1053 | # Extract playlist id | |
d67cc9fa | 1054 | mobj = re.match(self._VALID_URL, url) |
c5e8d7af PH |
1055 | if mobj is None: |
1056 | raise ExtractorError(u'Invalid URL: %s' % url) | |
47192f92 FV |
1057 | playlist_id = mobj.group(1) or mobj.group(2) |
1058 | ||
1059 | # Check if it's a video-specific URL | |
7c61bd36 | 1060 | query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query) |
47192f92 FV |
1061 | if 'v' in query_dict: |
1062 | video_id = query_dict['v'][0] | |
1063 | if self._downloader.params.get('noplaylist'): | |
1064 | self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id) | |
7012b23c | 1065 | return self.url_result(video_id, 'Youtube', video_id=video_id) |
47192f92 | 1066 | else: |
1db26669 | 1067 | self.to_screen(u'Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id)) |
c5e8d7af | 1068 | |
7d4afc55 | 1069 | if playlist_id.startswith('RD'): |
652cdaa2 JMF |
1070 | # Mixes require a custom extraction process |
1071 | return self._extract_mix(playlist_id) | |
0a688bc0 JMF |
1072 | if playlist_id.startswith('TL'): |
1073 | raise ExtractorError(u'For downloading YouTube.com top lists, use ' | |
1074 | u'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True) | |
652cdaa2 | 1075 | |
dbb94fb0 S |
1076 | url = self._TEMPLATE_URL % playlist_id |
1077 | page = self._download_webpage(url, playlist_id) | |
1078 | more_widget_html = content_html = page | |
1079 | ||
10c0e2d8 | 1080 | # Check if the playlist exists or is private |
e399853d | 1081 | if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None: |
10c0e2d8 JMF |
1082 | raise ExtractorError( |
1083 | u'The playlist doesn\'t exist or is private, use --username or ' | |
1084 | '--netrc to access it.', | |
1085 | expected=True) | |
1086 | ||
dcbb4580 JMF |
1087 | # Extract the video ids from the playlist pages |
1088 | ids = [] | |
c5e8d7af | 1089 | |
755eb032 | 1090 | for page_num in itertools.count(1): |
dbb94fb0 | 1091 | matches = re.finditer(self._VIDEO_RE, content_html) |
6e47b51e JMF |
1092 | # We remove the duplicates and the link with index 0 |
1093 | # (it's not the first video of the playlist) | |
1094 | new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0') | |
dcbb4580 | 1095 | ids.extend(new_ids) |
c5e8d7af | 1096 | |
dbb94fb0 S |
1097 | mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html) |
1098 | if not mobj: | |
c5e8d7af PH |
1099 | break |
1100 | ||
dbb94fb0 | 1101 | more = self._download_json( |
5912c639 PH |
1102 | 'https://youtube.com/%s' % mobj.group('more'), playlist_id, |
1103 | 'Downloading page #%s' % page_num, | |
1104 | transform_source=uppercase_escape) | |
dbb94fb0 S |
1105 | content_html = more['content_html'] |
1106 | more_widget_html = more['load_more_widget_html'] | |
1107 | ||
1108 | playlist_title = self._html_search_regex( | |
68eb8e90 PH |
1109 | r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>', |
1110 | page, u'title') | |
c5e8d7af | 1111 | |
652cdaa2 | 1112 | url_results = self._ids_to_results(ids) |
dcbb4580 | 1113 | return self.playlist_result(url_results, playlist_id, playlist_title) |
c5e8d7af PH |
1114 | |
1115 | ||
0a688bc0 JMF |
1116 | class YoutubeTopListIE(YoutubePlaylistIE): |
1117 | IE_NAME = u'youtube:toplist' | |
1118 | IE_DESC = (u'YouTube.com top lists, "yttoplist:{channel}:{list title}"' | |
1119 | u' (Example: "yttoplist:music:Top Tracks")') | |
1120 | _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$' | |
1121 | ||
1122 | def _real_extract(self, url): | |
1123 | mobj = re.match(self._VALID_URL, url) | |
1124 | channel = mobj.group('chann') | |
1125 | title = mobj.group('title') | |
1126 | query = compat_urllib_parse.urlencode({'title': title}) | |
beddbc2a | 1127 | playlist_re = 'href="([^"]+?%s.*?)"' % re.escape(query) |
0a688bc0 JMF |
1128 | channel_page = self._download_webpage('https://www.youtube.com/%s' % channel, title) |
1129 | link = self._html_search_regex(playlist_re, channel_page, u'list') | |
1130 | url = compat_urlparse.urljoin('https://www.youtube.com/', link) | |
1131 | ||
1132 | video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"' | |
1133 | ids = [] | |
1134 | # sometimes the webpage doesn't contain the videos | |
1135 | # retry until we get them | |
1136 | for i in itertools.count(0): | |
1137 | msg = u'Downloading Youtube mix' | |
1138 | if i > 0: | |
1139 | msg += ', retry #%d' % i | |
c9cc0bf5 | 1140 | |
0a688bc0 JMF |
1141 | webpage = self._download_webpage(url, title, msg) |
1142 | ids = orderedSet(re.findall(video_re, webpage)) | |
1143 | if ids: | |
1144 | break | |
1145 | url_results = self._ids_to_results(ids) | |
1146 | return self.playlist_result(url_results, playlist_title=title) | |
1147 | ||
1148 | ||
c5e8d7af | 1149 | class YoutubeChannelIE(InfoExtractor): |
0f818663 | 1150 | IE_DESC = u'YouTube.com channels' |
c5e8d7af | 1151 | _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)" |
c5e8d7af | 1152 | _MORE_PAGES_INDICATOR = 'yt-uix-load-more' |
38c2e5b8 | 1153 | _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 |
1154 | IE_NAME = u'youtube:channel' |
1155 | ||
1156 | def extract_videos_from_page(self, page): | |
1157 | ids_in_page = [] | |
1158 | for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page): | |
1159 | if mobj.group(1) not in ids_in_page: | |
1160 | ids_in_page.append(mobj.group(1)) | |
1161 | return ids_in_page | |
1162 | ||
1163 | def _real_extract(self, url): | |
1164 | # Extract channel id | |
1165 | mobj = re.match(self._VALID_URL, url) | |
1166 | if mobj is None: | |
1167 | raise ExtractorError(u'Invalid URL: %s' % url) | |
1168 | ||
1169 | # Download channel page | |
1170 | channel_id = mobj.group(1) | |
1171 | video_ids = [] | |
b9643eed JMF |
1172 | url = 'https://www.youtube.com/channel/%s/videos' % channel_id |
1173 | channel_page = self._download_webpage(url, channel_id) | |
31812a9e PH |
1174 | autogenerated = re.search(r'''(?x) |
1175 | class="[^"]*?(?: | |
1176 | channel-header-autogenerated-label| | |
1177 | yt-channel-title-autogenerated | |
1178 | )[^"]*"''', channel_page) is not None | |
c5e8d7af | 1179 | |
b9643eed JMF |
1180 | if autogenerated: |
1181 | # The videos are contained in a single page | |
1182 | # the ajax pages can't be used, they are empty | |
1183 | video_ids = self.extract_videos_from_page(channel_page) | |
1184 | else: | |
1185 | # Download all channel pages using the json-based channel_ajax query | |
1186 | for pagenum in itertools.count(1): | |
1187 | url = self._MORE_PAGES_URL % (pagenum, channel_id) | |
81c2f20b PH |
1188 | page = self._download_json( |
1189 | url, channel_id, note=u'Downloading page #%s' % pagenum, | |
1190 | transform_source=uppercase_escape) | |
1191 | ||
b9643eed JMF |
1192 | ids_in_page = self.extract_videos_from_page(page['content_html']) |
1193 | video_ids.extend(ids_in_page) | |
1194 | ||
1195 | if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']: | |
1196 | break | |
c5e8d7af PH |
1197 | |
1198 | self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids))) | |
1199 | ||
7012b23c PH |
1200 | url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id) |
1201 | for video_id in video_ids] | |
1202 | return self.playlist_result(url_entries, channel_id) | |
c5e8d7af PH |
1203 | |
1204 | ||
1205 | class YoutubeUserIE(InfoExtractor): | |
0f818663 | 1206 | IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)' |
c9ae7b95 | 1207 | _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)' |
38c2e5b8 | 1208 | _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s' |
c5e8d7af | 1209 | _GDATA_PAGE_SIZE = 50 |
38c2e5b8 | 1210 | _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json' |
c5e8d7af PH |
1211 | IE_NAME = u'youtube:user' |
1212 | ||
e3ea4790 | 1213 | @classmethod |
f4b05232 | 1214 | def suitable(cls, url): |
e3ea4790 JMF |
1215 | # Don't return True if the url can be extracted with other youtube |
1216 | # extractor, the regex would is too permissive and it would match. | |
1217 | other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls) | |
1218 | if any(ie.suitable(url) for ie in other_ies): return False | |
f4b05232 JMF |
1219 | else: return super(YoutubeUserIE, cls).suitable(url) |
1220 | ||
c5e8d7af PH |
1221 | def _real_extract(self, url): |
1222 | # Extract username | |
1223 | mobj = re.match(self._VALID_URL, url) | |
1224 | if mobj is None: | |
1225 | raise ExtractorError(u'Invalid URL: %s' % url) | |
1226 | ||
1227 | username = mobj.group(1) | |
1228 | ||
1229 | # Download video ids using YouTube Data API. Result size per | |
1230 | # query is limited (currently to 50 videos) so we need to query | |
1231 | # page by page until there are no video ids - it means we got | |
1232 | # all of them. | |
1233 | ||
b7ab0590 | 1234 | def download_page(pagenum): |
c5e8d7af PH |
1235 | start_index = pagenum * self._GDATA_PAGE_SIZE + 1 |
1236 | ||
1237 | gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index) | |
b7ab0590 PH |
1238 | page = self._download_webpage( |
1239 | gdata_url, username, | |
1240 | u'Downloading video ids from %d to %d' % ( | |
1241 | start_index, start_index + self._GDATA_PAGE_SIZE)) | |
c5e8d7af | 1242 | |
fd9cf738 JMF |
1243 | try: |
1244 | response = json.loads(page) | |
1245 | except ValueError as err: | |
1246 | raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err)) | |
71c82637 | 1247 | if 'entry' not in response['feed']: |
b7ab0590 | 1248 | return |
fd9cf738 | 1249 | |
c5e8d7af | 1250 | # Extract video identifiers |
e302f9ce PH |
1251 | entries = response['feed']['entry'] |
1252 | for entry in entries: | |
1253 | title = entry['title']['$t'] | |
1254 | video_id = entry['id']['$t'].split('/')[-1] | |
b7ab0590 | 1255 | yield { |
e302f9ce PH |
1256 | '_type': 'url', |
1257 | 'url': video_id, | |
1258 | 'ie_key': 'Youtube', | |
b11cec41 | 1259 | 'id': video_id, |
e302f9ce | 1260 | 'title': title, |
b7ab0590 PH |
1261 | } |
1262 | url_results = PagedList(download_page, self._GDATA_PAGE_SIZE) | |
c5e8d7af | 1263 | |
7012b23c PH |
1264 | return self.playlist_result(url_results, playlist_title=username) |
1265 | ||
b05654f0 PH |
1266 | |
1267 | class YoutubeSearchIE(SearchInfoExtractor): | |
0f818663 | 1268 | IE_DESC = u'YouTube.com searches' |
83d548ef | 1269 | _API_URL = u'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc' |
b05654f0 PH |
1270 | _MAX_RESULTS = 1000 |
1271 | IE_NAME = u'youtube:search' | |
1272 | _SEARCH_KEY = 'ytsearch' | |
1273 | ||
b05654f0 PH |
1274 | def _get_n_results(self, query, n): |
1275 | """Get a specified number of results for a query""" | |
1276 | ||
1277 | video_ids = [] | |
1278 | pagenum = 0 | |
1279 | limit = n | |
83d548ef | 1280 | PAGE_SIZE = 50 |
b05654f0 | 1281 | |
83d548ef PH |
1282 | while (PAGE_SIZE * pagenum) < limit: |
1283 | result_url = self._API_URL % ( | |
1284 | compat_urllib_parse.quote_plus(query.encode('utf-8')), | |
1285 | (PAGE_SIZE * pagenum) + 1) | |
7cc3570e PH |
1286 | data_json = self._download_webpage( |
1287 | result_url, video_id=u'query "%s"' % query, | |
1288 | note=u'Downloading page %s' % (pagenum + 1), | |
1289 | errnote=u'Unable to download API page') | |
1290 | data = json.loads(data_json) | |
1291 | api_response = data['data'] | |
1292 | ||
1293 | if 'items' not in api_response: | |
07ad22b8 PH |
1294 | raise ExtractorError( |
1295 | u'[youtube] No video results', expected=True) | |
b05654f0 PH |
1296 | |
1297 | new_ids = list(video['id'] for video in api_response['items']) | |
1298 | video_ids += new_ids | |
1299 | ||
1300 | limit = min(n, api_response['totalItems']) | |
1301 | pagenum += 1 | |
1302 | ||
1303 | if len(video_ids) > n: | |
1304 | video_ids = video_ids[:n] | |
7012b23c PH |
1305 | videos = [self.url_result(video_id, 'Youtube', video_id=video_id) |
1306 | for video_id in video_ids] | |
b05654f0 | 1307 | return self.playlist_result(videos, query) |
75dff0ee | 1308 | |
c9ae7b95 | 1309 | |
a3dd9248 | 1310 | class YoutubeSearchDateIE(YoutubeSearchIE): |
cb7fb546 | 1311 | IE_NAME = YoutubeSearchIE.IE_NAME + ':date' |
a3dd9248 CM |
1312 | _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published' |
1313 | _SEARCH_KEY = 'ytsearchdate' | |
08fb86c4 | 1314 | IE_DESC = u'YouTube.com searches, newest videos first' |
75dff0ee | 1315 | |
c9ae7b95 PH |
1316 | |
1317 | class YoutubeSearchURLIE(InfoExtractor): | |
1318 | IE_DESC = u'YouTube.com search URLs' | |
1319 | IE_NAME = u'youtube:search_url' | |
1320 | _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)' | |
1321 | ||
1322 | def _real_extract(self, url): | |
1323 | mobj = re.match(self._VALID_URL, url) | |
1324 | query = compat_urllib_parse.unquote_plus(mobj.group('query')) | |
1325 | ||
1326 | webpage = self._download_webpage(url, query) | |
1327 | result_code = self._search_regex( | |
6feb2d5e | 1328 | r'(?s)<ol class="item-section"(.*?)</ol>', webpage, u'result HTML') |
c9ae7b95 PH |
1329 | |
1330 | part_codes = re.findall( | |
1331 | r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code) | |
1332 | entries = [] | |
1333 | for part_code in part_codes: | |
1334 | part_title = self._html_search_regex( | |
6feb2d5e | 1335 | [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False) |
c9ae7b95 PH |
1336 | part_url_snippet = self._html_search_regex( |
1337 | r'(?s)href="([^"]+)"', part_code, 'item URL') | |
1338 | part_url = compat_urlparse.urljoin( | |
1339 | 'https://www.youtube.com/', part_url_snippet) | |
1340 | entries.append({ | |
1341 | '_type': 'url', | |
1342 | 'url': part_url, | |
1343 | 'title': part_title, | |
1344 | }) | |
1345 | ||
1346 | return { | |
1347 | '_type': 'playlist', | |
1348 | 'entries': entries, | |
1349 | 'title': query, | |
1350 | } | |
1351 | ||
1352 | ||
75dff0ee | 1353 | class YoutubeShowIE(InfoExtractor): |
0f818663 | 1354 | IE_DESC = u'YouTube.com (multi-season) shows' |
75dff0ee JMF |
1355 | _VALID_URL = r'https?://www\.youtube\.com/show/(.*)' |
1356 | IE_NAME = u'youtube:show' | |
1357 | ||
1358 | def _real_extract(self, url): | |
1359 | mobj = re.match(self._VALID_URL, url) | |
1360 | show_name = mobj.group(1) | |
1361 | webpage = self._download_webpage(url, show_name, u'Downloading show webpage') | |
1362 | # There's one playlist for each season of the show | |
1363 | m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage)) | |
1364 | self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons))) | |
1365 | return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons] | |
04cc9617 JMF |
1366 | |
1367 | ||
b2e8bc1b | 1368 | class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor): |
d7ae0639 JMF |
1369 | """ |
1370 | Base class for extractors that fetch info from | |
1371 | http://www.youtube.com/feed_ajax | |
1372 | Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties. | |
1373 | """ | |
b2e8bc1b | 1374 | _LOGIN_REQUIRED = True |
43ba5456 JMF |
1375 | # use action_load_personal_feed instead of action_load_system_feed |
1376 | _PERSONAL_FEED = False | |
04cc9617 | 1377 | |
d7ae0639 JMF |
1378 | @property |
1379 | def _FEED_TEMPLATE(self): | |
43ba5456 JMF |
1380 | action = 'action_load_system_feed' |
1381 | if self._PERSONAL_FEED: | |
1382 | action = 'action_load_personal_feed' | |
38c2e5b8 | 1383 | return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME) |
d7ae0639 JMF |
1384 | |
1385 | @property | |
1386 | def IE_NAME(self): | |
1387 | return u'youtube:%s' % self._FEED_NAME | |
04cc9617 | 1388 | |
81f0259b | 1389 | def _real_initialize(self): |
b2e8bc1b | 1390 | self._login() |
81f0259b | 1391 | |
04cc9617 JMF |
1392 | def _real_extract(self, url): |
1393 | feed_entries = [] | |
0e44d838 JMF |
1394 | paging = 0 |
1395 | for i in itertools.count(1): | |
f6177462 | 1396 | info = self._download_json(self._FEED_TEMPLATE % paging, |
d7ae0639 | 1397 | u'%s feed' % self._FEED_NAME, |
04cc9617 | 1398 | u'Downloading page %s' % i) |
f6177462 | 1399 | feed_html = info.get('feed_html') or info.get('content_html') |
43ba5456 | 1400 | m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html) |
04cc9617 | 1401 | ids = orderedSet(m.group(1) for m in m_ids) |
7012b23c PH |
1402 | feed_entries.extend( |
1403 | self.url_result(video_id, 'Youtube', video_id=video_id) | |
1404 | for video_id in ids) | |
05ee2b6d JMF |
1405 | mobj = re.search( |
1406 | r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)', | |
1407 | feed_html) | |
1408 | if mobj is None: | |
04cc9617 | 1409 | break |
05ee2b6d | 1410 | paging = mobj.group('paging') |
d7ae0639 JMF |
1411 | return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE) |
1412 | ||
d7ae0639 JMF |
1413 | class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor): |
1414 | IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)' | |
1415 | _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?' | |
1416 | _FEED_NAME = 'recommended' | |
1417 | _PLAYLIST_TITLE = u'Youtube Recommended videos' | |
c626a3d9 | 1418 | |
43ba5456 JMF |
1419 | class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor): |
1420 | IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)' | |
1421 | _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater' | |
1422 | _FEED_NAME = 'watch_later' | |
1423 | _PLAYLIST_TITLE = u'Youtube Watch Later' | |
43ba5456 | 1424 | _PERSONAL_FEED = True |
c626a3d9 | 1425 | |
f459d170 JMF |
1426 | class YoutubeHistoryIE(YoutubeFeedsInfoExtractor): |
1427 | IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)' | |
1428 | _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory' | |
1429 | _FEED_NAME = 'history' | |
1430 | _PERSONAL_FEED = True | |
1431 | _PLAYLIST_TITLE = u'Youtube Watch History' | |
1432 | ||
c626a3d9 JMF |
1433 | class YoutubeFavouritesIE(YoutubeBaseInfoExtractor): |
1434 | IE_NAME = u'youtube:favorites' | |
1435 | IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)' | |
c7a7750d | 1436 | _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?' |
c626a3d9 JMF |
1437 | _LOGIN_REQUIRED = True |
1438 | ||
1439 | def _real_extract(self, url): | |
1440 | webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos') | |
1441 | playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id') | |
1442 | return self.url_result(playlist_id, 'YoutubePlaylist') | |
15870e90 PH |
1443 | |
1444 | ||
1ed5b5c9 JMF |
1445 | class YoutubeSubscriptionsIE(YoutubePlaylistIE): |
1446 | IE_NAME = u'youtube:subscriptions' | |
1447 | IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)' | |
1448 | _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?' | |
1449 | ||
1450 | def _real_extract(self, url): | |
1451 | title = u'Youtube Subscriptions' | |
1452 | page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title) | |
1453 | ||
1454 | # The extraction process is the same as for playlists, but the regex | |
1455 | # for the video ids doesn't contain an index | |
1456 | ids = [] | |
1457 | more_widget_html = content_html = page | |
1458 | ||
1459 | for page_num in itertools.count(1): | |
1460 | matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html) | |
1461 | new_ids = orderedSet(matches) | |
1462 | ids.extend(new_ids) | |
1463 | ||
1464 | mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html) | |
1465 | if not mobj: | |
1466 | break | |
1467 | ||
1468 | more = self._download_json( | |
1469 | 'https://youtube.com/%s' % mobj.group('more'), title, | |
1470 | 'Downloading page #%s' % page_num, | |
1471 | transform_source=uppercase_escape) | |
1472 | content_html = more['content_html'] | |
1473 | more_widget_html = more['load_more_widget_html'] | |
1474 | ||
1475 | return { | |
1476 | '_type': 'playlist', | |
1477 | 'title': title, | |
1478 | 'entries': self._ids_to_results(ids), | |
1479 | } | |
1480 | ||
1481 | ||
15870e90 PH |
1482 | class YoutubeTruncatedURLIE(InfoExtractor): |
1483 | IE_NAME = 'youtube:truncated_url' | |
1484 | IE_DESC = False # Do not list | |
975d35db | 1485 | _VALID_URL = r'''(?x) |
c4808c60 PH |
1486 | (?:https?://)?[^/]+/watch\?(?: |
1487 | feature=[a-z_]+| | |
1488 | annotation_id=annotation_[^&]+ | |
1489 | )?$| | |
975d35db PH |
1490 | (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$ |
1491 | ''' | |
15870e90 | 1492 | |
c4808c60 PH |
1493 | _TESTS = [{ |
1494 | 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041', | |
1495 | 'only_matching': True, | |
dc2fc736 PH |
1496 | }, { |
1497 | 'url': 'http://www.youtube.com/watch?', | |
1498 | 'only_matching': True, | |
c4808c60 PH |
1499 | }] |
1500 | ||
15870e90 PH |
1501 | def _real_extract(self, url): |
1502 | raise ExtractorError( | |
1503 | u'Did you forget to quote the URL? Remember that & is a meta ' | |
1504 | u'character in most shells, so you want to put the URL in quotes, ' | |
1505 | u'like youtube-dl ' | |
b4622a32 PH |
1506 | u'"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" ' |
1507 | u' or simply youtube-dl BaW_jenozKc .', | |
15870e90 | 1508 | expected=True) |