]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/brightcove.py
Brightcove extractor: support customBC.createVideo(...); method
[yt-dlp.git] / youtube_dl / extractor / brightcove.py
CommitLineData
592882aa 1# encoding: utf-8
400e5810 2from __future__ import unicode_literals
592882aa 3
fbaaad49
JMF
4import re
5import json
cfe50f04 6import xml.etree.ElementTree
fbaaad49
JMF
7
8from .common import InfoExtractor
1cc79574 9from ..compat import (
7b0817e8 10 compat_parse_qs,
1cc79574
PH
11 compat_str,
12 compat_urllib_parse,
37aab278 13 compat_urllib_parse_urlparse,
1cc79574
PH
14 compat_urllib_request,
15 compat_urlparse,
16)
17from ..utils import (
5524b242 18 determine_ext,
592882aa 19 ExtractorError,
1cc79574
PH
20 find_xpath_attr,
21 fix_xml_ampersands,
ac6e4ca1 22 unescapeHTML,
1cc79574 23 unsmuggle_url,
cfe50f04 24)
fbaaad49 25
dd5bcdc4 26
fbaaad49 27class BrightcoveIE(InfoExtractor):
ec05fee4 28 _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
cfe50f04 29 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
592882aa
JMF
30
31 _TESTS = [
32 {
4de1994b 33 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
400e5810 34 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
400e5810
PH
35 'md5': '5423e113865d26e40624dce2e4b45d95',
36 'note': 'Test Brightcove downloads and detection in GenericIE',
37 'info_dict': {
96bef88f
JMF
38 'id': '2371591881001',
39 'ext': 'mp4',
400e5810
PH
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',
592882aa
JMF
43 }
44 },
45 {
4de1994b 46 # From http://medianetwork.oracle.com/video/player/1785452137001
400e5810 47 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
400e5810 48 'info_dict': {
96bef88f
JMF
49 'id': '1785452137001',
50 'ext': 'flv',
400e5810
PH
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',
592882aa
JMF
54 },
55 },
fc4a0c2a
JMF
56 {
57 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
400e5810
PH
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',
fc4a0c2a
JMF
65 },
66 },
77526143
JMF
67 {
68 # test that the default referer works
69 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
400e5810
PH
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',
77526143 77 },
5524b242
JMF
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 },
bd4e40df
JMF
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',
d47c26e1 98 'id': '3550319591001',
bd4e40df
JMF
99 },
100 'playlist_mincount': 7,
101 },
592882aa 102 ]
cfe50f04
JMF
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 """
46e28a84
PH
110
111 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
c1147c05 112 object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
46e28a84 113 lambda m: m.group(1) + '/>', object_str)
2d0efe70 114 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
400e5810 115 object_str = object_str.replace('<--', '<!--')
d6f714f3
JMF
116 # remove namespace to simplify extraction
117 object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
7b0817e8 118 object_str = fix_xml_ampersands(object_str)
46e28a84 119
94c12557
S
120 try:
121 object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
122 except xml.etree.ElementTree.ParseError:
123 return
7b0817e8
PH
124
125 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
47917f24
JMF
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 = {}
7b0817e8 132
36de0a0e 133 def find_param(name):
7b0817e8
PH
134 if name in flashvars:
135 return flashvars[name]
d214fdb8
JMF
136 node = find_xpath_attr(object_doc, './param', 'name', name)
137 if node is not None:
138 return node.attrib['value']
139 return None
7b0817e8
PH
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
36de0a0e 148 playerKey = find_param('playerKey')
cfe50f04
JMF
149 # Not all pages define this value
150 if playerKey is not None:
d214fdb8 151 params['playerKey'] = playerKey
36de0a0e
JMF
152 # The three fields hold the id of the video
153 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
abb285fb 154 if videoPlayer is not None:
d214fdb8 155 params['@videoPlayer'] = videoPlayer
36de0a0e 156 linkBase = find_param('linkBaseURL')
dd5bcdc4 157 if linkBase is not None:
d214fdb8 158 params['linkBaseURL'] = linkBase
cfe50f04
JMF
159 data = compat_urllib_parse.urlencode(params)
160 return cls._FEDERATED_URL_TEMPLATE % data
fbaaad49 161
eeb165e6
JMF
162 @classmethod
163 def _extract_brightcove_url(cls, webpage):
99877772 164 """Try to extract the brightcove url from the webpage, returns None
eeb165e6
JMF
165 if it can't be found
166 """
99877772
PH
167 urls = cls._extract_brightcove_urls(webpage)
168 return urls[0] if urls else None
169
170 @classmethod
171 def _extract_brightcove_urls(cls, webpage):
172 """Return a list of all Brightcove URLs from the webpage """
117bec93 173
e1ab5000 174 url_m = re.search(
b26733ba 175 r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
e1ab5000 176 webpage)
117bec93 177 if url_m:
381640e3
JMF
178 url = unescapeHTML(url_m.group(1))
179 # Some sites don't add it, we can't download with this url, for example:
180 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
e1ab5000 181 if 'playerKey' in url or 'videoId' in url:
381640e3 182 return [url]
117bec93 183
99877772 184 matches = re.findall(
7b0817e8
PH
185 r'''(?sx)<object
186 (?:
99877772 187 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
7b0817e8 188 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
476e1095 189 ).+?>\s*</object>''',
7b0817e8 190 webpage)
b4e1576a 191 if matches:
192 return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
193
194 custombcs = re.findall(r'customBC.\createVideo\((.+?)\);',webpage)
195 if custombcs:
196 urls = []
197 for match in custombcs:
198 # brightcove playerkey begins with AQ and is 50 characters in length,
199 # however it's appended to itself in places, so truncate.
200 f = re.search(r'["\'](AQ[^"\']{48}).*?["\'](\d+)["\']', match)
201 if f:
202 urls.append('brightcove:playerKey='+f.group(1)+'&%40videoPlayer='+f.group(2))
203 return urls
eeb165e6 204
fbaaad49 205 def _real_extract(self, url):
79f82953
PH
206 url, smuggled_data = unsmuggle_url(url, {})
207
51040b72
JMF
208 # Change the 'videoId' and others field to '@videoPlayer'
209 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
210 # Change bckey (used by bcove.me urls) to playerKey
211 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
fbaaad49 212 mobj = re.match(self._VALID_URL, url)
6543f0dc
JMF
213 query_str = mobj.group('query')
214 query = compat_urlparse.parse_qs(query_str)
fbaaad49 215
6543f0dc
JMF
216 videoPlayer = query.get('@videoPlayer')
217 if videoPlayer:
79f82953
PH
218 # We set the original url as the default 'Referer' header
219 referer = smuggled_data.get('Referer', url)
220 return self._get_video_info(
221 videoPlayer[0], query_str, query, referer=referer)
68575900 222 elif 'playerKey' in query:
6543f0dc
JMF
223 player_key = query['playerKey']
224 return self._get_playlist_info(player_key[0])
68575900
PH
225 else:
226 raise ExtractorError(
227 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
228 expected=True)
abb285fb 229
77526143 230 def _get_video_info(self, video_id, query_str, query, referer=None):
dd5bcdc4
JMF
231 request_url = self._FEDERATED_URL_TEMPLATE % query_str
232 req = compat_urllib_request.Request(request_url)
233 linkBase = query.get('linkBaseURL')
234 if linkBase is not None:
77526143
JMF
235 referer = linkBase[0]
236 if referer is not None:
237 req.add_header('Referer', referer)
dd5bcdc4 238 webpage = self._download_webpage(req, video_id)
fbaaad49 239
a5ed3e57 240 error_msg = self._html_search_regex(
4d46c1c6 241 r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
a5ed3e57
PH
242 'error message', default=None)
243 if error_msg is not None:
244 raise ExtractorError(
245 'brightcove said: %s' % error_msg, expected=True)
246
fbaaad49 247 self.report_extraction(video_id)
a013eba6 248 info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
fbaaad49
JMF
249 info = json.loads(info)['data']
250 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
7b0817e8 251 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
abb285fb
JMF
252
253 return self._extract_video_info(video_info)
254
255 def _get_playlist_info(self, player_key):
117bec93
PH
256 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
257 playlist_info = self._download_webpage(
258 info_url, player_key, 'Downloading playlist information')
abb285fb 259
59145479
PH
260 json_data = json.loads(playlist_info)
261 if 'videoList' not in json_data:
400e5810 262 raise ExtractorError('Empty playlist')
59145479 263 playlist_info = json_data['videoList']
abb285fb
JMF
264 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
265
d47c26e1 266 return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
abb285fb
JMF
267 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
268
269 def _extract_video_info(self, video_info):
592882aa 270 info = {
eeb165e6 271 'id': compat_str(video_info['id']),
066f6a06 272 'title': video_info['displayName'].strip(),
592882aa
JMF
273 'description': video_info.get('shortDescription'),
274 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
275 'uploader': video_info.get('publisherName'),
276 }
abb285fb 277
592882aa
JMF
278 renditions = video_info.get('renditions')
279 if renditions:
5524b242
JMF
280 formats = []
281 for rend in renditions:
282 url = rend['defaultURL']
b5af6fcd
NJ
283 if not url:
284 continue
233d37fb 285 ext = None
5524b242 286 if rend['remote']:
37aab278
NJ
287 url_comp = compat_urllib_parse_urlparse(url)
288 if url_comp.path.endswith('.m3u8'):
289 formats.extend(
290 self._extract_m3u8_formats(url, info['id'], 'mp4'))
291 continue
292 elif 'akamaihd.net' in url_comp.netloc:
293 # This type of renditions are served through
294 # akamaihd.net, but they don't use f4m manifests
295 url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
296 ext = 'flv'
233d37fb 297 if ext is None:
5524b242 298 ext = determine_ext(url)
35eacd0d 299 size = rend.get('size')
5524b242
JMF
300 formats.append({
301 'url': url,
302 'ext': ext,
303 'height': rend.get('frameHeight'),
304 'width': rend.get('frameWidth'),
35eacd0d 305 'filesize': size if size != 0 else None,
5524b242 306 })
35eacd0d 307 self._sort_formats(formats)
5524b242 308 info['formats'] = formats
592882aa
JMF
309 elif video_info.get('FLVFullLengthURL') is not None:
310 info.update({
311 'url': video_info['FLVFullLengthURL'],
592882aa 312 })
7b0817e8
PH
313
314 if self._downloader.params.get('include_ads', False):
315 adServerURL = video_info.get('_youtubedl_adServerURL')
316 if adServerURL:
317 ad_info = {
318 '_type': 'url',
319 'url': adServerURL,
320 }
321 if 'url' in info:
322 return {
323 '_type': 'playlist',
324 'title': info['title'],
325 'entries': [ad_info, info],
326 }
327 else:
328 return ad_info
329
d614aa40 330 if 'url' not in info and not info.get('formats'):
400e5810 331 raise ExtractorError('Unable to extract video url for %s' % info['id'])
592882aa 332 return info