]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/vevo.py
[facebook:post] Add extractor (Closes #8321)
[yt-dlp.git] / youtube_dl / extractor / vevo.py
CommitLineData
45d7bc2f
JMF
1from __future__ import unicode_literals
2
70d1924f 3import re
70d1924f
JMF
4
5from .common import InfoExtractor
ad30dc1e
YCH
6from ..compat import (
7 compat_etree_fromstring,
8 compat_urlparse,
9)
1cc79574 10from ..utils import (
70d1924f 11 ExtractorError,
7d3d06a1 12 int_or_none,
5c2266df 13 sanitized_Request,
70d1924f
JMF
14)
15
88bd97e3 16
70d1924f 17class VevoIE(InfoExtractor):
1c251cd9 18 """
0577177e 19 Accepts urls from vevo.com or in the format 'vevo:{id}'
3266f0c6 20 (currently used by MTVIE and MySpaceIE)
1c251cd9 21 """
f25571ff 22 _VALID_URL = r'''(?x)
91683085 23 (?:https?://www\.vevo\.com/watch/(?:[^/]+/(?:[^/]+/)?)?|
f25571ff 24 https?://cache\.vevo\.com/m/html/embed\.html\?video=|
ebce53b3 25 https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
f25571ff
PH
26 vevo:)
27 (?P<id>[^&?#]+)'''
fd5e6f7e 28
72321ead 29 _TESTS = [{
45d7bc2f 30 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
b686fc18 31 "md5": "95ee28ee45e70130e3ab02b0f579ae23",
45d7bc2f 32 'info_dict': {
27579b9e
PH
33 'id': 'GB1101300280',
34 'ext': 'mp4',
45d7bc2f
JMF
35 "upload_date": "20130624",
36 "uploader": "Hurts",
37 "title": "Somebody to Die For",
38 "duration": 230.12,
39 "width": 1920,
40 "height": 1080,
fd5e6f7e
PH
41 # timestamp and upload_date are often incorrect; seem to change randomly
42 'timestamp': int,
6f5ac90c 43 }
27579b9e
PH
44 }, {
45 'note': 'v3 SMIL format',
46 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
b686fc18 47 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
27579b9e
PH
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,
6cadf8c8 55 'age_limit': 0,
fd5e6f7e 56 'timestamp': int,
6cadf8c8
PH
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',
aba77bbf
PH
67 'upload_date': 're:2013070[34]',
68 'timestamp': int,
6cadf8c8
PH
69 },
70 'params': {
71 'skip_download': 'true',
27579b9e 72 }
ff51983e
YCH
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 },
b6afc225 83 'expected_warnings': ['Unable to download SMIL file'],
72321ead
PH
84 }]
85 _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
70d1924f 86
f0b5d6af 87 def _real_initialize(self):
5c2266df 88 req = sanitized_Request(
f0b5d6af
PH
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:
4bf99ade
YCH
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
f0b5d6af
PH
101 self._oauth_token = self._search_regex(
102 r'access_token":\s*"([^"]+)"',
103 webpage, 'access token', fatal=False)
104
72321ead 105 def _formats_from_json(self, video_info):
ff51983e
YCH
106 if not video_info:
107 return []
108
88bd97e3
JMF
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:
45d7bc2f 116 raise ExtractorError('Unable to extract last version of the video')
88bd97e3 117
36e6f62c 118 renditions = compat_etree_fromstring(last_version['data'])
88bd97e3
JMF
119 formats = []
120 # Already sorted from worst to best quality
121 for rend in renditions.findall('rendition'):
122 attr = rend.attrib
72321ead 123 format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
88bd97e3 124 formats.append({
e54fd4b2
PH
125 'url': attr['url'],
126 'format_id': attr['name'],
127 'format_note': format_note,
88bd97e3
JMF
128 'height': int(attr['frameheight']),
129 'width': int(attr['frameWidth']),
130 })
72321ead
PH
131 return formats
132
b6afc225 133 def _formats_from_smil(self, smil_doc):
72321ead 134 formats = []
72321ead
PH
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')
72321ead
PH
154 formats.append({
155 'url': format_url,
45d7bc2f 156 'format_id': 'SMIL_' + m.group('cbr'),
91c7271a
PH
157 'vcodec': m.group('vcodec'),
158 'acodec': m.group('acodec'),
159 'vbr': int(m.group('vbr')),
160 'abr': int(m.group('abr')),
72321ead
PH
161 'ext': m.group('ext'),
162 'width': int(m.group('width')),
163 'height': int(m.group('height')),
164 })
165 return formats
166
ad30dc1e 167 def _download_api_formats(self, video_id, video_url):
f0b5d6af
PH
168 if not self._oauth_token:
169 self._downloader.report_warning(
170 'No oauth token available, skipping API HLS download')
171 return []
172
ad30dc1e
YCH
173 api_url = compat_urlparse.urljoin(video_url, '//apiv2.vevo.com/video/%s/streams/hls?token=%s' % (
174 video_id, self._oauth_token))
f0b5d6af
PH
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
72321ead 187 def _real_extract(self, url):
4b942883 188 video_id = self._match_id(url)
72321ead 189
ff51983e
YCH
190 webpage = None
191
72321ead 192 json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
e97e53ee 193 response = self._download_json(json_url, video_id)
ff51983e 194 video_info = response['video'] or {}
e97e53ee 195
ff51983e 196 if not video_info and response.get('statusCode') != 909:
e97e53ee
S
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')
72321ead 200
ff51983e
YCH
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
72321ead 208 formats = self._formats_from_json(video_info)
27579b9e 209
6cadf8c8
PH
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
f0b5d6af 218 # Download via HLS API
ad30dc1e 219 formats.extend(self._download_api_formats(video_id, url))
f0b5d6af 220
7d3d06a1
PH
221 # Download SMIL
222 smil_blocks = sorted((
ff51983e 223 f for f in video_info.get('videoVersions', [])
7d3d06a1
PH
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:
b6afc225
YCH
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))
7d3d06a1 238
bff74bdd 239 self._sort_formats(formats)
ff51983e 240 timestamp = int_or_none(self._search_regex(
7d3d06a1 241 r'/Date\((\d+)\)/',
ff51983e
YCH
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))
9d2ecdbc 247
45d7bc2f 248 return {
88bd97e3 249 'id': video_id,
ff51983e 250 'title': title,
88bd97e3 251 'formats': formats,
ff51983e
YCH
252 'thumbnail': video_info.get('imageUrl'),
253 'timestamp': timestamp,
254 'uploader': video_info['mainArtists'][0]['artistName'] if video_info else None,
255 'duration': duration,
6cadf8c8 256 'age_limit': age_limit,
88bd97e3 257 }