]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/vevo.py
[xfileshare] Refactor _VALID_URL and remove ded sites
[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_str,
9     compat_urlparse,
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, item):
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)['default'][item]
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'],
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'],
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'],
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 - 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': 'Rap/Hip-Hop',
102         },
103     }, {
104         'note': 'Only available via webpage',
105         'url': 'http://www.vevo.com/watch/GBUV71600656',
106         'md5': '67e79210613865b66a47c33baa5e37fe',
107         'info_dict': {
108             'id': 'GBUV71600656',
109             'ext': 'mp4',
110             'title': 'ABC - Viva Love',
111             'age_limit': 0,
112             'timestamp': 1461830400,
113             'upload_date': '20160428',
114             'uploader': 'ABC',
115             'track': 'Viva Love',
116             'artist': 'ABC',
117             'genre': 'Pop',
118         },
119         'expected_warnings': ['Failed to download video versions info'],
120     }, {
121         # no genres available
122         'url': 'http://www.vevo.com/watch/INS171400764',
123         'only_matching': True,
124     }]
125     _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com'
126     _SOURCE_TYPES = {
127         0: 'youtube',
128         1: 'brightcove',
129         2: 'http',
130         3: 'hls_ios',
131         4: 'hls',
132         5: 'smil',  # http
133         7: 'f4m_cc',
134         8: 'f4m_ak',
135         9: 'f4m_l3',
136         10: 'ism',
137         13: 'smil',  # rtmp
138         18: 'dash',
139     }
140     _VERSIONS = {
141         0: 'youtube',  # only in AuthenticateVideo videoVersions
142         1: 'level3',
143         2: 'akamai',
144         3: 'level3',
145         4: 'amazon',
146     }
147
148     def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
149         formats = []
150         els = smil.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
151         for el in els:
152             src = el.attrib['src']
153             m = re.match(r'''(?xi)
154                 (?P<ext>[a-z0-9]+):
155                 (?P<path>
156                     [/a-z0-9]+     # The directory and main part of the URL
157                     _(?P<tbr>[0-9]+)k
158                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
159                     _(?P<vcodec>[a-z0-9]+)
160                     _(?P<vbr>[0-9]+)
161                     _(?P<acodec>[a-z0-9]+)
162                     _(?P<abr>[0-9]+)
163                     \.[a-z0-9]+  # File extension
164                 )''', src)
165             if not m:
166                 continue
167
168             format_url = self._SMIL_BASE_URL + m.group('path')
169             formats.append({
170                 'url': format_url,
171                 'format_id': 'smil_' + m.group('tbr'),
172                 'vcodec': m.group('vcodec'),
173                 'acodec': m.group('acodec'),
174                 'tbr': int(m.group('tbr')),
175                 'vbr': int(m.group('vbr')),
176                 'abr': int(m.group('abr')),
177                 'ext': m.group('ext'),
178                 'width': int(m.group('width')),
179                 'height': int(m.group('height')),
180             })
181         return formats
182
183     def _initialize_api(self, video_id):
184         req = sanitized_Request(
185             'http://www.vevo.com/auth', data=b'')
186         webpage = self._download_webpage(
187             req, None,
188             note='Retrieving oauth token',
189             errnote='Unable to retrieve oauth token')
190
191         if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in webpage:
192             raise ExtractorError(
193                 '%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
194
195         auth_info = self._parse_json(webpage, video_id)
196         self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['access_token']
197
198     def _call_api(self, path, *args, **kwargs):
199         return self._download_json(self._api_url_template % path, *args, **kwargs)
200
201     def _real_extract(self, url):
202         video_id = self._match_id(url)
203
204         json_url = 'http://api.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
205         response = self._download_json(
206             json_url, video_id, 'Downloading video info', 'Unable to download info')
207         video_info = response.get('video') or {}
208         artist = None
209         featured_artist = None
210         uploader = None
211         view_count = None
212         formats = []
213
214         if not video_info:
215             if response.get('statusCode') != 909:
216                 ytid = response.get('errorInfo', {}).get('ytid')
217                 if ytid:
218                     self.report_warning(
219                         'Video is geoblocked, trying with the YouTube video %s' % ytid)
220                     return self.url_result(ytid, 'Youtube', ytid)
221
222                 if 'statusMessage' in response:
223                     raise ExtractorError('%s said: %s' % (
224                         self.IE_NAME, response['statusMessage']), expected=True)
225                 raise ExtractorError('Unable to extract videos')
226
227             self._initialize_api(video_id)
228             video_info = self._call_api(
229                 'video/%s' % video_id, video_id, 'Downloading api video info',
230                 'Failed to download video info')
231
232             video_versions = self._call_api(
233                 'video/%s/streams' % video_id, video_id,
234                 'Downloading video versions info',
235                 'Failed to download video versions info',
236                 fatal=False)
237
238             # Some videos are only available via webpage (e.g.
239             # https://github.com/rg3/youtube-dl/issues/9366)
240             if not video_versions:
241                 webpage = self._download_webpage(url, video_id)
242                 video_versions = self._extract_json(webpage, video_id, 'streams')[video_id][0]
243
244             timestamp = parse_iso8601(video_info.get('releaseDate'))
245             artists = video_info.get('artists')
246             if artists:
247                 artist = uploader = artists[0]['name']
248             view_count = int_or_none(video_info.get('views', {}).get('total'))
249
250             for video_version in video_versions:
251                 version = self._VERSIONS.get(video_version['version'])
252                 version_url = video_version.get('url')
253                 if not version_url:
254                     continue
255
256                 if '.ism' in version_url:
257                     continue
258                 elif '.mpd' in version_url:
259                     formats.extend(self._extract_mpd_formats(
260                         version_url, video_id, mpd_id='dash-%s' % version,
261                         note='Downloading %s MPD information' % version,
262                         errnote='Failed to download %s MPD information' % version,
263                         fatal=False))
264                 elif '.m3u8' in version_url:
265                     formats.extend(self._extract_m3u8_formats(
266                         version_url, video_id, 'mp4', 'm3u8_native',
267                         m3u8_id='hls-%s' % version,
268                         note='Downloading %s m3u8 information' % version,
269                         errnote='Failed to download %s m3u8 information' % version,
270                         fatal=False))
271                 else:
272                     m = re.search(r'''(?xi)
273                         _(?P<width>[0-9]+)x(?P<height>[0-9]+)
274                         _(?P<vcodec>[a-z0-9]+)
275                         _(?P<vbr>[0-9]+)
276                         _(?P<acodec>[a-z0-9]+)
277                         _(?P<abr>[0-9]+)
278                         \.(?P<ext>[a-z0-9]+)''', version_url)
279                     if not m:
280                         continue
281
282                     formats.append({
283                         'url': version_url,
284                         'format_id': 'http-%s-%s' % (version, video_version['quality']),
285                         'vcodec': m.group('vcodec'),
286                         'acodec': m.group('acodec'),
287                         'vbr': int(m.group('vbr')),
288                         'abr': int(m.group('abr')),
289                         'ext': m.group('ext'),
290                         'width': int(m.group('width')),
291                         'height': int(m.group('height')),
292                     })
293         else:
294             timestamp = int_or_none(self._search_regex(
295                 r'/Date\((\d+)\)/',
296                 video_info['releaseDate'], 'release date', fatal=False),
297                 scale=1000)
298             artists = video_info.get('mainArtists')
299             if artists:
300                 artist = uploader = artists[0]['artistName']
301
302             featured_artists = video_info.get('featuredArtists')
303             if featured_artists:
304                 featured_artist = featured_artists[0]['artistName']
305
306             smil_parsed = False
307             for video_version in video_info['videoVersions']:
308                 version = self._VERSIONS.get(video_version['version'])
309                 if version == 'youtube':
310                     continue
311                 else:
312                     source_type = self._SOURCE_TYPES.get(video_version['sourceType'])
313                     renditions = compat_etree_fromstring(video_version['data'])
314                     if source_type == 'http':
315                         for rend in renditions.findall('rendition'):
316                             attr = rend.attrib
317                             formats.append({
318                                 'url': attr['url'],
319                                 'format_id': 'http-%s-%s' % (version, attr['name']),
320                                 'height': int_or_none(attr.get('frameheight')),
321                                 'width': int_or_none(attr.get('frameWidth')),
322                                 'tbr': int_or_none(attr.get('totalBitrate')),
323                                 'vbr': int_or_none(attr.get('videoBitrate')),
324                                 'abr': int_or_none(attr.get('audioBitrate')),
325                                 'vcodec': attr.get('videoCodec'),
326                                 'acodec': attr.get('audioCodec'),
327                             })
328                     elif source_type == 'hls':
329                         formats.extend(self._extract_m3u8_formats(
330                             renditions.find('rendition').attrib['url'], video_id,
331                             'mp4', 'm3u8_native', m3u8_id='hls-%s' % version,
332                             note='Downloading %s m3u8 information' % version,
333                             errnote='Failed to download %s m3u8 information' % version,
334                             fatal=False))
335                     elif source_type == 'smil' and version == 'level3' and not smil_parsed:
336                         formats.extend(self._extract_smil_formats(
337                             renditions.find('rendition').attrib['url'], video_id, False))
338                         smil_parsed = True
339         self._sort_formats(formats)
340
341         track = video_info['title']
342         if featured_artist:
343             artist = '%s ft. %s' % (artist, featured_artist)
344         title = '%s - %s' % (artist, track) if artist else track
345
346         genres = video_info.get('genres')
347         genre = (
348             genres[0] if genres and isinstance(genres, list) and
349             isinstance(genres[0], compat_str) else None)
350
351         is_explicit = video_info.get('isExplicit')
352         if is_explicit is True:
353             age_limit = 18
354         elif is_explicit is False:
355             age_limit = 0
356         else:
357             age_limit = None
358
359         duration = video_info.get('duration')
360
361         return {
362             'id': video_id,
363             'title': title,
364             'formats': formats,
365             'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
366             'timestamp': timestamp,
367             'uploader': uploader,
368             'duration': duration,
369             'view_count': view_count,
370             'age_limit': age_limit,
371             'track': track,
372             'artist': uploader,
373             'genre': genre,
374         }
375
376
377 class VevoPlaylistIE(VevoBaseIE):
378     _VALID_URL = r'https?://www\.vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
379
380     _TESTS = [{
381         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
382         'info_dict': {
383             'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
384             'title': 'Best-Of: Birdman',
385         },
386         'playlist_count': 10,
387     }, {
388         'url': 'http://www.vevo.com/watch/genre/rock',
389         'info_dict': {
390             'id': 'rock',
391             'title': 'Rock',
392         },
393         'playlist_count': 20,
394     }, {
395         'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
396         'md5': '32dcdfddddf9ec6917fc88ca26d36282',
397         'info_dict': {
398             'id': 'USCMV1100073',
399             'ext': 'mp4',
400             'title': 'Birdman - Y.U. MAD',
401             'timestamp': 1323417600,
402             'upload_date': '20111209',
403             'uploader': 'Birdman',
404             'track': 'Y.U. MAD',
405             'artist': 'Birdman',
406             'genre': 'Rap/Hip-Hop',
407         },
408         'expected_warnings': ['Unable to download SMIL file'],
409     }, {
410         'url': 'http://www.vevo.com/watch/genre/rock?index=0',
411         'only_matching': True,
412     }]
413
414     def _real_extract(self, url):
415         mobj = re.match(self._VALID_URL, url)
416         playlist_id = mobj.group('id')
417         playlist_kind = mobj.group('kind')
418
419         webpage = self._download_webpage(url, playlist_id)
420
421         qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
422         index = qs.get('index', [None])[0]
423
424         if index:
425             video_id = self._search_regex(
426                 r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
427                 webpage, 'video id', default=None, group='id')
428             if video_id:
429                 return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
430
431         playlists = self._extract_json(webpage, playlist_id, '%ss' % playlist_kind)
432
433         playlist = (list(playlists.values())[0]
434                     if playlist_kind == 'playlist' else playlists[playlist_id])
435
436         entries = [
437             self.url_result('vevo:%s' % src, VevoIE.ie_key())
438             for src in playlist['isrcs']]
439
440         return self.playlist_result(
441             entries, playlist.get('playlistId') or playlist_id,
442             playlist.get('name'), playlist.get('description'))