]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/vevo.py
[iprima] Skip test
[youtube-dl] / youtube_dl / extractor / vevo.py
1 from __future__ import unicode_literals
2
3 import re
4 import xml.etree.ElementTree
5
6 from .common import InfoExtractor
7 from ..utils import (
8     compat_HTTPError,
9     ExtractorError,
10 )
11
12
13 class VevoIE(InfoExtractor):
14     """
15     Accepts urls from vevo.com or in the format 'vevo:{id}'
16     (currently used by MTVIE)
17     """
18     _VALID_URL = r'''(?x)
19         (?:https?://www\.vevo\.com/watch/(?:[^/]+/[^/]+/)?|
20            https?://cache\.vevo\.com/m/html/embed\.html\?video=|
21            https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
22            vevo:)
23         (?P<id>[^&?#]+)'''
24     _TESTS = [{
25         'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
26         "md5": "06bea460acb744eab74a9d7dcb4bfd61",
27         'info_dict': {
28             'id': 'GB1101300280',
29             'ext': 'mp4',
30             "upload_date": "20130624",
31             "uploader": "Hurts",
32             "title": "Somebody to Die For",
33             "duration": 230.12,
34             "width": 1920,
35             "height": 1080,
36             'timestamp': 1372057200,
37         }
38     }, {
39         'note': 'v3 SMIL format',
40         'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
41         'md5': '893ec0e0d4426a1d96c01de8f2bdff58',
42         'info_dict': {
43             'id': 'USUV71302923',
44             'ext': 'mp4',
45             'upload_date': '20140219',
46             'uploader': 'Cassadee Pope',
47             'title': 'I Wish I Could Break Your Heart',
48             'duration': 226.101,
49             'age_limit': 0,
50             'timestamp': 1392796919,
51         }
52     }, {
53         'note': 'Age-limited video',
54         'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
55         'info_dict': {
56             'id': 'USRV81300282',
57             'ext': 'mp4',
58             'age_limit': 18,
59             'title': 'Tunnel Vision (Explicit)',
60             'uploader': 'Justin Timberlake',
61             # timestamp and upload_date are often incorrect; seem to change randomly
62             'upload_date': 're:2013070[34]',
63             'timestamp': int,
64         },
65         'params': {
66             'skip_download': 'true',
67         }
68     }]
69     _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
70
71     def _formats_from_json(self, video_info):
72         last_version = {'version': -1}
73         for version in video_info['videoVersions']:
74             # These are the HTTP downloads, other types are for different manifests
75             if version['sourceType'] == 2:
76                 if version['version'] > last_version['version']:
77                     last_version = version
78         if last_version['version'] == -1:
79             raise ExtractorError('Unable to extract last version of the video')
80
81         renditions = xml.etree.ElementTree.fromstring(last_version['data'])
82         formats = []
83         # Already sorted from worst to best quality
84         for rend in renditions.findall('rendition'):
85             attr = rend.attrib
86             format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
87             formats.append({
88                 'url': attr['url'],
89                 'format_id': attr['name'],
90                 'format_note': format_note,
91                 'height': int(attr['frameheight']),
92                 'width': int(attr['frameWidth']),
93             })
94         return formats
95
96     def _formats_from_smil(self, smil_xml):
97         formats = []
98         smil_doc = xml.etree.ElementTree.fromstring(smil_xml.encode('utf-8'))
99         els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
100         for el in els:
101             src = el.attrib['src']
102             m = re.match(r'''(?xi)
103                 (?P<ext>[a-z0-9]+):
104                 (?P<path>
105                     [/a-z0-9]+     # The directory and main part of the URL
106                     _(?P<cbr>[0-9]+)k
107                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
108                     _(?P<vcodec>[a-z0-9]+)
109                     _(?P<vbr>[0-9]+)
110                     _(?P<acodec>[a-z0-9]+)
111                     _(?P<abr>[0-9]+)
112                     \.[a-z0-9]+  # File extension
113                 )''', src)
114             if not m:
115                 continue
116
117             format_url = self._SMIL_BASE_URL + m.group('path')
118             formats.append({
119                 'url': format_url,
120                 'format_id': 'SMIL_' + m.group('cbr'),
121                 'vcodec': m.group('vcodec'),
122                 'acodec': m.group('acodec'),
123                 'vbr': int(m.group('vbr')),
124                 'abr': int(m.group('abr')),
125                 'ext': m.group('ext'),
126                 'width': int(m.group('width')),
127                 'height': int(m.group('height')),
128             })
129         return formats
130
131     def _real_extract(self, url):
132         mobj = re.match(self._VALID_URL, url)
133         video_id = mobj.group('id')
134
135         json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
136         video_info = self._download_json(json_url, video_id)['video']
137
138         formats = self._formats_from_json(video_info)
139
140         is_explicit = video_info.get('isExplicit')
141         if is_explicit is True:
142             age_limit = 18
143         elif is_explicit is False:
144             age_limit = 0
145         else:
146             age_limit = None
147
148         # Download SMIL
149         smil_blocks = sorted((
150             f for f in video_info['videoVersions']
151             if f['sourceType'] == 13),
152             key=lambda f: f['version'])
153
154         smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
155             self._SMIL_BASE_URL, video_id, video_id.lower())
156         if smil_blocks:
157             smil_url_m = self._search_regex(
158                 r'url="([^"]+)"', smil_blocks[-1]['data'], 'SMIL URL',
159                 fatal=False)
160             if smil_url_m is not None:
161                 smil_url = smil_url_m
162
163         try:
164             smil_xml = self._download_webpage(smil_url, video_id,
165                                               'Downloading SMIL info')
166             formats.extend(self._formats_from_smil(smil_xml))
167         except ExtractorError as ee:
168             if not isinstance(ee.cause, compat_HTTPError):
169                 raise
170             self._downloader.report_warning(
171                 'Cannot download SMIL information, falling back to JSON ..')
172
173         timestamp_ms = int(self._search_regex(
174             r'/Date\((\d+)\)/', video_info['launchDate'], 'launch date'))
175
176         return {
177             'id': video_id,
178             'title': video_info['title'],
179             'formats': formats,
180             'thumbnail': video_info['imageUrl'],
181             'timestamp': timestamp_ms // 1000,
182             'uploader': video_info['mainArtists'][0]['artistName'],
183             'duration': video_info['duration'],
184             'age_limit': age_limit,
185         }