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