]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/brightcove.py
[steam] Simplify
[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,
592882aa
JMF
17
18 ExtractorError,
79f82953 19 unsmuggle_url,
ac6e4ca1 20 unescapeHTML,
cfe50f04 21)
fbaaad49 22
dd5bcdc4 23
fbaaad49 24class BrightcoveIE(InfoExtractor):
abb285fb 25 _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
cfe50f04 26 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
592882aa
JMF
27
28 _TESTS = [
29 {
4de1994b 30 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
400e5810
PH
31 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
32 'file': '2371591881001.mp4',
33 'md5': '5423e113865d26e40624dce2e4b45d95',
34 'note': 'Test Brightcove downloads and detection in GenericIE',
35 'info_dict': {
36 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
37 'uploader': '8TV',
38 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
592882aa
JMF
39 }
40 },
41 {
4de1994b 42 # From http://medianetwork.oracle.com/video/player/1785452137001
400e5810
PH
43 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
44 'file': '1785452137001.flv',
45 'info_dict': {
46 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
47 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
48 'uploader': 'Oracle',
592882aa
JMF
49 },
50 },
fc4a0c2a
JMF
51 {
52 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
400e5810
PH
53 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
54 'info_dict': {
55 'id': '2750934548001',
56 'ext': 'mp4',
57 'title': 'This Bracelet Acts as a Personal Thermostat',
58 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
59 'uploader': 'Mashable',
fc4a0c2a
JMF
60 },
61 },
77526143
JMF
62 {
63 # test that the default referer works
64 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
400e5810
PH
65 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
66 'info_dict': {
67 'id': '2878862109001',
68 'ext': 'mp4',
69 'title': 'Lost in Motion II',
70 'description': 'md5:363109c02998fee92ec02211bd8000df',
71 'uploader': 'National Ballet of Canada',
77526143 72 },
117bec93 73 }
592882aa 74 ]
cfe50f04
JMF
75
76 @classmethod
77 def _build_brighcove_url(cls, object_str):
78 """
79 Build a Brightcove url from a xml string containing
80 <object class="BrightcoveExperience">{params}</object>
81 """
46e28a84
PH
82
83 # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
84 object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
85 lambda m: m.group(1) + '/>', object_str)
2d0efe70 86 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
400e5810 87 object_str = object_str.replace('<--', '<!--')
7b0817e8 88 object_str = fix_xml_ampersands(object_str)
46e28a84 89
0479c625 90 object_doc = xml.etree.ElementTree.fromstring(object_str.encode('utf-8'))
7b0817e8
PH
91
92 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
47917f24
JMF
93 if fv_el is not None:
94 flashvars = dict(
95 (k, v[0])
96 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
97 else:
98 flashvars = {}
7b0817e8 99
36de0a0e 100 def find_param(name):
7b0817e8
PH
101 if name in flashvars:
102 return flashvars[name]
d214fdb8
JMF
103 node = find_xpath_attr(object_doc, './param', 'name', name)
104 if node is not None:
105 return node.attrib['value']
106 return None
7b0817e8
PH
107
108 params = {}
109
110 playerID = find_param('playerID')
111 if playerID is None:
112 raise ExtractorError('Cannot find player ID')
113 params['playerID'] = playerID
114
36de0a0e 115 playerKey = find_param('playerKey')
cfe50f04
JMF
116 # Not all pages define this value
117 if playerKey is not None:
d214fdb8 118 params['playerKey'] = playerKey
36de0a0e
JMF
119 # The three fields hold the id of the video
120 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
abb285fb 121 if videoPlayer is not None:
d214fdb8 122 params['@videoPlayer'] = videoPlayer
36de0a0e 123 linkBase = find_param('linkBaseURL')
dd5bcdc4 124 if linkBase is not None:
d214fdb8 125 params['linkBaseURL'] = linkBase
cfe50f04
JMF
126 data = compat_urllib_parse.urlencode(params)
127 return cls._FEDERATED_URL_TEMPLATE % data
fbaaad49 128
eeb165e6
JMF
129 @classmethod
130 def _extract_brightcove_url(cls, webpage):
99877772 131 """Try to extract the brightcove url from the webpage, returns None
eeb165e6
JMF
132 if it can't be found
133 """
99877772
PH
134 urls = cls._extract_brightcove_urls(webpage)
135 return urls[0] if urls else None
136
137 @classmethod
138 def _extract_brightcove_urls(cls, webpage):
139 """Return a list of all Brightcove URLs from the webpage """
117bec93
PH
140
141 url_m = re.search(r'<meta\s+property="og:video"\s+content="(http://c.brightcove.com/[^"]+)"', webpage)
142 if url_m:
381640e3
JMF
143 url = unescapeHTML(url_m.group(1))
144 # Some sites don't add it, we can't download with this url, for example:
145 # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
146 if 'playerKey' in url:
147 return [url]
117bec93 148
99877772 149 matches = re.findall(
7b0817e8
PH
150 r'''(?sx)<object
151 (?:
99877772 152 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
7b0817e8
PH
153 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
154 ).+?</object>''',
155 webpage)
99877772 156 return [cls._build_brighcove_url(m) for m in matches]
eeb165e6 157
fbaaad49 158 def _real_extract(self, url):
79f82953
PH
159 url, smuggled_data = unsmuggle_url(url, {})
160
51040b72
JMF
161 # Change the 'videoId' and others field to '@videoPlayer'
162 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
163 # Change bckey (used by bcove.me urls) to playerKey
164 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
fbaaad49 165 mobj = re.match(self._VALID_URL, url)
6543f0dc
JMF
166 query_str = mobj.group('query')
167 query = compat_urlparse.parse_qs(query_str)
fbaaad49 168
6543f0dc
JMF
169 videoPlayer = query.get('@videoPlayer')
170 if videoPlayer:
79f82953
PH
171 # We set the original url as the default 'Referer' header
172 referer = smuggled_data.get('Referer', url)
173 return self._get_video_info(
174 videoPlayer[0], query_str, query, referer=referer)
abb285fb 175 else:
6543f0dc
JMF
176 player_key = query['playerKey']
177 return self._get_playlist_info(player_key[0])
abb285fb 178
77526143 179 def _get_video_info(self, video_id, query_str, query, referer=None):
dd5bcdc4
JMF
180 request_url = self._FEDERATED_URL_TEMPLATE % query_str
181 req = compat_urllib_request.Request(request_url)
182 linkBase = query.get('linkBaseURL')
183 if linkBase is not None:
77526143
JMF
184 referer = linkBase[0]
185 if referer is not None:
186 req.add_header('Referer', referer)
dd5bcdc4 187 webpage = self._download_webpage(req, video_id)
fbaaad49
JMF
188
189 self.report_extraction(video_id)
190 info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
191 info = json.loads(info)['data']
192 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
7b0817e8 193 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
abb285fb
JMF
194
195 return self._extract_video_info(video_info)
196
197 def _get_playlist_info(self, player_key):
117bec93
PH
198 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
199 playlist_info = self._download_webpage(
200 info_url, player_key, 'Downloading playlist information')
abb285fb 201
59145479
PH
202 json_data = json.loads(playlist_info)
203 if 'videoList' not in json_data:
400e5810 204 raise ExtractorError('Empty playlist')
59145479 205 playlist_info = json_data['videoList']
abb285fb
JMF
206 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
207
208 return self.playlist_result(videos, playlist_id=playlist_info['id'],
209 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
210
211 def _extract_video_info(self, video_info):
592882aa 212 info = {
eeb165e6 213 'id': compat_str(video_info['id']),
066f6a06 214 'title': video_info['displayName'].strip(),
592882aa
JMF
215 'description': video_info.get('shortDescription'),
216 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
217 'uploader': video_info.get('publisherName'),
218 }
abb285fb 219
592882aa
JMF
220 renditions = video_info.get('renditions')
221 if renditions:
222 renditions = sorted(renditions, key=lambda r: r['size'])
b0759f0c
JMF
223 info['formats'] = [{
224 'url': rend['defaultURL'],
225 'height': rend.get('frameHeight'),
226 'width': rend.get('frameWidth'),
227 } for rend in renditions]
592882aa
JMF
228 elif video_info.get('FLVFullLengthURL') is not None:
229 info.update({
230 'url': video_info['FLVFullLengthURL'],
592882aa 231 })
7b0817e8
PH
232
233 if self._downloader.params.get('include_ads', False):
234 adServerURL = video_info.get('_youtubedl_adServerURL')
235 if adServerURL:
236 ad_info = {
237 '_type': 'url',
238 'url': adServerURL,
239 }
240 if 'url' in info:
241 return {
242 '_type': 'playlist',
243 'title': info['title'],
244 'entries': [ad_info, info],
245 }
246 else:
247 return ad_info
248
d614aa40 249 if 'url' not in info and not info.get('formats'):
400e5810 250 raise ExtractorError('Unable to extract video url for %s' % info['id'])
592882aa 251 return info