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