]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/vevo.py
5b1a3ec787ac6c99c0db4d37d5ff2c33c6950ef6
[youtubedl] / 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_urllib_request,
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
25 _TESTS = [{
26 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
27 "md5": "95ee28ee45e70130e3ab02b0f579ae23",
28 'info_dict': {
29 'id': 'GB1101300280',
30 'ext': 'mp4',
31 "upload_date": "20130624",
32 "uploader": "Hurts",
33 "title": "Somebody to Die For",
34 "duration": 230.12,
35 "width": 1920,
36 "height": 1080,
37 # timestamp and upload_date are often incorrect; seem to change randomly
38 'timestamp': int,
39 }
40 }, {
41 'note': 'v3 SMIL format',
42 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
43 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
44 'info_dict': {
45 'id': 'USUV71302923',
46 'ext': 'mp4',
47 'upload_date': '20140219',
48 'uploader': 'Cassadee Pope',
49 'title': 'I Wish I Could Break Your Heart',
50 'duration': 226.101,
51 'age_limit': 0,
52 'timestamp': int,
53 }
54 }, {
55 'note': 'Age-limited video',
56 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
57 'info_dict': {
58 'id': 'USRV81300282',
59 'ext': 'mp4',
60 'age_limit': 18,
61 'title': 'Tunnel Vision (Explicit)',
62 'uploader': 'Justin Timberlake',
63 'upload_date': 're:2013070[34]',
64 'timestamp': int,
65 },
66 'params': {
67 'skip_download': 'true',
68 }
69 }]
70 _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
71
72 def _real_initialize(self):
73 req = compat_urllib_request.Request(
74 'http://www.vevo.com/auth', data=b'')
75 webpage = self._download_webpage(
76 req, None,
77 note='Retrieving oauth token',
78 errnote='Unable to retrieve oauth token',
79 fatal=False)
80 if webpage is False:
81 self._oauth_token = None
82 else:
83 self._oauth_token = self._search_regex(
84 r'access_token":\s*"([^"]+)"',
85 webpage, 'access token', fatal=False)
86
87 def _formats_from_json(self, video_info):
88 last_version = {'version': -1}
89 for version in video_info['videoVersions']:
90 # These are the HTTP downloads, other types are for different manifests
91 if version['sourceType'] == 2:
92 if version['version'] > last_version['version']:
93 last_version = version
94 if last_version['version'] == -1:
95 raise ExtractorError('Unable to extract last version of the video')
96
97 renditions = xml.etree.ElementTree.fromstring(last_version['data'])
98 formats = []
99 # Already sorted from worst to best quality
100 for rend in renditions.findall('rendition'):
101 attr = rend.attrib
102 format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
103 formats.append({
104 'url': attr['url'],
105 'format_id': attr['name'],
106 'format_note': format_note,
107 'height': int(attr['frameheight']),
108 'width': int(attr['frameWidth']),
109 })
110 return formats
111
112 def _formats_from_smil(self, smil_xml):
113 formats = []
114 smil_doc = xml.etree.ElementTree.fromstring(smil_xml.encode('utf-8'))
115 els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
116 for el in els:
117 src = el.attrib['src']
118 m = re.match(r'''(?xi)
119 (?P<ext>[a-z0-9]+):
120 (?P<path>
121 [/a-z0-9]+ # The directory and main part of the URL
122 _(?P<cbr>[0-9]+)k
123 _(?P<width>[0-9]+)x(?P<height>[0-9]+)
124 _(?P<vcodec>[a-z0-9]+)
125 _(?P<vbr>[0-9]+)
126 _(?P<acodec>[a-z0-9]+)
127 _(?P<abr>[0-9]+)
128 \.[a-z0-9]+ # File extension
129 )''', src)
130 if not m:
131 continue
132
133 format_url = self._SMIL_BASE_URL + m.group('path')
134 formats.append({
135 'url': format_url,
136 'format_id': 'SMIL_' + m.group('cbr'),
137 'vcodec': m.group('vcodec'),
138 'acodec': m.group('acodec'),
139 'vbr': int(m.group('vbr')),
140 'abr': int(m.group('abr')),
141 'ext': m.group('ext'),
142 'width': int(m.group('width')),
143 'height': int(m.group('height')),
144 })
145 return formats
146
147 def _download_api_formats(self, video_id):
148 if not self._oauth_token:
149 self._downloader.report_warning(
150 'No oauth token available, skipping API HLS download')
151 return []
152
153 api_url = 'https://apiv2.vevo.com/video/%s/streams/hls?token=%s' % (
154 video_id, self._oauth_token)
155 api_data = self._download_json(
156 api_url, video_id,
157 note='Downloading HLS formats',
158 errnote='Failed to download HLS format list', fatal=False)
159 if api_data is None:
160 return []
161
162 m3u8_url = api_data[0]['url']
163 return self._extract_m3u8_formats(
164 m3u8_url, video_id, entry_protocol='m3u8_native', ext='mp4',
165 preference=0)
166
167 def _real_extract(self, url):
168 mobj = re.match(self._VALID_URL, url)
169 video_id = mobj.group('id')
170
171 json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
172 response = self._download_json(json_url, video_id)
173 video_info = response['video']
174
175 if not video_info:
176 if 'statusMessage' in response:
177 raise ExtractorError('%s said: %s' % (self.IE_NAME, response['statusMessage']), expected=True)
178 raise ExtractorError('Unable to extract videos')
179
180 formats = self._formats_from_json(video_info)
181
182 is_explicit = video_info.get('isExplicit')
183 if is_explicit is True:
184 age_limit = 18
185 elif is_explicit is False:
186 age_limit = 0
187 else:
188 age_limit = None
189
190 # Download via HLS API
191 formats.extend(self._download_api_formats(video_id))
192
193 self._sort_formats(formats)
194 timestamp_ms = int(self._search_regex(
195 r'/Date\((\d+)\)/', video_info['launchDate'], 'launch date'))
196
197 return {
198 'id': video_id,
199 'title': video_info['title'],
200 'formats': formats,
201 'thumbnail': video_info['imageUrl'],
202 'timestamp': timestamp_ms // 1000,
203 'uploader': video_info['mainArtists'][0]['artistName'],
204 'duration': video_info['duration'],
205 'age_limit': age_limit,
206 }