[brightcove] Add support for renditions with 'remote' set to True (fixes #3081)
[youtube-dl] / youtube_dl / extractor / brightcove.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import xml.etree.ElementTree
7
8 from .common import InfoExtractor
9 from ..utils import (
10     compat_urllib_parse,
11     find_xpath_attr,
12     fix_xml_ampersands,
13     compat_urlparse,
14     compat_str,
15     compat_urllib_request,
16     compat_parse_qs,
17
18     determine_ext,
19     ExtractorError,
20     unsmuggle_url,
21     unescapeHTML,
22 )
23
24
25 class BrightcoveIE(InfoExtractor):
26     _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
27     _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
28
29     _TESTS = [
30         {
31             # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
32             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
33             'file': '2371591881001.mp4',
34             'md5': '5423e113865d26e40624dce2e4b45d95',
35             'note': 'Test Brightcove downloads and detection in GenericIE',
36             'info_dict': {
37                 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
38                 'uploader': '8TV',
39                 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
40             }
41         },
42         {
43             # From http://medianetwork.oracle.com/video/player/1785452137001
44             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
45             'file': '1785452137001.flv',
46             'info_dict': {
47                 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
48                 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
49                 'uploader': 'Oracle',
50             },
51         },
52         {
53             # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
54             'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
55             'info_dict': {
56                 'id': '2750934548001',
57                 'ext': 'mp4',
58                 'title': 'This Bracelet Acts as a Personal Thermostat',
59                 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
60                 'uploader': 'Mashable',
61             },
62         },
63         {
64             # test that the default referer works
65             # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
66             'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
67             'info_dict': {
68                 'id': '2878862109001',
69                 'ext': 'mp4',
70                 'title': 'Lost in Motion II',
71                 'description': 'md5:363109c02998fee92ec02211bd8000df',
72                 'uploader': 'National Ballet of Canada',
73             },
74         },
75         {
76             # test flv videos served by akamaihd.net
77             # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
78             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?%40videoPlayer=ref%3ABC2996102916001&linkBaseURL=http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fvideos%2F1331655630249%2Freplay-uci-fort-william-2014-dh&playerKey=AQ%7E%7E%2CAAAApYJ7UqE%7E%2Cxqr_zXk0I-zzNndy8NlHogrCb5QdyZRf&playerID=1398061561001#__youtubedl_smuggle=%7B%22Referer%22%3A+%22http%3A%2F%2Fwww.redbull.com%2Fen%2Fbike%2Fstories%2F1331655643987%2Freplay-uci-dh-world-cup-2014-from-fort-william%22%7D',
79             # The md5 checksum changes on each download
80             'info_dict': {
81                 'id': '2996102916001',
82                 'ext': 'flv',
83                 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
84                 'uploader': 'Red Bull TV',
85                 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
86             },
87         },
88     ]
89
90     @classmethod
91     def _build_brighcove_url(cls, object_str):
92         """
93         Build a Brightcove url from a xml string containing
94         <object class="BrightcoveExperience">{params}</object>
95         """
96
97         # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
98         object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
99                             lambda m: m.group(1) + '/>', object_str)
100         # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
101         object_str = object_str.replace('<--', '<!--')
102         object_str = fix_xml_ampersands(object_str)
103
104         object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
105
106         fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
107         if fv_el is not None:
108             flashvars = dict(
109                 (k, v[0])
110                 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
111         else:
112             flashvars = {}
113
114         def find_param(name):
115             if name in flashvars:
116                 return flashvars[name]
117             node = find_xpath_attr(object_doc, './param', 'name', name)
118             if node is not None:
119                 return node.attrib['value']
120             return None
121
122         params = {}
123
124         playerID = find_param('playerID')
125         if playerID is None:
126             raise ExtractorError('Cannot find player ID')
127         params['playerID'] = playerID
128
129         playerKey = find_param('playerKey')
130         # Not all pages define this value
131         if playerKey is not None:
132             params['playerKey'] = playerKey
133         # The three fields hold the id of the video
134         videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
135         if videoPlayer is not None:
136             params['@videoPlayer'] = videoPlayer
137         linkBase = find_param('linkBaseURL')
138         if linkBase is not None:
139             params['linkBaseURL'] = linkBase
140         data = compat_urllib_parse.urlencode(params)
141         return cls._FEDERATED_URL_TEMPLATE % data
142
143     @classmethod
144     def _extract_brightcove_url(cls, webpage):
145         """Try to extract the brightcove url from the webpage, returns None
146         if it can't be found
147         """
148         urls = cls._extract_brightcove_urls(webpage)
149         return urls[0] if urls else None
150
151     @classmethod
152     def _extract_brightcove_urls(cls, webpage):
153         """Return a list of all Brightcove URLs from the webpage """
154
155         url_m = re.search(r'<meta\s+property="og:video"\s+content="(http://c.brightcove.com/[^"]+)"', webpage)
156         if url_m:
157             url = unescapeHTML(url_m.group(1))
158             # Some sites don't add it, we can't download with this url, for example:
159             # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
160             if 'playerKey' in url:
161                 return [url]
162
163         matches = re.findall(
164             r'''(?sx)<object
165             (?:
166                 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
167                 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
168             ).+?</object>''',
169             webpage)
170         return [cls._build_brighcove_url(m) for m in matches]
171
172     def _real_extract(self, url):
173         url, smuggled_data = unsmuggle_url(url, {})
174
175         # Change the 'videoId' and others field to '@videoPlayer'
176         url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
177         # Change bckey (used by bcove.me urls) to playerKey
178         url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
179         mobj = re.match(self._VALID_URL, url)
180         query_str = mobj.group('query')
181         query = compat_urlparse.parse_qs(query_str)
182
183         videoPlayer = query.get('@videoPlayer')
184         if videoPlayer:
185             # We set the original url as the default 'Referer' header
186             referer = smuggled_data.get('Referer', url)
187             return self._get_video_info(
188                 videoPlayer[0], query_str, query, referer=referer)
189         else:
190             player_key = query['playerKey']
191             return self._get_playlist_info(player_key[0])
192
193     def _get_video_info(self, video_id, query_str, query, referer=None):
194         request_url = self._FEDERATED_URL_TEMPLATE % query_str
195         req = compat_urllib_request.Request(request_url)
196         linkBase = query.get('linkBaseURL')
197         if linkBase is not None:
198             referer = linkBase[0]
199         if referer is not None:
200             req.add_header('Referer', referer)
201         webpage = self._download_webpage(req, video_id)
202
203         self.report_extraction(video_id)
204         info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
205         info = json.loads(info)['data']
206         video_info = info['programmedContent']['videoPlayer']['mediaDTO']
207         video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
208
209         return self._extract_video_info(video_info)
210
211     def _get_playlist_info(self, player_key):
212         info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
213         playlist_info = self._download_webpage(
214             info_url, player_key, 'Downloading playlist information')
215
216         json_data = json.loads(playlist_info)
217         if 'videoList' not in json_data:
218             raise ExtractorError('Empty playlist')
219         playlist_info = json_data['videoList']
220         videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
221
222         return self.playlist_result(videos, playlist_id=playlist_info['id'],
223                                     playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
224
225     def _extract_video_info(self, video_info):
226         info = {
227             'id': compat_str(video_info['id']),
228             'title': video_info['displayName'].strip(),
229             'description': video_info.get('shortDescription'),
230             'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
231             'uploader': video_info.get('publisherName'),
232         }
233
234         renditions = video_info.get('renditions')
235         if renditions:
236             renditions = sorted(renditions, key=lambda r: r['size'])
237             formats = []
238             for rend in renditions:
239                 url = rend['defaultURL']
240                 if rend['remote']:
241                     # This type of renditions are served through akamaihd.net,
242                     # but they don't use f4m manifests
243                     url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
244                     ext = 'flv'
245                 else:
246                     ext = determine_ext(url)
247                 formats.append({
248                     'url': url,
249                     'ext': ext,
250                     'height': rend.get('frameHeight'),
251                     'width': rend.get('frameWidth'),
252                 })
253             info['formats'] = formats
254         elif video_info.get('FLVFullLengthURL') is not None:
255             info.update({
256                 'url': video_info['FLVFullLengthURL'],
257             })
258
259         if self._downloader.params.get('include_ads', False):
260             adServerURL = video_info.get('_youtubedl_adServerURL')
261             if adServerURL:
262                 ad_info = {
263                     '_type': 'url',
264                     'url': adServerURL,
265                 }
266                 if 'url' in info:
267                     return {
268                         '_type': 'playlist',
269                         'title': info['title'],
270                         'entries': [ad_info, info],
271                     }
272                 else:
273                     return ad_info
274
275         if 'url' not in info and not info.get('formats'):
276             raise ExtractorError('Unable to extract video url for %s' % info['id'])
277         return info