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