]>
Commit | Line | Data |
---|---|---|
1 | import base64 | |
2 | import re | |
3 | import struct | |
4 | import xml.etree.ElementTree | |
5 | ||
6 | from .adobepass import AdobePassIE | |
7 | from .common import InfoExtractor | |
8 | from ..compat import ( | |
9 | compat_etree_fromstring, | |
10 | compat_HTTPError, | |
11 | compat_parse_qs, | |
12 | compat_urlparse, | |
13 | ) | |
14 | from ..utils import ( | |
15 | clean_html, | |
16 | dict_get, | |
17 | extract_attributes, | |
18 | ExtractorError, | |
19 | find_xpath_attr, | |
20 | fix_xml_ampersands, | |
21 | float_or_none, | |
22 | int_or_none, | |
23 | js_to_json, | |
24 | mimetype2ext, | |
25 | parse_iso8601, | |
26 | parse_qs, | |
27 | smuggle_url, | |
28 | str_or_none, | |
29 | try_get, | |
30 | unescapeHTML, | |
31 | unsmuggle_url, | |
32 | UnsupportedError, | |
33 | update_url_query, | |
34 | url_or_none, | |
35 | ) | |
36 | ||
37 | ||
38 | class BrightcoveLegacyIE(InfoExtractor): | |
39 | IE_NAME = 'brightcove:legacy' | |
40 | _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)' | |
41 | ||
42 | _TESTS = [ | |
43 | { | |
44 | # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/ | |
45 | 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001', | |
46 | 'md5': '5423e113865d26e40624dce2e4b45d95', | |
47 | 'note': 'Test Brightcove downloads and detection in GenericIE', | |
48 | 'info_dict': { | |
49 | 'id': '2371591881001', | |
50 | 'ext': 'mp4', | |
51 | 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”', | |
52 | 'uploader': '8TV', | |
53 | 'description': 'md5:a950cc4285c43e44d763d036710cd9cd', | |
54 | 'timestamp': 1368213670, | |
55 | 'upload_date': '20130510', | |
56 | 'uploader_id': '1589608506001', | |
57 | }, | |
58 | 'skip': 'The player has been deactivated by the content owner', | |
59 | }, | |
60 | { | |
61 | # From http://medianetwork.oracle.com/video/player/1785452137001 | |
62 | 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001', | |
63 | 'info_dict': { | |
64 | 'id': '1785452137001', | |
65 | 'ext': 'flv', | |
66 | 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges', | |
67 | 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.', | |
68 | 'uploader': 'Oracle', | |
69 | 'timestamp': 1344975024, | |
70 | 'upload_date': '20120814', | |
71 | 'uploader_id': '1460825906', | |
72 | }, | |
73 | 'skip': 'video not playable', | |
74 | }, | |
75 | { | |
76 | # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/ | |
77 | 'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001', | |
78 | 'info_dict': { | |
79 | 'id': '2750934548001', | |
80 | 'ext': 'mp4', | |
81 | 'title': 'This Bracelet Acts as a Personal Thermostat', | |
82 | 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0', | |
83 | # 'uploader': 'Mashable', | |
84 | 'timestamp': 1382041798, | |
85 | 'upload_date': '20131017', | |
86 | 'uploader_id': '1130468786001', | |
87 | }, | |
88 | }, | |
89 | { | |
90 | # test that the default referer works | |
91 | # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/ | |
92 | 'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001', | |
93 | 'info_dict': { | |
94 | 'id': '2878862109001', | |
95 | 'ext': 'mp4', | |
96 | 'title': 'Lost in Motion II', | |
97 | 'description': 'md5:363109c02998fee92ec02211bd8000df', | |
98 | 'uploader': 'National Ballet of Canada', | |
99 | }, | |
100 | 'skip': 'Video gone', | |
101 | }, | |
102 | { | |
103 | # test flv videos served by akamaihd.net | |
104 | # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william | |
105 | 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?%40videoPlayer=ref%3Aevent-stream-356&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', | |
106 | # The md5 checksum changes on each download | |
107 | 'info_dict': { | |
108 | 'id': '3750436379001', | |
109 | 'ext': 'flv', | |
110 | 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals', | |
111 | 'uploader': 'RBTV Old (do not use)', | |
112 | 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals', | |
113 | 'timestamp': 1409122195, | |
114 | 'upload_date': '20140827', | |
115 | 'uploader_id': '710858724001', | |
116 | }, | |
117 | 'skip': 'Video gone', | |
118 | }, | |
119 | { | |
120 | # playlist with 'videoList' | |
121 | # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players | |
122 | 'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL', | |
123 | 'info_dict': { | |
124 | 'title': 'Sealife', | |
125 | 'id': '3550319591001', | |
126 | }, | |
127 | 'playlist_mincount': 7, | |
128 | 'skip': 'Unsupported URL', | |
129 | }, | |
130 | { | |
131 | # playlist with 'playlistTab' (https://github.com/ytdl-org/youtube-dl/issues/9965) | |
132 | 'url': 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=AQ%7E%7E,AAABXlLMdok%7E,NJ4EoMlZ4rZdx9eU1rkMVd8EaYPBBUlg', | |
133 | 'info_dict': { | |
134 | 'id': '1522758701001', | |
135 | 'title': 'Lesson 08', | |
136 | }, | |
137 | 'playlist_mincount': 10, | |
138 | 'skip': 'Unsupported URL', | |
139 | }, | |
140 | { | |
141 | # playerID inferred from bcpid | |
142 | # from http://www.un.org/chinese/News/story.asp?NewsID=27724 | |
143 | 'url': 'https://link.brightcove.com/services/player/bcpid1722935254001/?bctid=5360463607001&autoStart=false&secureConnections=true&width=650&height=350', | |
144 | 'only_matching': True, # Tested in GenericIE | |
145 | } | |
146 | ] | |
147 | ||
148 | @classmethod | |
149 | def _build_brightcove_url(cls, object_str): | |
150 | """ | |
151 | Build a Brightcove url from a xml string containing | |
152 | <object class="BrightcoveExperience">{params}</object> | |
153 | """ | |
154 | ||
155 | # Fix up some stupid HTML, see https://github.com/ytdl-org/youtube-dl/issues/1553 | |
156 | object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>', | |
157 | lambda m: m.group(1) + '/>', object_str) | |
158 | # Fix up some stupid XML, see https://github.com/ytdl-org/youtube-dl/issues/1608 | |
159 | object_str = object_str.replace('<--', '<!--') | |
160 | # remove namespace to simplify extraction | |
161 | object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str) | |
162 | object_str = fix_xml_ampersands(object_str) | |
163 | ||
164 | try: | |
165 | object_doc = compat_etree_fromstring(object_str.encode('utf-8')) | |
166 | except xml.etree.ElementTree.ParseError: | |
167 | return | |
168 | ||
169 | fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars') | |
170 | if fv_el is not None: | |
171 | flashvars = dict( | |
172 | (k, v[0]) | |
173 | for k, v in compat_parse_qs(fv_el.attrib['value']).items()) | |
174 | else: | |
175 | flashvars = {} | |
176 | ||
177 | data_url = object_doc.attrib.get('data', '') | |
178 | data_url_params = parse_qs(data_url) | |
179 | ||
180 | def find_param(name): | |
181 | if name in flashvars: | |
182 | return flashvars[name] | |
183 | node = find_xpath_attr(object_doc, './param', 'name', name) | |
184 | if node is not None: | |
185 | return node.attrib['value'] | |
186 | return data_url_params.get(name) | |
187 | ||
188 | params = {} | |
189 | ||
190 | playerID = find_param('playerID') or find_param('playerId') | |
191 | if playerID is None: | |
192 | raise ExtractorError('Cannot find player ID') | |
193 | params['playerID'] = playerID | |
194 | ||
195 | playerKey = find_param('playerKey') | |
196 | # Not all pages define this value | |
197 | if playerKey is not None: | |
198 | params['playerKey'] = playerKey | |
199 | # These fields hold the id of the video | |
200 | videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList') | |
201 | if videoPlayer is not None: | |
202 | if isinstance(videoPlayer, list): | |
203 | videoPlayer = videoPlayer[0] | |
204 | videoPlayer = videoPlayer.strip() | |
205 | # UUID is also possible for videoPlayer (e.g. | |
206 | # http://www.popcornflix.com/hoodies-vs-hooligans/7f2d2b87-bbf2-4623-acfb-ea942b4f01dd | |
207 | # or http://www8.hp.com/cn/zh/home.html) | |
208 | if not (re.match( | |
209 | r'^(?:\d+|[\da-fA-F]{8}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{4}-?[\da-fA-F]{12})$', | |
210 | videoPlayer) or videoPlayer.startswith('ref:')): | |
211 | return None | |
212 | params['@videoPlayer'] = videoPlayer | |
213 | linkBase = find_param('linkBaseURL') | |
214 | if linkBase is not None: | |
215 | params['linkBaseURL'] = linkBase | |
216 | return cls._make_brightcove_url(params) | |
217 | ||
218 | @classmethod | |
219 | def _build_brightcove_url_from_js(cls, object_js): | |
220 | # The layout of JS is as follows: | |
221 | # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) { | |
222 | # // build Brightcove <object /> XML | |
223 | # } | |
224 | m = re.search( | |
225 | r'''(?x)customBC\.createVideo\( | |
226 | .*? # skipping width and height | |
227 | ["\'](?P<playerID>\d+)["\']\s*,\s* # playerID | |
228 | ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s* # playerKey begins with AQ and is 50 characters | |
229 | # in length, however it's appended to itself | |
230 | # in places, so truncate | |
231 | ["\'](?P<videoID>\d+)["\'] # @videoPlayer | |
232 | ''', object_js) | |
233 | if m: | |
234 | return cls._make_brightcove_url(m.groupdict()) | |
235 | ||
236 | @classmethod | |
237 | def _make_brightcove_url(cls, params): | |
238 | return update_url_query( | |
239 | 'http://c.brightcove.com/services/viewer/htmlFederated', params) | |
240 | ||
241 | @classmethod | |
242 | def _extract_brightcove_url(cls, webpage): | |
243 | """Try to extract the brightcove url from the webpage, returns None | |
244 | if it can't be found | |
245 | """ | |
246 | urls = cls._extract_brightcove_urls(webpage) | |
247 | return urls[0] if urls else None | |
248 | ||
249 | @classmethod | |
250 | def _extract_brightcove_urls(cls, webpage): | |
251 | """Return a list of all Brightcove URLs from the webpage """ | |
252 | ||
253 | url_m = re.search( | |
254 | r'''(?x) | |
255 | <meta\s+ | |
256 | (?:property|itemprop)=([\'"])(?:og:video|embedURL)\1[^>]+ | |
257 | content=([\'"])(?P<url>https?://(?:secure|c)\.brightcove.com/(?:(?!\2).)+)\2 | |
258 | ''', webpage) | |
259 | if url_m: | |
260 | url = unescapeHTML(url_m.group('url')) | |
261 | # Some sites don't add it, we can't download with this url, for example: | |
262 | # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/ | |
263 | if 'playerKey' in url or 'videoId' in url or 'idVideo' in url: | |
264 | return [url] | |
265 | ||
266 | matches = re.findall( | |
267 | r'''(?sx)<object | |
268 | (?: | |
269 | [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] | | |
270 | [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/ | |
271 | ).+?>\s*</object>''', | |
272 | webpage) | |
273 | if matches: | |
274 | return list(filter(None, [cls._build_brightcove_url(m) for m in matches])) | |
275 | ||
276 | matches = re.findall(r'(customBC\.createVideo\(.+?\);)', webpage) | |
277 | if matches: | |
278 | return list(filter(None, [ | |
279 | cls._build_brightcove_url_from_js(custom_bc) | |
280 | for custom_bc in matches])) | |
281 | return [src for _, src in re.findall( | |
282 | r'<iframe[^>]+src=([\'"])((?:https?:)?//link\.brightcove\.com/services/player/(?!\1).+)\1', webpage)] | |
283 | ||
284 | def _real_extract(self, url): | |
285 | url, smuggled_data = unsmuggle_url(url, {}) | |
286 | ||
287 | # Change the 'videoId' and others field to '@videoPlayer' | |
288 | url = re.sub(r'(?<=[?&])(videoI(d|D)|idVideo|bctid)', '%40videoPlayer', url) | |
289 | # Change bckey (used by bcove.me urls) to playerKey | |
290 | url = re.sub(r'(?<=[?&])bckey', 'playerKey', url) | |
291 | mobj = self._match_valid_url(url) | |
292 | query_str = mobj.group('query') | |
293 | query = compat_urlparse.parse_qs(query_str) | |
294 | ||
295 | videoPlayer = query.get('@videoPlayer') | |
296 | if videoPlayer: | |
297 | # We set the original url as the default 'Referer' header | |
298 | referer = query.get('linkBaseURL', [None])[0] or smuggled_data.get('Referer', url) | |
299 | video_id = videoPlayer[0] | |
300 | if 'playerID' not in query: | |
301 | mobj = re.search(r'/bcpid(\d+)', url) | |
302 | if mobj is not None: | |
303 | query['playerID'] = [mobj.group(1)] | |
304 | publisher_id = query.get('publisherId') | |
305 | if publisher_id and publisher_id[0].isdigit(): | |
306 | publisher_id = publisher_id[0] | |
307 | if not publisher_id: | |
308 | player_key = query.get('playerKey') | |
309 | if player_key and ',' in player_key[0]: | |
310 | player_key = player_key[0] | |
311 | else: | |
312 | player_id = query.get('playerID') | |
313 | if player_id and player_id[0].isdigit(): | |
314 | headers = {} | |
315 | if referer: | |
316 | headers['Referer'] = referer | |
317 | player_page = self._download_webpage( | |
318 | 'http://link.brightcove.com/services/player/bcpid' + player_id[0], | |
319 | video_id, headers=headers, fatal=False) | |
320 | if player_page: | |
321 | player_key = self._search_regex( | |
322 | r'<param\s+name="playerKey"\s+value="([\w~,-]+)"', | |
323 | player_page, 'player key', fatal=False) | |
324 | if player_key: | |
325 | enc_pub_id = player_key.split(',')[1].replace('~', '=') | |
326 | publisher_id = struct.unpack('>Q', base64.urlsafe_b64decode(enc_pub_id))[0] | |
327 | if publisher_id: | |
328 | brightcove_new_url = 'http://players.brightcove.net/%s/default_default/index.html?videoId=%s' % (publisher_id, video_id) | |
329 | if referer: | |
330 | brightcove_new_url = smuggle_url(brightcove_new_url, {'referrer': referer}) | |
331 | return self.url_result(brightcove_new_url, BrightcoveNewIE.ie_key(), video_id) | |
332 | # TODO: figure out if it's possible to extract playlistId from playerKey | |
333 | # elif 'playerKey' in query: | |
334 | # player_key = query['playerKey'] | |
335 | # return self._get_playlist_info(player_key[0]) | |
336 | raise UnsupportedError(url) | |
337 | ||
338 | ||
339 | class BrightcoveNewIE(AdobePassIE): | |
340 | IE_NAME = 'brightcove:new' | |
341 | _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*(?P<content_type>video|playlist)Id=(?P<video_id>\d+|ref:[^&]+)' | |
342 | _TESTS = [{ | |
343 | 'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001', | |
344 | 'md5': 'c8100925723840d4b0d243f7025703be', | |
345 | 'info_dict': { | |
346 | 'id': '4463358922001', | |
347 | 'ext': 'mp4', | |
348 | 'title': 'Meet the man behind Popcorn Time', | |
349 | 'description': 'md5:eac376a4fe366edc70279bfb681aea16', | |
350 | 'duration': 165.768, | |
351 | 'timestamp': 1441391203, | |
352 | 'upload_date': '20150904', | |
353 | 'uploader_id': '929656772001', | |
354 | 'formats': 'mincount:20', | |
355 | }, | |
356 | }, { | |
357 | # with rtmp streams | |
358 | 'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001', | |
359 | 'info_dict': { | |
360 | 'id': '4279049078001', | |
361 | 'ext': 'mp4', | |
362 | 'title': 'Titansgrave: Chapter 0', | |
363 | 'description': 'Titansgrave: Chapter 0', | |
364 | 'duration': 1242.058, | |
365 | 'timestamp': 1433556729, | |
366 | 'upload_date': '20150606', | |
367 | 'uploader_id': '4036320279001', | |
368 | 'formats': 'mincount:39', | |
369 | }, | |
370 | 'params': { | |
371 | # m3u8 download | |
372 | 'skip_download': True, | |
373 | } | |
374 | }, { | |
375 | # playlist stream | |
376 | 'url': 'https://players.brightcove.net/1752604059001/S13cJdUBz_default/index.html?playlistId=5718313430001', | |
377 | 'info_dict': { | |
378 | 'id': '5718313430001', | |
379 | 'title': 'No Audio Playlist', | |
380 | }, | |
381 | 'playlist_count': 7, | |
382 | 'params': { | |
383 | # m3u8 download | |
384 | 'skip_download': True, | |
385 | } | |
386 | }, { | |
387 | 'url': 'http://players.brightcove.net/5690807595001/HyZNerRl7_default/index.html?playlistId=5743160747001', | |
388 | 'only_matching': True, | |
389 | }, { | |
390 | # ref: prefixed video id | |
391 | 'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442', | |
392 | 'only_matching': True, | |
393 | }, { | |
394 | # non numeric ref: prefixed video id | |
395 | 'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356', | |
396 | 'only_matching': True, | |
397 | }, { | |
398 | # unavailable video without message but with error_code | |
399 | 'url': 'http://players.brightcove.net/1305187701/c832abfb-641b-44eb-9da0-2fe76786505f_default/index.html?videoId=4377407326001', | |
400 | 'only_matching': True, | |
401 | }] | |
402 | ||
403 | @staticmethod | |
404 | def _extract_url(ie, webpage): | |
405 | urls = BrightcoveNewIE._extract_brightcove_urls(ie, webpage) | |
406 | return urls[0] if urls else None | |
407 | ||
408 | @staticmethod | |
409 | def _extract_brightcove_urls(ie, webpage): | |
410 | # Reference: | |
411 | # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe | |
412 | # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#tag | |
413 | # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript | |
414 | # 4. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/in-page-embed-player-implementation.html | |
415 | # 5. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player | |
416 | ||
417 | entries = [] | |
418 | ||
419 | # Look for iframe embeds [1] | |
420 | for _, url in re.findall( | |
421 | r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage): | |
422 | entries.append(url if url.startswith('http') else 'http:' + url) | |
423 | ||
424 | # Look for <video> tags [2] and embed_in_page embeds [3] | |
425 | # [2] looks like: | |
426 | for video, script_tag, account_id, player_id, embed in re.findall( | |
427 | r'''(?isx) | |
428 | (<video(?:-js)?\s+[^>]*\bdata-video-id\s*=\s*['"]?[^>]+>) | |
429 | (?:.*? | |
430 | (<script[^>]+ | |
431 | src=["\'](?:https?:)?//players\.brightcove\.net/ | |
432 | (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js | |
433 | ) | |
434 | )? | |
435 | ''', webpage): | |
436 | attrs = extract_attributes(video) | |
437 | ||
438 | # According to examples from [4] it's unclear whether video id | |
439 | # may be optional and what to do when it is | |
440 | video_id = attrs.get('data-video-id') | |
441 | if not video_id: | |
442 | continue | |
443 | ||
444 | account_id = account_id or attrs.get('data-account') | |
445 | if not account_id: | |
446 | continue | |
447 | ||
448 | player_id = player_id or attrs.get('data-player') or 'default' | |
449 | embed = embed or attrs.get('data-embed') or 'default' | |
450 | ||
451 | bc_url = 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s' % ( | |
452 | account_id, player_id, embed, video_id) | |
453 | ||
454 | # Some brightcove videos may be embedded with video tag only and | |
455 | # without script tag or any mentioning of brightcove at all. Such | |
456 | # embeds are considered ambiguous since they are matched based only | |
457 | # on data-video-id and data-account attributes and in the wild may | |
458 | # not be brightcove embeds at all. Let's check reconstructed | |
459 | # brightcove URLs in case of such embeds and only process valid | |
460 | # ones. By this we ensure there is indeed a brightcove embed. | |
461 | if not script_tag and not ie._is_valid_url( | |
462 | bc_url, video_id, 'possible brightcove video'): | |
463 | continue | |
464 | ||
465 | entries.append(bc_url) | |
466 | ||
467 | return entries | |
468 | ||
469 | def _parse_brightcove_metadata(self, json_data, video_id, headers={}): | |
470 | title = json_data['name'].strip() | |
471 | ||
472 | formats, subtitles = [], {} | |
473 | sources = json_data.get('sources') or [] | |
474 | for source in sources: | |
475 | container = source.get('container') | |
476 | ext = mimetype2ext(source.get('type')) | |
477 | src = source.get('src') | |
478 | if ext == 'm3u8' or container == 'M2TS': | |
479 | if not src: | |
480 | continue | |
481 | fmts, subs = self._extract_m3u8_formats_and_subtitles( | |
482 | src, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False) | |
483 | subtitles = self._merge_subtitles(subtitles, subs) | |
484 | elif ext == 'mpd': | |
485 | if not src: | |
486 | continue | |
487 | fmts, subs = self._extract_mpd_formats_and_subtitles(src, video_id, 'dash', fatal=False) | |
488 | subtitles = self._merge_subtitles(subtitles, subs) | |
489 | else: | |
490 | streaming_src = source.get('streaming_src') | |
491 | stream_name, app_name = source.get('stream_name'), source.get('app_name') | |
492 | if not src and not streaming_src and (not stream_name or not app_name): | |
493 | continue | |
494 | tbr = float_or_none(source.get('avg_bitrate'), 1000) | |
495 | height = int_or_none(source.get('height')) | |
496 | width = int_or_none(source.get('width')) | |
497 | f = { | |
498 | 'tbr': tbr, | |
499 | 'filesize': int_or_none(source.get('size')), | |
500 | 'container': container, | |
501 | 'ext': ext or container.lower(), | |
502 | } | |
503 | if width == 0 and height == 0: | |
504 | f.update({ | |
505 | 'vcodec': 'none', | |
506 | }) | |
507 | else: | |
508 | f.update({ | |
509 | 'width': width, | |
510 | 'height': height, | |
511 | 'vcodec': source.get('codec'), | |
512 | }) | |
513 | ||
514 | def build_format_id(kind): | |
515 | format_id = kind | |
516 | if tbr: | |
517 | format_id += '-%dk' % int(tbr) | |
518 | if height: | |
519 | format_id += '-%dp' % height | |
520 | return format_id | |
521 | ||
522 | if src or streaming_src: | |
523 | f.update({ | |
524 | 'url': src or streaming_src, | |
525 | 'format_id': build_format_id('http' if src else 'http-streaming'), | |
526 | 'source_preference': 0 if src else -1, | |
527 | }) | |
528 | else: | |
529 | f.update({ | |
530 | 'url': app_name, | |
531 | 'play_path': stream_name, | |
532 | 'format_id': build_format_id('rtmp'), | |
533 | }) | |
534 | fmts = [f] | |
535 | ||
536 | # https://support.brightcove.com/playback-api-video-fields-reference#key_systems_object | |
537 | if container == 'WVM' or source.get('key_systems') or ext == 'ism': | |
538 | for f in fmts: | |
539 | f['has_drm'] = True | |
540 | formats.extend(fmts) | |
541 | ||
542 | if not formats: | |
543 | errors = json_data.get('errors') | |
544 | if errors: | |
545 | error = errors[0] | |
546 | self.raise_no_formats( | |
547 | error.get('message') or error.get('error_subcode') or error['error_code'], expected=True) | |
548 | ||
549 | for f in formats: | |
550 | f.setdefault('http_headers', {}).update(headers) | |
551 | ||
552 | for text_track in json_data.get('text_tracks', []): | |
553 | if text_track.get('kind') != 'captions': | |
554 | continue | |
555 | text_track_url = url_or_none(text_track.get('src')) | |
556 | if not text_track_url: | |
557 | continue | |
558 | lang = (str_or_none(text_track.get('srclang')) | |
559 | or str_or_none(text_track.get('label')) or 'en').lower() | |
560 | subtitles.setdefault(lang, []).append({ | |
561 | 'url': text_track_url, | |
562 | }) | |
563 | ||
564 | is_live = False | |
565 | duration = float_or_none(json_data.get('duration'), 1000) | |
566 | if duration is not None and duration <= 0: | |
567 | is_live = True | |
568 | ||
569 | common_res = [(160, 90), (320, 180), (480, 720), (640, 360), (768, 432), (1024, 576), (1280, 720), (1366, 768), (1920, 1080)] | |
570 | thumb_base_url = dict_get(json_data, ('poster', 'thumbnail')) | |
571 | thumbnails = [{ | |
572 | 'url': re.sub(r'\d+x\d+', f'{w}x{h}', thumb_base_url), | |
573 | 'width': w, | |
574 | 'height': h, | |
575 | } for w, h in common_res] if thumb_base_url else None | |
576 | ||
577 | return { | |
578 | 'id': video_id, | |
579 | 'title': title, | |
580 | 'description': clean_html(json_data.get('description')), | |
581 | 'thumbnails': thumbnails, | |
582 | 'duration': duration, | |
583 | 'timestamp': parse_iso8601(json_data.get('published_at')), | |
584 | 'uploader_id': json_data.get('account_id'), | |
585 | 'formats': formats, | |
586 | 'subtitles': subtitles, | |
587 | 'tags': json_data.get('tags', []), | |
588 | 'is_live': is_live, | |
589 | } | |
590 | ||
591 | def _real_extract(self, url): | |
592 | url, smuggled_data = unsmuggle_url(url, {}) | |
593 | self._initialize_geo_bypass({ | |
594 | 'countries': smuggled_data.get('geo_countries'), | |
595 | 'ip_blocks': smuggled_data.get('geo_ip_blocks'), | |
596 | }) | |
597 | ||
598 | account_id, player_id, embed, content_type, video_id = self._match_valid_url(url).groups() | |
599 | ||
600 | policy_key_id = '%s_%s' % (account_id, player_id) | |
601 | policy_key = self.cache.load('brightcove', policy_key_id) | |
602 | policy_key_extracted = False | |
603 | store_pk = lambda x: self.cache.store('brightcove', policy_key_id, x) | |
604 | ||
605 | def extract_policy_key(): | |
606 | base_url = 'http://players.brightcove.net/%s/%s_%s/' % (account_id, player_id, embed) | |
607 | config = self._download_json( | |
608 | base_url + 'config.json', video_id, fatal=False) or {} | |
609 | policy_key = try_get( | |
610 | config, lambda x: x['video_cloud']['policy_key']) | |
611 | if not policy_key: | |
612 | webpage = self._download_webpage( | |
613 | base_url + 'index.min.js', video_id) | |
614 | ||
615 | catalog = self._search_regex( | |
616 | r'catalog\(({.+?})\);', webpage, 'catalog', default=None) | |
617 | if catalog: | |
618 | catalog = self._parse_json( | |
619 | js_to_json(catalog), video_id, fatal=False) | |
620 | if catalog: | |
621 | policy_key = catalog.get('policyKey') | |
622 | ||
623 | if not policy_key: | |
624 | policy_key = self._search_regex( | |
625 | r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1', | |
626 | webpage, 'policy key', group='pk') | |
627 | ||
628 | store_pk(policy_key) | |
629 | return policy_key | |
630 | ||
631 | api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/%ss/%s' % (account_id, content_type, video_id) | |
632 | headers = {} | |
633 | referrer = smuggled_data.get('referrer') | |
634 | if referrer: | |
635 | headers.update({ | |
636 | 'Referer': referrer, | |
637 | 'Origin': re.search(r'https?://[^/]+', referrer).group(0), | |
638 | }) | |
639 | ||
640 | for _ in range(2): | |
641 | if not policy_key: | |
642 | policy_key = extract_policy_key() | |
643 | policy_key_extracted = True | |
644 | headers['Accept'] = 'application/json;pk=%s' % policy_key | |
645 | try: | |
646 | json_data = self._download_json(api_url, video_id, headers=headers) | |
647 | break | |
648 | except ExtractorError as e: | |
649 | if isinstance(e.cause, compat_HTTPError) and e.cause.code in (401, 403): | |
650 | json_data = self._parse_json(e.cause.read().decode(), video_id)[0] | |
651 | message = json_data.get('message') or json_data['error_code'] | |
652 | if json_data.get('error_subcode') == 'CLIENT_GEO': | |
653 | self.raise_geo_restricted(msg=message) | |
654 | elif json_data.get('error_code') == 'INVALID_POLICY_KEY' and not policy_key_extracted: | |
655 | policy_key = None | |
656 | store_pk(None) | |
657 | continue | |
658 | raise ExtractorError(message, expected=True) | |
659 | raise | |
660 | ||
661 | errors = json_data.get('errors') | |
662 | if errors and errors[0].get('error_subcode') == 'TVE_AUTH': | |
663 | custom_fields = json_data['custom_fields'] | |
664 | tve_token = self._extract_mvpd_auth( | |
665 | smuggled_data['source_url'], video_id, | |
666 | custom_fields['bcadobepassrequestorid'], | |
667 | custom_fields['bcadobepassresourceid']) | |
668 | json_data = self._download_json( | |
669 | api_url, video_id, headers={ | |
670 | 'Accept': 'application/json;pk=%s' % policy_key | |
671 | }, query={ | |
672 | 'tveToken': tve_token, | |
673 | }) | |
674 | ||
675 | if content_type == 'playlist': | |
676 | return self.playlist_result( | |
677 | [self._parse_brightcove_metadata(vid, vid.get('id'), headers) | |
678 | for vid in json_data.get('videos', []) if vid.get('id')], | |
679 | json_data.get('id'), json_data.get('name'), | |
680 | json_data.get('description')) | |
681 | ||
682 | return self._parse_brightcove_metadata( | |
683 | json_data, video_id, headers=headers) |