]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/youtube.py
[test_youtube_chapters] PEP 8
[yt-dlp.git] / youtube_dl / extractor / youtube.py
CommitLineData
c5e8d7af 1# coding: utf-8
c5e8d7af 2
78caa52a
PH
3from __future__ import unicode_literals
4
5
0ca96d48 6import itertools
c5e8d7af 7import json
c4417ddb 8import os.path
d77ab8e2 9import random
c5e8d7af 10import re
42939b61 11import time
e0df6211 12import traceback
c5e8d7af 13
b05654f0 14from .common import InfoExtractor, SearchInfoExtractor
2b25cb5d 15from ..jsinterp import JSInterpreter
54256267 16from ..swfinterp import SWFInterpreter
4bb4a188 17from ..compat import (
edf3e38e 18 compat_chr,
c5e8d7af 19 compat_parse_qs,
7fd002c0
S
20 compat_urllib_parse_unquote,
21 compat_urllib_parse_unquote_plus,
15707c7e 22 compat_urllib_parse_urlencode,
7c80519c 23 compat_urllib_parse_urlparse,
7c61bd36 24 compat_urlparse,
c5e8d7af 25 compat_str,
4bb4a188
PH
26)
27from ..utils import (
c5e8d7af 28 clean_html,
9b9c5355 29 error_to_compat_str,
c5e8d7af 30 ExtractorError,
2d30521a 31 float_or_none,
4bb4a188
PH
32 get_element_by_attribute,
33 get_element_by_id,
dd27fd17 34 int_or_none,
94278f72 35 mimetype2ext,
4bb4a188 36 orderedSet,
6310acf5 37 parse_codecs,
7c80519c 38 parse_duration,
0cb58b02 39 remove_quotes,
e00eb564 40 # remove_start,
cf7e015f 41 smuggle_url,
c93d53f5 42 str_to_int,
556dbe7f 43 try_get,
c5e8d7af
PH
44 unescapeHTML,
45 unified_strdate,
cf7e015f 46 unsmuggle_url,
81c2f20b 47 uppercase_escape,
6e6bc8da 48 urlencode_postdata,
c5e8d7af
PH
49)
50
5f6a1245 51
de7f3446 52class YoutubeBaseInfoExtractor(InfoExtractor):
b2e8bc1b
JMF
53 """Provide base functions for Youtube extractors"""
54 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
9303ce3e 55 _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
e00eb564
S
56
57 _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
58 _LOOKUP_REQ_TEMPLATE = '["{0}",null,[],null,"US",null,null,2,false,true,[null,null,[2,1,null,1,"https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn",null,[],4],1,[null,null,[]],null,null,null,true],"{0}"]'
59
60 _PASSWORD_CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
61 _PASSWORD_CHALLENGE_REQ_TEMPLATE = '["{0}",null,1,null,[1,null,null,null,["{1}",null,true]],[null,null,[2,1,null,1,"https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn",null,[],4],1,[null,null,[]],null,null,null,true]]'
62
63 _TFA_URL = 'https://accounts.google.com/_/signin/challenge'
64 _TFA_REQ_TEMPLATE = '["{0}",null,2,null,[9,null,null,null,null,null,null,null,[null,"{1}",false,2]]]'
65
b2e8bc1b
JMF
66 _NETRC_MACHINE = 'youtube'
67 # If True it will raise an error if no login info is provided
68 _LOGIN_REQUIRED = False
69
d0ba5587
S
70 _PLAYLIST_ID_RE = r'(?:PL|LL|EC|UU|FL|RD|UL|TL)[0-9A-Za-z-_]{10,}'
71
b2e8bc1b 72 def _set_language(self):
810fb84d
PH
73 self._set_cookie(
74 '.youtube.com', 'PREF', 'f1=50000000&hl=en',
42939b61 75 # YouTube sets the expire time to about two months
810fb84d 76 expire_time=time.time() + 2 * 30 * 24 * 3600)
b2e8bc1b 77
25f14e9f
S
78 def _ids_to_results(self, ids):
79 return [
80 self.url_result(vid_id, 'Youtube', video_id=vid_id)
81 for vid_id in ids]
82
b2e8bc1b 83 def _login(self):
83317f69 84 """
85 Attempt to log in to YouTube.
86 True is returned if successful or skipped.
87 False is returned if login failed.
88
89 If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
90 """
b2e8bc1b
JMF
91 (username, password) = self._get_login_info()
92 # No authentication to be performed
93 if username is None:
94 if self._LOGIN_REQUIRED:
69ea8ca4 95 raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
83317f69 96 return True
b2e8bc1b 97
7cc3570e
PH
98 login_page = self._download_webpage(
99 self._LOGIN_URL, None,
69ea8ca4
PH
100 note='Downloading login page',
101 errnote='unable to fetch login page', fatal=False)
7cc3570e
PH
102 if login_page is False:
103 return
b2e8bc1b 104
1212e997 105 login_form = self._hidden_inputs(login_page)
c5e8d7af 106
e00eb564
S
107 def req(url, f_req, note, errnote):
108 data = login_form.copy()
109 data.update({
110 'pstMsg': 1,
111 'checkConnection': 'youtube',
112 'checkedDomains': 'youtube',
113 'hl': 'en',
114 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
115 'f.req': f_req,
116 'flowName': 'GlifWebSignIn',
117 'flowEntry': 'ServiceLogin',
041bc3ad 118 })
e00eb564
S
119 return self._download_json(
120 url, None, note=note, errnote=errnote,
121 transform_source=lambda s: re.sub(r'^[^[]*', '', s),
122 fatal=False,
123 data=urlencode_postdata(data), headers={
124 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
125 'Google-Accounts-XSRF': 1,
126 })
127
128 lookup_results = req(
129 self._LOOKUP_URL, self._LOOKUP_REQ_TEMPLATE.format(username),
130 'Looking up account info', 'Unable to look up account info')
131
132 if lookup_results is False:
133 return False
041bc3ad 134
e00eb564 135 user_hash = lookup_results[0][2]
83317f69 136
e00eb564
S
137 password_challenge_results = req(
138 self._PASSWORD_CHALLENGE_URL,
139 self._PASSWORD_CHALLENGE_REQ_TEMPLATE.format(user_hash, password),
140 'Logging in', 'Unable to log in')[0]
83317f69 141
e00eb564
S
142 if password_challenge_results is False:
143 return
83317f69 144
e00eb564
S
145 msg = password_challenge_results[5]
146 if msg is not None and isinstance(msg, list):
147 raise ExtractorError('Unable to login: %s' % msg[5], expected=True)
148
149 password_challenge_results = password_challenge_results[-1]
150
151 # tfa = password_challenge_results[0]
152 # if isinstance(tfa, list) and tfa[0][2] == 'TWO_STEP_VERIFICATION':
153 # tfa_code = self._get_tfa_info('2-step verification code')
154 #
155 # if not tfa_code:
156 # self._downloader.report_warning(
157 # 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
158 # '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
159 # return False
160 #
161 # tfa_code = remove_start(tfa_code, 'G-')
162 # print('tfa', tfa_code)
163 # tfa_results = req(
164 # self._TFA_URL,
165 # self._TFA_REQ_TEMPLATE.format(user_hash, tfa_code),
166 # 'Submitting TFA code', 'Unable to submit TFA code')
167 #
168 # TODO
169
170 check_cookie_results = self._download_webpage(
171 password_challenge_results[2], None, 'Checking cookie')
172
173 if '>Sign out<' not in check_cookie_results:
174 self._downloader.report_warning('Unable to log in')
b2e8bc1b 175 return False
e00eb564 176
b2e8bc1b
JMF
177 return True
178
b2e8bc1b
JMF
179 def _real_initialize(self):
180 if self._downloader is None:
181 return
42939b61 182 self._set_language()
b2e8bc1b
JMF
183 if not self._login():
184 return
c5e8d7af 185
8377574c 186
8e7aad20 187class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
061a75ed 188 # Extract entries from page with "Load more" button
648e6a1f
S
189 def _entries(self, page, playlist_id):
190 more_widget_html = content_html = page
191 for page_num in itertools.count(1):
061a75ed
S
192 for entry in self._process_page(content_html):
193 yield entry
648e6a1f
S
194
195 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
196 if not mobj:
197 break
198
199 more = self._download_json(
200 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
201 'Downloading page #%s' % page_num,
202 transform_source=uppercase_escape)
203 content_html = more['content_html']
204 if not content_html.strip():
205 # Some webpages show a "Load more" button but they don't
206 # have more videos
207 break
208 more_widget_html = more['load_more_widget_html']
209
061a75ed
S
210
211class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
212 def _process_page(self, content):
213 for video_id, video_title in self.extract_videos_from_page(content):
214 yield self.url_result(video_id, 'Youtube', video_id, video_title)
215
648e6a1f
S
216 def extract_videos_from_page(self, page):
217 ids_in_page = []
218 titles_in_page = []
219 for mobj in re.finditer(self._VIDEO_RE, page):
220 # The link with index 0 is not the first video of the playlist (not sure if still actual)
221 if 'index' in mobj.groupdict() and mobj.group('id') == '0':
222 continue
223 video_id = mobj.group('id')
224 video_title = unescapeHTML(mobj.group('title'))
225 if video_title:
226 video_title = video_title.strip()
227 try:
228 idx = ids_in_page.index(video_id)
229 if video_title and not titles_in_page[idx]:
230 titles_in_page[idx] = video_title
231 except ValueError:
232 ids_in_page.append(video_id)
233 titles_in_page.append(video_title)
234 return zip(ids_in_page, titles_in_page)
235
236
061a75ed
S
237class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
238 def _process_page(self, content):
6dee688e
S
239 for playlist_id in orderedSet(re.findall(
240 r'<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*><a[^>]+href="/?playlist\?list=([0-9A-Za-z-_]{10,})"',
241 content)):
061a75ed
S
242 yield self.url_result(
243 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
244
0c148415
S
245 def _real_extract(self, url):
246 playlist_id = self._match_id(url)
247 webpage = self._download_webpage(url, playlist_id)
0c148415 248 title = self._og_search_title(webpage, fatal=False)
061a75ed 249 return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
0c148415
S
250
251
360e1ca5 252class YoutubeIE(YoutubeBaseInfoExtractor):
78caa52a 253 IE_DESC = 'YouTube.com'
cb7dfeea 254 _VALID_URL = r"""(?x)^
c5e8d7af 255 (
edb53e2d 256 (?:https?://|//) # http(s):// or protocol-independent URL
cb7dfeea 257 (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
484aaeb2 258 (?:www\.)?deturl\.com/www\.youtube\.com/|
e70dc1d1 259 (?:www\.)?pwnyoutube\.com/|
f7000f3a 260 (?:www\.)?yourepeat\.com/|
e69ae5b9
JMF
261 tube\.majestyc\.net/|
262 youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
c5e8d7af
PH
263 (?:.*?\#/)? # handle anchor (#/) redirect urls
264 (?: # the various things that can precede the ID:
ac7553d0 265 (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
c5e8d7af 266 |(?: # or the v= param in all its forms
f7000f3a 267 (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
c5e8d7af 268 (?:\?|\#!?) # the params delimiter ? or # or #!
040ac686 269 (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
c5e8d7af
PH
270 v=
271 )
f4b05232 272 ))
cbaed4bb
S
273 |(?:
274 youtu\.be| # just youtu.be/xxxx
6d4fc66b
S
275 vid\.plus| # or vid.plus/xxxx
276 zwearz\.com/watch| # or zwearz.com/watch/xxxx
cbaed4bb 277 )/
edb53e2d 278 |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
f4b05232 279 )
c5e8d7af 280 )? # all until now is optional -> you can pass the naked ID
8963d9c2 281 ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
d0ba5587
S
282 (?!.*?\blist=
283 (?:
284 %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
285 WL # WL are handled by the watch later IE
286 )
287 )
c5e8d7af 288 (?(1).+)? # if we found the ID, everything can follow
d0ba5587 289 $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
c5e8d7af 290 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
2c62dc26 291 _formats = {
c2d3cb4c 292 '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
293 '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
294 '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
295 '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
296 '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
297 '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
298 '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
299 '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
3834d3e3 300 # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
c2d3cb4c 301 '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
302 '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
303 '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
304 '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
305 '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
306 '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
e1a0bfdf 307 '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
c2d3cb4c 308 '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
309 '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
e1a0bfdf 310
311
312 # 3D videos
c2d3cb4c 313 '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
314 '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
315 '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
316 '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
e1a0bfdf 317 '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
318 '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
319 '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
836a086c 320
96fb5605 321 # Apple HTTP Live Streaming
11f12195 322 '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
c2d3cb4c 323 '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
324 '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
325 '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
326 '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
327 '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
e1a0bfdf 328 '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
329 '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
2c62dc26
PH
330
331 # DASH mp4 video
d23028a8
S
332 '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
333 '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
334 '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
335 '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
336 '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
337 '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
338 '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
339 '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
340 '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
341 '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
342 '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
343 '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
836a086c 344
f6f1fc92 345 # Dash mp4 audio
d23028a8
S
346 '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
347 '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
348 '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
349 '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
350 '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
351 '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
352 '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
836a086c
AZ
353
354 # Dash webm
d23028a8
S
355 '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
356 '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
357 '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
358 '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
359 '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
360 '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
361 '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
362 '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
363 '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
364 '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
365 '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
366 '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
367 '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
368 '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
369 '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
4c6b4764 370 # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
d23028a8
S
371 '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
372 '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
373 '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
374 '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
375 '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
376 '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
2c62dc26
PH
377
378 # Dash webm audio
d23028a8
S
379 '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
380 '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
ce6b9a2d 381
0857baad 382 # Dash webm audio with opus inside
d23028a8
S
383 '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
384 '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
385 '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
0857baad 386
ce6b9a2d
PH
387 # RTMP (unnamed)
388 '_rtmp': {'protocol': 'rtmp'},
c5e8d7af 389 }
23d17e4b 390 _SUBTITLE_FORMATS = ('ttml', 'vtt')
836a086c 391
fd5c4aab
S
392 _GEO_BYPASS = False
393
78caa52a 394 IE_NAME = 'youtube'
2eb88d95
PH
395 _TESTS = [
396 {
2d3d2997 397 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
4bc3a23e
PH
398 'info_dict': {
399 'id': 'BaW_jenozKc',
400 'ext': 'mp4',
401 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
402 'uploader': 'Philipp Hagemeister',
403 'uploader_id': 'phihag',
ec85ded8 404 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
4bc3a23e 405 'upload_date': '20121002',
7caf9830 406 'license': 'Standard YouTube License',
4bc3a23e
PH
407 'description': '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 .',
408 'categories': ['Science & Technology'],
000b6b5a 409 'tags': ['youtube-dl'],
556dbe7f 410 'duration': 10,
3e7c1224
PH
411 'like_count': int,
412 'dislike_count': int,
7c80519c 413 'start_time': 1,
297a564b 414 'end_time': 9,
2eb88d95 415 }
0e853ca4 416 },
0e853ca4 417 {
2d3d2997 418 'url': 'https://www.youtube.com/watch?v=UxxajLWwzqY',
4bc3a23e
PH
419 'note': 'Test generic use_cipher_signature video (#897)',
420 'info_dict': {
421 'id': 'UxxajLWwzqY',
422 'ext': 'mp4',
423 'upload_date': '20120506',
424 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
0cb58b02 425 'alt_title': 'I Love It (feat. Charli XCX)',
7caf9830 426 'description': 'md5:f3ceb5ef83a08d95b9d146f973157cc8',
000b6b5a
S
427 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
428 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
429 'iconic ep', 'iconic', 'love', 'it'],
556dbe7f 430 'duration': 180,
4bc3a23e
PH
431 'uploader': 'Icona Pop',
432 'uploader_id': 'IconaPop',
ec85ded8 433 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IconaPop',
7caf9830 434 'license': 'Standard YouTube License',
0cb58b02 435 'creator': 'Icona Pop',
2eb88d95 436 }
c108eb73
JMF
437 },
438 {
4bc3a23e
PH
439 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
440 'note': 'Test VEVO video with age protection (#956)',
441 'info_dict': {
442 'id': '07FYdnEawAQ',
443 'ext': 'mp4',
444 'upload_date': '20130703',
445 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
0cb58b02 446 'alt_title': 'Tunnel Vision',
4bc3a23e 447 'description': 'md5:64249768eec3bc4276236606ea996373',
556dbe7f 448 'duration': 419,
4bc3a23e
PH
449 'uploader': 'justintimberlakeVEVO',
450 'uploader_id': 'justintimberlakeVEVO',
ec85ded8 451 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/justintimberlakeVEVO',
7caf9830 452 'license': 'Standard YouTube License',
0cb58b02 453 'creator': 'Justin Timberlake',
34952f09 454 'age_limit': 18,
c108eb73
JMF
455 }
456 },
fccd3771 457 {
4bc3a23e
PH
458 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
459 'note': 'Embed-only video (#1746)',
460 'info_dict': {
461 'id': 'yZIXLfi8CZQ',
462 'ext': 'mp4',
463 'upload_date': '20120608',
464 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
465 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
466 'uploader': 'SET India',
94bfcd23 467 'uploader_id': 'setindia',
ec85ded8 468 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
7caf9830 469 'license': 'Standard YouTube License',
94bfcd23 470 'age_limit': 18,
fccd3771
PH
471 }
472 },
11b56058 473 {
2d3d2997 474 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
11b56058
PM
475 'note': 'Use the first video ID in the URL',
476 'info_dict': {
477 'id': 'BaW_jenozKc',
478 'ext': 'mp4',
479 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
480 'uploader': 'Philipp Hagemeister',
481 'uploader_id': 'phihag',
ec85ded8 482 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
11b56058 483 'upload_date': '20121002',
7caf9830 484 'license': 'Standard YouTube License',
11b56058
PM
485 'description': '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 .',
486 'categories': ['Science & Technology'],
487 'tags': ['youtube-dl'],
556dbe7f 488 'duration': 10,
11b56058
PM
489 'like_count': int,
490 'dislike_count': int,
34a7de29
S
491 },
492 'params': {
493 'skip_download': True,
494 },
11b56058 495 },
dd27fd17 496 {
2d3d2997 497 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
4bc3a23e
PH
498 'note': '256k DASH audio (format 141) via DASH manifest',
499 'info_dict': {
500 'id': 'a9LDPn-MO4I',
501 'ext': 'm4a',
502 'upload_date': '20121002',
503 'uploader_id': '8KVIDEO',
ec85ded8 504 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
4bc3a23e
PH
505 'description': '',
506 'uploader': '8KVIDEO',
7caf9830 507 'license': 'Standard YouTube License',
4bc3a23e 508 'title': 'UHDTV TEST 8K VIDEO.mp4'
4919603f 509 },
4bc3a23e
PH
510 'params': {
511 'youtube_include_dash_manifest': True,
512 'format': '141',
4919603f 513 },
de3c7fe0 514 'skip': 'format 141 not served anymore',
dd27fd17 515 },
3489b7d2
JMF
516 # DASH manifest with encrypted signature
517 {
78caa52a
PH
518 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
519 'info_dict': {
520 'id': 'IB3lcPjvWLA',
521 'ext': 'm4a',
b766eb27
JMF
522 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
523 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
556dbe7f 524 'duration': 244,
78caa52a
PH
525 'uploader': 'AfrojackVEVO',
526 'uploader_id': 'AfrojackVEVO',
527 'upload_date': '20131011',
7caf9830 528 'license': 'Standard YouTube License',
3489b7d2 529 },
4bc3a23e 530 'params': {
78caa52a 531 'youtube_include_dash_manifest': True,
de3c7fe0 532 'format': '141/bestaudio[ext=m4a]',
3489b7d2
JMF
533 },
534 },
aaeb86f6
S
535 # JS player signature function name containing $
536 {
537 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
538 'info_dict': {
539 'id': 'nfWlot6h_JM',
540 'ext': 'm4a',
541 'title': 'Taylor Swift - Shake It Off',
0cb58b02 542 'alt_title': 'Shake It Off',
f57b7835 543 'description': 'md5:95f66187cd7c8b2c13eb78e1223b63c3',
556dbe7f 544 'duration': 242,
aaeb86f6
S
545 'uploader': 'TaylorSwiftVEVO',
546 'uploader_id': 'TaylorSwiftVEVO',
547 'upload_date': '20140818',
7caf9830 548 'license': 'Standard YouTube License',
0cb58b02 549 'creator': 'Taylor Swift',
aaeb86f6
S
550 },
551 'params': {
552 'youtube_include_dash_manifest': True,
de3c7fe0 553 'format': '141/bestaudio[ext=m4a]',
aaeb86f6
S
554 },
555 },
aa79ac0c
PH
556 # Controversy video
557 {
558 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
559 'info_dict': {
560 'id': 'T4XJQO3qol8',
561 'ext': 'mp4',
556dbe7f 562 'duration': 219,
aa79ac0c
PH
563 'upload_date': '20100909',
564 'uploader': 'The Amazing Atheist',
565 'uploader_id': 'TheAmazingAtheist',
ec85ded8 566 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
7caf9830 567 'license': 'Standard YouTube License',
aa79ac0c
PH
568 'title': 'Burning Everyone\'s Koran',
569 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
570 }
c522adb1
JMF
571 },
572 # Normal age-gate video (No vevo, embed allowed)
573 {
2d3d2997 574 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
c522adb1
JMF
575 'info_dict': {
576 'id': 'HtVdAasjOgU',
577 'ext': 'mp4',
578 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
ec85ded8 579 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
556dbe7f 580 'duration': 142,
c522adb1
JMF
581 'uploader': 'The Witcher',
582 'uploader_id': 'WitcherGame',
ec85ded8 583 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
c522adb1 584 'upload_date': '20140605',
7caf9830 585 'license': 'Standard YouTube License',
34952f09 586 'age_limit': 18,
c522adb1
JMF
587 },
588 },
fccae2b9
S
589 # Age-gate video with encrypted signature
590 {
2d3d2997 591 'url': 'https://www.youtube.com/watch?v=6kLq3WMV1nU',
fccae2b9
S
592 'info_dict': {
593 'id': '6kLq3WMV1nU',
594 'ext': 'mp4',
595 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
596 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
556dbe7f 597 'duration': 247,
fccae2b9
S
598 'uploader': 'LloydVEVO',
599 'uploader_id': 'LloydVEVO',
ec85ded8 600 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/LloydVEVO',
fccae2b9 601 'upload_date': '20110629',
7caf9830 602 'license': 'Standard YouTube License',
34952f09 603 'age_limit': 18,
fccae2b9
S
604 },
605 },
774e208f
PH
606 # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
607 {
608 'url': '__2ABJjxzNo',
609 'info_dict': {
610 'id': '__2ABJjxzNo',
611 'ext': 'mp4',
556dbe7f 612 'duration': 266,
774e208f
PH
613 'upload_date': '20100430',
614 'uploader_id': 'deadmau5',
ec85ded8 615 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
0cb58b02 616 'creator': 'deadmau5',
774e208f
PH
617 'description': 'md5:12c56784b8032162bb936a5f76d55360',
618 'uploader': 'deadmau5',
7caf9830 619 'license': 'Standard YouTube License',
774e208f 620 'title': 'Deadmau5 - Some Chords (HD)',
0cb58b02 621 'alt_title': 'Some Chords',
774e208f
PH
622 },
623 'expected_warnings': [
624 'DASH manifest missing',
625 ]
e52a40ab
PH
626 },
627 # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
628 {
629 'url': 'lqQg6PlCWgI',
630 'info_dict': {
631 'id': 'lqQg6PlCWgI',
632 'ext': 'mp4',
556dbe7f 633 'duration': 6085,
90227264 634 'upload_date': '20150827',
cbe2bd91 635 'uploader_id': 'olympic',
ec85ded8 636 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
7caf9830 637 'license': 'Standard YouTube License',
cbe2bd91 638 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
be49068d 639 'uploader': 'Olympic',
cbe2bd91
PH
640 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
641 },
642 'params': {
643 'skip_download': 'requires avconv',
e52a40ab 644 }
cbe2bd91 645 },
6271f1ca
PH
646 # Non-square pixels
647 {
648 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
649 'info_dict': {
650 'id': '_b-2C3KPAM0',
651 'ext': 'mp4',
652 'stretched_ratio': 16 / 9.,
556dbe7f 653 'duration': 85,
6271f1ca
PH
654 'upload_date': '20110310',
655 'uploader_id': 'AllenMeow',
ec85ded8 656 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
6271f1ca
PH
657 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
658 'uploader': '孫艾倫',
7caf9830 659 'license': 'Standard YouTube License',
6271f1ca
PH
660 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
661 },
06b491eb
S
662 },
663 # url_encoded_fmt_stream_map is empty string
664 {
665 'url': 'qEJwOuvDf7I',
666 'info_dict': {
667 'id': 'qEJwOuvDf7I',
f57b7835 668 'ext': 'webm',
06b491eb
S
669 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
670 'description': '',
671 'upload_date': '20150404',
672 'uploader_id': 'spbelect',
673 'uploader': 'Наблюдатели Петербурга',
674 },
675 'params': {
676 'skip_download': 'requires avconv',
e323cf3f
S
677 },
678 'skip': 'This live event has ended.',
06b491eb 679 },
da77d856
S
680 # Extraction from multiple DASH manifests (https://github.com/rg3/youtube-dl/pull/6097)
681 {
682 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
683 'info_dict': {
684 'id': 'FIl7x6_3R5Y',
685 'ext': 'mp4',
686 'title': 'md5:7b81415841e02ecd4313668cde88737a',
687 'description': 'md5:116377fd2963b81ec4ce64b542173306',
556dbe7f 688 'duration': 220,
da77d856
S
689 'upload_date': '20150625',
690 'uploader_id': 'dorappi2000',
ec85ded8 691 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
da77d856 692 'uploader': 'dorappi2000',
7caf9830 693 'license': 'Standard YouTube License',
be49068d 694 'formats': 'mincount:32',
da77d856 695 },
2ee8f5d8 696 },
8a1a26ce
YCH
697 # DASH manifest with segment_list
698 {
699 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
700 'md5': '8ce563a1d667b599d21064e982ab9e31',
701 'info_dict': {
702 'id': 'CsmdDsKjzN8',
703 'ext': 'mp4',
17ee98e1 704 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
8a1a26ce
YCH
705 'uploader': 'Airtek',
706 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
707 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
7caf9830 708 'license': 'Standard YouTube License',
8a1a26ce
YCH
709 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
710 },
711 'params': {
712 'youtube_include_dash_manifest': True,
713 'format': '135', # bestvideo
be49068d
S
714 },
715 'skip': 'This live event has ended.',
2ee8f5d8 716 },
cf7e015f
S
717 {
718 # Multifeed videos (multiple cameras), URL is for Main Camera
719 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
720 'info_dict': {
721 'id': 'jqWvoWXjCVs',
722 'title': 'teamPGP: Rocket League Noob Stream',
723 'description': 'md5:dc7872fb300e143831327f1bae3af010',
724 },
725 'playlist': [{
726 'info_dict': {
727 'id': 'jqWvoWXjCVs',
728 'ext': 'mp4',
729 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
730 'description': 'md5:dc7872fb300e143831327f1bae3af010',
556dbe7f 731 'duration': 7335,
cf7e015f
S
732 'upload_date': '20150721',
733 'uploader': 'Beer Games Beer',
734 'uploader_id': 'beergamesbeer',
ec85ded8 735 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
7caf9830 736 'license': 'Standard YouTube License',
cf7e015f
S
737 },
738 }, {
739 'info_dict': {
740 'id': '6h8e8xoXJzg',
741 'ext': 'mp4',
742 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
743 'description': 'md5:dc7872fb300e143831327f1bae3af010',
556dbe7f 744 'duration': 7337,
cf7e015f
S
745 'upload_date': '20150721',
746 'uploader': 'Beer Games Beer',
747 'uploader_id': 'beergamesbeer',
ec85ded8 748 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
7caf9830 749 'license': 'Standard YouTube License',
cf7e015f
S
750 },
751 }, {
752 'info_dict': {
753 'id': 'PUOgX5z9xZw',
754 'ext': 'mp4',
755 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
756 'description': 'md5:dc7872fb300e143831327f1bae3af010',
556dbe7f 757 'duration': 7337,
cf7e015f
S
758 'upload_date': '20150721',
759 'uploader': 'Beer Games Beer',
760 'uploader_id': 'beergamesbeer',
ec85ded8 761 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
7caf9830 762 'license': 'Standard YouTube License',
cf7e015f
S
763 },
764 }, {
765 'info_dict': {
766 'id': 'teuwxikvS5k',
767 'ext': 'mp4',
768 'title': 'teamPGP: Rocket League Noob Stream (zim)',
769 'description': 'md5:dc7872fb300e143831327f1bae3af010',
556dbe7f 770 'duration': 7334,
cf7e015f
S
771 'upload_date': '20150721',
772 'uploader': 'Beer Games Beer',
773 'uploader_id': 'beergamesbeer',
ec85ded8 774 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
7caf9830 775 'license': 'Standard YouTube License',
cf7e015f
S
776 },
777 }],
778 'params': {
779 'skip_download': True,
780 },
cbaed4bb 781 },
f9f49d87
S
782 {
783 # Multifeed video with comma in title (see https://github.com/rg3/youtube-dl/issues/8536)
784 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
785 'info_dict': {
786 'id': 'gVfLd0zydlo',
787 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
788 },
789 'playlist_count': 2,
be49068d 790 'skip': 'Not multifeed anymore',
f9f49d87 791 },
cbaed4bb 792 {
2d3d2997 793 'url': 'https://vid.plus/FlRa-iH7PGw',
cbaed4bb 794 'only_matching': True,
0e49d9a6 795 },
6d4fc66b 796 {
2d3d2997 797 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
6d4fc66b
S
798 'only_matching': True,
799 },
0e49d9a6 800 {
61f92af1 801 # Title with JS-like syntax "};" (see https://github.com/rg3/youtube-dl/issues/7468)
a8776b10
S
802 # Also tests cut-off URL expansion in video description (see
803 # https://github.com/rg3/youtube-dl/issues/1892,
804 # https://github.com/rg3/youtube-dl/issues/8164)
0e49d9a6
LL
805 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
806 'info_dict': {
807 'id': 'lsguqyKfVQg',
808 'ext': 'mp4',
809 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
0cb58b02 810 'alt_title': 'Dark Walk',
0e49d9a6 811 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
556dbe7f 812 'duration': 133,
0e49d9a6
LL
813 'upload_date': '20151119',
814 'uploader_id': 'IronSoulElf',
ec85ded8 815 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
0e49d9a6 816 'uploader': 'IronSoulElf',
7caf9830 817 'license': 'Standard YouTube License',
0cb58b02 818 'creator': 'Todd Haberman, Daniel Law Heath & Aaron Kaplan',
0e49d9a6
LL
819 },
820 'params': {
821 'skip_download': True,
822 },
823 },
61f92af1
S
824 {
825 # Tags with '};' (see https://github.com/rg3/youtube-dl/issues/7468)
826 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
827 'only_matching': True,
828 },
313dfc45
LL
829 {
830 # Video with yt:stretch=17:0
831 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
832 'info_dict': {
833 'id': 'Q39EVAstoRM',
834 'ext': 'mp4',
835 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
836 'description': 'md5:ee18a25c350637c8faff806845bddee9',
837 'upload_date': '20151107',
838 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
839 'uploader': 'CH GAMER DROID',
840 },
841 'params': {
842 'skip_download': True,
843 },
be49068d 844 'skip': 'This video does not exist.',
313dfc45 845 },
7caf9830
S
846 {
847 # Video licensed under Creative Commons
848 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
849 'info_dict': {
850 'id': 'M4gD1WSo5mA',
851 'ext': 'mp4',
852 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
853 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
556dbe7f 854 'duration': 721,
7caf9830
S
855 'upload_date': '20150127',
856 'uploader_id': 'BerkmanCenter',
ec85ded8 857 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
556dbe7f 858 'uploader': 'The Berkman Klein Center for Internet & Society',
7caf9830
S
859 'license': 'Creative Commons Attribution license (reuse allowed)',
860 },
861 'params': {
862 'skip_download': True,
863 },
864 },
fd050249
S
865 {
866 # Channel-like uploader_url
867 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
868 'info_dict': {
869 'id': 'eQcmzGIKrzg',
870 'ext': 'mp4',
871 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
872 'description': 'md5:dda0d780d5a6e120758d1711d062a867',
556dbe7f 873 'duration': 4060,
fd050249
S
874 'upload_date': '20151119',
875 'uploader': 'Bernie 2016',
876 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
ec85ded8 877 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
fd050249
S
878 'license': 'Creative Commons Attribution license (reuse allowed)',
879 },
880 'params': {
881 'skip_download': True,
882 },
883 },
040ac686
S
884 {
885 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
886 'only_matching': True,
7f29cf54
S
887 },
888 {
889 # YouTube Red paid video (https://github.com/rg3/youtube-dl/issues/10059)
890 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
891 'only_matching': True,
6496ccb4
S
892 },
893 {
894 # Rental video preview
895 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
896 'info_dict': {
897 'id': 'uGpuVWrhIzE',
898 'ext': 'mp4',
899 'title': 'Piku - Trailer',
900 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
901 'upload_date': '20150811',
902 'uploader': 'FlixMatrix',
903 'uploader_id': 'FlixMatrixKaravan',
ec85ded8 904 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
6496ccb4
S
905 'license': 'Standard YouTube License',
906 },
907 'params': {
908 'skip_download': True,
909 },
022a5d66 910 },
12afdc2a
S
911 {
912 # YouTube Red video with episode data
913 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
914 'info_dict': {
915 'id': 'iqKdEhx-dD4',
916 'ext': 'mp4',
917 'title': 'Isolation - Mind Field (Ep 1)',
556dbe7f
S
918 'description': 'md5:8013b7ddea787342608f63a13ddc9492',
919 'duration': 2085,
12afdc2a
S
920 'upload_date': '20170118',
921 'uploader': 'Vsauce',
922 'uploader_id': 'Vsauce',
923 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
924 'license': 'Standard YouTube License',
925 'series': 'Mind Field',
926 'season_number': 1,
927 'episode_number': 1,
928 },
929 'params': {
930 'skip_download': True,
931 },
932 'expected_warnings': [
933 'Skipping DASH manifest',
934 ],
935 },
022a5d66
S
936 {
937 # itag 212
938 'url': '1t24XAntNCY',
939 'only_matching': True,
fd5c4aab
S
940 },
941 {
942 # geo restricted to JP
943 'url': 'sJL6WA-aGkQ',
944 'only_matching': True,
945 },
d0ba5587
S
946 {
947 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
948 'only_matching': True,
949 },
2eb88d95
PH
950 ]
951
e0df6211
PH
952 def __init__(self, *args, **kwargs):
953 super(YoutubeIE, self).__init__(*args, **kwargs)
83799698 954 self._player_cache = {}
e0df6211 955
c5e8d7af
PH
956 def report_video_info_webpage_download(self, video_id):
957 """Report attempt to download video info webpage."""
69ea8ca4 958 self.to_screen('%s: Downloading video info webpage' % video_id)
c5e8d7af 959
c5e8d7af
PH
960 def report_information_extraction(self, video_id):
961 """Report attempt to extract video information."""
69ea8ca4 962 self.to_screen('%s: Extracting video information' % video_id)
c5e8d7af
PH
963
964 def report_unavailable_format(self, video_id, format):
965 """Report extracted video URL."""
69ea8ca4 966 self.to_screen('%s: Format %s not available' % (video_id, format))
c5e8d7af
PH
967
968 def report_rtmp_download(self):
969 """Indicate the download will use the RTMP protocol."""
69ea8ca4 970 self.to_screen('RTMP download detected')
c5e8d7af 971
60064c53
PH
972 def _signature_cache_id(self, example_sig):
973 """ Return a string representation of a signature """
78caa52a 974 return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
60064c53
PH
975
976 def _extract_signature_function(self, video_id, player_url, example_sig):
cf010131 977 id_m = re.match(
e31fed95 978 r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|(?:/[a-z]{2}_[A-Z]{2})?/base)?\.(?P<ext>[a-z]+)$',
cf010131 979 player_url)
c081b35c
PH
980 if not id_m:
981 raise ExtractorError('Cannot identify player %r' % player_url)
e0df6211
PH
982 player_type = id_m.group('ext')
983 player_id = id_m.group('id')
984
c4417ddb 985 # Read from filesystem cache
60064c53
PH
986 func_id = '%s_%s_%s' % (
987 player_type, player_id, self._signature_cache_id(example_sig))
c4417ddb 988 assert os.path.basename(func_id) == func_id
a0e07d31 989
69ea8ca4 990 cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
a0e07d31 991 if cache_spec is not None:
78caa52a 992 return lambda s: ''.join(s[i] for i in cache_spec)
83799698 993
6d1a55a5
PH
994 download_note = (
995 'Downloading player %s' % player_url
996 if self._downloader.params.get('verbose') else
997 'Downloading %s player %s' % (player_type, player_id)
998 )
e0df6211
PH
999 if player_type == 'js':
1000 code = self._download_webpage(
1001 player_url, video_id,
6d1a55a5 1002 note=download_note,
69ea8ca4 1003 errnote='Download of %s failed' % player_url)
83799698 1004 res = self._parse_sig_js(code)
c4417ddb 1005 elif player_type == 'swf':
e0df6211
PH
1006 urlh = self._request_webpage(
1007 player_url, video_id,
6d1a55a5 1008 note=download_note,
69ea8ca4 1009 errnote='Download of %s failed' % player_url)
e0df6211 1010 code = urlh.read()
83799698 1011 res = self._parse_sig_swf(code)
e0df6211
PH
1012 else:
1013 assert False, 'Invalid player type %r' % player_type
1014
785521bf
PH
1015 test_string = ''.join(map(compat_chr, range(len(example_sig))))
1016 cache_res = res(test_string)
1017 cache_spec = [ord(c) for c in cache_res]
83799698 1018
69ea8ca4 1019 self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
83799698
PH
1020 return res
1021
60064c53 1022 def _print_sig_code(self, func, example_sig):
edf3e38e
PH
1023 def gen_sig_code(idxs):
1024 def _genslice(start, end, step):
78caa52a 1025 starts = '' if start == 0 else str(start)
8bcc8756 1026 ends = (':%d' % (end + step)) if end + step >= 0 else ':'
69ea8ca4 1027 steps = '' if step == 1 else (':%d' % step)
78caa52a 1028 return 's[%s%s%s]' % (starts, ends, steps)
edf3e38e
PH
1029
1030 step = None
7af808a5
PH
1031 # Quelch pyflakes warnings - start will be set when step is set
1032 start = '(Never used)'
edf3e38e
PH
1033 for i, prev in zip(idxs[1:], idxs[:-1]):
1034 if step is not None:
1035 if i - prev == step:
1036 continue
1037 yield _genslice(start, prev, step)
1038 step = None
1039 continue
1040 if i - prev in [-1, 1]:
1041 step = i - prev
1042 start = prev
1043 continue
1044 else:
78caa52a 1045 yield 's[%d]' % prev
edf3e38e 1046 if step is None:
78caa52a 1047 yield 's[%d]' % i
edf3e38e
PH
1048 else:
1049 yield _genslice(start, i, step)
1050
78caa52a 1051 test_string = ''.join(map(compat_chr, range(len(example_sig))))
c705320f 1052 cache_res = func(test_string)
edf3e38e 1053 cache_spec = [ord(c) for c in cache_res]
78caa52a 1054 expr_code = ' + '.join(gen_sig_code(cache_spec))
60064c53
PH
1055 signature_id_tuple = '(%s)' % (
1056 ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
69ea8ca4 1057 code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
78caa52a 1058 ' return %s\n') % (signature_id_tuple, expr_code)
69ea8ca4 1059 self.to_screen('Extracted signature function:\n' + code)
edf3e38e 1060
e0df6211
PH
1061 def _parse_sig_js(self, jscode):
1062 funcname = self._search_regex(
3c90cc8b
S
1063 (r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
1064 r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\('),
1065 jscode, 'Initial JS player signature function name', group='sig')
2b25cb5d
PH
1066
1067 jsi = JSInterpreter(jscode)
1068 initial_function = jsi.extract_function(funcname)
e0df6211
PH
1069 return lambda s: initial_function([s])
1070
1071 def _parse_sig_swf(self, file_contents):
54256267 1072 swfi = SWFInterpreter(file_contents)
78caa52a 1073 TARGET_CLASSNAME = 'SignatureDecipher'
54256267 1074 searched_class = swfi.extract_class(TARGET_CLASSNAME)
78caa52a 1075 initial_function = swfi.extract_function(searched_class, 'decipher')
e0df6211
PH
1076 return lambda s: initial_function([s])
1077
83799698 1078 def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
257a2501 1079 """Turn the encrypted s field into a working signature"""
6b37f0be 1080
c8bf86d5 1081 if player_url is None:
69ea8ca4 1082 raise ExtractorError('Cannot decrypt signature without player_url')
920de7a2 1083
69ea8ca4 1084 if player_url.startswith('//'):
78caa52a 1085 player_url = 'https:' + player_url
3c90cc8b
S
1086 elif not re.match(r'https?://', player_url):
1087 player_url = compat_urlparse.urljoin(
1088 'https://www.youtube.com', player_url)
c8bf86d5 1089 try:
62af3a0e 1090 player_id = (player_url, self._signature_cache_id(s))
c8bf86d5
PH
1091 if player_id not in self._player_cache:
1092 func = self._extract_signature_function(
60064c53 1093 video_id, player_url, s
c8bf86d5
PH
1094 )
1095 self._player_cache[player_id] = func
1096 func = self._player_cache[player_id]
1097 if self._downloader.params.get('youtube_print_sig_code'):
60064c53 1098 self._print_sig_code(func, s)
c8bf86d5
PH
1099 return func(s)
1100 except Exception as e:
1101 tb = traceback.format_exc()
1102 raise ExtractorError(
78caa52a 1103 'Signature extraction failed: ' + tb, cause=e)
e0df6211 1104
360e1ca5 1105 def _get_subtitles(self, video_id, webpage):
de7f3446 1106 try:
60e47a26 1107 subs_doc = self._download_xml(
38c2e5b8 1108 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
7fad1c63
JMF
1109 video_id, note=False)
1110 except ExtractorError as err:
9b9c5355 1111 self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
de7f3446 1112 return {}
de7f3446
JMF
1113
1114 sub_lang_list = {}
60e47a26
JMF
1115 for track in subs_doc.findall('track'):
1116 lang = track.attrib['lang_code']
7e660ac1
LD
1117 if lang in sub_lang_list:
1118 continue
360e1ca5 1119 sub_formats = []
23d17e4b 1120 for ext in self._SUBTITLE_FORMATS:
15707c7e 1121 params = compat_urllib_parse_urlencode({
360e1ca5
JMF
1122 'lang': lang,
1123 'v': video_id,
1124 'fmt': ext,
1125 'name': track.attrib['name'].encode('utf-8'),
1126 })
1127 sub_formats.append({
1128 'url': 'https://www.youtube.com/api/timedtext?' + params,
1129 'ext': ext,
1130 })
1131 sub_lang_list[lang] = sub_formats
de7f3446 1132 if not sub_lang_list:
69ea8ca4 1133 self._downloader.report_warning('video doesn\'t have subtitles')
de7f3446
JMF
1134 return {}
1135 return sub_lang_list
1136
a72778d3
S
1137 def _get_ytplayer_config(self, video_id, webpage):
1138 patterns = (
526b3b07
S
1139 # User data may contain arbitrary character sequences that may affect
1140 # JSON extraction with regex, e.g. when '};' is contained the second
1141 # regex won't capture the whole JSON. Yet working around by trying more
1142 # concrete regex first keeping in mind proper quoted string handling
1143 # to be implemented in future that will replace this workaround (see
1144 # https://github.com/rg3/youtube-dl/issues/7468,
1145 # https://github.com/rg3/youtube-dl/pull/7599)
a72778d3
S
1146 r';ytplayer\.config\s*=\s*({.+?});ytplayer',
1147 r';ytplayer\.config\s*=\s*({.+?});',
1148 )
1149 config = self._search_regex(
1150 patterns, webpage, 'ytplayer.config', default=None)
1151 if config:
1152 return self._parse_json(
1153 uppercase_escape(config), video_id, fatal=False)
0e49d9a6 1154
360e1ca5 1155 def _get_automatic_captions(self, video_id, webpage):
de7f3446
JMF
1156 """We need the webpage for getting the captions url, pass it as an
1157 argument to speed up the process."""
69ea8ca4 1158 self.to_screen('%s: Looking for automatic captions' % video_id)
a72778d3 1159 player_config = self._get_ytplayer_config(video_id, webpage)
78caa52a 1160 err_msg = 'Couldn\'t find automatic captions for %s' % video_id
a72778d3 1161 if not player_config:
de7f3446
JMF
1162 self._downloader.report_warning(err_msg)
1163 return {}
de7f3446 1164 try:
0792d563 1165 args = player_config['args']
b78b292f
S
1166 caption_url = args.get('ttsurl')
1167 if caption_url:
1168 timestamp = args['timestamp']
1169 # We get the available subtitles
15707c7e 1170 list_params = compat_urllib_parse_urlencode({
b78b292f
S
1171 'type': 'list',
1172 'tlangs': 1,
1173 'asrs': 1,
1174 })
1175 list_url = caption_url + '&' + list_params
1176 caption_list = self._download_xml(list_url, video_id)
1177 original_lang_node = caption_list.find('track')
1178 if original_lang_node is None:
1179 self._downloader.report_warning('Video doesn\'t have automatic captions')
1180 return {}
1181 original_lang = original_lang_node.attrib['lang_code']
1182 caption_kind = original_lang_node.attrib.get('kind', '')
1183
1184 sub_lang_list = {}
1185 for lang_node in caption_list.findall('target'):
1186 sub_lang = lang_node.attrib['lang_code']
1187 sub_formats = []
1188 for ext in self._SUBTITLE_FORMATS:
15707c7e 1189 params = compat_urllib_parse_urlencode({
b78b292f
S
1190 'lang': original_lang,
1191 'tlang': sub_lang,
1192 'fmt': ext,
1193 'ts': timestamp,
1194 'kind': caption_kind,
1195 })
1196 sub_formats.append({
1197 'url': caption_url + '&' + params,
1198 'ext': ext,
1199 })
1200 sub_lang_list[sub_lang] = sub_formats
1201 return sub_lang_list
1202
1203 # Some videos don't provide ttsurl but rather caption_tracks and
1204 # caption_translation_languages (e.g. 20LmZk1hakA)
1205 caption_tracks = args['caption_tracks']
1206 caption_translation_languages = args['caption_translation_languages']
1207 caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
15707c7e 1208 parsed_caption_url = compat_urllib_parse_urlparse(caption_url)
b78b292f 1209 caption_qs = compat_parse_qs(parsed_caption_url.query)
055e6f36
JMF
1210
1211 sub_lang_list = {}
b78b292f
S
1212 for lang in caption_translation_languages.split(','):
1213 lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
1214 sub_lang = lang_qs.get('lc', [None])[0]
1215 if not sub_lang:
1216 continue
360e1ca5 1217 sub_formats = []
23d17e4b 1218 for ext in self._SUBTITLE_FORMATS:
b78b292f
S
1219 caption_qs.update({
1220 'tlang': [sub_lang],
1221 'fmt': [ext],
360e1ca5 1222 })
b78b292f 1223 sub_url = compat_urlparse.urlunparse(parsed_caption_url._replace(
15707c7e 1224 query=compat_urllib_parse_urlencode(caption_qs, True)))
360e1ca5 1225 sub_formats.append({
b78b292f 1226 'url': sub_url,
360e1ca5
JMF
1227 'ext': ext,
1228 })
1229 sub_lang_list[sub_lang] = sub_formats
055e6f36 1230 return sub_lang_list
de7f3446
JMF
1231 # An extractor error can be raise by the download process if there are
1232 # no automatic captions but there are subtitles
1233 except (KeyError, ExtractorError):
1234 self._downloader.report_warning(err_msg)
1235 return {}
1236
d77ab8e2
S
1237 def _mark_watched(self, video_id, video_info):
1238 playback_url = video_info.get('videostats_playback_base_url', [None])[0]
1239 if not playback_url:
1240 return
1241 parsed_playback_url = compat_urlparse.urlparse(playback_url)
1242 qs = compat_urlparse.parse_qs(parsed_playback_url.query)
1243
1244 # cpn generation algorithm is reverse engineered from base.js.
1245 # In fact it works even with dummy cpn.
1246 CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
1247 cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
1248
1249 qs.update({
1250 'ver': ['2'],
1251 'cpn': [cpn],
1252 })
1253 playback_url = compat_urlparse.urlunparse(
15707c7e 1254 parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
d77ab8e2
S
1255
1256 self._download_webpage(
1257 playback_url, video_id, 'Marking watched',
1258 'Unable to mark watched', fatal=False)
1259
97665381
PH
1260 @classmethod
1261 def extract_id(cls, url):
1262 mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
c5e8d7af 1263 if mobj is None:
69ea8ca4 1264 raise ExtractorError('Invalid URL: %s' % url)
c5e8d7af
PH
1265 video_id = mobj.group(2)
1266 return video_id
1267
1fb07d10
JG
1268 def _extract_annotations(self, video_id):
1269 url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
69ea8ca4 1270 return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
1fb07d10 1271
9cafc3fd
S
1272 @staticmethod
1273 def _extract_chapters(description, duration):
1274 if not description:
1275 return None
1276 chapter_lines = re.findall(
1277 r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
1278 description)
1279 if not chapter_lines:
1280 return None
1281 chapters = []
1282 for next_num, (chapter_line, time_point) in enumerate(
1283 chapter_lines, start=1):
1284 start_time = parse_duration(time_point)
1285 if start_time is None:
1286 continue
1287 end_time = (duration if next_num == len(chapter_lines)
1288 else parse_duration(chapter_lines[next_num][1]))
1289 if end_time is None:
1290 continue
1291 chapter_title = re.sub(
1292 r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
1293 chapter_title = re.sub(r'\s+', ' ', chapter_title)
1294 chapters.append({
1295 'start_time': start_time,
1296 'end_time': end_time,
1297 'title': chapter_title,
1298 })
1299 return chapters
1300
c5e8d7af 1301 def _real_extract(self, url):
cf7e015f
S
1302 url, smuggled_data = unsmuggle_url(url, {})
1303
7e8c0af0 1304 proto = (
78caa52a
PH
1305 'http' if self._downloader.params.get('prefer_insecure', False)
1306 else 'https')
7e8c0af0 1307
7c80519c 1308 start_time = None
297a564b 1309 end_time = None
7c80519c
JMF
1310 parsed_url = compat_urllib_parse_urlparse(url)
1311 for component in [parsed_url.fragment, parsed_url.query]:
1312 query = compat_parse_qs(component)
297a564b 1313 if start_time is None and 't' in query:
7c80519c 1314 start_time = parse_duration(query['t'][0])
2929fa0e
JMF
1315 if start_time is None and 'start' in query:
1316 start_time = parse_duration(query['start'][0])
297a564b
JMF
1317 if end_time is None and 'end' in query:
1318 end_time = parse_duration(query['end'][0])
7c80519c 1319
c5e8d7af
PH
1320 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
1321 mobj = re.search(self._NEXT_URL_RE, url)
1322 if mobj:
7fd002c0 1323 url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
97665381 1324 video_id = self.extract_id(url)
c5e8d7af
PH
1325
1326 # Get video webpage
aa79ac0c 1327 url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
a1f934b1 1328 video_webpage = self._download_webpage(url, video_id)
c5e8d7af
PH
1329
1330 # Attempt to extract SWF player URL
e0df6211 1331 mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
c5e8d7af
PH
1332 if mobj is not None:
1333 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
1334 else:
1335 player_url = None
1336
d8d24a92
S
1337 dash_mpds = []
1338
1339 def add_dash_mpd(video_info):
1340 dash_mpd = video_info.get('dashmpd')
1341 if dash_mpd and dash_mpd[0] not in dash_mpds:
1342 dash_mpds.append(dash_mpd[0])
1343
c5e8d7af 1344 # Get video info
6449cd80 1345 embed_webpage = None
2fe1ff85 1346 is_live = None
c108eb73 1347 if re.search(r'player-age-gate-content">', video_webpage) is not None:
c108eb73
JMF
1348 age_gate = True
1349 # We simulate the access to the video from www.youtube.com/v/{video_id}
1350 # this can be viewed without login into Youtube
beb95e77
CL
1351 url = proto + '://www.youtube.com/embed/%s' % video_id
1352 embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
15707c7e 1353 data = compat_urllib_parse_urlencode({
2c57c7fa
JMF
1354 'video_id': video_id,
1355 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
c084c934 1356 'sts': self._search_regex(
beb95e77 1357 r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
2c57c7fa 1358 })
7e8c0af0 1359 video_info_url = proto + '://www.youtube.com/get_video_info?' + data
94bd3613
PH
1360 video_info_webpage = self._download_webpage(
1361 video_info_url, video_id,
20436c30 1362 note='Refetching age-gated info webpage',
94bd3613 1363 errnote='unable to download video info webpage')
c5e8d7af 1364 video_info = compat_parse_qs(video_info_webpage)
d8d24a92 1365 add_dash_mpd(video_info)
c108eb73
JMF
1366 else:
1367 age_gate = False
bc93bdb5 1368 video_info = None
d8d24a92 1369 # Try looking directly into the video webpage
a72778d3
S
1370 ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
1371 if ytplayer_config:
4e62ebe2 1372 args = ytplayer_config['args']
d8d24a92
S
1373 if args.get('url_encoded_fmt_stream_map'):
1374 # Convert to the same format returned by compat_parse_qs
1375 video_info = dict((k, [v]) for k, v in args.items())
1376 add_dash_mpd(video_info)
6496ccb4
S
1377 # Rental video is not rented but preview is available (e.g.
1378 # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
1379 # https://github.com/rg3/youtube-dl/issues/10532)
1380 if not video_info and args.get('ypc_vid'):
1381 return self.url_result(
1382 args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
2fe1ff85
JMF
1383 if args.get('livestream') == '1' or args.get('live_playback') == 1:
1384 is_live = True
0a3cf9ad
S
1385 if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
1386 # We also try looking in get_video_info since it may contain different dashmpd
1387 # URL that points to a DASH manifest with possibly different itag set (some itags
1388 # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
1389 # manifest pointed by get_video_info's dashmpd).
1390 # The general idea is to take a union of itags of both DASH manifests (for example
1391 # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
4e62ebe2 1392 self.report_video_info_webpage_download(video_id)
0a3cf9ad 1393 for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
810fb84d
PH
1394 video_info_url = (
1395 '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
1396 % (proto, video_id, el_type))
1397 video_info_webpage = self._download_webpage(
1398 video_info_url,
4e62ebe2
JMF
1399 video_id, note=False,
1400 errnote='unable to download video info webpage')
0a3cf9ad 1401 get_video_info = compat_parse_qs(video_info_webpage)
87dc4511
JMF
1402 if get_video_info.get('use_cipher_signature') != ['True']:
1403 add_dash_mpd(get_video_info)
0a3cf9ad
S
1404 if not video_info:
1405 video_info = get_video_info
1406 if 'token' in get_video_info:
89ea063e
S
1407 # Different get_video_info requests may report different results, e.g.
1408 # some may report video unavailability, but some may serve it without
1409 # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
1410 # the original webpage as well as el=info and el=embedded get_video_info
1411 # requests report video unavailability due to geo restriction while
1412 # el=detailpage succeeds and returns valid data). This is probably
1413 # due to YouTube measures against IP ranges of hosting providers.
1414 # Working around by preferring the first succeeded video_info containing
1415 # the token if no such video_info yet was found.
44b2264f
S
1416 if 'token' not in video_info:
1417 video_info = get_video_info
4e62ebe2 1418 break
c5e8d7af
PH
1419 if 'token' not in video_info:
1420 if 'reason' in video_info:
af214c3a 1421 if 'The uploader has not made this video available in your country.' in video_info['reason']:
fd5c4aab
S
1422 regions_allowed = self._html_search_meta(
1423 'regionsAllowed', video_webpage, default=None)
1424 countries = regions_allowed.split(',') if regions_allowed else None
1425 self.raise_geo_restricted(
1426 msg=video_info['reason'][0], countries=countries)
d11271dd 1427 raise ExtractorError(
78caa52a 1428 'YouTube said: %s' % video_info['reason'][0],
d11271dd 1429 expected=True, video_id=video_id)
c5e8d7af 1430 else:
d11271dd 1431 raise ExtractorError(
78caa52a 1432 '"token" parameter not in video info for unknown reason',
d11271dd 1433 video_id=video_id)
c5e8d7af 1434
cf7e015f
S
1435 # title
1436 if 'title' in video_info:
1437 video_title = video_info['title'][0]
1438 else:
1439 self._downloader.report_warning('Unable to extract video title')
1440 video_title = '_'
1441
1442 # description
9cafc3fd 1443 description_original = video_description = get_element_by_id("eow-description", video_webpage)
cf7e015f 1444 if video_description:
9cafc3fd 1445 description_original = video_description = re.sub(r'''(?x)
cf7e015f 1446 <a\s+
25cb7a0e 1447 (?:[a-zA-Z-]+="[^"]*"\s+)*?
23f13e97 1448 (?:title|href)="([^"]+)"\s+
25cb7a0e 1449 (?:[a-zA-Z-]+="[^"]*"\s+)*?
525cedb9 1450 class="[^"]*"[^>]*>
23f13e97 1451 [^<]+\.{3}\s*
cf7e015f
S
1452 </a>
1453 ''', r'\1', video_description)
1454 video_description = clean_html(video_description)
1455 else:
1456 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
1457 if fd_mobj:
1458 video_description = unescapeHTML(fd_mobj.group(1))
1459 else:
1460 video_description = ''
1461
5e1eddb9
S
1462 if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
1463 if not self._downloader.params.get('noplaylist'):
1464 entries = []
1465 feed_ids = []
6863631c 1466 multifeed_metadata_list = video_info['multifeed_metadata_list'][0]
5e1eddb9 1467 for feed in multifeed_metadata_list.split(','):
6863631c
S
1468 # Unquote should take place before split on comma (,) since textual
1469 # fields may contain comma as well (see
1470 # https://github.com/rg3/youtube-dl/issues/8536)
1471 feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
5e1eddb9
S
1472 entries.append({
1473 '_type': 'url_transparent',
1474 'ie_key': 'Youtube',
1475 'url': smuggle_url(
1476 '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
1477 {'force_singlefeed': True}),
1478 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
1479 })
1480 feed_ids.append(feed_data['id'][0])
1481 self.to_screen(
1482 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
1483 % (', '.join(feed_ids), video_id))
1484 return self.playlist_result(entries, video_id, video_title, video_description)
1485 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
cf7e015f 1486
1d699755
PH
1487 if 'view_count' in video_info:
1488 view_count = int(video_info['view_count'][0])
1489 else:
1490 view_count = None
1491
c5e8d7af
PH
1492 # Check for "rental" videos
1493 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
c9612c04 1494 raise ExtractorError('"rental" videos not supported. See https://github.com/rg3/youtube-dl/issues/359 for more information.', expected=True)
c5e8d7af
PH
1495
1496 # Start extracting information
1497 self.report_information_extraction(video_id)
1498
1499 # uploader
1500 if 'author' not in video_info:
69ea8ca4 1501 raise ExtractorError('Unable to extract uploader name')
7fd002c0 1502 video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
c5e8d7af
PH
1503
1504 # uploader_id
1505 video_uploader_id = None
fd050249
S
1506 video_uploader_url = None
1507 mobj = re.search(
1508 r'<link itemprop="url" href="(?P<uploader_url>https?://www.youtube.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
1509 video_webpage)
c5e8d7af 1510 if mobj is not None:
fd050249
S
1511 video_uploader_id = mobj.group('uploader_id')
1512 video_uploader_url = mobj.group('uploader_url')
c5e8d7af 1513 else:
69ea8ca4 1514 self._downloader.report_warning('unable to extract uploader nickname')
c5e8d7af 1515
c5e8d7af 1516 # thumbnail image
7763b04e
JMF
1517 # We try first to get a high quality image:
1518 m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
1519 video_webpage, re.DOTALL)
1520 if m_thumb is not None:
1521 video_thumbnail = m_thumb.group(1)
1522 elif 'thumbnail_url' not in video_info:
69ea8ca4 1523 self._downloader.report_warning('unable to extract video thumbnail')
f490e77e 1524 video_thumbnail = None
c5e8d7af 1525 else: # don't panic if we can't find it
7fd002c0 1526 video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
c5e8d7af
PH
1527
1528 # upload date
9d0b581f
S
1529 upload_date = self._html_search_meta(
1530 'datePublished', video_webpage, 'upload date', default=None)
1531 if not upload_date:
1532 upload_date = self._search_regex(
1533 [r'(?s)id="eow-date.*?>(.*?)</span>',
1534 r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
1535 video_webpage, 'upload date', default=None)
1536 if upload_date:
1537 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
1538 upload_date = unified_strdate(upload_date)
c5e8d7af 1539
7caf9830
S
1540 video_license = self._html_search_regex(
1541 r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
1542 video_webpage, 'license', default=None)
1543
0cb58b02
S
1544 m_music = re.search(
1545 r'<h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*<ul[^>]*>\s*<li>(?P<title>.+?) by (?P<creator>.+?)(?:\(.+?\))?</li',
1546 video_webpage)
1547 if m_music:
1548 video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
1549 video_creator = clean_html(m_music.group('creator'))
1550 else:
1551 video_alt_title = video_creator = None
1552
12afdc2a
S
1553 m_episode = re.search(
1554 r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
1555 video_webpage)
1556 if m_episode:
1557 series = m_episode.group('series')
1558 season_number = int(m_episode.group('season'))
1559 episode_number = int(m_episode.group('episode'))
1560 else:
1561 series = season_number = episode_number = None
1562
55f7bd2d
PH
1563 m_cat_container = self._search_regex(
1564 r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
624dcebf 1565 video_webpage, 'categories', default=None)
ec8deefc 1566 if m_cat_container:
ad3bc6ac 1567 category = self._html_search_regex(
01ed5c9b 1568 r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
ad3bc6ac
PH
1569 default=None)
1570 video_categories = None if category is None else [category]
1571 else:
1572 video_categories = None
ec8deefc 1573
000b6b5a
S
1574 video_tags = [
1575 unescapeHTML(m.group('content'))
1576 for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
1577
f30a38be 1578 def _extract_count(count_name):
c93d53f5
S
1579 return str_to_int(self._search_regex(
1580 r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
1581 % re.escape(count_name),
1582 video_webpage, count_name, default=None))
1583
69ea8ca4
PH
1584 like_count = _extract_count('like')
1585 dislike_count = _extract_count('dislike')
336c3a69 1586
c5e8d7af 1587 # subtitles
d82134c3 1588 video_subtitles = self.extract_subtitles(video_id, video_webpage)
360e1ca5 1589 automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
c5e8d7af 1590
556dbe7f
S
1591 video_duration = try_get(
1592 video_info, lambda x: int_or_none(x['length_seconds'][0]))
1593 if not video_duration:
1594 video_duration = parse_duration(self._html_search_meta(
1595 'duration', video_webpage, 'video duration'))
c5e8d7af 1596
1fb07d10
JG
1597 # annotations
1598 video_annotations = None
1599 if self._downloader.params.get('writeannotations', False):
5f6a1245 1600 video_annotations = self._extract_annotations(video_id)
1fb07d10 1601
9cafc3fd
S
1602 chapters = self._extract_chapters(description_original, video_duration)
1603
c5e8d7af
PH
1604 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
1605 self.report_rtmp_download()
dd27fd17
PH
1606 formats = [{
1607 'format_id': '_rtmp',
1608 'protocol': 'rtmp',
1609 'url': video_info['conn'][0],
1610 'player_url': player_url,
1611 }]
24270b03 1612 elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
5f6a1245 1613 encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
00fe14fc 1614 if 'rtmpe%3Dyes' in encoded_url_map:
a7055eb9 1615 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
3318832e 1616 formats_spec = {}
82156fdb 1617 fmt_list = video_info.get('fmt_list', [''])[0]
1618 if fmt_list:
1619 for fmt in fmt_list.split(','):
1620 spec = fmt.split('/')
3318832e 1621 if len(spec) > 1:
1622 width_height = spec[1].split('x')
1623 if len(width_height) == 2:
1624 formats_spec[spec[0]] = {
1625 'resolution': spec[1],
1626 'width': int_or_none(width_height[0]),
1627 'height': int_or_none(width_height[1]),
1628 }
c9afb51c 1629 formats = []
00fe14fc 1630 for url_data_str in encoded_url_map.split(','):
c5e8d7af 1631 url_data = compat_parse_qs(url_data_str)
201e9eaa
PH
1632 if 'itag' not in url_data or 'url' not in url_data:
1633 continue
1634 format_id = url_data['itag'][0]
1635 url = url_data['url'][0]
1636
1637 if 'sig' in url_data:
1638 url += '&signature=' + url_data['sig'][0]
1639 elif 's' in url_data:
1640 encrypted_sig = url_data['s'][0]
6449cd80 1641 ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
201e9eaa 1642
beb95e77 1643 jsplayer_url_json = self._search_regex(
6449cd80
PH
1644 ASSETS_RE,
1645 embed_webpage if age_gate else video_webpage,
1646 'JS player URL (1)', default=None)
1647 if not jsplayer_url_json and not age_gate:
1648 # We need the embed website after all
1649 if embed_webpage is None:
1650 embed_url = proto + '://www.youtube.com/embed/%s' % video_id
1651 embed_webpage = self._download_webpage(
1652 embed_url, video_id, 'Downloading embed webpage')
1653 jsplayer_url_json = self._search_regex(
1654 ASSETS_RE, embed_webpage, 'JS player URL')
1655
beb95e77 1656 player_url = json.loads(jsplayer_url_json)
201e9eaa
PH
1657 if player_url is None:
1658 player_url_json = self._search_regex(
1659 r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
78caa52a 1660 video_webpage, 'age gate player URL')
201e9eaa
PH
1661 player_url = json.loads(player_url_json)
1662
1663 if self._downloader.params.get('verbose'):
cf010131 1664 if player_url is None:
201e9eaa
PH
1665 player_version = 'unknown'
1666 player_desc = 'unknown'
1667 else:
1668 if player_url.endswith('swf'):
1669 player_version = self._search_regex(
1670 r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
78caa52a 1671 'flash player', fatal=False)
201e9eaa 1672 player_desc = 'flash player %s' % player_version
cf010131 1673 else:
201e9eaa 1674 player_version = self._search_regex(
b62985a9
YCH
1675 [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js',
1676 r'(?:www|player)-([^/]+)(?:/[a-z]{2}_[A-Z]{2})?/base\.js'],
201e9eaa
PH
1677 player_url,
1678 'html5 player', fatal=False)
78caa52a 1679 player_desc = 'html5 player %s' % player_version
201e9eaa 1680
60064c53 1681 parts_sizes = self._signature_cache_id(encrypted_sig)
69ea8ca4 1682 self.to_screen('{%s} signature length %s, %s' %
9e1a5b84 1683 (format_id, parts_sizes, player_desc))
201e9eaa
PH
1684
1685 signature = self._decrypt_signature(
1686 encrypted_sig, video_id, player_url, age_gate)
1687 url += '&signature=' + signature
1688 if 'ratebypass' not in url:
1689 url += '&ratebypass=yes'
c9afb51c 1690
94278f72
YCH
1691 dct = {
1692 'format_id': format_id,
1693 'url': url,
1694 'player_url': player_url,
1695 }
1696 if format_id in self._formats:
1697 dct.update(self._formats[format_id])
3318832e 1698 if format_id in formats_spec:
1699 dct.update(formats_spec[format_id])
94278f72 1700
aabc2be6
S
1701 # Some itags are not included in DASH manifest thus corresponding formats will
1702 # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
1703 # Trying to extract metadata from url_encoded_fmt_stream_map entry.
1704 mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
1705 width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
94278f72
YCH
1706
1707 more_fields = {
c9afb51c 1708 'filesize': int_or_none(url_data.get('clen', [None])[0]),
aabc2be6 1709 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
c9afb51c
AH
1710 'width': width,
1711 'height': height,
1712 'fps': int_or_none(url_data.get('fps', [None])[0]),
aabc2be6 1713 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
c9afb51c 1714 }
94278f72
YCH
1715 for key, value in more_fields.items():
1716 if value:
1717 dct[key] = value
aabc2be6
S
1718 type_ = url_data.get('type', [None])[0]
1719 if type_:
1720 type_split = type_.split(';')
1721 kind_ext = type_split[0].split('/')
1722 if len(kind_ext) == 2:
94278f72
YCH
1723 kind, _ = kind_ext
1724 dct['ext'] = mimetype2ext(type_split[0])
aabc2be6
S
1725 if kind in ('audio', 'video'):
1726 codecs = None
1727 for mobj in re.finditer(
1728 r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
1729 if mobj.group('key') == 'codecs':
1730 codecs = mobj.group('val')
1731 break
1732 if codecs:
6310acf5 1733 dct.update(parse_codecs(codecs))
aabc2be6 1734 formats.append(dct)
1d043b93
JMF
1735 elif video_info.get('hlsvp'):
1736 manifest_url = video_info['hlsvp'][0]
89beedd3
RA
1737 formats = []
1738 m3u8_formats = self._extract_m3u8_formats(
1739 manifest_url, video_id, 'mp4', fatal=False)
1740 for a_format in m3u8_formats:
1741 itag = self._search_regex(
1742 r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
1743 if itag:
1744 a_format['format_id'] = itag
1745 if itag in self._formats:
1746 dct = self._formats[itag].copy()
1747 dct.update(a_format)
1748 a_format = dct
1749 a_format['player_url'] = player_url
1750 # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
049d71d8 1751 a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
89beedd3 1752 formats.append(a_format)
c5e8d7af 1753 else:
8ceabd4d
S
1754 unavailable_message = self._html_search_regex(
1755 r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
1756 video_webpage, 'unavailable message', default=None)
1757 if unavailable_message:
1758 raise ExtractorError(unavailable_message, expected=True)
69ea8ca4 1759 raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
c5e8d7af 1760
dd27fd17 1761 # Look for the DASH manifest
203fb43f 1762 if self._downloader.params.get('youtube_include_dash_manifest', True):
77c6fb5b 1763 dash_mpd_fatal = True
8ff648e4 1764 for mpd_url in dash_mpds:
d8d24a92 1765 dash_formats = {}
774e208f 1766 try:
05d0d131
YCH
1767 def decrypt_sig(mobj):
1768 s = mobj.group(1)
1769 dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
1770 return '/signature/%s' % dec_s
1771
8ff648e4 1772 mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
2d2fa82d 1773
8ff648e4 1774 for df in self._extract_mpd_formats(
1775 mpd_url, video_id, fatal=dash_mpd_fatal,
1776 formats_dict=self._formats):
d8d24a92
S
1777 # Do not overwrite DASH format found in some previous DASH manifest
1778 if df['format_id'] not in dash_formats:
1779 dash_formats[df['format_id']] = df
77c6fb5b
S
1780 # Additional DASH manifests may end up in HTTP Error 403 therefore
1781 # allow them to fail without bug report message if we already have
1782 # some DASH manifest succeeded. This is temporary workaround to reduce
1783 # burst of bug reports until we figure out the reason and whether it
1784 # can be fixed at all.
1785 dash_mpd_fatal = False
774e208f
PH
1786 except (ExtractorError, KeyError) as e:
1787 self.report_warning(
1788 'Skipping DASH manifest: %r' % e, video_id)
d8d24a92 1789 if dash_formats:
04b3b3df
JMF
1790 # Remove the formats we found through non-DASH, they
1791 # contain less info and it can be wrong, because we use
1792 # fixed values (for example the resolution). See
1793 # https://github.com/rg3/youtube-dl/issues/5774 for an
1794 # example.
d80265cc 1795 formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
d8d24a92 1796 formats.extend(dash_formats.values())
d80044c2 1797
6271f1ca
PH
1798 # Check for malformed aspect ratio
1799 stretched_m = re.search(
1800 r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
1801 video_webpage)
1802 if stretched_m:
313dfc45
LL
1803 w = float(stretched_m.group('w'))
1804 h = float(stretched_m.group('h'))
5faf9fed
S
1805 # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
1806 # We will only process correct ratios.
313dfc45 1807 if w > 0 and h > 0:
41f24c32 1808 ratio = w / h
313dfc45
LL
1809 for f in formats:
1810 if f.get('vcodec') != 'none':
1811 f['stretched_ratio'] = ratio
6271f1ca 1812
4bcc7bd1 1813 self._sort_formats(formats)
4ea3be0a 1814
d77ab8e2
S
1815 self.mark_watched(video_id, video_info)
1816
4ea3be0a 1817 return {
8bcc8756
JW
1818 'id': video_id,
1819 'uploader': video_uploader,
1820 'uploader_id': video_uploader_id,
fd050249 1821 'uploader_url': video_uploader_url,
8bcc8756 1822 'upload_date': upload_date,
7caf9830 1823 'license': video_license,
0cb58b02 1824 'creator': video_creator,
8bcc8756 1825 'title': video_title,
0cb58b02 1826 'alt_title': video_alt_title,
8bcc8756
JW
1827 'thumbnail': video_thumbnail,
1828 'description': video_description,
1829 'categories': video_categories,
000b6b5a 1830 'tags': video_tags,
8bcc8756 1831 'subtitles': video_subtitles,
360e1ca5 1832 'automatic_captions': automatic_captions,
8bcc8756
JW
1833 'duration': video_duration,
1834 'age_limit': 18 if age_gate else 0,
1835 'annotations': video_annotations,
9cafc3fd 1836 'chapters': chapters,
7e8c0af0 1837 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
8bcc8756 1838 'view_count': view_count,
4ea3be0a 1839 'like_count': like_count,
1840 'dislike_count': dislike_count,
2d30521a 1841 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
8bcc8756 1842 'formats': formats,
2fe1ff85 1843 'is_live': is_live,
7c80519c 1844 'start_time': start_time,
297a564b 1845 'end_time': end_time,
12afdc2a
S
1846 'series': series,
1847 'season_number': season_number,
1848 'episode_number': episode_number,
4ea3be0a 1849 }
c5e8d7af 1850
5f6a1245 1851
40805306 1852class YoutubeSharedVideoIE(InfoExtractor):
fd8c8c7d 1853 _VALID_URL = r'(?:https?:)?//(?:www\.)?youtube\.com/shared\?.*\bci=(?P<id>[0-9A-Za-z_-]{11})'
40805306
YCH
1854 IE_NAME = 'youtube:shared'
1855
1856 _TEST = {
1857 'url': 'https://www.youtube.com/shared?ci=1nEzmT-M4fU',
1858 'info_dict': {
1859 'id': 'uPDB5I9wfp8',
1860 'ext': 'webm',
1861 'title': 'Pocoyo: 90 minutos de episódios completos Português para crianças - PARTE 3',
1862 'description': 'md5:d9e4d9346a2dfff4c7dc4c8cec0f546d',
1863 'upload_date': '20160219',
1864 'uploader': 'Pocoyo - Português (BR)',
1865 'uploader_id': 'PocoyoBrazil',
1866 },
1867 'add_ie': ['Youtube'],
1868 'params': {
1869 # There are already too many Youtube downloads
1870 'skip_download': True,
1871 },
1872 }
1873
1874 def _real_extract(self, url):
1875 video_id = self._match_id(url)
1876
1877 webpage = self._download_webpage(url, video_id)
1878
1879 real_video_id = self._html_search_meta(
1880 'videoId', webpage, 'YouTube video id', fatal=True)
1881
1882 return self.url_result(real_video_id, YoutubeIE.ie_key())
1883
1884
8e7aad20 1885class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
78caa52a 1886 IE_DESC = 'YouTube.com playlists'
d67cc9fa 1887 _VALID_URL = r"""(?x)(?:
c5e8d7af
PH
1888 (?:https?://)?
1889 (?:\w+\.)?
c5e8d7af 1890 (?:
feaa5ad7
S
1891 youtube\.com/
1892 (?:
87dadd45 1893 (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
feaa5ad7
S
1894 \? (?:.*?[&;])*? (?:p|a|list)=
1895 | p/
1896 )|
1897 youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
c5e8d7af 1898 )
d67cc9fa 1899 (
a6857510 1900 (?:PL|LL|EC|UU|FL|RD|UL|TL)?[0-9A-Za-z-_]{10,}
5f6a1245 1901 # Top tracks, they can also include dots
d67cc9fa
JMF
1902 |(?:MC)[\w\.]*
1903 )
c5e8d7af
PH
1904 .*
1905 |
d0ba5587
S
1906 (%(playlist_id)s)
1907 )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
c867adc6 1908 _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&disable_polymer=true'
648e6a1f 1909 _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
78caa52a 1910 IE_NAME = 'youtube:playlist'
81127aa5
PH
1911 _TESTS = [{
1912 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
1913 'info_dict': {
1914 'title': 'ytdl test PL',
a1cf99d0 1915 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
81127aa5
PH
1916 },
1917 'playlist_count': 3,
9291475f
PH
1918 }, {
1919 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
1920 'info_dict': {
acf757f4 1921 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
9291475f
PH
1922 'title': 'YDL_Empty_List',
1923 },
1924 'playlist_count': 0,
4201ba13 1925 'skip': 'This playlist is private',
9291475f
PH
1926 }, {
1927 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
1928 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
1929 'info_dict': {
1930 'title': '29C3: Not my department',
acf757f4 1931 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
9291475f
PH
1932 },
1933 'playlist_count': 95,
1934 }, {
1935 'note': 'issue #673',
1936 'url': 'PLBB231211A4F62143',
1937 'info_dict': {
f46a8702 1938 'title': '[OLD]Team Fortress 2 (Class-based LP)',
acf757f4 1939 'id': 'PLBB231211A4F62143',
9291475f
PH
1940 },
1941 'playlist_mincount': 26,
1942 }, {
1943 'note': 'Large playlist',
1944 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
1945 'info_dict': {
1946 'title': 'Uploads from Cauchemar',
acf757f4 1947 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
9291475f
PH
1948 },
1949 'playlist_mincount': 799,
1950 }, {
1951 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
1952 'info_dict': {
1953 'title': 'YDL_safe_search',
acf757f4 1954 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
9291475f
PH
1955 },
1956 'playlist_count': 2,
4201ba13 1957 'skip': 'This playlist is private',
ac7553d0
PH
1958 }, {
1959 'note': 'embedded',
2d3d2997 1960 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
ac7553d0
PH
1961 'playlist_count': 4,
1962 'info_dict': {
1963 'title': 'JODA15',
acf757f4 1964 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
ac7553d0 1965 }
87dadd45
S
1966 }, {
1967 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
1968 'playlist_mincount': 485,
1969 'info_dict': {
1970 'title': '2017 華語最新單曲 (2/24更新)',
1971 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
1972 }
6b08cdf6
PH
1973 }, {
1974 'note': 'Embedded SWF player',
2d3d2997 1975 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
6b08cdf6
PH
1976 'playlist_count': 4,
1977 'info_dict': {
1978 'title': 'JODA7',
acf757f4 1979 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
6b08cdf6 1980 }
4b7df0d3
JMF
1981 }, {
1982 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
1983 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
1984 'info_dict': {
acf757f4
PH
1985 'title': 'Uploads from Interstellar Movie',
1986 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
4b7df0d3 1987 },
481cc733 1988 'playlist_mincount': 21,
dacb3a86
S
1989 }, {
1990 # Playlist URL that does not actually serve a playlist
1991 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
1992 'info_dict': {
1993 'id': 'FqZTN594JQw',
1994 'ext': 'webm',
1995 'title': "Smiley's People 01 detective, Adventure Series, Action",
1996 'uploader': 'STREEM',
1997 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
ec85ded8 1998 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
dacb3a86
S
1999 'upload_date': '20150526',
2000 'license': 'Standard YouTube License',
2001 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
2002 'categories': ['People & Blogs'],
2003 'tags': list,
2004 'like_count': int,
2005 'dislike_count': int,
2006 },
2007 'params': {
2008 'skip_download': True,
2009 },
2010 'add_ie': [YoutubeIE.ie_key()],
481cc733
S
2011 }, {
2012 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
2013 'info_dict': {
2014 'id': 'yeWKywCrFtk',
2015 'ext': 'mp4',
2016 'title': 'Small Scale Baler and Braiding Rugs',
2017 'uploader': 'Backus-Page House Museum',
2018 'uploader_id': 'backuspagemuseum',
ec85ded8 2019 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
481cc733
S
2020 'upload_date': '20161008',
2021 'license': 'Standard YouTube License',
2022 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
2023 'categories': ['Nonprofits & Activism'],
2024 'tags': list,
2025 'like_count': int,
2026 'dislike_count': int,
2027 },
2028 'params': {
2029 'noplaylist': True,
2030 'skip_download': True,
2031 },
feaa5ad7
S
2032 }, {
2033 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
2034 'only_matching': True,
a6857510
S
2035 }, {
2036 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
2037 'only_matching': True,
81127aa5 2038 }]
c5e8d7af 2039
880e1c52
JMF
2040 def _real_initialize(self):
2041 self._login()
2042
652cdaa2 2043 def _extract_mix(self, playlist_id):
99209c29 2044 # The mixes are generated from a single video
652cdaa2 2045 # the id of the playlist is just 'RD' + video_id
1b6182d8
JMF
2046 ids = []
2047 last_id = playlist_id[-11:]
2048 for n in itertools.count(1):
2049 url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
2050 webpage = self._download_webpage(
2051 url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
2052 new_ids = orderedSet(re.findall(
2053 r'''(?xs)data-video-username=".*?".*?
2054 href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
2055 webpage))
2056 # Fetch new pages until all the videos are repeated, it seems that
2057 # there are always 51 unique videos.
2058 new_ids = [_id for _id in new_ids if _id not in ids]
2059 if not new_ids:
2060 break
2061 ids.extend(new_ids)
2062 last_id = ids[-1]
2063
2064 url_results = self._ids_to_results(ids)
2065
bc2f773b 2066 search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
c9cc0bf5
PH
2067 title_span = (
2068 search_title('playlist-title') or
2069 search_title('title long-title') or
2070 search_title('title'))
76d1700b 2071 title = clean_html(title_span)
652cdaa2
JMF
2072
2073 return self.playlist_result(url_results, playlist_id, title)
2074
448830ce 2075 def _extract_playlist(self, playlist_id):
dbb94fb0
S
2076 url = self._TEMPLATE_URL % playlist_id
2077 page = self._download_webpage(url, playlist_id)
dbb94fb0 2078
8bc0800d
G
2079 # the yt-alert-message now has tabindex attribute (see https://github.com/rg3/youtube-dl/issues/11604)
2080 for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
39b62db1
YCH
2081 match = match.strip()
2082 # Check if the playlist exists or is private
4201ba13
S
2083 mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
2084 if mobj:
2085 reason = mobj.group('reason')
2086 message = 'This playlist %s' % reason
2087 if 'private' in reason:
2088 message += ', use --username or --netrc to access it'
2089 message += '.'
2090 raise ExtractorError(message, expected=True)
39b62db1
YCH
2091 elif re.match(r'[^<]*Invalid parameters[^<]*', match):
2092 raise ExtractorError(
2093 'Invalid parameters. Maybe URL is incorrect.',
2094 expected=True)
2095 elif re.match(r'[^<]*Choose your language[^<]*', match):
2096 continue
2097 else:
2098 self.report_warning('Youtube gives an alert message: ' + match)
10c0e2d8 2099
dbb94fb0 2100 playlist_title = self._html_search_regex(
63b4295d 2101 r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
dacb3a86 2102 page, 'title', default=None)
c5e8d7af 2103
dacb3a86
S
2104 has_videos = True
2105
2106 if not playlist_title:
2107 try:
2108 # Some playlist URLs don't actually serve a playlist (e.g.
2109 # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
2110 next(self._entries(page, playlist_id))
2111 except StopIteration:
2112 has_videos = False
2113
2114 return has_videos, self.playlist_result(
2115 self._entries(page, playlist_id), playlist_id, playlist_title)
c5e8d7af 2116
ebf1b291 2117 def _check_download_just_video(self, url, playlist_id):
448830ce
S
2118 # Check if it's a video-specific URL
2119 query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
481cc733 2120 video_id = query_dict.get('v', [None])[0] or self._search_regex(
87dadd45 2121 r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
481cc733
S
2122 'video id', default=None)
2123 if video_id:
448830ce
S
2124 if self._downloader.params.get('noplaylist'):
2125 self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
dacb3a86 2126 return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
448830ce
S
2127 else:
2128 self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
dacb3a86
S
2129 return video_id, None
2130 return None, None
448830ce 2131
ebf1b291
S
2132 def _real_extract(self, url):
2133 # Extract playlist id
2134 mobj = re.match(self._VALID_URL, url)
2135 if mobj is None:
2136 raise ExtractorError('Invalid URL: %s' % url)
2137 playlist_id = mobj.group(1) or mobj.group(2)
2138
dacb3a86 2139 video_id, video = self._check_download_just_video(url, playlist_id)
ebf1b291
S
2140 if video:
2141 return video
2142
466a6145 2143 if playlist_id.startswith(('RD', 'UL', 'PU')):
448830ce
S
2144 # Mixes require a custom extraction process
2145 return self._extract_mix(playlist_id)
2146
dacb3a86
S
2147 has_videos, playlist = self._extract_playlist(playlist_id)
2148 if has_videos or not video_id:
2149 return playlist
2150
2151 # Some playlist URLs don't actually serve a playlist (see
2152 # https://github.com/rg3/youtube-dl/issues/10537).
2153 # Fallback to plain video extraction if there is a video id
2154 # along with playlist id.
2155 return self.url_result(video_id, 'Youtube', video_id=video_id)
448830ce 2156
c5e8d7af 2157
648e6a1f 2158class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
78caa52a 2159 IE_DESC = 'YouTube.com channels'
9ff67727 2160 _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
eb0f3e7e 2161 _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
648e6a1f 2162 _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
78caa52a 2163 IE_NAME = 'youtube:channel'
cdc628a4
PH
2164 _TESTS = [{
2165 'note': 'paginated channel',
2166 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
2167 'playlist_mincount': 91,
acf757f4 2168 'info_dict': {
9170ca5b
JMF
2169 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
2170 'title': 'Uploads from lex will',
acf757f4 2171 }
5c43afd4
JMF
2172 }, {
2173 'note': 'Age restricted channel',
2174 # from https://www.youtube.com/user/DeusExOfficial
2175 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
2176 'playlist_mincount': 64,
2177 'info_dict': {
2178 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
2179 'title': 'Uploads from Deus Ex',
2180 },
cdc628a4 2181 }]
c5e8d7af 2182
e462474e
S
2183 @classmethod
2184 def suitable(cls, url):
f07e276a
S
2185 return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
2186 else super(YoutubeChannelIE, cls).suitable(url))
e462474e 2187
9558dcec
S
2188 def _build_template_url(self, url, channel_id):
2189 return self._TEMPLATE_URL % channel_id
2190
c5e8d7af 2191 def _real_extract(self, url):
9ff67727 2192 channel_id = self._match_id(url)
c5e8d7af 2193
9558dcec 2194 url = self._build_template_url(url, channel_id)
386bdfa6
S
2195
2196 # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
2197 # Workaround by extracting as a playlist if managed to obtain channel playlist URL
2198 # otherwise fallback on channel by page extraction
2199 channel_page = self._download_webpage(
2200 url + '?view=57', channel_id,
2201 'Downloading channel page', fatal=False)
2b3c2546
PH
2202 if channel_page is False:
2203 channel_playlist_id = False
2204 else:
2205 channel_playlist_id = self._html_search_meta(
2206 'channelId', channel_page, 'channel id', default=None)
2207 if not channel_playlist_id:
73c4ac2c
S
2208 channel_url = self._html_search_meta(
2209 ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
2210 channel_page, 'channel url', default=None)
2211 if channel_url:
2212 channel_playlist_id = self._search_regex(
2213 r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
2214 channel_url, 'channel id', default=None)
386bdfa6
S
2215 if channel_playlist_id and channel_playlist_id.startswith('UC'):
2216 playlist_id = 'UU' + channel_playlist_id[2:]
d2a9de78
IK
2217 return self.url_result(
2218 compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
386bdfa6 2219
60bf45c8 2220 channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
31812a9e
PH
2221 autogenerated = re.search(r'''(?x)
2222 class="[^"]*?(?:
2223 channel-header-autogenerated-label|
2224 yt-channel-title-autogenerated
2225 )[^"]*"''', channel_page) is not None
c5e8d7af 2226
b9643eed
JMF
2227 if autogenerated:
2228 # The videos are contained in a single page
2229 # the ajax pages can't be used, they are empty
b82f815f 2230 entries = [
fb69240c
S
2231 self.url_result(
2232 video_id, 'Youtube', video_id=video_id,
2233 video_title=video_title)
8f02ad4f 2234 for video_id, video_title in self.extract_videos_from_page(channel_page)]
b82f815f
PH
2235 return self.playlist_result(entries, channel_id)
2236
73c4ac2c
S
2237 try:
2238 next(self._entries(channel_page, channel_id))
2239 except StopIteration:
2240 alert_message = self._html_search_regex(
2241 r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
2242 channel_page, 'alert', default=None, group='alert')
2243 if alert_message:
2244 raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
2245
648e6a1f 2246 return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
c5e8d7af
PH
2247
2248
eb0f3e7e 2249class YoutubeUserIE(YoutubeChannelIE):
78caa52a 2250 IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
9558dcec
S
2251 _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:(?P<user>user|c)/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
2252 _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
78caa52a 2253 IE_NAME = 'youtube:user'
c5e8d7af 2254
cdc628a4
PH
2255 _TESTS = [{
2256 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
2257 'playlist_mincount': 320,
2258 'info_dict': {
73c4ac2c
S
2259 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
2260 'title': 'Uploads from The Linux Foundation',
cdc628a4 2261 }
9558dcec
S
2262 }, {
2263 # Only available via https://www.youtube.com/c/12minuteathlete/videos
2264 # but not https://www.youtube.com/user/12minuteathlete/videos
2265 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
2266 'playlist_mincount': 249,
2267 'info_dict': {
2268 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
2269 'title': 'Uploads from 12 Minute Athlete',
2270 }
cdc628a4
PH
2271 }, {
2272 'url': 'ytuser:phihag',
2273 'only_matching': True,
daa0df9e
YCH
2274 }, {
2275 'url': 'https://www.youtube.com/c/gametrailers',
2276 'only_matching': True,
9558dcec
S
2277 }, {
2278 'url': 'https://www.youtube.com/gametrailers',
2279 'only_matching': True,
73c4ac2c 2280 }, {
0e879f43 2281 # This channel is not available, geo restricted to JP
73c4ac2c
S
2282 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
2283 'only_matching': True,
cdc628a4
PH
2284 }]
2285
e3ea4790 2286 @classmethod
f4b05232 2287 def suitable(cls, url):
e3ea4790
JMF
2288 # Don't return True if the url can be extracted with other youtube
2289 # extractor, the regex would is too permissive and it would match.
f3a58d46 2290 other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
2291 if any(ie.suitable(url) for ie in other_yt_ies):
5f6a1245
JW
2292 return False
2293 else:
2294 return super(YoutubeUserIE, cls).suitable(url)
f4b05232 2295
9558dcec
S
2296 def _build_template_url(self, url, channel_id):
2297 mobj = re.match(self._VALID_URL, url)
2298 return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
2299
b05654f0 2300
f07e276a
S
2301class YoutubeLiveIE(YoutubeBaseInfoExtractor):
2302 IE_DESC = 'YouTube.com live streams'
073d5bf5 2303 _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
f07e276a
S
2304 IE_NAME = 'youtube:live'
2305
2306 _TESTS = [{
2d3d2997 2307 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
f07e276a
S
2308 'info_dict': {
2309 'id': 'a48o2S1cPoo',
2310 'ext': 'mp4',
2311 'title': 'The Young Turks - Live Main Show',
2312 'uploader': 'The Young Turks',
2313 'uploader_id': 'TheYoungTurks',
ec85ded8 2314 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
f07e276a
S
2315 'upload_date': '20150715',
2316 'license': 'Standard YouTube License',
2317 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
2318 'categories': ['News & Politics'],
2319 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
2320 'like_count': int,
2321 'dislike_count': int,
2322 },
2323 'params': {
2324 'skip_download': True,
2325 },
2326 }, {
2d3d2997 2327 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
f07e276a 2328 'only_matching': True,
c1b2a085
S
2329 }, {
2330 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
2331 'only_matching': True,
073d5bf5
S
2332 }, {
2333 'url': 'https://www.youtube.com/TheYoungTurks/live',
2334 'only_matching': True,
f07e276a
S
2335 }]
2336
2337 def _real_extract(self, url):
2338 mobj = re.match(self._VALID_URL, url)
2339 channel_id = mobj.group('id')
2340 base_url = mobj.group('base_url')
2341 webpage = self._download_webpage(url, channel_id, fatal=False)
2342 if webpage:
2343 page_type = self._og_search_property(
2344 'type', webpage, 'page type', default=None)
2345 video_id = self._html_search_meta(
2346 'videoId', webpage, 'video id', default=None)
2347 if page_type == 'video' and video_id and re.match(r'^[0-9A-Za-z_-]{11}$', video_id):
2348 return self.url_result(video_id, YoutubeIE.ie_key())
2349 return self.url_result(base_url)
2350
2351
e462474e
S
2352class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
2353 IE_DESC = 'YouTube.com user/channel playlists'
2354 _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
2355 IE_NAME = 'youtube:playlists'
0c148415 2356
e568c223 2357 _TESTS = [{
2d3d2997 2358 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
0c148415
S
2359 'playlist_mincount': 4,
2360 'info_dict': {
2361 'id': 'ThirstForScience',
2362 'title': 'Thirst for Science',
2363 },
e568c223
S
2364 }, {
2365 # with "Load more" button
2d3d2997 2366 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
e568c223
S
2367 'playlist_mincount': 70,
2368 'info_dict': {
2369 'id': 'igorkle1',
2370 'title': 'Игорь Клейнер',
2371 },
e462474e
S
2372 }, {
2373 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
2374 'playlist_mincount': 17,
2375 'info_dict': {
2376 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
2377 'title': 'Chem Player',
2378 },
e568c223 2379 }]
0c148415
S
2380
2381
b4c08069 2382class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
78caa52a 2383 IE_DESC = 'YouTube.com searches'
b4c08069
JMF
2384 # there doesn't appear to be a real limit, for example if you search for
2385 # 'python' you get more than 8.000.000 results
2386 _MAX_RESULTS = float('inf')
78caa52a 2387 IE_NAME = 'youtube:search'
b05654f0 2388 _SEARCH_KEY = 'ytsearch'
b4c08069 2389 _EXTRA_QUERY_ARGS = {}
9dd8e46a 2390 _TESTS = []
b05654f0 2391
b05654f0
PH
2392 def _get_n_results(self, query, n):
2393 """Get a specified number of results for a query"""
2394
b4c08069 2395 videos = []
b05654f0
PH
2396 limit = n
2397
a22b2fd1
YCH
2398 url_query = {
2399 'search_query': query.encode('utf-8'),
2400 }
2401 url_query.update(self._EXTRA_QUERY_ARGS)
2402 result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
2403
b4c08069 2404 for pagenum in itertools.count(1):
b4c08069 2405 data = self._download_json(
69ea8ca4 2406 result_url, video_id='query "%s"' % query,
b4c08069 2407 note='Downloading page %s' % pagenum,
a22b2fd1
YCH
2408 errnote='Unable to download API page',
2409 query={'spf': 'navigate'})
b4c08069 2410 html_content = data[1]['body']['content']
7cc3570e 2411
b4c08069 2412 if 'class="search-message' in html_content:
07ad22b8 2413 raise ExtractorError(
78caa52a 2414 '[youtube] No video results', expected=True)
b05654f0 2415
b4c08069
JMF
2416 new_videos = self._ids_to_results(orderedSet(re.findall(
2417 r'href="/watch\?v=(.{11})', html_content)))
2418 videos += new_videos
2419 if not new_videos or len(videos) > limit:
2420 break
a22b2fd1
YCH
2421 next_link = self._html_search_regex(
2422 r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
2423 html_content, 'next link', default=None)
2424 if next_link is None:
2425 break
2426 result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
b05654f0 2427
b4c08069
JMF
2428 if len(videos) > n:
2429 videos = videos[:n]
b05654f0 2430 return self.playlist_result(videos, query)
75dff0ee 2431
c9ae7b95 2432
a3dd9248 2433class YoutubeSearchDateIE(YoutubeSearchIE):
cb7fb546 2434 IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
a3dd9248 2435 _SEARCH_KEY = 'ytsearchdate'
78caa52a 2436 IE_DESC = 'YouTube.com searches, newest videos first'
b4c08069 2437 _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
75dff0ee 2438
c9ae7b95 2439
175c2e9e 2440class YoutubeSearchURLIE(YoutubePlaylistBaseInfoExtractor):
78caa52a
PH
2441 IE_DESC = 'YouTube.com search URLs'
2442 IE_NAME = 'youtube:search_url'
d2c1f79f 2443 _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
175c2e9e 2444 _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
cdc628a4
PH
2445 _TESTS = [{
2446 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
2447 'playlist_mincount': 5,
2448 'info_dict': {
2449 'title': 'youtube-dl test video',
2450 }
d2c1f79f
S
2451 }, {
2452 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
2453 'only_matching': True,
cdc628a4 2454 }]
c9ae7b95
PH
2455
2456 def _real_extract(self, url):
2457 mobj = re.match(self._VALID_URL, url)
7fd002c0 2458 query = compat_urllib_parse_unquote_plus(mobj.group('query'))
c9ae7b95 2459 webpage = self._download_webpage(url, query)
175c2e9e 2460 return self.playlist_result(self._process_page(webpage), playlist_title=query)
c9ae7b95
PH
2461
2462
136dadde 2463class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
78caa52a 2464 IE_DESC = 'YouTube.com (multi-season) shows'
92519402 2465 _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
78caa52a 2466 IE_NAME = 'youtube:show'
cdc628a4 2467 _TESTS = [{
4003bd82 2468 'url': 'https://www.youtube.com/show/airdisasters',
8801255d 2469 'playlist_mincount': 5,
cdc628a4
PH
2470 'info_dict': {
2471 'id': 'airdisasters',
2472 'title': 'Air Disasters',
2473 }
2474 }]
75dff0ee
JMF
2475
2476 def _real_extract(self, url):
136dadde
S
2477 playlist_id = self._match_id(url)
2478 return super(YoutubeShowIE, self)._real_extract(
2479 'https://www.youtube.com/show/%s/playlists' % playlist_id)
04cc9617
JMF
2480
2481
b2e8bc1b 2482class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
d7ae0639 2483 """
25f14e9f 2484 Base class for feed extractors
d7ae0639
JMF
2485 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
2486 """
b2e8bc1b 2487 _LOGIN_REQUIRED = True
d7ae0639
JMF
2488
2489 @property
2490 def IE_NAME(self):
78caa52a 2491 return 'youtube:%s' % self._FEED_NAME
04cc9617 2492
81f0259b 2493 def _real_initialize(self):
b2e8bc1b 2494 self._login()
81f0259b 2495
04cc9617 2496 def _real_extract(self, url):
25f14e9f
S
2497 page = self._download_webpage(
2498 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
2bc43303
JMF
2499
2500 # The extraction process is the same as for playlists, but the regex
2501 # for the video ids doesn't contain an index
2502 ids = []
2503 more_widget_html = content_html = page
2bc43303
JMF
2504 for page_num in itertools.count(1):
2505 matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
62c95fd5
S
2506
2507 # 'recommended' feed has infinite 'load more' and each new portion spins
2508 # the same videos in (sometimes) slightly different order, so we'll check
2509 # for unicity and break when portion has no new videos
2510 new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
2511 if not new_ids:
2512 break
2513
2bc43303
JMF
2514 ids.extend(new_ids)
2515
2516 mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
2517 if not mobj:
2518 break
2519
2520 more = self._download_json(
25f14e9f 2521 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
2bc43303
JMF
2522 'Downloading page #%s' % page_num,
2523 transform_source=uppercase_escape)
2524 content_html = more['content_html']
2525 more_widget_html = more['load_more_widget_html']
2526
25f14e9f
S
2527 return self.playlist_result(
2528 self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
2529
2530
2531class YoutubeWatchLaterIE(YoutubePlaylistIE):
2532 IE_NAME = 'youtube:watchlater'
2533 IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
92519402 2534 _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
25f14e9f 2535
bc7a9cd8
S
2536 _TESTS = [{
2537 'url': 'https://www.youtube.com/playlist?list=WL',
2538 'only_matching': True,
2539 }, {
2540 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
2541 'only_matching': True,
2542 }]
25f14e9f
S
2543
2544 def _real_extract(self, url):
7e5dc339 2545 _, video = self._check_download_just_video(url, 'WL')
ebf1b291
S
2546 if video:
2547 return video
dacb3a86
S
2548 _, playlist = self._extract_playlist('WL')
2549 return playlist
f459d170 2550
5f6a1245 2551
c626a3d9 2552class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
78caa52a 2553 IE_NAME = 'youtube:favorites'
f3a34072 2554 IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
92519402 2555 _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
c626a3d9
JMF
2556 _LOGIN_REQUIRED = True
2557
2558 def _real_extract(self, url):
2559 webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
78caa52a 2560 playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
c626a3d9 2561 return self.url_result(playlist_id, 'YoutubePlaylist')
15870e90
PH
2562
2563
25f14e9f
S
2564class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
2565 IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
92519402 2566 _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
25f14e9f
S
2567 _FEED_NAME = 'recommended'
2568 _PLAYLIST_TITLE = 'Youtube Recommended videos'
1ed5b5c9 2569
1ed5b5c9 2570
25f14e9f
S
2571class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
2572 IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
92519402 2573 _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
25f14e9f
S
2574 _FEED_NAME = 'subscriptions'
2575 _PLAYLIST_TITLE = 'Youtube Subscriptions'
1ed5b5c9 2576
1ed5b5c9 2577
25f14e9f
S
2578class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
2579 IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
92519402 2580 _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
25f14e9f
S
2581 _FEED_NAME = 'history'
2582 _PLAYLIST_TITLE = 'Youtube History'
1ed5b5c9
JMF
2583
2584
15870e90
PH
2585class YoutubeTruncatedURLIE(InfoExtractor):
2586 IE_NAME = 'youtube:truncated_url'
2587 IE_DESC = False # Do not list
975d35db 2588 _VALID_URL = r'''(?x)
b95aab84
PH
2589 (?:https?://)?
2590 (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
2591 (?:watch\?(?:
c4808c60 2592 feature=[a-z_]+|
b95aab84
PH
2593 annotation_id=annotation_[^&]+|
2594 x-yt-cl=[0-9]+|
c1708b89 2595 hl=[^&]*|
287be8c6 2596 t=[0-9]+
b95aab84
PH
2597 )?
2598 |
2599 attribution_link\?a=[^&]+
2600 )
2601 $
975d35db 2602 '''
15870e90 2603
c4808c60 2604 _TESTS = [{
2d3d2997 2605 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
c4808c60 2606 'only_matching': True,
dc2fc736 2607 }, {
2d3d2997 2608 'url': 'https://www.youtube.com/watch?',
dc2fc736 2609 'only_matching': True,
b95aab84
PH
2610 }, {
2611 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
2612 'only_matching': True,
2613 }, {
2614 'url': 'https://www.youtube.com/watch?feature=foo',
2615 'only_matching': True,
c1708b89
PH
2616 }, {
2617 'url': 'https://www.youtube.com/watch?hl=en-GB',
2618 'only_matching': True,
287be8c6
PH
2619 }, {
2620 'url': 'https://www.youtube.com/watch?t=2372',
2621 'only_matching': True,
c4808c60
PH
2622 }]
2623
15870e90
PH
2624 def _real_extract(self, url):
2625 raise ExtractorError(
78caa52a
PH
2626 'Did you forget to quote the URL? Remember that & is a meta '
2627 'character in most shells, so you want to put the URL in quotes, '
2628 'like youtube-dl '
2d3d2997 2629 '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
78caa52a 2630 ' or simply youtube-dl BaW_jenozKc .',
15870e90 2631 expected=True)
772fd5cc
PH
2632
2633
2634class YoutubeTruncatedIDIE(InfoExtractor):
2635 IE_NAME = 'youtube:truncated_id'
2636 IE_DESC = False # Do not list
b95aab84 2637 _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
772fd5cc
PH
2638
2639 _TESTS = [{
2640 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
2641 'only_matching': True,
2642 }]
2643
2644 def _real_extract(self, url):
2645 video_id = self._match_id(url)
2646 raise ExtractorError(
2647 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
2648 expected=True)