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