]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/youtube.py
release 2013.09.05
[yt-dlp.git] / youtube_dl / extractor / youtube.py
CommitLineData
c5e8d7af 1# coding: utf-8
c5e8d7af
PH
2
3import json
4import netrc
5import re
6import socket
04cc9617 7import itertools
c5e8d7af 8
b05654f0 9from .common import InfoExtractor, SearchInfoExtractor
c5e8d7af
PH
10from ..utils import (
11 compat_http_client,
12 compat_parse_qs,
13 compat_urllib_error,
14 compat_urllib_parse,
15 compat_urllib_request,
16 compat_str,
17
18 clean_html,
19 get_element_by_id,
20 ExtractorError,
21 unescapeHTML,
22 unified_strdate,
04cc9617 23 orderedSet,
c5e8d7af
PH
24)
25
b2e8bc1b
JMF
26class YoutubeBaseInfoExtractor(InfoExtractor):
27 """Provide base functions for Youtube extractors"""
28 _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
29 _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
30 _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
31 _NETRC_MACHINE = 'youtube'
32 # If True it will raise an error if no login info is provided
33 _LOGIN_REQUIRED = False
34
35 def report_lang(self):
36 """Report attempt to set language."""
37 self.to_screen(u'Setting language')
38
39 def _set_language(self):
40 request = compat_urllib_request.Request(self._LANG_URL)
41 try:
42 self.report_lang()
43 compat_urllib_request.urlopen(request).read()
44 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
45 self._downloader.report_warning(u'unable to set language: %s' % compat_str(err))
46 return False
47 return True
48
49 def _login(self):
50 (username, password) = self._get_login_info()
51 # No authentication to be performed
52 if username is None:
53 if self._LOGIN_REQUIRED:
54 raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
55 return False
56
57 request = compat_urllib_request.Request(self._LOGIN_URL)
58 try:
59 login_page = compat_urllib_request.urlopen(request).read().decode('utf-8')
60 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
61 self._downloader.report_warning(u'unable to fetch login page: %s' % compat_str(err))
62 return False
63
64 galx = None
65 dsh = None
66 match = re.search(re.compile(r'<input.+?name="GALX".+?value="(.+?)"', re.DOTALL), login_page)
67 if match:
68 galx = match.group(1)
69 match = re.search(re.compile(r'<input.+?name="dsh".+?value="(.+?)"', re.DOTALL), login_page)
70 if match:
71 dsh = match.group(1)
c5e8d7af 72
b2e8bc1b
JMF
73 # Log in
74 login_form_strs = {
75 u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
76 u'Email': username,
77 u'GALX': galx,
78 u'Passwd': password,
79 u'PersistentCookie': u'yes',
80 u'_utf8': u'霱',
81 u'bgresponse': u'js_disabled',
82 u'checkConnection': u'',
83 u'checkedDomains': u'youtube',
84 u'dnConn': u'',
85 u'dsh': dsh,
86 u'pstMsg': u'0',
87 u'rmShown': u'1',
88 u'secTok': u'',
89 u'signIn': u'Sign in',
90 u'timeStmp': u'',
91 u'service': u'youtube',
92 u'uilel': u'3',
93 u'hl': u'en_US',
94 }
95 # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
96 # chokes on unicode
97 login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
98 login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
99 request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
100 try:
101 self.report_login()
102 login_results = compat_urllib_request.urlopen(request).read().decode('utf-8')
103 if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
104 self._downloader.report_warning(u'unable to log in: bad username or password')
105 return False
106 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
107 self._downloader.report_warning(u'unable to log in: %s' % compat_str(err))
108 return False
109 return True
110
111 def _confirm_age(self):
112 age_form = {
113 'next_url': '/',
114 'action_confirm': 'Confirm',
115 }
116 request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
117 try:
118 self.report_age_confirmation()
119 compat_urllib_request.urlopen(request).read().decode('utf-8')
120 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
121 raise ExtractorError(u'Unable to confirm age: %s' % compat_str(err))
122 return True
123
124 def _real_initialize(self):
125 if self._downloader is None:
126 return
127 if not self._set_language():
128 return
129 if not self._login():
130 return
131 self._confirm_age()
132
133class YoutubeIE(YoutubeBaseInfoExtractor):
0f818663 134 IE_DESC = u'YouTube.com'
c5e8d7af
PH
135 _VALID_URL = r"""^
136 (
137 (?:https?://)? # http(s):// (optional)
138 (?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/|
139 tube\.majestyc\.net/) # the various hostnames, with wildcard subdomains
140 (?:.*?\#/)? # handle anchor (#/) redirect urls
141 (?: # the various things that can precede the ID:
142 (?:(?:v|embed|e)/) # v/ or embed/ or e/
143 |(?: # or the v= param in all its forms
d741e55a 144 (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
c5e8d7af
PH
145 (?:\?|\#!?) # the params delimiter ? or # or #!
146 (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
147 v=
148 )
149 )? # optional -> youtube.com/xxxx is OK
150 )? # all until now is optional -> you can pass the naked ID
151 ([0-9A-Za-z_-]+) # here is it! the YouTube video ID
152 (?(1).+)? # if we found the ID, everything can follow
153 $"""
c5e8d7af 154 _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
c5e8d7af 155 # Listed in order of quality
bdc6b3fc 156 _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
96fb5605 157 # Apple HTTP Live Streaming
bdc6b3fc 158 '96', '95', '94', '93', '92', '132', '151',
939fbd26
JMF
159 # 3D
160 '85', '84', '102', '83', '101', '82', '100',
161 # Dash video
162 '138', '137', '248', '136', '247', '135', '246',
163 '245', '244', '134', '243', '133', '242', '160',
164 # Dash audio
165 '141', '172', '140', '171', '139',
1d043b93 166 ]
bdc6b3fc 167 _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
96fb5605 168 # Apple HTTP Live Streaming
bdc6b3fc
AZ
169 '96', '95', '94', '93', '92', '132', '151',
170 # 3D
86fe61c8 171 '85', '102', '84', '101', '83', '100', '82',
939fbd26
JMF
172 # Dash video
173 '138', '248', '137', '247', '136', '246', '245',
174 '244', '135', '243', '134', '242', '133', '160',
175 # Dash audio
176 '172', '141', '171', '140', '139',
1d043b93 177 ]
bdc6b3fc
AZ
178 _video_formats_map = {
179 'flv': ['35', '34', '6', '5'],
180 '3gp': ['36', '17', '13'],
181 'mp4': ['38', '37', '22', '18'],
182 'webm': ['46', '45', '44', '43'],
183 }
c5e8d7af
PH
184 _video_extensions = {
185 '13': '3gp',
bdc6b3fc 186 '17': '3gp',
c5e8d7af
PH
187 '18': 'mp4',
188 '22': 'mp4',
bdc6b3fc 189 '36': '3gp',
c5e8d7af 190 '37': 'mp4',
d69cf69a 191 '38': 'mp4',
c5e8d7af
PH
192 '43': 'webm',
193 '44': 'webm',
194 '45': 'webm',
195 '46': 'webm',
1d043b93 196
86fe61c8
AZ
197 # 3d videos
198 '82': 'mp4',
199 '83': 'mp4',
200 '84': 'mp4',
201 '85': 'mp4',
202 '100': 'webm',
203 '101': 'webm',
204 '102': 'webm',
836a086c 205
96fb5605 206 # Apple HTTP Live Streaming
1d043b93
JMF
207 '92': 'mp4',
208 '93': 'mp4',
209 '94': 'mp4',
210 '95': 'mp4',
211 '96': 'mp4',
212 '132': 'mp4',
213 '151': 'mp4',
836a086c
AZ
214
215 # Dash mp4
216 '133': 'mp4',
217 '134': 'mp4',
218 '135': 'mp4',
219 '136': 'mp4',
220 '137': 'mp4',
221 '138': 'mp4',
222 '139': 'mp4',
223 '140': 'mp4',
224 '141': 'mp4',
225 '160': 'mp4',
226
227 # Dash webm
228 '171': 'webm',
229 '172': 'webm',
230 '242': 'webm',
231 '243': 'webm',
232 '244': 'webm',
233 '245': 'webm',
234 '246': 'webm',
235 '247': 'webm',
236 '248': 'webm',
c5e8d7af
PH
237 }
238 _video_dimensions = {
239 '5': '240x400',
240 '6': '???',
241 '13': '???',
242 '17': '144x176',
243 '18': '360x640',
244 '22': '720x1280',
245 '34': '360x640',
246 '35': '480x854',
bdc6b3fc 247 '36': '240x320',
c5e8d7af
PH
248 '37': '1080x1920',
249 '38': '3072x4096',
250 '43': '360x640',
251 '44': '480x854',
252 '45': '720x1280',
253 '46': '1080x1920',
86fe61c8
AZ
254 '82': '360p',
255 '83': '480p',
256 '84': '720p',
257 '85': '1080p',
1d043b93
JMF
258 '92': '240p',
259 '93': '360p',
260 '94': '480p',
261 '95': '720p',
262 '96': '1080p',
86fe61c8
AZ
263 '100': '360p',
264 '101': '480p',
836a086c 265 '102': '720p',
1d043b93
JMF
266 '132': '240p',
267 '151': '72p',
836a086c
AZ
268 '133': '240p',
269 '134': '360p',
270 '135': '480p',
271 '136': '720p',
272 '137': '1080p',
273 '138': '>1080p',
274 '139': '48k',
275 '140': '128k',
276 '141': '256k',
277 '160': '192p',
278 '171': '128k',
279 '172': '256k',
280 '242': '240p',
281 '243': '360p',
282 '244': '480p',
283 '245': '480p',
284 '246': '480p',
285 '247': '720p',
286 '248': '1080p',
c5e8d7af 287 }
836a086c
AZ
288 _special_itags = {
289 '82': '3D',
290 '83': '3D',
291 '84': '3D',
292 '85': '3D',
293 '100': '3D',
294 '101': '3D',
295 '102': '3D',
296 '133': 'DASH Video',
297 '134': 'DASH Video',
298 '135': 'DASH Video',
299 '136': 'DASH Video',
300 '137': 'DASH Video',
301 '138': 'DASH Video',
302 '139': 'DASH Audio',
303 '140': 'DASH Audio',
304 '141': 'DASH Audio',
305 '160': 'DASH Video',
306 '171': 'DASH Audio',
307 '172': 'DASH Audio',
308 '242': 'DASH Video',
309 '243': 'DASH Video',
310 '244': 'DASH Video',
311 '245': 'DASH Video',
312 '246': 'DASH Video',
313 '247': 'DASH Video',
314 '248': 'DASH Video',
c5e8d7af 315 }
836a086c 316
c5e8d7af 317 IE_NAME = u'youtube'
2eb88d95
PH
318 _TESTS = [
319 {
0e853ca4
PH
320 u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
321 u"file": u"BaW_jenozKc.mp4",
322 u"info_dict": {
323 u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
324 u"uploader": u"Philipp Hagemeister",
325 u"uploader_id": u"phihag",
326 u"upload_date": u"20121002",
327 u"description": u"test chars: \"'/\\ä↭𝕐\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de ."
2eb88d95 328 }
0e853ca4
PH
329 },
330 {
331 u"url": u"http://www.youtube.com/watch?v=1ltcDfZMA3U",
332 u"file": u"1ltcDfZMA3U.flv",
333 u"note": u"Test VEVO video (#897)",
334 u"info_dict": {
335 u"upload_date": u"20070518",
336 u"title": u"Maps - It Will Find You",
337 u"description": u"Music video by Maps performing It Will Find You.",
338 u"uploader": u"MuteUSA",
339 u"uploader_id": u"MuteUSA"
2eb88d95 340 }
0e853ca4
PH
341 },
342 {
343 u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
344 u"file": u"UxxajLWwzqY.mp4",
345 u"note": u"Test generic use_cipher_signature video (#897)",
346 u"info_dict": {
347 u"upload_date": u"20120506",
348 u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
c7bf7366 349 u"description": u"md5:3e2666e0a55044490499ea45fe9037b7",
45ed795c 350 u"uploader": u"Icona Pop",
0e853ca4 351 u"uploader_id": u"IconaPop"
2eb88d95 352 }
c108eb73
JMF
353 },
354 {
355 u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
356 u"file": u"07FYdnEawAQ.mp4",
357 u"note": u"Test VEVO video with age protection (#956)",
358 u"info_dict": {
359 u"upload_date": u"20130703",
360 u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
361 u"description": u"md5:64249768eec3bc4276236606ea996373",
362 u"uploader": u"justintimberlakeVEVO",
363 u"uploader_id": u"justintimberlakeVEVO"
364 }
365 },
1d043b93
JMF
366 {
367 u'url': u'https://www.youtube.com/watch?v=TGi3HqYrWHE',
368 u'file': u'TGi3HqYrWHE.mp4',
369 u'note': u'm3u8 video',
370 u'info_dict': {
371 u'title': u'Triathlon - Men - London 2012 Olympic Games',
372 u'description': u'- Men - TR02 - Triathlon - 07 August 2012 - London 2012 Olympic Games',
373 u'uploader': u'olympic',
374 u'upload_date': u'20120807',
375 u'uploader_id': u'olympic',
376 },
377 u'params': {
378 u'skip_download': True,
379 },
380 },
2eb88d95
PH
381 ]
382
c5e8d7af
PH
383
384 @classmethod
385 def suitable(cls, url):
386 """Receives a URL and returns True if suitable for this IE."""
04cc9617 387 if YoutubePlaylistIE.suitable(url) or YoutubeSubscriptionsIE.suitable(url): return False
c5e8d7af
PH
388 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
389
c5e8d7af
PH
390 def report_video_webpage_download(self, video_id):
391 """Report attempt to download video webpage."""
392 self.to_screen(u'%s: Downloading video webpage' % video_id)
393
394 def report_video_info_webpage_download(self, video_id):
395 """Report attempt to download video info webpage."""
396 self.to_screen(u'%s: Downloading video info webpage' % video_id)
397
398 def report_video_subtitles_download(self, video_id):
399 """Report attempt to download video info webpage."""
400 self.to_screen(u'%s: Checking available subtitles' % video_id)
401
402 def report_video_subtitles_request(self, video_id, sub_lang, format):
403 """Report attempt to download video info webpage."""
404 self.to_screen(u'%s: Downloading video subtitles for %s.%s' % (video_id, sub_lang, format))
405
406 def report_video_subtitles_available(self, video_id, sub_lang_list):
407 """Report available subtitles."""
408 sub_lang = ",".join(list(sub_lang_list.keys()))
409 self.to_screen(u'%s: Available subtitles for video: %s' % (video_id, sub_lang))
410
411 def report_information_extraction(self, video_id):
412 """Report attempt to extract video information."""
413 self.to_screen(u'%s: Extracting video information' % video_id)
414
415 def report_unavailable_format(self, video_id, format):
416 """Report extracted video URL."""
417 self.to_screen(u'%s: Format %s not available' % (video_id, format))
418
419 def report_rtmp_download(self):
420 """Indicate the download will use the RTMP protocol."""
421 self.to_screen(u'RTMP download detected')
422
98bcd283 423 def _decrypt_signature(self, s):
257a2501 424 """Turn the encrypted s field into a working signature"""
6b37f0be 425
444b1165
JMF
426 if len(s) == 92:
427 return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
428 elif len(s) == 90:
429 return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
8a9d86a2 430 elif len(s) == 89:
431 return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
444b1165 432 elif len(s) == 88:
3e223834 433 return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
be547e1d 434 elif len(s) == 87:
3a725669 435 return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
be547e1d 436 elif len(s) == 86:
2e756879 437 return s[81:73:-1] + s[84] + s[72:58:-1] + s[0] + s[57:35:-1] + s[85] + s[34:0:-1]
be547e1d 438 elif len(s) == 85:
f9c3c90c 439 return s[83:34:-1] + s[0] + s[33:27:-1] + s[3] + s[26:19:-1] + s[34] + s[18:3:-1] + s[27]
be547e1d 440 elif len(s) == 84:
23b00bc0 441 return s[81:36:-1] + s[0] + s[35:2:-1]
be547e1d 442 elif len(s) == 83:
e1842025 443 return s[81:64:-1] + s[82] + s[63:52:-1] + s[45] + s[51:45:-1] + s[1] + s[44:1:-1] + s[0]
be547e1d 444 elif len(s) == 82:
3669cdba 445 return s[1:19] + s[0] + s[20:68] + s[19] + s[69:82]
be547e1d 446 elif len(s) == 81:
aedd6bb9 447 return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
066090dd
JMF
448 elif len(s) == 80:
449 return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
5c468ca8
JMF
450 elif len(s) == 79:
451 return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
be547e1d
PH
452
453 else:
454 raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
c5e8d7af 455
75952c6e
JMF
456 def _decrypt_signature_age_gate(self, s):
457 # The videos with age protection use another player, so the algorithms
458 # can be different.
459 if len(s) == 86:
460 return s[2:63] + s[82] + s[64:82] + s[63]
461 else:
462 # Fallback to the other algortihms
b072a9de 463 return self._decrypt_signature(s)
75952c6e
JMF
464
465
c5e8d7af
PH
466 def _get_available_subtitles(self, video_id):
467 self.report_video_subtitles_download(video_id)
468 request = compat_urllib_request.Request('http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id)
469 try:
470 sub_list = compat_urllib_request.urlopen(request).read().decode('utf-8')
471 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
5d51a883
JMF
472 self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
473 return {}
c5e8d7af
PH
474 sub_lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
475 sub_lang_list = dict((l[1], l[0]) for l in sub_lang_list)
476 if not sub_lang_list:
5d51a883
JMF
477 self._downloader.report_warning(u'video doesn\'t have subtitles')
478 return {}
c5e8d7af
PH
479 return sub_lang_list
480
481 def _list_available_subtitles(self, video_id):
482 sub_lang_list = self._get_available_subtitles(video_id)
483 self.report_video_subtitles_available(video_id, sub_lang_list)
484
485 def _request_subtitle(self, sub_lang, sub_name, video_id, format):
486 """
5d51a883 487 Return the subtitle as a string or None if they are not found
c5e8d7af
PH
488 """
489 self.report_video_subtitles_request(video_id, sub_lang, format)
490 params = compat_urllib_parse.urlencode({
491 'lang': sub_lang,
492 'name': sub_name,
493 'v': video_id,
494 'fmt': format,
495 })
496 url = 'http://www.youtube.com/api/timedtext?' + params
497 try:
498 sub = compat_urllib_request.urlopen(url).read().decode('utf-8')
499 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
5d51a883
JMF
500 self._downloader.report_warning(u'unable to download video subtitles for %s: %s' % (sub_lang, compat_str(err)))
501 return
c5e8d7af 502 if not sub:
5d51a883
JMF
503 self._downloader.report_warning(u'Did not fetch video subtitles')
504 return
505 return sub
c5e8d7af
PH
506
507 def _request_automatic_caption(self, video_id, webpage):
508 """We need the webpage for getting the captions url, pass it as an
509 argument to speed up the process."""
aa6a10c4 510 sub_lang = (self._downloader.params.get('subtitleslangs') or ['en'])[0]
c5e8d7af
PH
511 sub_format = self._downloader.params.get('subtitlesformat')
512 self.to_screen(u'%s: Looking for automatic captions' % video_id)
513 mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
514 err_msg = u'Couldn\'t find automatic captions for "%s"' % sub_lang
515 if mobj is None:
5d51a883
JMF
516 self._downloader.report_warning(err_msg)
517 return {}
c5e8d7af
PH
518 player_config = json.loads(mobj.group(1))
519 try:
520 args = player_config[u'args']
521 caption_url = args[u'ttsurl']
522 timestamp = args[u'timestamp']
523 params = compat_urllib_parse.urlencode({
524 'lang': 'en',
525 'tlang': sub_lang,
526 'fmt': sub_format,
527 'ts': timestamp,
528 'kind': 'asr',
529 })
530 subtitles_url = caption_url + '&' + params
531 sub = self._download_webpage(subtitles_url, video_id, u'Downloading automatic captions')
5d51a883 532 return {sub_lang: sub}
2f799533
JMF
533 # An extractor error can be raise by the download process if there are
534 # no automatic captions but there are subtitles
535 except (KeyError, ExtractorError):
5d51a883
JMF
536 self._downloader.report_warning(err_msg)
537 return {}
88ae5991
JMF
538
539 def _extract_subtitles(self, video_id):
c5e8d7af 540 """
5d51a883
JMF
541 Return a dictionary: {language: subtitles} or {} if the subtitles
542 couldn't be found
c5e8d7af 543 """
aa6a10c4 544 available_subs_list = self._get_available_subtitles(video_id)
c5e8d7af 545 sub_format = self._downloader.params.get('subtitlesformat')
aa6a10c4 546 if not available_subs_list: #There was some error, it didn't get the available subtitles
5d51a883 547 return {}
df3df7fb 548 if self._downloader.params.get('allsubtitles', False):
aa6a10c4 549 sub_lang_list = available_subs_list
df3df7fb 550 else:
aa6a10c4
JMF
551 if self._downloader.params.get('subtitleslangs', False):
552 reqested_langs = self._downloader.params.get('subtitleslangs')
553 elif 'en' in available_subs_list:
554 reqested_langs = ['en']
88ae5991 555 else:
aa6a10c4
JMF
556 reqested_langs = [list(available_subs_list.keys())[0]]
557
558 sub_lang_list = {}
559 for sub_lang in reqested_langs:
560 if not sub_lang in available_subs_list:
561 self._downloader.report_warning(u'no closed captions found in the specified language "%s"' % sub_lang)
562 continue
563 sub_lang_list[sub_lang] = available_subs_list[sub_lang]
5d51a883 564 subtitles = {}
c5e8d7af
PH
565 for sub_lang in sub_lang_list:
566 subtitle = self._request_subtitle(sub_lang, sub_lang_list[sub_lang].encode('utf-8'), video_id, sub_format)
5d51a883
JMF
567 if subtitle:
568 subtitles[sub_lang] = subtitle
c5e8d7af
PH
569 return subtitles
570
571 def _print_formats(self, formats):
572 print('Available formats:')
573 for x in formats:
03cc7c20
JMF
574 print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
575 self._video_dimensions.get(x, '???'),
836a086c 576 ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
c5e8d7af 577
c5e8d7af
PH
578 def _extract_id(self, url):
579 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
580 if mobj is None:
581 raise ExtractorError(u'Invalid URL: %s' % url)
582 video_id = mobj.group(2)
583 return video_id
584
1d043b93
JMF
585 def _get_video_url_list(self, url_map):
586 """
587 Transform a dictionary in the format {itag:url} to a list of (itag, url)
588 with the requested formats.
589 """
590 req_format = self._downloader.params.get('format', None)
591 format_limit = self._downloader.params.get('format_limit', None)
592 available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
593 if format_limit is not None and format_limit in available_formats:
594 format_list = available_formats[available_formats.index(format_limit):]
595 else:
596 format_list = available_formats
597 existing_formats = [x for x in format_list if x in url_map]
598 if len(existing_formats) == 0:
599 raise ExtractorError(u'no known formats available for video')
600 if self._downloader.params.get('listformats', None):
601 self._print_formats(existing_formats)
602 return
603 if req_format is None or req_format == 'best':
604 video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
605 elif req_format == 'worst':
606 video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
607 elif req_format in ('-1', 'all'):
608 video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
609 else:
610 # Specific formats. We pick the first in a slash-delimeted sequence.
bdc6b3fc
AZ
611 # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
612 # available in the specified format. For example,
613 # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
614 # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
615 # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
1d043b93
JMF
616 req_formats = req_format.split('/')
617 video_url_list = None
618 for rf in req_formats:
619 if rf in url_map:
620 video_url_list = [(rf, url_map[rf])]
621 break
bdc6b3fc
AZ
622 if rf in self._video_formats_map:
623 for srf in self._video_formats_map[rf]:
624 if srf in url_map:
625 video_url_list = [(srf, url_map[srf])]
626 break
627 else:
628 continue
629 break
1d043b93
JMF
630 if video_url_list is None:
631 raise ExtractorError(u'requested format not available')
632 return video_url_list
633
634 def _extract_from_m3u8(self, manifest_url, video_id):
635 url_map = {}
636 def _get_urls(_manifest):
637 lines = _manifest.split('\n')
638 urls = filter(lambda l: l and not l.startswith('#'),
639 lines)
640 return urls
641 manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
642 formats_urls = _get_urls(manifest)
643 for format_url in formats_urls:
644 itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
645 url_map[itag] = format_url
646 return url_map
647
c5e8d7af 648 def _real_extract(self, url):
d7f44b5b
PH
649 if re.match(r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$', url):
650 self._downloader.report_warning(u'Did you forget to quote the URL? Remember that & is a meta-character in most shells, so you want to put the URL in quotes, like youtube-dl \'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\' (or simply youtube-dl BaW_jenozKc ).')
651
c5e8d7af
PH
652 # Extract original video URL from URL with redirection, like age verification, using next_url parameter
653 mobj = re.search(self._NEXT_URL_RE, url)
654 if mobj:
655 url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
656 video_id = self._extract_id(url)
657
658 # Get video webpage
659 self.report_video_webpage_download(video_id)
660 url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
661 request = compat_urllib_request.Request(url)
662 try:
663 video_webpage_bytes = compat_urllib_request.urlopen(request).read()
664 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
665 raise ExtractorError(u'Unable to download video webpage: %s' % compat_str(err))
666
667 video_webpage = video_webpage_bytes.decode('utf-8', 'ignore')
668
669 # Attempt to extract SWF player URL
670 mobj = re.search(r'swfConfig.*?"(http:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
671 if mobj is not None:
672 player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
673 else:
674 player_url = None
675
676 # Get video info
677 self.report_video_info_webpage_download(video_id)
c108eb73
JMF
678 if re.search(r'player-age-gate-content">', video_webpage) is not None:
679 self.report_age_confirmation()
680 age_gate = True
681 # We simulate the access to the video from www.youtube.com/v/{video_id}
682 # this can be viewed without login into Youtube
683 data = compat_urllib_parse.urlencode({'video_id': video_id,
684 'el': 'embedded',
685 'gl': 'US',
686 'hl': 'en',
687 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
688 'asv': 3,
689 'sts':'1588',
690 })
691 video_info_url = 'https://www.youtube.com/get_video_info?' + data
c5e8d7af
PH
692 video_info_webpage = self._download_webpage(video_info_url, video_id,
693 note=False,
694 errnote='unable to download video info webpage')
695 video_info = compat_parse_qs(video_info_webpage)
c108eb73
JMF
696 else:
697 age_gate = False
698 for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
699 video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
700 % (video_id, el_type))
701 video_info_webpage = self._download_webpage(video_info_url, video_id,
702 note=False,
703 errnote='unable to download video info webpage')
704 video_info = compat_parse_qs(video_info_webpage)
705 if 'token' in video_info:
706 break
c5e8d7af
PH
707 if 'token' not in video_info:
708 if 'reason' in video_info:
9a82b238 709 raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
c5e8d7af
PH
710 else:
711 raise ExtractorError(u'"token" parameter not in video info for unknown reason')
712
713 # Check for "rental" videos
714 if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
715 raise ExtractorError(u'"rental" videos not supported')
716
717 # Start extracting information
718 self.report_information_extraction(video_id)
719
720 # uploader
721 if 'author' not in video_info:
722 raise ExtractorError(u'Unable to extract uploader name')
723 video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
724
725 # uploader_id
726 video_uploader_id = None
727 mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
728 if mobj is not None:
729 video_uploader_id = mobj.group(1)
730 else:
731 self._downloader.report_warning(u'unable to extract uploader nickname')
732
733 # title
734 if 'title' not in video_info:
735 raise ExtractorError(u'Unable to extract video title')
736 video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
737
738 # thumbnail image
7763b04e
JMF
739 # We try first to get a high quality image:
740 m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
741 video_webpage, re.DOTALL)
742 if m_thumb is not None:
743 video_thumbnail = m_thumb.group(1)
744 elif 'thumbnail_url' not in video_info:
c5e8d7af
PH
745 self._downloader.report_warning(u'unable to extract video thumbnail')
746 video_thumbnail = ''
747 else: # don't panic if we can't find it
748 video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
749
750 # upload date
751 upload_date = None
752 mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
753 if mobj is not None:
754 upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
755 upload_date = unified_strdate(upload_date)
756
757 # description
758 video_description = get_element_by_id("eow-description", video_webpage)
759 if video_description:
760 video_description = clean_html(video_description)
761 else:
762 fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
763 if fd_mobj:
764 video_description = unescapeHTML(fd_mobj.group(1))
765 else:
766 video_description = u''
767
768 # subtitles
769 video_subtitles = None
770
88ae5991
JMF
771 if self._downloader.params.get('writesubtitles', False) or self._downloader.params.get('allsubtitles', False):
772 video_subtitles = self._extract_subtitles(video_id)
5d51a883 773 elif self._downloader.params.get('writeautomaticsub', False):
b004821f 774 video_subtitles = self._request_automatic_caption(video_id, video_webpage)
c5e8d7af
PH
775
776 if self._downloader.params.get('listsubtitles', False):
93d3a642 777 self._list_available_subtitles(video_id)
c5e8d7af
PH
778 return
779
780 if 'length_seconds' not in video_info:
781 self._downloader.report_warning(u'unable to extract video duration')
782 video_duration = ''
783 else:
784 video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
785
c5e8d7af 786 # Decide which formats to download
c5e8d7af
PH
787
788 try:
789 mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
50be92c1
PH
790 if not mobj:
791 raise ValueError('Could not find vevo ID')
c5e8d7af
PH
792 info = json.loads(mobj.group(1))
793 args = info['args']
7ce7e394
JMF
794 # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
795 # this signatures are encrypted
796 m_s = re.search(r'[&,]s=', args['url_encoded_fmt_stream_map'])
797 if m_s is not None:
798 self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
c5e8d7af 799 video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
cde846b3 800 m_s = re.search(r'[&,]s=', args.get('adaptive_fmts', u''))
b7a68384 801 if m_s is not None:
37b6d5f6
AZ
802 if 'url_encoded_fmt_stream_map' in video_info:
803 video_info['url_encoded_fmt_stream_map'][0] += ',' + args['adaptive_fmts']
804 else:
805 video_info['url_encoded_fmt_stream_map'] = [args['adaptive_fmts']]
211fbc13 806 elif 'adaptive_fmts' in video_info:
37b6d5f6
AZ
807 if 'url_encoded_fmt_stream_map' in video_info:
808 video_info['url_encoded_fmt_stream_map'][0] += ',' + video_info['adaptive_fmts'][0]
809 else:
810 video_info['url_encoded_fmt_stream_map'] = video_info['adaptive_fmts']
c5e8d7af
PH
811 except ValueError:
812 pass
813
814 if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
815 self.report_rtmp_download()
816 video_url_list = [(None, video_info['conn'][0])]
817 elif 'url_encoded_fmt_stream_map' in video_info and len(video_info['url_encoded_fmt_stream_map']) >= 1:
a7055eb9
JMF
818 if 'rtmpe%3Dyes' in video_info['url_encoded_fmt_stream_map'][0]:
819 raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
c5e8d7af
PH
820 url_map = {}
821 for url_data_str in video_info['url_encoded_fmt_stream_map'][0].split(','):
822 url_data = compat_parse_qs(url_data_str)
823 if 'itag' in url_data and 'url' in url_data:
824 url = url_data['url'][0]
825 if 'sig' in url_data:
826 url += '&signature=' + url_data['sig'][0]
827 elif 's' in url_data:
769fda3c
FV
828 if self._downloader.params.get('verbose'):
829 s = url_data['s'][0]
c108eb73
JMF
830 if age_gate:
831 player_version = self._search_regex(r'ad3-(.+?)\.swf',
ed27d356
JMF
832 video_info['ad3_module'][0] if 'ad3_module' in video_info else 'NOT FOUND',
833 'flash player', fatal=False)
c108eb73
JMF
834 player = 'flash player %s' % player_version
835 else:
836 player = u'html5 player %s' % self._search_regex(r'html5player-(.+?)\.js', video_webpage,
837 'html5 player', fatal=False)
5a76c651
JMF
838 parts_sizes = u'.'.join(compat_str(len(part)) for part in s.split('.'))
839 self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
840 (len(s), parts_sizes, url_data['itag'][0], player))
75952c6e
JMF
841 encrypted_sig = url_data['s'][0]
842 if age_gate:
843 signature = self._decrypt_signature_age_gate(encrypted_sig)
844 else:
845 signature = self._decrypt_signature(encrypted_sig)
c5e8d7af
PH
846 url += '&signature=' + signature
847 if 'ratebypass' not in url:
848 url += '&ratebypass=yes'
849 url_map[url_data['itag'][0]] = url
1d043b93
JMF
850 video_url_list = self._get_video_url_list(url_map)
851 if not video_url_list:
c5e8d7af 852 return
1d043b93
JMF
853 elif video_info.get('hlsvp'):
854 manifest_url = video_info['hlsvp'][0]
855 url_map = self._extract_from_m3u8(manifest_url, video_id)
856 video_url_list = self._get_video_url_list(url_map)
857 if not video_url_list:
858 return
859
c5e8d7af
PH
860 else:
861 raise ExtractorError(u'no conn or url_encoded_fmt_stream_map information found in video info')
862
863 results = []
864 for format_param, video_real_url in video_url_list:
865 # Extension
866 video_extension = self._video_extensions.get(format_param, 'flv')
867
03cc7c20
JMF
868 video_format = '{0} - {1}{2}'.format(format_param if format_param else video_extension,
869 self._video_dimensions.get(format_param, '???'),
836a086c 870 ' ('+self._special_itags[format_param]+')' if format_param in self._special_itags else '')
c5e8d7af
PH
871
872 results.append({
873 'id': video_id,
874 'url': video_real_url,
875 'uploader': video_uploader,
876 'uploader_id': video_uploader_id,
877 'upload_date': upload_date,
878 'title': video_title,
879 'ext': video_extension,
880 'format': video_format,
881 'thumbnail': video_thumbnail,
882 'description': video_description,
883 'player_url': player_url,
884 'subtitles': video_subtitles,
885 'duration': video_duration
886 })
887 return results
888
889class YoutubePlaylistIE(InfoExtractor):
0f818663 890 IE_DESC = u'YouTube.com playlists'
c5e8d7af
PH
891 _VALID_URL = r"""(?:
892 (?:https?://)?
893 (?:\w+\.)?
894 youtube\.com/
895 (?:
896 (?:course|view_play_list|my_playlists|artist|playlist|watch)
897 \? (?:.*?&)*? (?:p|a|list)=
898 | p/
899 )
c626a3d9 900 ((?:PL|EC|UU|FL)?[0-9A-Za-z-_]{10,})
c5e8d7af
PH
901 .*
902 |
c626a3d9 903 ((?:PL|EC|UU|FL)[0-9A-Za-z-_]{10,})
c5e8d7af
PH
904 )"""
905 _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/playlists/%s?max-results=%i&start-index=%i&v=2&alt=json&safeSearch=none'
906 _MAX_RESULTS = 50
907 IE_NAME = u'youtube:playlist'
908
909 @classmethod
910 def suitable(cls, url):
911 """Receives a URL and returns True if suitable for this IE."""
912 return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
913
914 def _real_extract(self, url):
915 # Extract playlist id
916 mobj = re.match(self._VALID_URL, url, re.VERBOSE)
917 if mobj is None:
918 raise ExtractorError(u'Invalid URL: %s' % url)
919
920 # Download playlist videos from API
921 playlist_id = mobj.group(1) or mobj.group(2)
c5e8d7af
PH
922 videos = []
923
755eb032 924 for page_num in itertools.count(1):
771822eb
JMF
925 start_index = self._MAX_RESULTS * (page_num - 1) + 1
926 if start_index >= 1000:
927 self._downloader.report_warning(u'Max number of results reached')
928 break
929 url = self._TEMPLATE_URL % (playlist_id, self._MAX_RESULTS, start_index)
c5e8d7af
PH
930 page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
931
932 try:
933 response = json.loads(page)
934 except ValueError as err:
935 raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
936
937 if 'feed' not in response:
938 raise ExtractorError(u'Got a malformed response from YouTube API')
939 playlist_title = response['feed']['title']['$t']
940 if 'entry' not in response['feed']:
941 # Number of videos is a multiple of self._MAX_RESULTS
942 break
943
944 for entry in response['feed']['entry']:
945 index = entry['yt$position']['$t']
c215217e
JMF
946 if 'media$group' in entry and 'yt$videoid' in entry['media$group']:
947 videos.append((
948 index,
949 'https://www.youtube.com/watch?v=' + entry['media$group']['yt$videoid']['$t']
950 ))
c5e8d7af
PH
951
952 videos = [v[1] for v in sorted(videos)]
953
20c3893f 954 url_results = [self.url_result(vurl, 'Youtube') for vurl in videos]
c5e8d7af
PH
955 return [self.playlist_result(url_results, playlist_id, playlist_title)]
956
957
958class YoutubeChannelIE(InfoExtractor):
0f818663 959 IE_DESC = u'YouTube.com channels'
c5e8d7af
PH
960 _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
961 _TEMPLATE_URL = 'http://www.youtube.com/channel/%s/videos?sort=da&flow=list&view=0&page=%s&gl=US&hl=en'
962 _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
252580c5 963 _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
c5e8d7af
PH
964 IE_NAME = u'youtube:channel'
965
966 def extract_videos_from_page(self, page):
967 ids_in_page = []
968 for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
969 if mobj.group(1) not in ids_in_page:
970 ids_in_page.append(mobj.group(1))
971 return ids_in_page
972
973 def _real_extract(self, url):
974 # Extract channel id
975 mobj = re.match(self._VALID_URL, url)
976 if mobj is None:
977 raise ExtractorError(u'Invalid URL: %s' % url)
978
979 # Download channel page
980 channel_id = mobj.group(1)
981 video_ids = []
982 pagenum = 1
983
984 url = self._TEMPLATE_URL % (channel_id, pagenum)
985 page = self._download_webpage(url, channel_id,
986 u'Downloading page #%s' % pagenum)
987
988 # Extract video identifiers
989 ids_in_page = self.extract_videos_from_page(page)
990 video_ids.extend(ids_in_page)
991
992 # Download any subsequent channel pages using the json-based channel_ajax query
993 if self._MORE_PAGES_INDICATOR in page:
755eb032 994 for pagenum in itertools.count(1):
c5e8d7af
PH
995 url = self._MORE_PAGES_URL % (pagenum, channel_id)
996 page = self._download_webpage(url, channel_id,
997 u'Downloading page #%s' % pagenum)
998
999 page = json.loads(page)
1000
1001 ids_in_page = self.extract_videos_from_page(page['content_html'])
1002 video_ids.extend(ids_in_page)
1003
1004 if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
1005 break
1006
1007 self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
1008
1009 urls = ['http://www.youtube.com/watch?v=%s' % id for id in video_ids]
20c3893f 1010 url_entries = [self.url_result(eurl, 'Youtube') for eurl in urls]
c5e8d7af
PH
1011 return [self.playlist_result(url_entries, channel_id)]
1012
1013
1014class YoutubeUserIE(InfoExtractor):
0f818663 1015 IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
c5e8d7af
PH
1016 _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/user/)|ytuser:)([A-Za-z0-9_-]+)'
1017 _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
1018 _GDATA_PAGE_SIZE = 50
1019 _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d'
1020 _VIDEO_INDICATOR = r'/watch\?v=(.+?)[\<&]'
1021 IE_NAME = u'youtube:user'
1022
1023 def _real_extract(self, url):
1024 # Extract username
1025 mobj = re.match(self._VALID_URL, url)
1026 if mobj is None:
1027 raise ExtractorError(u'Invalid URL: %s' % url)
1028
1029 username = mobj.group(1)
1030
1031 # Download video ids using YouTube Data API. Result size per
1032 # query is limited (currently to 50 videos) so we need to query
1033 # page by page until there are no video ids - it means we got
1034 # all of them.
1035
1036 video_ids = []
c5e8d7af 1037
755eb032 1038 for pagenum in itertools.count(0):
c5e8d7af
PH
1039 start_index = pagenum * self._GDATA_PAGE_SIZE + 1
1040
1041 gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
1042 page = self._download_webpage(gdata_url, username,
1043 u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
1044
1045 # Extract video identifiers
1046 ids_in_page = []
1047
1048 for mobj in re.finditer(self._VIDEO_INDICATOR, page):
1049 if mobj.group(1) not in ids_in_page:
1050 ids_in_page.append(mobj.group(1))
1051
1052 video_ids.extend(ids_in_page)
1053
1054 # A little optimization - if current page is not
1055 # "full", ie. does not contain PAGE_SIZE video ids then
1056 # we can assume that this page is the last one - there
1057 # are no more ids on further pages - no need to query
1058 # again.
1059
1060 if len(ids_in_page) < self._GDATA_PAGE_SIZE:
1061 break
1062
c5e8d7af 1063 urls = ['http://www.youtube.com/watch?v=%s' % video_id for video_id in video_ids]
20c3893f 1064 url_results = [self.url_result(rurl, 'Youtube') for rurl in urls]
c5e8d7af 1065 return [self.playlist_result(url_results, playlist_title = username)]
b05654f0
PH
1066
1067class YoutubeSearchIE(SearchInfoExtractor):
0f818663 1068 IE_DESC = u'YouTube.com searches'
b05654f0
PH
1069 _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
1070 _MAX_RESULTS = 1000
1071 IE_NAME = u'youtube:search'
1072 _SEARCH_KEY = 'ytsearch'
1073
1074 def report_download_page(self, query, pagenum):
1075 """Report attempt to download search page with given number."""
1076 self._downloader.to_screen(u'[youtube] query "%s": Downloading page %s' % (query, pagenum))
1077
1078 def _get_n_results(self, query, n):
1079 """Get a specified number of results for a query"""
1080
1081 video_ids = []
1082 pagenum = 0
1083 limit = n
1084
1085 while (50 * pagenum) < limit:
1086 self.report_download_page(query, pagenum+1)
1087 result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
1088 request = compat_urllib_request.Request(result_url)
1089 try:
1090 data = compat_urllib_request.urlopen(request).read().decode('utf-8')
1091 except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
1092 raise ExtractorError(u'Unable to download API page: %s' % compat_str(err))
1093 api_response = json.loads(data)['data']
1094
1095 if not 'items' in api_response:
1096 raise ExtractorError(u'[youtube] No video results')
1097
1098 new_ids = list(video['id'] for video in api_response['items'])
1099 video_ids += new_ids
1100
1101 limit = min(n, api_response['totalItems'])
1102 pagenum += 1
1103
1104 if len(video_ids) > n:
1105 video_ids = video_ids[:n]
1106 videos = [self.url_result('http://www.youtube.com/watch?v=%s' % id, 'Youtube') for id in video_ids]
1107 return self.playlist_result(videos, query)
75dff0ee
JMF
1108
1109
1110class YoutubeShowIE(InfoExtractor):
0f818663 1111 IE_DESC = u'YouTube.com (multi-season) shows'
75dff0ee
JMF
1112 _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
1113 IE_NAME = u'youtube:show'
1114
1115 def _real_extract(self, url):
1116 mobj = re.match(self._VALID_URL, url)
1117 show_name = mobj.group(1)
1118 webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
1119 # There's one playlist for each season of the show
1120 m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
1121 self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
1122 return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
04cc9617
JMF
1123
1124
b2e8bc1b 1125class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
d7ae0639
JMF
1126 """
1127 Base class for extractors that fetch info from
1128 http://www.youtube.com/feed_ajax
1129 Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
1130 """
b2e8bc1b 1131 _LOGIN_REQUIRED = True
04cc9617 1132 _PAGING_STEP = 30
43ba5456
JMF
1133 # use action_load_personal_feed instead of action_load_system_feed
1134 _PERSONAL_FEED = False
04cc9617 1135
d7ae0639
JMF
1136 @property
1137 def _FEED_TEMPLATE(self):
43ba5456
JMF
1138 action = 'action_load_system_feed'
1139 if self._PERSONAL_FEED:
1140 action = 'action_load_personal_feed'
1141 return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
d7ae0639
JMF
1142
1143 @property
1144 def IE_NAME(self):
1145 return u'youtube:%s' % self._FEED_NAME
1146
81f0259b 1147 def _real_initialize(self):
b2e8bc1b 1148 self._login()
81f0259b 1149
04cc9617
JMF
1150 def _real_extract(self, url):
1151 feed_entries = []
1152 # The step argument is available only in 2.7 or higher
1153 for i in itertools.count(0):
1154 paging = i*self._PAGING_STEP
d7ae0639
JMF
1155 info = self._download_webpage(self._FEED_TEMPLATE % paging,
1156 u'%s feed' % self._FEED_NAME,
04cc9617
JMF
1157 u'Downloading page %s' % i)
1158 info = json.loads(info)
1159 feed_html = info['feed_html']
43ba5456 1160 m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
04cc9617
JMF
1161 ids = orderedSet(m.group(1) for m in m_ids)
1162 feed_entries.extend(self.url_result(id, 'Youtube') for id in ids)
1163 if info['paging'] is None:
1164 break
d7ae0639
JMF
1165 return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
1166
1167class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
1168 IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
1169 _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
1170 _FEED_NAME = 'subscriptions'
1171 _PLAYLIST_TITLE = u'Youtube Subscriptions'
1172
1173class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
1174 IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
1175 _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
1176 _FEED_NAME = 'recommended'
1177 _PLAYLIST_TITLE = u'Youtube Recommended videos'
c626a3d9 1178
43ba5456
JMF
1179class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
1180 IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
1181 _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
1182 _FEED_NAME = 'watch_later'
1183 _PLAYLIST_TITLE = u'Youtube Watch Later'
1184 _PAGING_STEP = 100
1185 _PERSONAL_FEED = True
c626a3d9
JMF
1186
1187class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
1188 IE_NAME = u'youtube:favorites'
1189 IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
c7a7750d 1190 _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
c626a3d9
JMF
1191 _LOGIN_REQUIRED = True
1192
1193 def _real_extract(self, url):
1194 webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
1195 playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
1196 return self.url_result(playlist_id, 'YoutubePlaylist')