]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/vevo.py
[vevo] Add test for video only available via webpage
[yt-dlp.git] / youtube_dl / extractor / vevo.py
CommitLineData
45d7bc2f
JMF
1from __future__ import unicode_literals
2
70d1924f 3import re
70d1924f
JMF
4
5from .common import InfoExtractor
e0da32df
S
6from ..compat import (
7 compat_etree_fromstring,
8 compat_urlparse,
9)
1cc79574 10from ..utils import (
70d1924f 11 ExtractorError,
7d3d06a1 12 int_or_none,
9165d6ba 13 sanitized_Request,
14 parse_iso8601,
70d1924f
JMF
15)
16
88bd97e3 17
9618c448
S
18class VevoBaseIE(InfoExtractor):
19 def _extract_json(self, webpage, video_id, item):
20 return self._parse_json(
21 self._search_regex(
22 r'window\.__INITIAL_STORE__\s*=\s*({.+?});\s*</script>',
23 webpage, 'initial store'),
24 video_id)['default'][item]
25
26
27class VevoIE(VevoBaseIE):
2975fe1a 28 '''
0577177e 29 Accepts urls from vevo.com or in the format 'vevo:{id}'
3266f0c6 30 (currently used by MTVIE and MySpaceIE)
2975fe1a 31 '''
f25571ff 32 _VALID_URL = r'''(?x)
e0da32df 33 (?:https?://www\.vevo\.com/watch/(?!playlist|genre)(?:[^/]+/(?:[^/]+/)?)?|
f25571ff 34 https?://cache\.vevo\.com/m/html/embed\.html\?video=|
ebce53b3 35 https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
f25571ff
PH
36 vevo:)
37 (?P<id>[^&?#]+)'''
fd5e6f7e 38
72321ead 39 _TESTS = [{
45d7bc2f 40 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
682f8c43 41 'md5': '95ee28ee45e70130e3ab02b0f579ae23',
45d7bc2f 42 'info_dict': {
682f8c43 43 'id': 'GB1101300280',
27579b9e 44 'ext': 'mp4',
682f8c43 45 'title': 'Somebody to Die For',
2975fe1a 46 'upload_date': '20130624',
682f8c43 47 'uploader': 'Hurts',
48 'timestamp': 1372057200,
2975fe1a 49 },
27579b9e
PH
50 }, {
51 'note': 'v3 SMIL format',
52 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
682f8c43 53 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
27579b9e 54 'info_dict': {
682f8c43 55 'id': 'USUV71302923',
27579b9e 56 'ext': 'mp4',
682f8c43 57 'title': 'I Wish I Could Break Your Heart',
27579b9e 58 'upload_date': '20140219',
682f8c43 59 'uploader': 'Cassadee Pope',
60 'timestamp': 1392796919,
2975fe1a 61 },
6cadf8c8
PH
62 }, {
63 'note': 'Age-limited video',
64 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
65 'info_dict': {
682f8c43 66 'id': 'USRV81300282',
6cadf8c8 67 'ext': 'mp4',
682f8c43 68 'title': 'Tunnel Vision (Explicit)',
2975fe1a 69 'upload_date': '20130703',
682f8c43 70 'age_limit': 18,
71 'uploader': 'Justin Timberlake',
72 'timestamp': 1372888800,
2975fe1a 73 },
ff51983e
YCH
74 }, {
75 'note': 'No video_info',
76 'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
682f8c43 77 'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
ff51983e 78 'info_dict': {
682f8c43 79 'id': 'USUV71503000',
ff51983e 80 'ext': 'mp4',
682f8c43 81 'title': 'Till I Die',
9165d6ba 82 'upload_date': '20151207',
682f8c43 83 'age_limit': 18,
84 'uploader': 'K Camp',
85 'timestamp': 1449468000,
ff51983e 86 },
8e7d0048
S
87 }, {
88 'note': 'Only available via webpage',
89 'url': 'http://www.vevo.com/watch/GBUV71600656',
90 'md5': '67e79210613865b66a47c33baa5e37fe',
91 'info_dict': {
92 'id': 'GBUV71600656',
93 'ext': 'mp4',
94 'title': 'Viva Love',
95 'upload_date': '20160428',
96 'age_limit': 0,
97 'uploader': 'ABC',
98 'timestamp': 1461830400,
99 },
100 'expected_warnings': ['Failed to download video versions info'],
72321ead 101 }]
2975fe1a 102 _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com'
103 _SOURCE_TYPES = {
104 0: 'youtube',
105 1: 'brightcove',
106 2: 'http',
107 3: 'hls_ios',
108 4: 'hls',
109 5: 'smil', # http
110 7: 'f4m_cc',
111 8: 'f4m_ak',
112 9: 'f4m_l3',
113 10: 'ism',
114 13: 'smil', # rtmp
115 18: 'dash',
116 }
117 _VERSIONS = {
9165d6ba 118 0: 'youtube', # only in AuthenticateVideo videoVersions
2975fe1a 119 1: 'level3',
120 2: 'akamai',
121 3: 'level3',
122 4: 'amazon',
123 }
124
125 def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
72321ead 126 formats = []
2975fe1a 127 els = smil.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
72321ead
PH
128 for el in els:
129 src = el.attrib['src']
130 m = re.match(r'''(?xi)
131 (?P<ext>[a-z0-9]+):
132 (?P<path>
133 [/a-z0-9]+ # The directory and main part of the URL
2975fe1a 134 _(?P<tbr>[0-9]+)k
72321ead
PH
135 _(?P<width>[0-9]+)x(?P<height>[0-9]+)
136 _(?P<vcodec>[a-z0-9]+)
137 _(?P<vbr>[0-9]+)
138 _(?P<acodec>[a-z0-9]+)
139 _(?P<abr>[0-9]+)
140 \.[a-z0-9]+ # File extension
141 )''', src)
142 if not m:
143 continue
144
145 format_url = self._SMIL_BASE_URL + m.group('path')
72321ead
PH
146 formats.append({
147 'url': format_url,
2975fe1a 148 'format_id': 'smil_' + m.group('tbr'),
91c7271a
PH
149 'vcodec': m.group('vcodec'),
150 'acodec': m.group('acodec'),
2975fe1a 151 'tbr': int(m.group('tbr')),
91c7271a
PH
152 'vbr': int(m.group('vbr')),
153 'abr': int(m.group('abr')),
72321ead
PH
154 'ext': m.group('ext'),
155 'width': int(m.group('width')),
156 'height': int(m.group('height')),
157 })
158 return formats
159
682f8c43 160 def _initialize_api(self, video_id):
9165d6ba 161 req = sanitized_Request(
162 'http://www.vevo.com/auth', data=b'')
163 webpage = self._download_webpage(
164 req, None,
165 note='Retrieving oauth token',
166 errnote='Unable to retrieve oauth token')
167
168 if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in webpage:
682f8c43 169 raise ExtractorError(
170 '%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
9165d6ba 171
172 auth_info = self._parse_json(webpage, video_id)
173 self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['access_token']
174
516ea41a
S
175 def _call_api(self, path, *args, **kwargs):
176 return self._download_json(self._api_url_template % path, *args, **kwargs)
9165d6ba 177
72321ead 178 def _real_extract(self, url):
4b942883 179 video_id = self._match_id(url)
72321ead 180
4cf3489c 181 json_url = 'http://api.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
682f8c43 182 response = self._download_json(
183 json_url, video_id, 'Downloading video info', 'Unable to download info')
9165d6ba 184 video_info = response.get('video') or {}
185 video_versions = video_info.get('videoVersions')
186 uploader = None
187 timestamp = None
188 view_count = None
189 formats = []
e97e53ee 190
ff51983e 191 if not video_info:
2975fe1a 192 if response.get('statusCode') != 909:
682f8c43 193 ytid = response.get('errorInfo', {}).get('ytid')
194 if ytid:
195 self.report_warning(
196 'Video is geoblocked, trying with the YouTube video %s' % ytid)
197 return self.url_result(ytid, 'Youtube', ytid)
198
2975fe1a 199 if 'statusMessage' in response:
200 raise ExtractorError('%s said: %s' % (
201 self.IE_NAME, response['statusMessage']), expected=True)
202 raise ExtractorError('Unable to extract videos')
203
682f8c43 204 self._initialize_api(video_id)
9165d6ba 205 video_info = self._call_api(
206 'video/%s' % video_id, video_id, 'Downloading api video info',
207 'Failed to download video info')
ff51983e 208
9165d6ba 209 video_versions = self._call_api(
210 'video/%s/streams' % video_id, video_id,
211 'Downloading video versions info',
9618c448
S
212 'Failed to download video versions info',
213 fatal=False)
214
215 # Some videos are only available via webpage (e.g.
216 # https://github.com/rg3/youtube-dl/issues/9366)
217 if not video_versions:
218 webpage = self._download_webpage(url, video_id)
219 video_versions = self._extract_json(webpage, video_id, 'streams')[video_id][0]
9165d6ba 220
221 timestamp = parse_iso8601(video_info.get('releaseDate'))
222 artists = video_info.get('artists')
223 if artists:
224 uploader = artists[0]['name']
225 view_count = int_or_none(video_info.get('views', {}).get('total'))
226
227 for video_version in video_versions:
228 version = self._VERSIONS.get(video_version['version'])
229 version_url = video_version.get('url')
230 if not version_url:
682f8c43 231 continue
9165d6ba 232
5976e7ab 233 if '.ism' in version_url:
9165d6ba 234 continue
5976e7ab 235 elif '.mpd' in version_url:
236 formats.extend(self._extract_mpd_formats(
237 version_url, video_id, mpd_id='dash-%s' % version,
238 note='Downloading %s MPD information' % version,
239 errnote='Failed to download %s MPD information' % version,
240 fatal=False))
9165d6ba 241 elif '.m3u8' in version_url:
2975fe1a 242 formats.extend(self._extract_m3u8_formats(
9165d6ba 243 version_url, video_id, 'mp4', 'm3u8_native',
244 m3u8_id='hls-%s' % version,
245 note='Downloading %s m3u8 information' % version,
246 errnote='Failed to download %s m3u8 information' % version,
247 fatal=False))
248 else:
249 m = re.search(r'''(?xi)
250 _(?P<width>[0-9]+)x(?P<height>[0-9]+)
251 _(?P<vcodec>[a-z0-9]+)
252 _(?P<vbr>[0-9]+)
253 _(?P<acodec>[a-z0-9]+)
254 _(?P<abr>[0-9]+)
255 \.(?P<ext>[a-z0-9]+)''', version_url)
256 if not m:
257 continue
258
259 formats.append({
260 'url': version_url,
261 'format_id': 'http-%s-%s' % (version, video_version['quality']),
262 'vcodec': m.group('vcodec'),
263 'acodec': m.group('acodec'),
264 'vbr': int(m.group('vbr')),
265 'abr': int(m.group('abr')),
266 'ext': m.group('ext'),
267 'width': int(m.group('width')),
268 'height': int(m.group('height')),
269 })
270 else:
271 timestamp = int_or_none(self._search_regex(
272 r'/Date\((\d+)\)/',
273 video_info['releaseDate'], 'release date', fatal=False),
274 scale=1000)
275 artists = video_info.get('mainArtists')
276 if artists:
277 uploader = artists[0]['artistName']
278
279 smil_parsed = False
280 for video_version in video_info['videoVersions']:
281 version = self._VERSIONS.get(video_version['version'])
282 if version == 'youtube':
682f8c43 283 continue
9165d6ba 284 else:
285 source_type = self._SOURCE_TYPES.get(video_version['sourceType'])
286 renditions = compat_etree_fromstring(video_version['data'])
287 if source_type == 'http':
288 for rend in renditions.findall('rendition'):
289 attr = rend.attrib
290 formats.append({
291 'url': attr['url'],
292 'format_id': 'http-%s-%s' % (version, attr['name']),
293 'height': int_or_none(attr.get('frameheight')),
294 'width': int_or_none(attr.get('frameWidth')),
295 'tbr': int_or_none(attr.get('totalBitrate')),
296 'vbr': int_or_none(attr.get('videoBitrate')),
297 'abr': int_or_none(attr.get('audioBitrate')),
298 'vcodec': attr.get('videoCodec'),
299 'acodec': attr.get('audioCodec'),
300 })
301 elif source_type == 'hls':
302 formats.extend(self._extract_m3u8_formats(
303 renditions.find('rendition').attrib['url'], video_id,
304 'mp4', 'm3u8_native', m3u8_id='hls-%s' % version,
305 note='Downloading %s m3u8 information' % version,
306 errnote='Failed to download %s m3u8 information' % version,
307 fatal=False))
682f8c43 308 elif source_type == 'smil' and version == 'level3' and not smil_parsed:
9165d6ba 309 formats.extend(self._extract_smil_formats(
310 renditions.find('rendition').attrib['url'], video_id, False))
311 smil_parsed = True
2975fe1a 312 self._sort_formats(formats)
27579b9e 313
9165d6ba 314 title = video_info['title']
315
6cadf8c8
PH
316 is_explicit = video_info.get('isExplicit')
317 if is_explicit is True:
318 age_limit = 18
319 elif is_explicit is False:
320 age_limit = 0
321 else:
322 age_limit = None
323
9165d6ba 324 duration = video_info.get('duration')
9d2ecdbc 325
45d7bc2f 326 return {
88bd97e3 327 'id': video_id,
ff51983e 328 'title': title,
88bd97e3 329 'formats': formats,
9165d6ba 330 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
ff51983e 331 'timestamp': timestamp,
9165d6ba 332 'uploader': uploader,
ff51983e 333 'duration': duration,
9165d6ba 334 'view_count': view_count,
6cadf8c8 335 'age_limit': age_limit,
88bd97e3 336 }
e0da32df
S
337
338
9618c448 339class VevoPlaylistIE(VevoBaseIE):
e2bd301c 340 _VALID_URL = r'https?://www\.vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
e0da32df
S
341
342 _TESTS = [{
343 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
344 'info_dict': {
345 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
346 'title': 'Best-Of: Birdman',
347 },
348 'playlist_count': 10,
e2bd301c
S
349 }, {
350 'url': 'http://www.vevo.com/watch/genre/rock',
351 'info_dict': {
352 'id': 'rock',
353 'title': 'Rock',
354 },
355 'playlist_count': 20,
e0da32df
S
356 }, {
357 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
358 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
359 'info_dict': {
360 'id': 'USCMV1100073',
361 'ext': 'mp4',
362 'title': 'Y.U. MAD',
363 'timestamp': 1323417600,
364 'upload_date': '20111209',
365 'uploader': 'Birdman',
366 },
367 'expected_warnings': ['Unable to download SMIL file'],
e0da32df
S
368 }, {
369 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
370 'only_matching': True,
371 }]
372
373 def _real_extract(self, url):
e2bd301c
S
374 mobj = re.match(self._VALID_URL, url)
375 playlist_id = mobj.group('id')
376 playlist_kind = mobj.group('kind')
e0da32df
S
377
378 webpage = self._download_webpage(url, playlist_id)
379
380 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
381 index = qs.get('index', [None])[0]
382
383 if index:
384 video_id = self._search_regex(
385 r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
386 webpage, 'video id', default=None, group='id')
387 if video_id:
388 return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
389
9618c448 390 playlists = self._extract_json(webpage, playlist_id, '%ss' % playlist_kind)
e0da32df 391
e2bd301c
S
392 playlist = (list(playlists.values())[0]
393 if playlist_kind == 'playlist' else playlists[playlist_id])
e0da32df
S
394
395 entries = [
396 self.url_result('vevo:%s' % src, VevoIE.ie_key())
397 for src in playlist['isrcs']]
398
399 return self.playlist_result(
400 entries, playlist.get('playlistId'),
401 playlist.get('name'), playlist.get('description'))