Merge branch 'atomicdryad-brightcove_custombc_extractor'
[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 ..compat import (
10     compat_parse_qs,
11     compat_str,
12     compat_urllib_parse,
13     compat_urllib_parse_urlparse,
14     compat_urllib_request,
15     compat_urlparse,
16 )
17 from ..utils import (
18     determine_ext,
19     ExtractorError,
20     find_xpath_attr,
21     fix_xml_ampersands,
22     unescapeHTML,
23     unsmuggle_url,
24 )
25
26
27 class BrightcoveIE(InfoExtractor):
28     _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
29     _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
30
31     _TESTS = [
32         {
33             # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
34             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
35             'md5': '5423e113865d26e40624dce2e4b45d95',
36             'note': 'Test Brightcove downloads and detection in GenericIE',
37             'info_dict': {
38                 'id': '2371591881001',
39                 'ext': 'mp4',
40                 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
41                 'uploader': '8TV',
42                 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
43             }
44         },
45         {
46             # From http://medianetwork.oracle.com/video/player/1785452137001
47             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
48             'info_dict': {
49                 'id': '1785452137001',
50                 'ext': 'flv',
51                 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
52                 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
53                 'uploader': 'Oracle',
54             },
55         },
56         {
57             # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
58             'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
59             'info_dict': {
60                 'id': '2750934548001',
61                 'ext': 'mp4',
62                 'title': 'This Bracelet Acts as a Personal Thermostat',
63                 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
64                 'uploader': 'Mashable',
65             },
66         },
67         {
68             # test that the default referer works
69             # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
70             'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
71             'info_dict': {
72                 'id': '2878862109001',
73                 'ext': 'mp4',
74                 'title': 'Lost in Motion II',
75                 'description': 'md5:363109c02998fee92ec02211bd8000df',
76                 'uploader': 'National Ballet of Canada',
77             },
78         },
79         {
80             # test flv videos served by akamaihd.net
81             # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
82             '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',
83             # The md5 checksum changes on each download
84             'info_dict': {
85                 'id': '2996102916001',
86                 'ext': 'flv',
87                 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
88                 'uploader': 'Red Bull TV',
89                 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
90             },
91         },
92         {
93             # playlist test
94             # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
95             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
96             'info_dict': {
97                 'title': 'Sealife',
98                 'id': '3550319591001',
99             },
100             'playlist_mincount': 7,
101         },
102     ]
103
104     @classmethod
105     def _build_brighcove_url(cls, object_str):
106         """
107         Build a Brightcove url from a xml string containing
108         <object class="BrightcoveExperience">{params}</object>
109         """
110
111         # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
112         object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
113                             lambda m: m.group(1) + '/>', object_str)
114         # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
115         object_str = object_str.replace('<--', '<!--')
116         # remove namespace to simplify extraction
117         object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
118         object_str = fix_xml_ampersands(object_str)
119
120         try:
121             object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
122         except xml.etree.ElementTree.ParseError:
123             return
124
125         fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
126         if fv_el is not None:
127             flashvars = dict(
128                 (k, v[0])
129                 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
130         else:
131             flashvars = {}
132
133         def find_param(name):
134             if name in flashvars:
135                 return flashvars[name]
136             node = find_xpath_attr(object_doc, './param', 'name', name)
137             if node is not None:
138                 return node.attrib['value']
139             return None
140
141         params = {}
142
143         playerID = find_param('playerID')
144         if playerID is None:
145             raise ExtractorError('Cannot find player ID')
146         params['playerID'] = playerID
147
148         playerKey = find_param('playerKey')
149         # Not all pages define this value
150         if playerKey is not None:
151             params['playerKey'] = playerKey
152         # The three fields hold the id of the video
153         videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
154         if videoPlayer is not None:
155             params['@videoPlayer'] = videoPlayer
156         linkBase = find_param('linkBaseURL')
157         if linkBase is not None:
158             params['linkBaseURL'] = linkBase
159         return cls._make_brightcove_url(params)
160
161     @classmethod
162     def _build_brighcove_url_from_js(cls, object_js):
163         # The layout of JS is as follows:
164         # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
165         #   // build Brightcove <object /> XML
166         # }
167         m = re.search(
168             r'''(?x)customBC.\createVideo\(
169                 .*?                                                  # skipping width and height
170                 ["\'](?P<playerID>\d+)["\']\s*,\s*                   # playerID
171                 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s*  # playerKey begins with AQ and is 50 characters
172                                                                      # in length, however it's appended to itself
173                                                                      # in places, so truncate
174                 ["\'](?P<videoID>\d+)["\']                           # @videoPlayer
175             ''', object_js)
176         if m:
177             return cls._make_brightcove_url(m.groupdict())
178
179     @classmethod
180     def _make_brightcove_url(cls, params):
181         data = compat_urllib_parse.urlencode(params)
182         return cls._FEDERATED_URL_TEMPLATE % data
183
184     @classmethod
185     def _extract_brightcove_url(cls, webpage):
186         """Try to extract the brightcove url from the webpage, returns None
187         if it can't be found
188         """
189         urls = cls._extract_brightcove_urls(webpage)
190         return urls[0] if urls else None
191
192     @classmethod
193     def _extract_brightcove_urls(cls, webpage):
194         """Return a list of all Brightcove URLs from the webpage """
195
196         url_m = re.search(
197             r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
198             webpage)
199         if url_m:
200             url = unescapeHTML(url_m.group(1))
201             # Some sites don't add it, we can't download with this url, for example:
202             # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
203             if 'playerKey' in url or 'videoId' in url:
204                 return [url]
205
206         matches = re.findall(
207             r'''(?sx)<object
208             (?:
209                 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
210                 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
211             ).+?>\s*</object>''',
212             webpage)
213         if matches:
214             return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
215
216         return list(filter(None, [
217             cls._build_brighcove_url_from_js(custom_bc)
218             for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
219
220     def _real_extract(self, url):
221         url, smuggled_data = unsmuggle_url(url, {})
222
223         # Change the 'videoId' and others field to '@videoPlayer'
224         url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
225         # Change bckey (used by bcove.me urls) to playerKey
226         url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
227         mobj = re.match(self._VALID_URL, url)
228         query_str = mobj.group('query')
229         query = compat_urlparse.parse_qs(query_str)
230
231         videoPlayer = query.get('@videoPlayer')
232         if videoPlayer:
233             # We set the original url as the default 'Referer' header
234             referer = smuggled_data.get('Referer', url)
235             return self._get_video_info(
236                 videoPlayer[0], query_str, query, referer=referer)
237         elif 'playerKey' in query:
238             player_key = query['playerKey']
239             return self._get_playlist_info(player_key[0])
240         else:
241             raise ExtractorError(
242                 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
243                 expected=True)
244
245     def _get_video_info(self, video_id, query_str, query, referer=None):
246         request_url = self._FEDERATED_URL_TEMPLATE % query_str
247         req = compat_urllib_request.Request(request_url)
248         linkBase = query.get('linkBaseURL')
249         if linkBase is not None:
250             referer = linkBase[0]
251         if referer is not None:
252             req.add_header('Referer', referer)
253         webpage = self._download_webpage(req, video_id)
254
255         error_msg = self._html_search_regex(
256             r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
257             'error message', default=None)
258         if error_msg is not None:
259             raise ExtractorError(
260                 'brightcove said: %s' % error_msg, expected=True)
261
262         self.report_extraction(video_id)
263         info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
264         info = json.loads(info)['data']
265         video_info = info['programmedContent']['videoPlayer']['mediaDTO']
266         video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
267
268         return self._extract_video_info(video_info)
269
270     def _get_playlist_info(self, player_key):
271         info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
272         playlist_info = self._download_webpage(
273             info_url, player_key, 'Downloading playlist information')
274
275         json_data = json.loads(playlist_info)
276         if 'videoList' not in json_data:
277             raise ExtractorError('Empty playlist')
278         playlist_info = json_data['videoList']
279         videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
280
281         return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
282                                     playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
283
284     def _extract_video_info(self, video_info):
285         info = {
286             'id': compat_str(video_info['id']),
287             'title': video_info['displayName'].strip(),
288             'description': video_info.get('shortDescription'),
289             'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
290             'uploader': video_info.get('publisherName'),
291         }
292
293         renditions = video_info.get('renditions')
294         if renditions:
295             formats = []
296             for rend in renditions:
297                 url = rend['defaultURL']
298                 if not url:
299                     continue
300                 ext = None
301                 if rend['remote']:
302                     url_comp = compat_urllib_parse_urlparse(url)
303                     if url_comp.path.endswith('.m3u8'):
304                         formats.extend(
305                             self._extract_m3u8_formats(url, info['id'], 'mp4'))
306                         continue
307                     elif 'akamaihd.net' in url_comp.netloc:
308                         # This type of renditions are served through
309                         # akamaihd.net, but they don't use f4m manifests
310                         url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
311                         ext = 'flv'
312                 if ext is None:
313                     ext = determine_ext(url)
314                 size = rend.get('size')
315                 formats.append({
316                     'url': url,
317                     'ext': ext,
318                     'height': rend.get('frameHeight'),
319                     'width': rend.get('frameWidth'),
320                     'filesize': size if size != 0 else None,
321                 })
322             self._sort_formats(formats)
323             info['formats'] = formats
324         elif video_info.get('FLVFullLengthURL') is not None:
325             info.update({
326                 'url': video_info['FLVFullLengthURL'],
327             })
328
329         if self._downloader.params.get('include_ads', False):
330             adServerURL = video_info.get('_youtubedl_adServerURL')
331             if adServerURL:
332                 ad_info = {
333                     '_type': 'url',
334                     'url': adServerURL,
335                 }
336                 if 'url' in info:
337                     return {
338                         '_type': 'playlist',
339                         'title': info['title'],
340                         'entries': [ad_info, info],
341                     }
342                 else:
343                     return ad_info
344
345         if 'url' not in info and not info.get('formats'):
346             raise ExtractorError('Unable to extract video url for %s' % info['id'])
347         return info