[vevo] Add test for video only available via webpage
[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_urlparse,
9 )
10 from ..utils import (
11     ExtractorError,
12     int_or_none,
13     sanitized_Request,
14     parse_iso8601,
15 )
16
17
18 class 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
27 class VevoIE(VevoBaseIE):
28     '''
29     Accepts urls from vevo.com or in the format 'vevo:{id}'
30     (currently used by MTVIE and MySpaceIE)
31     '''
32     _VALID_URL = r'''(?x)
33         (?:https?://www\.vevo\.com/watch/(?!playlist|genre)(?:[^/]+/(?:[^/]+/)?)?|
34            https?://cache\.vevo\.com/m/html/embed\.html\?video=|
35            https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
36            vevo:)
37         (?P<id>[^&?#]+)'''
38
39     _TESTS = [{
40         'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
41         'md5': '95ee28ee45e70130e3ab02b0f579ae23',
42         'info_dict': {
43             'id': 'GB1101300280',
44             'ext': 'mp4',
45             'title': 'Somebody to Die For',
46             'upload_date': '20130624',
47             'uploader': 'Hurts',
48             'timestamp': 1372057200,
49         },
50     }, {
51         'note': 'v3 SMIL format',
52         'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
53         'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
54         'info_dict': {
55             'id': 'USUV71302923',
56             'ext': 'mp4',
57             'title': 'I Wish I Could Break Your Heart',
58             'upload_date': '20140219',
59             'uploader': 'Cassadee Pope',
60             'timestamp': 1392796919,
61         },
62     }, {
63         'note': 'Age-limited video',
64         'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
65         'info_dict': {
66             'id': 'USRV81300282',
67             'ext': 'mp4',
68             'title': 'Tunnel Vision (Explicit)',
69             'upload_date': '20130703',
70             'age_limit': 18,
71             'uploader': 'Justin Timberlake',
72             'timestamp': 1372888800,
73         },
74     }, {
75         'note': 'No video_info',
76         'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
77         'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
78         'info_dict': {
79             'id': 'USUV71503000',
80             'ext': 'mp4',
81             'title': 'Till I Die',
82             'upload_date': '20151207',
83             'age_limit': 18,
84             'uploader': 'K Camp',
85             'timestamp': 1449468000,
86         },
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'],
101     }]
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 = {
118         0: 'youtube',  # only in AuthenticateVideo videoVersions
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):
126         formats = []
127         els = smil.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
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
134                     _(?P<tbr>[0-9]+)k
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')
146             formats.append({
147                 'url': format_url,
148                 'format_id': 'smil_' + m.group('tbr'),
149                 'vcodec': m.group('vcodec'),
150                 'acodec': m.group('acodec'),
151                 'tbr': int(m.group('tbr')),
152                 'vbr': int(m.group('vbr')),
153                 'abr': int(m.group('abr')),
154                 'ext': m.group('ext'),
155                 'width': int(m.group('width')),
156                 'height': int(m.group('height')),
157             })
158         return formats
159
160     def _initialize_api(self, video_id):
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:
169             raise ExtractorError(
170                 '%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
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
175     def _call_api(self, path, *args, **kwargs):
176         return self._download_json(self._api_url_template % path, *args, **kwargs)
177
178     def _real_extract(self, url):
179         video_id = self._match_id(url)
180
181         json_url = 'http://api.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
182         response = self._download_json(
183             json_url, video_id, 'Downloading video info', 'Unable to download info')
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 = []
190
191         if not video_info:
192             if response.get('statusCode') != 909:
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
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
204             self._initialize_api(video_id)
205             video_info = self._call_api(
206                 'video/%s' % video_id, video_id, 'Downloading api video info',
207                 'Failed to download video info')
208
209             video_versions = self._call_api(
210                 'video/%s/streams' % video_id, video_id,
211                 'Downloading video versions info',
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]
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:
231                     continue
232
233                 if '.ism' in version_url:
234                     continue
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))
241                 elif '.m3u8' in version_url:
242                     formats.extend(self._extract_m3u8_formats(
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':
283                     continue
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))
308                     elif source_type == 'smil' and version == 'level3' and not smil_parsed:
309                         formats.extend(self._extract_smil_formats(
310                             renditions.find('rendition').attrib['url'], video_id, False))
311                         smil_parsed = True
312         self._sort_formats(formats)
313
314         title = video_info['title']
315
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
324         duration = video_info.get('duration')
325
326         return {
327             'id': video_id,
328             'title': title,
329             'formats': formats,
330             'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
331             'timestamp': timestamp,
332             'uploader': uploader,
333             'duration': duration,
334             'view_count': view_count,
335             'age_limit': age_limit,
336         }
337
338
339 class VevoPlaylistIE(VevoBaseIE):
340     _VALID_URL = r'https?://www\.vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
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,
349     }, {
350         'url': 'http://www.vevo.com/watch/genre/rock',
351         'info_dict': {
352             'id': 'rock',
353             'title': 'Rock',
354         },
355         'playlist_count': 20,
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'],
368     }, {
369         'url': 'http://www.vevo.com/watch/genre/rock?index=0',
370         'only_matching': True,
371     }]
372
373     def _real_extract(self, url):
374         mobj = re.match(self._VALID_URL, url)
375         playlist_id = mobj.group('id')
376         playlist_kind = mobj.group('kind')
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
390         playlists = self._extract_json(webpage, playlist_id, '%ss' % playlist_kind)
391
392         playlist = (list(playlists.values())[0]
393                     if playlist_kind == 'playlist' else playlists[playlist_id])
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'))