]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/brightcove.py
Imported Upstream version 2014.02.17
[youtubedl] / 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 ExtractorError,
19 unsmuggle_url,
20 unescapeHTML,
21 )
22
23
24 class BrightcoveIE(InfoExtractor):
25 _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
26 _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
27
28 _TESTS = [
29 {
30 # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
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',
39 }
40 },
41 {
42 # From http://medianetwork.oracle.com/video/player/1785452137001
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',
49 },
50 },
51 {
52 # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
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',
60 },
61 },
62 {
63 # test that the default referer works
64 # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
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',
72 },
73 }
74 ]
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 """
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)
86 # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
87 object_str = object_str.replace('<--', '<!--')
88 object_str = fix_xml_ampersands(object_str)
89
90 object_doc = xml.etree.ElementTree.fromstring(object_str)
91
92 fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
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 = {}
99
100 def find_param(name):
101 if name in flashvars:
102 return flashvars[name]
103 node = find_xpath_attr(object_doc, './param', 'name', name)
104 if node is not None:
105 return node.attrib['value']
106 return None
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
115 playerKey = find_param('playerKey')
116 # Not all pages define this value
117 if playerKey is not None:
118 params['playerKey'] = playerKey
119 # The three fields hold the id of the video
120 videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID')
121 if videoPlayer is not None:
122 params['@videoPlayer'] = videoPlayer
123 linkBase = find_param('linkBaseURL')
124 if linkBase is not None:
125 params['linkBaseURL'] = linkBase
126 data = compat_urllib_parse.urlencode(params)
127 return cls._FEDERATED_URL_TEMPLATE % data
128
129 @classmethod
130 def _extract_brightcove_url(cls, webpage):
131 """Try to extract the brightcove url from the webpage, returns None
132 if it can't be found
133 """
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 """
140
141 url_m = re.search(r'<meta\s+property="og:video"\s+content="(http://c.brightcove.com/[^"]+)"', webpage)
142 if url_m:
143 return [unescapeHTML(url_m.group(1))]
144
145 matches = re.findall(
146 r'''(?sx)<object
147 (?:
148 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
149 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
150 ).+?</object>''',
151 webpage)
152 return [cls._build_brighcove_url(m) for m in matches]
153
154 def _real_extract(self, url):
155 url, smuggled_data = unsmuggle_url(url, {})
156
157 # Change the 'videoId' and others field to '@videoPlayer'
158 url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
159 # Change bckey (used by bcove.me urls) to playerKey
160 url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
161 mobj = re.match(self._VALID_URL, url)
162 query_str = mobj.group('query')
163 query = compat_urlparse.parse_qs(query_str)
164
165 videoPlayer = query.get('@videoPlayer')
166 if videoPlayer:
167 # We set the original url as the default 'Referer' header
168 referer = smuggled_data.get('Referer', url)
169 return self._get_video_info(
170 videoPlayer[0], query_str, query, referer=referer)
171 else:
172 player_key = query['playerKey']
173 return self._get_playlist_info(player_key[0])
174
175 def _get_video_info(self, video_id, query_str, query, referer=None):
176 request_url = self._FEDERATED_URL_TEMPLATE % query_str
177 req = compat_urllib_request.Request(request_url)
178 linkBase = query.get('linkBaseURL')
179 if linkBase is not None:
180 referer = linkBase[0]
181 if referer is not None:
182 req.add_header('Referer', referer)
183 webpage = self._download_webpage(req, video_id)
184
185 self.report_extraction(video_id)
186 info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
187 info = json.loads(info)['data']
188 video_info = info['programmedContent']['videoPlayer']['mediaDTO']
189 video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
190
191 return self._extract_video_info(video_info)
192
193 def _get_playlist_info(self, player_key):
194 info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
195 playlist_info = self._download_webpage(
196 info_url, player_key, 'Downloading playlist information')
197
198 json_data = json.loads(playlist_info)
199 if 'videoList' not in json_data:
200 raise ExtractorError('Empty playlist')
201 playlist_info = json_data['videoList']
202 videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
203
204 return self.playlist_result(videos, playlist_id=playlist_info['id'],
205 playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
206
207 def _extract_video_info(self, video_info):
208 info = {
209 'id': compat_str(video_info['id']),
210 'title': video_info['displayName'].strip(),
211 'description': video_info.get('shortDescription'),
212 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
213 'uploader': video_info.get('publisherName'),
214 }
215
216 renditions = video_info.get('renditions')
217 if renditions:
218 renditions = sorted(renditions, key=lambda r: r['size'])
219 info['formats'] = [{
220 'url': rend['defaultURL'],
221 'height': rend.get('frameHeight'),
222 'width': rend.get('frameWidth'),
223 } for rend in renditions]
224 elif video_info.get('FLVFullLengthURL') is not None:
225 info.update({
226 'url': video_info['FLVFullLengthURL'],
227 })
228
229 if self._downloader.params.get('include_ads', False):
230 adServerURL = video_info.get('_youtubedl_adServerURL')
231 if adServerURL:
232 ad_info = {
233 '_type': 'url',
234 'url': adServerURL,
235 }
236 if 'url' in info:
237 return {
238 '_type': 'playlist',
239 'title': info['title'],
240 'entries': [ad_info, info],
241 }
242 else:
243 return ad_info
244
245 if 'url' not in info and not info.get('formats'):
246 raise ExtractorError('Unable to extract video url for %s' % info['id'])
247 return info