[vevo] Simplify artists extraction
[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 curr_artist.get('role') == 'Featured':
263                     featured_artist = curr_artist['name']
264                 else:
265                     artist = uploader = curr_artist['name']
266             view_count = int_or_none(video_info.get('views', {}).get('total'))
267
268             for video_version in video_versions:
269                 version = self._VERSIONS.get(video_version['version'])
270                 version_url = video_version.get('url')
271                 if not version_url:
272                     continue
273
274                 if '.ism' in version_url:
275                     continue
276                 elif '.mpd' in version_url:
277                     formats.extend(self._extract_mpd_formats(
278                         version_url, video_id, mpd_id='dash-%s' % version,
279                         note='Downloading %s MPD information' % version,
280                         errnote='Failed to download %s MPD information' % version,
281                         fatal=False))
282                 elif '.m3u8' in version_url:
283                     formats.extend(self._extract_m3u8_formats(
284                         version_url, video_id, 'mp4', 'm3u8_native',
285                         m3u8_id='hls-%s' % version,
286                         note='Downloading %s m3u8 information' % version,
287                         errnote='Failed to download %s m3u8 information' % version,
288                         fatal=False))
289                 else:
290                     m = re.search(r'''(?xi)
291                         _(?P<width>[0-9]+)x(?P<height>[0-9]+)
292                         _(?P<vcodec>[a-z0-9]+)
293                         _(?P<vbr>[0-9]+)
294                         _(?P<acodec>[a-z0-9]+)
295                         _(?P<abr>[0-9]+)
296                         \.(?P<ext>[a-z0-9]+)''', version_url)
297                     if not m:
298                         continue
299
300                     formats.append({
301                         'url': version_url,
302                         'format_id': 'http-%s-%s' % (version, video_version['quality']),
303                         'vcodec': m.group('vcodec'),
304                         'acodec': m.group('acodec'),
305                         'vbr': int(m.group('vbr')),
306                         'abr': int(m.group('abr')),
307                         'ext': m.group('ext'),
308                         'width': int(m.group('width')),
309                         'height': int(m.group('height')),
310                     })
311         else:
312             timestamp = int_or_none(self._search_regex(
313                 r'/Date\((\d+)\)/',
314                 video_info['releaseDate'], 'release date', fatal=False),
315                 scale=1000)
316             artists = video_info.get('mainArtists')
317             if artists:
318                 artist = uploader = artists[0]['artistName']
319
320             featured_artists = video_info.get('featuredArtists')
321             if featured_artists:
322                 featured_artist = featured_artists[0]['artistName']
323
324             smil_parsed = False
325             for video_version in video_info['videoVersions']:
326                 version = self._VERSIONS.get(video_version['version'])
327                 if version == 'youtube':
328                     continue
329                 else:
330                     source_type = self._SOURCE_TYPES.get(video_version['sourceType'])
331                     renditions = compat_etree_fromstring(video_version['data'])
332                     if source_type == 'http':
333                         for rend in renditions.findall('rendition'):
334                             attr = rend.attrib
335                             formats.append({
336                                 'url': attr['url'],
337                                 'format_id': 'http-%s-%s' % (version, attr['name']),
338                                 'height': int_or_none(attr.get('frameheight')),
339                                 'width': int_or_none(attr.get('frameWidth')),
340                                 'tbr': int_or_none(attr.get('totalBitrate')),
341                                 'vbr': int_or_none(attr.get('videoBitrate')),
342                                 'abr': int_or_none(attr.get('audioBitrate')),
343                                 'vcodec': attr.get('videoCodec'),
344                                 'acodec': attr.get('audioCodec'),
345                             })
346                     elif source_type == 'hls':
347                         formats.extend(self._extract_m3u8_formats(
348                             renditions.find('rendition').attrib['url'], video_id,
349                             'mp4', 'm3u8_native', m3u8_id='hls-%s' % version,
350                             note='Downloading %s m3u8 information' % version,
351                             errnote='Failed to download %s m3u8 information' % version,
352                             fatal=False))
353                     elif source_type == 'smil' and version == 'level3' and not smil_parsed:
354                         formats.extend(self._extract_smil_formats(
355                             renditions.find('rendition').attrib['url'], video_id, False))
356                         smil_parsed = True
357         self._sort_formats(formats)
358
359         track = video_info['title']
360         if featured_artist:
361             artist = '%s ft. %s' % (artist, featured_artist)
362         title = '%s - %s' % (artist, track) if artist else track
363
364         genres = video_info.get('genres')
365         genre = (
366             genres[0] if genres and isinstance(genres, list) and
367             isinstance(genres[0], compat_str) else None)
368
369         is_explicit = video_info.get('isExplicit')
370         if is_explicit is True:
371             age_limit = 18
372         elif is_explicit is False:
373             age_limit = 0
374         else:
375             age_limit = None
376
377         duration = video_info.get('duration')
378
379         return {
380             'id': video_id,
381             'title': title,
382             'formats': formats,
383             'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
384             'timestamp': timestamp,
385             'uploader': uploader,
386             'duration': duration,
387             'view_count': view_count,
388             'age_limit': age_limit,
389             'track': track,
390             'artist': uploader,
391             'genre': genre,
392         }
393
394
395 class VevoPlaylistIE(VevoBaseIE):
396     _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
397
398     _TESTS = [{
399         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
400         'info_dict': {
401             'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
402             'title': 'Best-Of: Birdman',
403         },
404         'playlist_count': 10,
405     }, {
406         'url': 'http://www.vevo.com/watch/genre/rock',
407         'info_dict': {
408             'id': 'rock',
409             'title': 'Rock',
410         },
411         'playlist_count': 20,
412     }, {
413         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
414         'md5': '32dcdfddddf9ec6917fc88ca26d36282',
415         'info_dict': {
416             'id': 'USCMV1100073',
417             'ext': 'mp4',
418             'title': 'Birdman - Y.U. MAD',
419             'timestamp': 1323417600,
420             'upload_date': '20111209',
421             'uploader': 'Birdman',
422             'track': 'Y.U. MAD',
423             'artist': 'Birdman',
424             'genre': 'Rap/Hip-Hop',
425         },
426         'expected_warnings': ['Unable to download SMIL file'],
427     }, {
428         'url': 'http://www.vevo.com/watch/genre/rock?index=0',
429         'only_matching': True,
430     }]
431
432     def _real_extract(self, url):
433         mobj = re.match(self._VALID_URL, url)
434         playlist_id = mobj.group('id')
435         playlist_kind = mobj.group('kind')
436
437         webpage = self._download_webpage(url, playlist_id)
438
439         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
440         index = qs.get('index', [None])[0]
441
442         if index:
443             video_id = self._search_regex(
444                 r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
445                 webpage, 'video id', default=None, group='id')
446             if video_id:
447                 return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
448
449         playlists = self._extract_json(webpage, playlist_id, '%ss' % playlist_kind)
450
451         playlist = (list(playlists.values())[0]
452                     if playlist_kind == 'playlist' else playlists[playlist_id])
453
454         entries = [
455             self.url_result('vevo:%s' % src, VevoIE.ie_key())
456             for src in playlist['isrcs']]
457
458         return self.playlist_result(
459             entries, playlist.get('playlistId') or playlist_id,
460             playlist.get('name'), playlist.get('description'))