Add support for embedded vevo player (Fixes #1957)
[youtube-dl] / youtube_dl / extractor / vevo.py
1 import re
2 import json
3 import xml.etree.ElementTree
4 import datetime
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            vevo:)
22         (?P<id>[^&?#]+)'''
23     _TESTS = [{
24         u'url': u'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
25         u'file': u'GB1101300280.mp4',
26         u"md5": u"06bea460acb744eab74a9d7dcb4bfd61",
27         u'info_dict': {
28             u"upload_date": u"20130624",
29             u"uploader": u"Hurts",
30             u"title": u"Somebody to Die For",
31             u"duration": 230.12,
32             u"width": 1920,
33             u"height": 1080,
34         }
35     }]
36     _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
37
38     def _formats_from_json(self, video_info):
39         last_version = {'version': -1}
40         for version in video_info['videoVersions']:
41             # These are the HTTP downloads, other types are for different manifests
42             if version['sourceType'] == 2:
43                 if version['version'] > last_version['version']:
44                     last_version = version
45         if last_version['version'] == -1:
46             raise ExtractorError(u'Unable to extract last version of the video')
47
48         renditions = xml.etree.ElementTree.fromstring(last_version['data'])
49         formats = []
50         # Already sorted from worst to best quality
51         for rend in renditions.findall('rendition'):
52             attr = rend.attrib
53             format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
54             formats.append({
55                 'url': attr['url'],
56                 'format_id': attr['name'],
57                 'format_note': format_note,
58                 'height': int(attr['frameheight']),
59                 'width': int(attr['frameWidth']),
60             })
61         return formats
62
63     def _formats_from_smil(self, smil_xml):
64         formats = []
65         smil_doc = xml.etree.ElementTree.fromstring(smil_xml.encode('utf-8'))
66         els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
67         for el in els:
68             src = el.attrib['src']
69             m = re.match(r'''(?xi)
70                 (?P<ext>[a-z0-9]+):
71                 (?P<path>
72                     [/a-z0-9]+     # The directory and main part of the URL
73                     _(?P<cbr>[0-9]+)k
74                     _(?P<width>[0-9]+)x(?P<height>[0-9]+)
75                     _(?P<vcodec>[a-z0-9]+)
76                     _(?P<vbr>[0-9]+)
77                     _(?P<acodec>[a-z0-9]+)
78                     _(?P<abr>[0-9]+)
79                     \.[a-z0-9]+  # File extension
80                 )''', src)
81             if not m:
82                 continue
83
84             format_url = self._SMIL_BASE_URL + m.group('path')
85             formats.append({
86                 'url': format_url,
87                 'format_id': u'SMIL_' + m.group('cbr'),
88                 'vcodec': m.group('vcodec'),
89                 'acodec': m.group('acodec'),
90                 'vbr': int(m.group('vbr')),
91                 'abr': int(m.group('abr')),
92                 'ext': m.group('ext'),
93                 'width': int(m.group('width')),
94                 'height': int(m.group('height')),
95             })
96         return formats
97
98     def _real_extract(self, url):
99         mobj = re.match(self._VALID_URL, url)
100         video_id = mobj.group('id')
101
102         json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
103         info_json = self._download_webpage(json_url, video_id, u'Downloading json info')
104         video_info = json.loads(info_json)['video']
105
106         formats = self._formats_from_json(video_info)
107         try:
108             smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
109                 self._SMIL_BASE_URL, video_id, video_id.lower())
110             smil_xml = self._download_webpage(smil_url, video_id,
111                                               u'Downloading SMIL info')
112             formats.extend(self._formats_from_smil(smil_xml))
113         except ExtractorError as ee:
114             if not isinstance(ee.cause, compat_HTTPError):
115                 raise
116             self._downloader.report_warning(
117                 u'Cannot download SMIL information, falling back to JSON ..')
118
119         timestamp_ms = int(self._search_regex(
120             r'/Date\((\d+)\)/', video_info['launchDate'], u'launch date'))
121         upload_date = datetime.datetime.fromtimestamp(timestamp_ms // 1000)
122         info = {
123             'id': video_id,
124             'title': video_info['title'],
125             'formats': formats,
126             'thumbnail': video_info['imageUrl'],
127             'upload_date': upload_date.strftime('%Y%m%d'),
128             'uploader': video_info['mainArtists'][0]['artistName'],
129             'duration': video_info['duration'],
130         }
131
132         return info