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