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