]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/vevo.py
Prepare to release.
[youtubedl] / 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_str,
8 compat_urlparse,
9 compat_HTTPError,
10 )
11 from ..utils import (
12 ExtractorError,
13 int_or_none,
14 sanitized_Request,
15 parse_iso8601,
16 )
17
18
19 class VevoBaseIE(InfoExtractor):
20 def _extract_json(self, webpage, video_id):
21 return self._parse_json(
22 self._search_regex(
23 r'window\.__INITIAL_STORE__\s*=\s*({.+?});\s*</script>',
24 webpage, 'initial store'),
25 video_id)
26
27
28 class VevoIE(VevoBaseIE):
29 '''
30 Accepts urls from vevo.com or in the format 'vevo:{id}'
31 (currently used by MTVIE and MySpaceIE)
32 '''
33 _VALID_URL = r'''(?x)
34 (?:https?://(?:www\.)?vevo\.com/watch/(?!playlist|genre)(?:[^/]+/(?:[^/]+/)?)?|
35 https?://cache\.vevo\.com/m/html/embed\.html\?video=|
36 https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
37 vevo:)
38 (?P<id>[^&?#]+)'''
39
40 _TESTS = [{
41 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
42 'md5': '95ee28ee45e70130e3ab02b0f579ae23',
43 'info_dict': {
44 'id': 'GB1101300280',
45 'ext': 'mp4',
46 'title': 'Hurts - Somebody to Die For',
47 'timestamp': 1372057200,
48 'upload_date': '20130624',
49 'uploader': 'Hurts',
50 'track': 'Somebody to Die For',
51 'artist': 'Hurts',
52 'genre': 'Pop',
53 },
54 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
55 }, {
56 'note': 'v3 SMIL format',
57 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
58 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
59 'info_dict': {
60 'id': 'USUV71302923',
61 'ext': 'mp4',
62 'title': 'Cassadee Pope - I Wish I Could Break Your Heart',
63 'timestamp': 1392796919,
64 'upload_date': '20140219',
65 'uploader': 'Cassadee Pope',
66 'track': 'I Wish I Could Break Your Heart',
67 'artist': 'Cassadee Pope',
68 'genre': 'Country',
69 },
70 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
71 }, {
72 'note': 'Age-limited video',
73 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
74 'info_dict': {
75 'id': 'USRV81300282',
76 'ext': 'mp4',
77 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
78 'age_limit': 18,
79 'timestamp': 1372888800,
80 'upload_date': '20130703',
81 'uploader': 'Justin Timberlake',
82 'track': 'Tunnel Vision (Explicit)',
83 'artist': 'Justin Timberlake',
84 'genre': 'Pop',
85 },
86 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
87 }, {
88 'note': 'No video_info',
89 'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
90 'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
91 'info_dict': {
92 'id': 'USUV71503000',
93 'ext': 'mp4',
94 'title': 'K Camp ft. T.I. - Till I Die',
95 'age_limit': 18,
96 'timestamp': 1449468000,
97 'upload_date': '20151207',
98 'uploader': 'K Camp',
99 'track': 'Till I Die',
100 'artist': 'K Camp',
101 'genre': 'Hip-Hop',
102 },
103 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
104 }, {
105 'note': 'Featured test',
106 'url': 'https://www.vevo.com/watch/lemaitre/Wait/USUV71402190',
107 'md5': 'd28675e5e8805035d949dc5cf161071d',
108 'info_dict': {
109 'id': 'USUV71402190',
110 'ext': 'mp4',
111 'title': 'Lemaitre ft. LoLo - Wait',
112 'age_limit': 0,
113 'timestamp': 1413432000,
114 'upload_date': '20141016',
115 'uploader': 'Lemaitre',
116 'track': 'Wait',
117 'artist': 'Lemaitre',
118 'genre': 'Electronic',
119 },
120 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
121 }, {
122 'note': 'Only available via webpage',
123 'url': 'http://www.vevo.com/watch/GBUV71600656',
124 'md5': '67e79210613865b66a47c33baa5e37fe',
125 'info_dict': {
126 'id': 'GBUV71600656',
127 'ext': 'mp4',
128 'title': 'ABC - Viva Love',
129 'age_limit': 0,
130 'timestamp': 1461830400,
131 'upload_date': '20160428',
132 'uploader': 'ABC',
133 'track': 'Viva Love',
134 'artist': 'ABC',
135 'genre': 'Pop',
136 },
137 'expected_warnings': ['Failed to download video versions info'],
138 }, {
139 # no genres available
140 'url': 'http://www.vevo.com/watch/INS171400764',
141 'only_matching': True,
142 }, {
143 # Another case available only via the webpage; using streams/streamsV3 formats
144 # Geo-restricted to Netherlands/Germany
145 'url': 'http://www.vevo.com/watch/boostee/pop-corn-clip-officiel/FR1A91600909',
146 'only_matching': True,
147 }]
148 _VERSIONS = {
149 0: 'youtube', # only in AuthenticateVideo videoVersions
150 1: 'level3',
151 2: 'akamai',
152 3: 'level3',
153 4: 'amazon',
154 }
155
156 def _initialize_api(self, video_id):
157 req = sanitized_Request(
158 'http://www.vevo.com/auth', data=b'')
159 webpage = self._download_webpage(
160 req, None,
161 note='Retrieving oauth token',
162 errnote='Unable to retrieve oauth token')
163
164 if re.search(r'(?i)THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION', webpage):
165 self.raise_geo_restricted(
166 '%s said: This page is currently unavailable in your region' % self.IE_NAME)
167
168 auth_info = self._parse_json(webpage, video_id)
169 self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['access_token']
170
171 def _call_api(self, path, *args, **kwargs):
172 try:
173 data = self._download_json(self._api_url_template % path, *args, **kwargs)
174 except ExtractorError as e:
175 if isinstance(e.cause, compat_HTTPError):
176 errors = self._parse_json(e.cause.read().decode(), None)['errors']
177 error_message = ', '.join([error['message'] for error in errors])
178 raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
179 raise
180 return data
181
182 def _real_extract(self, url):
183 video_id = self._match_id(url)
184
185 self._initialize_api(video_id)
186
187 video_info = self._call_api(
188 'video/%s' % video_id, video_id, 'Downloading api video info',
189 'Failed to download video info')
190
191 video_versions = self._call_api(
192 'video/%s/streams' % video_id, video_id,
193 'Downloading video versions info',
194 'Failed to download video versions info',
195 fatal=False)
196
197 # Some videos are only available via webpage (e.g.
198 # https://github.com/rg3/youtube-dl/issues/9366)
199 if not video_versions:
200 webpage = self._download_webpage(url, video_id)
201 json_data = self._extract_json(webpage, video_id)
202 if 'streams' in json_data.get('default', {}):
203 video_versions = json_data['default']['streams'][video_id][0]
204 else:
205 video_versions = [
206 value
207 for key, value in json_data['apollo']['data'].items()
208 if key.startswith('%s.streams' % video_id)]
209
210 uploader = None
211 artist = None
212 featured_artist = None
213 artists = video_info.get('artists')
214 for curr_artist in artists:
215 if curr_artist.get('role') == 'Featured':
216 featured_artist = curr_artist['name']
217 else:
218 artist = uploader = curr_artist['name']
219
220 formats = []
221 for video_version in video_versions:
222 version = self._VERSIONS.get(video_version.get('version'), 'generic')
223 version_url = video_version.get('url')
224 if not version_url:
225 continue
226
227 if '.ism' in version_url:
228 continue
229 elif '.mpd' in version_url:
230 formats.extend(self._extract_mpd_formats(
231 version_url, video_id, mpd_id='dash-%s' % version,
232 note='Downloading %s MPD information' % version,
233 errnote='Failed to download %s MPD information' % version,
234 fatal=False))
235 elif '.m3u8' in version_url:
236 formats.extend(self._extract_m3u8_formats(
237 version_url, video_id, 'mp4', 'm3u8_native',
238 m3u8_id='hls-%s' % version,
239 note='Downloading %s m3u8 information' % version,
240 errnote='Failed to download %s m3u8 information' % version,
241 fatal=False))
242 else:
243 m = re.search(r'''(?xi)
244 _(?P<width>[0-9]+)x(?P<height>[0-9]+)
245 _(?P<vcodec>[a-z0-9]+)
246 _(?P<vbr>[0-9]+)
247 _(?P<acodec>[a-z0-9]+)
248 _(?P<abr>[0-9]+)
249 \.(?P<ext>[a-z0-9]+)''', version_url)
250 if not m:
251 continue
252
253 formats.append({
254 'url': version_url,
255 'format_id': 'http-%s-%s' % (version, video_version['quality']),
256 'vcodec': m.group('vcodec'),
257 'acodec': m.group('acodec'),
258 'vbr': int(m.group('vbr')),
259 'abr': int(m.group('abr')),
260 'ext': m.group('ext'),
261 'width': int(m.group('width')),
262 'height': int(m.group('height')),
263 })
264 self._sort_formats(formats)
265
266 track = video_info['title']
267 if featured_artist:
268 artist = '%s ft. %s' % (artist, featured_artist)
269 title = '%s - %s' % (artist, track) if artist else track
270
271 genres = video_info.get('genres')
272 genre = (
273 genres[0] if genres and isinstance(genres, list) and
274 isinstance(genres[0], compat_str) else None)
275
276 is_explicit = video_info.get('isExplicit')
277 if is_explicit is True:
278 age_limit = 18
279 elif is_explicit is False:
280 age_limit = 0
281 else:
282 age_limit = None
283
284 return {
285 'id': video_id,
286 'title': title,
287 'formats': formats,
288 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
289 'timestamp': parse_iso8601(video_info.get('releaseDate')),
290 'uploader': uploader,
291 'duration': int_or_none(video_info.get('duration')),
292 'view_count': int_or_none(video_info.get('views', {}).get('total')),
293 'age_limit': age_limit,
294 'track': track,
295 'artist': uploader,
296 'genre': genre,
297 }
298
299
300 class VevoPlaylistIE(VevoBaseIE):
301 _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
302
303 _TESTS = [{
304 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
305 'info_dict': {
306 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
307 'title': 'Best-Of: Birdman',
308 },
309 'playlist_count': 10,
310 }, {
311 'url': 'http://www.vevo.com/watch/genre/rock',
312 'info_dict': {
313 'id': 'rock',
314 'title': 'Rock',
315 },
316 'playlist_count': 20,
317 }, {
318 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
319 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
320 'info_dict': {
321 'id': 'USCMV1100073',
322 'ext': 'mp4',
323 'title': 'Birdman - Y.U. MAD',
324 'timestamp': 1323417600,
325 'upload_date': '20111209',
326 'uploader': 'Birdman',
327 'track': 'Y.U. MAD',
328 'artist': 'Birdman',
329 'genre': 'Rap/Hip-Hop',
330 },
331 'expected_warnings': ['Unable to download SMIL file'],
332 }, {
333 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
334 'only_matching': True,
335 }]
336
337 def _real_extract(self, url):
338 mobj = re.match(self._VALID_URL, url)
339 playlist_id = mobj.group('id')
340 playlist_kind = mobj.group('kind')
341
342 webpage = self._download_webpage(url, playlist_id)
343
344 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
345 index = qs.get('index', [None])[0]
346
347 if index:
348 video_id = self._search_regex(
349 r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
350 webpage, 'video id', default=None, group='id')
351 if video_id:
352 return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
353
354 playlists = self._extract_json(webpage, playlist_id)['default']['%ss' % playlist_kind]
355
356 playlist = (list(playlists.values())[0]
357 if playlist_kind == 'playlist' else playlists[playlist_id])
358
359 entries = [
360 self.url_result('vevo:%s' % src, VevoIE.ie_key())
361 for src in playlist['isrcs']]
362
363 return self.playlist_result(
364 entries, playlist.get('playlistId') or playlist_id,
365 playlist.get('name'), playlist.get('description'))