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