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