]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/vevo.py
Merge branch 'ustream-embed-recorded2' of https://github.com/anovicecodemonkey/youtub...
[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
25     _TESTS = [{
26         'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
27         "md5": "06bea460acb744eab74a9d7dcb4bfd61",
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': '893ec0e0d4426a1d96c01de8f2bdff58',
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 _formats_from_json(self, video_info):
73         last_version = {'version': -1}
74         for version in video_info['videoVersions']:
75             # These are the HTTP downloads, other types are for different manifests
76             if version['sourceType'] == 2:
77                 if version['version'] > last_version['version']:
78                     last_version = version
79         if last_version['version'] == -1:
80             raise ExtractorError('Unable to extract last version of the video')
81
82         renditions = xml.etree.ElementTree.fromstring(last_version['data'])
83         formats = []
84         # Already sorted from worst to best quality
85         for rend in renditions.findall('rendition'):
86             attr = rend.attrib
87             format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
88             formats.append({
89                 'url': attr['url'],
90                 'format_id': attr['name'],
91                 'format_note': format_note,
92                 'height': int(attr['frameheight']),
93                 'width': int(attr['frameWidth']),
94             })
95         return formats
96
97     def _formats_from_smil(self, smil_xml):
98         formats = []
99         smil_doc = xml.etree.ElementTree.fromstring(smil_xml.encode('utf-8'))
100         els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
101         for el in els:
102             src = el.attrib['src']
103             m = re.match(r'''(?xi)
104                 (?P<ext>[a-z0-9]+):
105                 (?P<path>
106                     [/a-z0-9]+     # The directory and main part of the URL
107                     _(?P<cbr>[0-9]+)k
108                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
109                     _(?P<vcodec>[a-z0-9]+)
110                     _(?P<vbr>[0-9]+)
111                     _(?P<acodec>[a-z0-9]+)
112                     _(?P<abr>[0-9]+)
113                     \.[a-z0-9]+  # File extension
114                 )''', src)
115             if not m:
116                 continue
117
118             format_url = self._SMIL_BASE_URL + m.group('path')
119             formats.append({
120                 'url': format_url,
121                 'format_id': 'SMIL_' + m.group('cbr'),
122                 'vcodec': m.group('vcodec'),
123                 'acodec': m.group('acodec'),
124                 'vbr': int(m.group('vbr')),
125                 'abr': int(m.group('abr')),
126                 'ext': m.group('ext'),
127                 'width': int(m.group('width')),
128                 'height': int(m.group('height')),
129             })
130         return formats
131
132     def _real_extract(self, url):
133         mobj = re.match(self._VALID_URL, url)
134         video_id = mobj.group('id')
135
136         json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
137         response = self._download_json(json_url, video_id)
138         video_info = response['video']
139
140         if not video_info:
141             if 'statusMessage' in response:
142                 raise ExtractorError('%s said: %s' % (self.IE_NAME, response['statusMessage']), expected=True)
143             raise ExtractorError('Unable to extract videos')
144
145         formats = self._formats_from_json(video_info)
146
147         is_explicit = video_info.get('isExplicit')
148         if is_explicit is True:
149             age_limit = 18
150         elif is_explicit is False:
151             age_limit = 0
152         else:
153             age_limit = None
154
155         # Download SMIL
156         smil_blocks = sorted((
157             f for f in video_info['videoVersions']
158             if f['sourceType'] == 13),
159             key=lambda f: f['version'])
160
161         smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
162             self._SMIL_BASE_URL, video_id, video_id.lower())
163         if smil_blocks:
164             smil_url_m = self._search_regex(
165                 r'url="([^"]+)"', smil_blocks[-1]['data'], 'SMIL URL',
166                 fatal=False)
167             if smil_url_m is not None:
168                 smil_url = smil_url_m
169
170         try:
171             smil_xml = self._download_webpage(smil_url, video_id,
172                                               'Downloading SMIL info')
173             formats.extend(self._formats_from_smil(smil_xml))
174         except ExtractorError as ee:
175             if not isinstance(ee.cause, compat_HTTPError):
176                 raise
177             self._downloader.report_warning(
178                 'Cannot download SMIL information, falling back to JSON ..')
179
180         timestamp_ms = int(self._search_regex(
181             r'/Date\((\d+)\)/', video_info['launchDate'], 'launch date'))
182
183         return {
184             'id': video_id,
185             'title': video_info['title'],
186             'formats': formats,
187             'thumbnail': video_info['imageUrl'],
188             'timestamp': timestamp_ms // 1000,
189             'uploader': video_info['mainArtists'][0]['artistName'],
190             'duration': video_info['duration'],
191             'age_limit': age_limit,
192         }