[vevo] Handle videos without video_info (#7802)
[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 compat_etree_fromstring
7 from ..utils import (
8     ExtractorError,
9     int_or_none,
10     sanitized_Request,
11 )
12
13
14 class VevoIE(InfoExtractor):
15     """
16     Accepts urls from vevo.com or in the format 'vevo:{id}'
17     (currently used by MTVIE and MySpaceIE)
18     """
19     _VALID_URL = r'''(?x)
20         (?:https?://www\.vevo\.com/watch/(?:[^/]+/(?:[^/]+/)?)?|
21            https?://cache\.vevo\.com/m/html/embed\.html\?video=|
22            https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
23            vevo:)
24         (?P<id>[^&?#]+)'''
25
26     _TESTS = [{
27         'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
28         "md5": "95ee28ee45e70130e3ab02b0f579ae23",
29         'info_dict': {
30             'id': 'GB1101300280',
31             'ext': 'mp4',
32             "upload_date": "20130624",
33             "uploader": "Hurts",
34             "title": "Somebody to Die For",
35             "duration": 230.12,
36             "width": 1920,
37             "height": 1080,
38             # timestamp and upload_date are often incorrect; seem to change randomly
39             'timestamp': int,
40         }
41     }, {
42         'note': 'v3 SMIL format',
43         'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
44         'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
45         'info_dict': {
46             'id': 'USUV71302923',
47             'ext': 'mp4',
48             'upload_date': '20140219',
49             'uploader': 'Cassadee Pope',
50             'title': 'I Wish I Could Break Your Heart',
51             'duration': 226.101,
52             'age_limit': 0,
53             'timestamp': int,
54         }
55     }, {
56         'note': 'Age-limited video',
57         'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
58         'info_dict': {
59             'id': 'USRV81300282',
60             'ext': 'mp4',
61             'age_limit': 18,
62             'title': 'Tunnel Vision (Explicit)',
63             'uploader': 'Justin Timberlake',
64             'upload_date': 're:2013070[34]',
65             'timestamp': int,
66         },
67         'params': {
68             'skip_download': 'true',
69         }
70     }, {
71         'note': 'No video_info',
72         'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
73         'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
74         'info_dict': {
75             'id': 'USUV71503000',
76             'ext': 'mp4',
77             'title': 'Till I Die - K Camp ft. T.I.',
78             'duration': 193,
79         },
80         'expected_warnings': ['HTTP Error 404'],
81     }]
82     _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
83
84     def _real_initialize(self):
85         req = sanitized_Request(
86             'http://www.vevo.com/auth', data=b'')
87         webpage = self._download_webpage(
88             req, None,
89             note='Retrieving oauth token',
90             errnote='Unable to retrieve oauth token',
91             fatal=False)
92         if webpage is False:
93             self._oauth_token = None
94         else:
95             if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in webpage:
96                 raise ExtractorError('%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
97
98             self._oauth_token = self._search_regex(
99                 r'access_token":\s*"([^"]+)"',
100                 webpage, 'access token', fatal=False)
101
102     def _formats_from_json(self, video_info):
103         if not video_info:
104             return []
105
106         last_version = {'version': -1}
107         for version in video_info['videoVersions']:
108             # These are the HTTP downloads, other types are for different manifests
109             if version['sourceType'] == 2:
110                 if version['version'] > last_version['version']:
111                     last_version = version
112         if last_version['version'] == -1:
113             raise ExtractorError('Unable to extract last version of the video')
114
115         renditions = compat_etree_fromstring(last_version['data'])
116         formats = []
117         # Already sorted from worst to best quality
118         for rend in renditions.findall('rendition'):
119             attr = rend.attrib
120             format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
121             formats.append({
122                 'url': attr['url'],
123                 'format_id': attr['name'],
124                 'format_note': format_note,
125                 'height': int(attr['frameheight']),
126                 'width': int(attr['frameWidth']),
127             })
128         return formats
129
130     def _formats_from_smil(self, smil_xml):
131         formats = []
132         smil_doc = compat_etree_fromstring(smil_xml.encode('utf-8'))
133         els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
134         for el in els:
135             src = el.attrib['src']
136             m = re.match(r'''(?xi)
137                 (?P<ext>[a-z0-9]+):
138                 (?P<path>
139                     [/a-z0-9]+     # The directory and main part of the URL
140                     _(?P<cbr>[0-9]+)k
141                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
142                     _(?P<vcodec>[a-z0-9]+)
143                     _(?P<vbr>[0-9]+)
144                     _(?P<acodec>[a-z0-9]+)
145                     _(?P<abr>[0-9]+)
146                     \.[a-z0-9]+  # File extension
147                 )''', src)
148             if not m:
149                 continue
150
151             format_url = self._SMIL_BASE_URL + m.group('path')
152             formats.append({
153                 'url': format_url,
154                 'format_id': 'SMIL_' + m.group('cbr'),
155                 'vcodec': m.group('vcodec'),
156                 'acodec': m.group('acodec'),
157                 'vbr': int(m.group('vbr')),
158                 'abr': int(m.group('abr')),
159                 'ext': m.group('ext'),
160                 'width': int(m.group('width')),
161                 'height': int(m.group('height')),
162             })
163         return formats
164
165     def _download_api_formats(self, video_id):
166         if not self._oauth_token:
167             self._downloader.report_warning(
168                 'No oauth token available, skipping API HLS download')
169             return []
170
171         api_url = 'https://apiv2.vevo.com/video/%s/streams/hls?token=%s' % (
172             video_id, self._oauth_token)
173         api_data = self._download_json(
174             api_url, video_id,
175             note='Downloading HLS formats',
176             errnote='Failed to download HLS format list', fatal=False)
177         if api_data is None:
178             return []
179
180         m3u8_url = api_data[0]['url']
181         return self._extract_m3u8_formats(
182             m3u8_url, video_id, entry_protocol='m3u8_native', ext='mp4',
183             preference=0)
184
185     def _real_extract(self, url):
186         video_id = self._match_id(url)
187
188         webpage = None
189
190         json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
191         response = self._download_json(json_url, video_id)
192         video_info = response['video'] or {}
193
194         if not video_info and response.get('statusCode') != 909:
195             if 'statusMessage' in response:
196                 raise ExtractorError('%s said: %s' % (self.IE_NAME, response['statusMessage']), expected=True)
197             raise ExtractorError('Unable to extract videos')
198
199         if not video_info:
200             if url.startswith('vevo:'):
201                 raise ExtractorError('Please specify full Vevo URL for downloading', expected=True)
202             webpage = self._download_webpage(url, video_id)
203
204         title = video_info.get('title') or self._og_search_title(webpage)
205
206         formats = self._formats_from_json(video_info)
207
208         is_explicit = video_info.get('isExplicit')
209         if is_explicit is True:
210             age_limit = 18
211         elif is_explicit is False:
212             age_limit = 0
213         else:
214             age_limit = None
215
216         # Download via HLS API
217         formats.extend(self._download_api_formats(video_id))
218
219         # Download SMIL
220         smil_blocks = sorted((
221             f for f in video_info.get('videoVersions', [])
222             if f['sourceType'] == 13),
223             key=lambda f: f['version'])
224         smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
225             self._SMIL_BASE_URL, video_id, video_id.lower())
226         if smil_blocks:
227             smil_url_m = self._search_regex(
228                 r'url="([^"]+)"', smil_blocks[-1]['data'], 'SMIL URL',
229                 default=None)
230             if smil_url_m is not None:
231                 smil_url = smil_url_m
232         if smil_url:
233             smil_xml = self._download_webpage(
234                 smil_url, video_id, 'Downloading SMIL info', fatal=False)
235             if smil_xml:
236                 formats.extend(self._formats_from_smil(smil_xml))
237
238         self._sort_formats(formats)
239         timestamp = int_or_none(self._search_regex(
240             r'/Date\((\d+)\)/',
241             video_info['launchDate'], 'launch date', fatal=False),
242             scale=1000) if video_info else None
243
244         duration = video_info.get('duration') or int_or_none(
245             self._html_search_meta('video:duration', webpage))
246
247         return {
248             'id': video_id,
249             'title': title,
250             'formats': formats,
251             'thumbnail': video_info.get('imageUrl'),
252             'timestamp': timestamp,
253             'uploader': video_info['mainArtists'][0]['artistName'] if video_info else None,
254             'duration': duration,
255             'age_limit': age_limit,
256         }