[vevo] Fix extraction (config.token.key)
[youtube-dl] / youtube_dl / extractor / vevo.py
1 from __future__ import unicode_literals
2
3 import re
4 import json
5
6 from .common import InfoExtractor
7 from ..compat import (
8     compat_str,
9     compat_urlparse,
10     compat_HTTPError,
11 )
12 from ..utils import (
13     ExtractorError,
14     int_or_none,
15     sanitized_Request,
16     parse_iso8601,
17 )
18
19
20 class VevoBaseIE(InfoExtractor):
21     def _extract_json(self, webpage, video_id):
22         return self._parse_json(
23             self._search_regex(
24                 r'window\.__INITIAL_STORE__\s*=\s*({.+?});\s*</script>',
25                 webpage, 'initial store'),
26             video_id)
27
28
29 class VevoIE(VevoBaseIE):
30     '''
31     Accepts urls from vevo.com or in the format 'vevo:{id}'
32     (currently used by MTVIE and MySpaceIE)
33     '''
34     _VALID_URL = r'''(?x)
35         (?:https?://(?:www\.)?vevo\.com/watch/(?!playlist|genre)(?:[^/]+/(?:[^/]+/)?)?|
36            https?://cache\.vevo\.com/m/html/embed\.html\?video=|
37            https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
38            vevo:)
39         (?P<id>[^&?#]+)'''
40
41     _TESTS = [{
42         'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
43         'md5': '95ee28ee45e70130e3ab02b0f579ae23',
44         'info_dict': {
45             'id': 'GB1101300280',
46             'ext': 'mp4',
47             'title': 'Hurts - Somebody to Die For',
48             'timestamp': 1372057200,
49             'upload_date': '20130624',
50             'uploader': 'Hurts',
51             'track': 'Somebody to Die For',
52             'artist': 'Hurts',
53             'genre': 'Pop',
54         },
55         'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
56     }, {
57         'note': 'v3 SMIL format',
58         'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
59         'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
60         'info_dict': {
61             'id': 'USUV71302923',
62             'ext': 'mp4',
63             'title': 'Cassadee Pope - I Wish I Could Break Your Heart',
64             'timestamp': 1392796919,
65             'upload_date': '20140219',
66             'uploader': 'Cassadee Pope',
67             'track': 'I Wish I Could Break Your Heart',
68             'artist': 'Cassadee Pope',
69             'genre': 'Country',
70         },
71         'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
72     }, {
73         'note': 'Age-limited video',
74         'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
75         'info_dict': {
76             'id': 'USRV81300282',
77             'ext': 'mp4',
78             'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
79             'age_limit': 18,
80             'timestamp': 1372888800,
81             'upload_date': '20130703',
82             'uploader': 'Justin Timberlake',
83             'track': 'Tunnel Vision (Explicit)',
84             'artist': 'Justin Timberlake',
85             'genre': 'Pop',
86         },
87         'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
88     }, {
89         'note': 'No video_info',
90         'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
91         'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
92         'info_dict': {
93             'id': 'USUV71503000',
94             'ext': 'mp4',
95             'title': 'K Camp ft. T.I. - Till I Die',
96             'age_limit': 18,
97             'timestamp': 1449468000,
98             'upload_date': '20151207',
99             'uploader': 'K Camp',
100             'track': 'Till I Die',
101             'artist': 'K Camp',
102             'genre': 'Hip-Hop',
103         },
104         'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
105     }, {
106         'note': 'Featured test',
107         'url': 'https://www.vevo.com/watch/lemaitre/Wait/USUV71402190',
108         'md5': 'd28675e5e8805035d949dc5cf161071d',
109         'info_dict': {
110             'id': 'USUV71402190',
111             'ext': 'mp4',
112             'title': 'Lemaitre ft. LoLo - Wait',
113             'age_limit': 0,
114             'timestamp': 1413432000,
115             'upload_date': '20141016',
116             'uploader': 'Lemaitre',
117             'track': 'Wait',
118             'artist': 'Lemaitre',
119             'genre': 'Electronic',
120         },
121         'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
122     }, {
123         'note': 'Only available via webpage',
124         'url': 'http://www.vevo.com/watch/GBUV71600656',
125         'md5': '67e79210613865b66a47c33baa5e37fe',
126         'info_dict': {
127             'id': 'GBUV71600656',
128             'ext': 'mp4',
129             'title': 'ABC - Viva Love',
130             'age_limit': 0,
131             'timestamp': 1461830400,
132             'upload_date': '20160428',
133             'uploader': 'ABC',
134             'track': 'Viva Love',
135             'artist': 'ABC',
136             'genre': 'Pop',
137         },
138         'expected_warnings': ['Failed to download video versions info'],
139     }, {
140         # no genres available
141         'url': 'http://www.vevo.com/watch/INS171400764',
142         'only_matching': True,
143     }, {
144         # Another case available only via the webpage; using streams/streamsV3 formats
145         # Geo-restricted to Netherlands/Germany
146         'url': 'http://www.vevo.com/watch/boostee/pop-corn-clip-officiel/FR1A91600909',
147         'only_matching': True,
148     }]
149     _VERSIONS = {
150         0: 'youtube',  # only in AuthenticateVideo videoVersions
151         1: 'level3',
152         2: 'akamai',
153         3: 'level3',
154         4: 'amazon',
155     }
156
157     def _initialize_api(self, video_id):
158         post_data = json.dumps({
159             'client_id': 'SPupX1tvqFEopQ1YS6SS',
160             'grant_type': 'urn:vevo:params:oauth:grant-type:anonymous',
161         }).encode('utf-8')
162         headers = {
163             'Content-Type': 'application/json',
164         }
165         req = sanitized_Request(
166             'https://accounts.vevo.com/token', post_data, headers)
167         webpage = self._download_webpage(
168             req, None,
169             note='Retrieving oauth token',
170             errnote='Unable to retrieve oauth token')
171
172         if re.search(r'(?i)THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION', webpage):
173             self.raise_geo_restricted(
174                 '%s said: This page is currently unavailable in your region' % self.IE_NAME)
175
176         auth_info = self._parse_json(webpage, video_id)
177         self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['legacy_token']
178
179     def _call_api(self, path, *args, **kwargs):
180         try:
181             data = self._download_json(self._api_url_template % path, *args, **kwargs)
182         except ExtractorError as e:
183             if isinstance(e.cause, compat_HTTPError):
184                 errors = self._parse_json(e.cause.read().decode(), None)['errors']
185                 error_message = ', '.join([error['message'] for error in errors])
186                 raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
187             raise
188         return data
189
190     def _real_extract(self, url):
191         video_id = self._match_id(url)
192
193         self._initialize_api(video_id)
194
195         video_info = self._call_api(
196             'video/%s' % video_id, video_id, 'Downloading api video info',
197             'Failed to download video info')
198
199         video_versions = self._call_api(
200             'video/%s/streams' % video_id, video_id,
201             'Downloading video versions info',
202             'Failed to download video versions info',
203             fatal=False)
204
205         # Some videos are only available via webpage (e.g.
206         # https://github.com/rg3/youtube-dl/issues/9366)
207         if not video_versions:
208             webpage = self._download_webpage(url, video_id)
209             json_data = self._extract_json(webpage, video_id)
210             if 'streams' in json_data.get('default', {}):
211                 video_versions = json_data['default']['streams'][video_id][0]
212             else:
213                 video_versions = [
214                     value
215                     for key, value in json_data['apollo']['data'].items()
216                     if key.startswith('%s.streams' % video_id)]
217
218         uploader = None
219         artist = None
220         featured_artist = None
221         artists = video_info.get('artists')
222         for curr_artist in artists:
223             if curr_artist.get('role') == 'Featured':
224                 featured_artist = curr_artist['name']
225             else:
226                 artist = uploader = curr_artist['name']
227
228         formats = []
229         for video_version in video_versions:
230             version = self._VERSIONS.get(video_version.get('version'), 'generic')
231             version_url = video_version.get('url')
232             if not version_url:
233                 continue
234
235             if '.ism' in version_url:
236                 continue
237             elif '.mpd' in version_url:
238                 formats.extend(self._extract_mpd_formats(
239                     version_url, video_id, mpd_id='dash-%s' % version,
240                     note='Downloading %s MPD information' % version,
241                     errnote='Failed to download %s MPD information' % version,
242                     fatal=False))
243             elif '.m3u8' in version_url:
244                 formats.extend(self._extract_m3u8_formats(
245                     version_url, video_id, 'mp4', 'm3u8_native',
246                     m3u8_id='hls-%s' % version,
247                     note='Downloading %s m3u8 information' % version,
248                     errnote='Failed to download %s m3u8 information' % version,
249                     fatal=False))
250             else:
251                 m = re.search(r'''(?xi)
252                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
253                     _(?P<vcodec>[a-z0-9]+)
254                     _(?P<vbr>[0-9]+)
255                     _(?P<acodec>[a-z0-9]+)
256                     _(?P<abr>[0-9]+)
257                     \.(?P<ext>[a-z0-9]+)''', version_url)
258                 if not m:
259                     continue
260
261                 formats.append({
262                     'url': version_url,
263                     'format_id': 'http-%s-%s' % (version, video_version['quality']),
264                     'vcodec': m.group('vcodec'),
265                     'acodec': m.group('acodec'),
266                     'vbr': int(m.group('vbr')),
267                     'abr': int(m.group('abr')),
268                     'ext': m.group('ext'),
269                     'width': int(m.group('width')),
270                     'height': int(m.group('height')),
271                 })
272         self._sort_formats(formats)
273
274         track = video_info['title']
275         if featured_artist:
276             artist = '%s ft. %s' % (artist, featured_artist)
277         title = '%s - %s' % (artist, track) if artist else track
278
279         genres = video_info.get('genres')
280         genre = (
281             genres[0] if genres and isinstance(genres, list) and
282             isinstance(genres[0], compat_str) else None)
283
284         is_explicit = video_info.get('isExplicit')
285         if is_explicit is True:
286             age_limit = 18
287         elif is_explicit is False:
288             age_limit = 0
289         else:
290             age_limit = None
291
292         return {
293             'id': video_id,
294             'title': title,
295             'formats': formats,
296             'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
297             'timestamp': parse_iso8601(video_info.get('releaseDate')),
298             'uploader': uploader,
299             'duration': int_or_none(video_info.get('duration')),
300             'view_count': int_or_none(video_info.get('views', {}).get('total')),
301             'age_limit': age_limit,
302             'track': track,
303             'artist': uploader,
304             'genre': genre,
305         }
306
307
308 class VevoPlaylistIE(VevoBaseIE):
309     _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
310
311     _TESTS = [{
312         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
313         'info_dict': {
314             'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
315             'title': 'Best-Of: Birdman',
316         },
317         'playlist_count': 10,
318     }, {
319         'url': 'http://www.vevo.com/watch/genre/rock',
320         'info_dict': {
321             'id': 'rock',
322             'title': 'Rock',
323         },
324         'playlist_count': 20,
325     }, {
326         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
327         'md5': '32dcdfddddf9ec6917fc88ca26d36282',
328         'info_dict': {
329             'id': 'USCMV1100073',
330             'ext': 'mp4',
331             'title': 'Birdman - Y.U. MAD',
332             'timestamp': 1323417600,
333             'upload_date': '20111209',
334             'uploader': 'Birdman',
335             'track': 'Y.U. MAD',
336             'artist': 'Birdman',
337             'genre': 'Rap/Hip-Hop',
338         },
339         'expected_warnings': ['Unable to download SMIL file'],
340     }, {
341         'url': 'http://www.vevo.com/watch/genre/rock?index=0',
342         'only_matching': True,
343     }]
344
345     def _real_extract(self, url):
346         mobj = re.match(self._VALID_URL, url)
347         playlist_id = mobj.group('id')
348         playlist_kind = mobj.group('kind')
349
350         webpage = self._download_webpage(url, playlist_id)
351
352         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
353         index = qs.get('index', [None])[0]
354
355         if index:
356             video_id = self._search_regex(
357                 r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
358                 webpage, 'video id', default=None, group='id')
359             if video_id:
360                 return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
361
362         playlists = self._extract_json(webpage, playlist_id)['default']['%ss' % playlist_kind]
363
364         playlist = (list(playlists.values())[0]
365                     if playlist_kind == 'playlist' else playlists[playlist_id])
366
367         entries = [
368             self.url_result('vevo:%s' % src, VevoIE.ie_key())
369             for src in playlist['isrcs']]
370
371         return self.playlist_result(
372             entries, playlist.get('playlistId') or playlist_id,
373             playlist.get('name'), playlist.get('description'))