]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/vevo.py
Merge branch 'googledrive' of github.com:remitamine/youtube-dl into remitamine-google...
[yt-dlp.git] / 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': ['Unable to download SMIL file'],
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_doc):
134 formats = []
135 els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
136 for el in els:
137 src = el.attrib['src']
138 m = re.match(r'''(?xi)
139 (?P<ext>[a-z0-9]+):
140 (?P<path>
141 [/a-z0-9]+ # The directory and main part of the URL
142 _(?P<cbr>[0-9]+)k
143 _(?P<width>[0-9]+)x(?P<height>[0-9]+)
144 _(?P<vcodec>[a-z0-9]+)
145 _(?P<vbr>[0-9]+)
146 _(?P<acodec>[a-z0-9]+)
147 _(?P<abr>[0-9]+)
148 \.[a-z0-9]+ # File extension
149 )''', src)
150 if not m:
151 continue
152
153 format_url = self._SMIL_BASE_URL + m.group('path')
154 formats.append({
155 'url': format_url,
156 'format_id': 'SMIL_' + m.group('cbr'),
157 'vcodec': m.group('vcodec'),
158 'acodec': m.group('acodec'),
159 'vbr': int(m.group('vbr')),
160 'abr': int(m.group('abr')),
161 'ext': m.group('ext'),
162 'width': int(m.group('width')),
163 'height': int(m.group('height')),
164 })
165 return formats
166
167 def _download_api_formats(self, video_id, video_url):
168 if not self._oauth_token:
169 self._downloader.report_warning(
170 'No oauth token available, skipping API HLS download')
171 return []
172
173 api_url = compat_urlparse.urljoin(video_url, '//apiv2.vevo.com/video/%s/streams/hls?token=%s' % (
174 video_id, self._oauth_token))
175 api_data = self._download_json(
176 api_url, video_id,
177 note='Downloading HLS formats',
178 errnote='Failed to download HLS format list', fatal=False)
179 if api_data is None:
180 return []
181
182 m3u8_url = api_data[0]['url']
183 return self._extract_m3u8_formats(
184 m3u8_url, video_id, entry_protocol='m3u8_native', ext='mp4',
185 preference=0)
186
187 def _real_extract(self, url):
188 video_id = self._match_id(url)
189
190 webpage = None
191
192 json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
193 response = self._download_json(json_url, video_id)
194 video_info = response['video'] or {}
195
196 if not video_info and response.get('statusCode') != 909:
197 if 'statusMessage' in response:
198 raise ExtractorError('%s said: %s' % (self.IE_NAME, response['statusMessage']), expected=True)
199 raise ExtractorError('Unable to extract videos')
200
201 if not video_info:
202 if url.startswith('vevo:'):
203 raise ExtractorError('Please specify full Vevo URL for downloading', expected=True)
204 webpage = self._download_webpage(url, video_id)
205
206 title = video_info.get('title') or self._og_search_title(webpage)
207
208 formats = self._formats_from_json(video_info)
209
210 is_explicit = video_info.get('isExplicit')
211 if is_explicit is True:
212 age_limit = 18
213 elif is_explicit is False:
214 age_limit = 0
215 else:
216 age_limit = None
217
218 # Download via HLS API
219 formats.extend(self._download_api_formats(video_id, url))
220
221 # Download SMIL
222 smil_blocks = sorted((
223 f for f in video_info.get('videoVersions', [])
224 if f['sourceType'] == 13),
225 key=lambda f: f['version'])
226 smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
227 self._SMIL_BASE_URL, video_id, video_id.lower())
228 if smil_blocks:
229 smil_url_m = self._search_regex(
230 r'url="([^"]+)"', smil_blocks[-1]['data'], 'SMIL URL',
231 default=None)
232 if smil_url_m is not None:
233 smil_url = smil_url_m
234 if smil_url:
235 smil_doc = self._download_smil(smil_url, video_id, fatal=False)
236 if smil_doc:
237 formats.extend(self._formats_from_smil(smil_doc))
238
239 self._sort_formats(formats)
240 timestamp = int_or_none(self._search_regex(
241 r'/Date\((\d+)\)/',
242 video_info['launchDate'], 'launch date', fatal=False),
243 scale=1000) if video_info else None
244
245 duration = video_info.get('duration') or int_or_none(
246 self._html_search_meta('video:duration', webpage))
247
248 return {
249 'id': video_id,
250 'title': title,
251 'formats': formats,
252 'thumbnail': video_info.get('imageUrl'),
253 'timestamp': timestamp,
254 'uploader': video_info['mainArtists'][0]['artistName'] if video_info else None,
255 'duration': duration,
256 'age_limit': age_limit,
257 }