[brightcover] Remove unused import
[youtube-dl] / youtube_dl / extractor / brightcove.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_etree_fromstring,
10     compat_parse_qs,
11     compat_str,
12     compat_urllib_parse_urlparse,
13     compat_urlparse,
14     compat_xml_parse_error,
15     compat_HTTPError,
16 )
17 from ..utils import (
18     determine_ext,
19     ExtractorError,
20     find_xpath_attr,
21     fix_xml_ampersands,
22     float_or_none,
23     js_to_json,
24     int_or_none,
25     parse_iso8601,
26     unescapeHTML,
27     unsmuggle_url,
28     update_url_query,
29 )
30
31
32 class BrightcoveLegacyIE(InfoExtractor):
33     IE_NAME = 'brightcove:legacy'
34     _VALID_URL = r'(?:https?://.*brightcove\.com/(services|viewer).*?\?|brightcove:)(?P<query>.*)'
35     _FEDERATED_URL = 'http://c.brightcove.com/services/viewer/htmlFederated'
36
37     _TESTS = [
38         {
39             # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
40             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
41             'md5': '5423e113865d26e40624dce2e4b45d95',
42             'note': 'Test Brightcove downloads and detection in GenericIE',
43             'info_dict': {
44                 'id': '2371591881001',
45                 'ext': 'mp4',
46                 'title': 'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
47                 'uploader': '8TV',
48                 'description': 'md5:a950cc4285c43e44d763d036710cd9cd',
49             }
50         },
51         {
52             # From http://medianetwork.oracle.com/video/player/1785452137001
53             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
54             'info_dict': {
55                 'id': '1785452137001',
56                 'ext': 'flv',
57                 'title': 'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
58                 'description': 'John Rose speaks at the JVM Language Summit, August 1, 2012.',
59                 'uploader': 'Oracle',
60             },
61         },
62         {
63             # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
64             'url': 'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
65             'info_dict': {
66                 'id': '2750934548001',
67                 'ext': 'mp4',
68                 'title': 'This Bracelet Acts as a Personal Thermostat',
69                 'description': 'md5:547b78c64f4112766ccf4e151c20b6a0',
70                 'uploader': 'Mashable',
71             },
72         },
73         {
74             # test that the default referer works
75             # from http://national.ballet.ca/interact/video/Lost_in_Motion_II/
76             'url': 'http://link.brightcove.com/services/player/bcpid756015033001?bckey=AQ~~,AAAApYJi_Ck~,GxhXCegT1Dp39ilhXuxMJxasUhVNZiil&bctid=2878862109001',
77             'info_dict': {
78                 'id': '2878862109001',
79                 'ext': 'mp4',
80                 'title': 'Lost in Motion II',
81                 'description': 'md5:363109c02998fee92ec02211bd8000df',
82                 'uploader': 'National Ballet of Canada',
83             },
84         },
85         {
86             # test flv videos served by akamaihd.net
87             # From http://www.redbull.com/en/bike/stories/1331655643987/replay-uci-dh-world-cup-2014-from-fort-william
88             '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',
89             # The md5 checksum changes on each download
90             'info_dict': {
91                 'id': '2996102916001',
92                 'ext': 'flv',
93                 'title': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
94                 'uploader': 'Red Bull TV',
95                 'description': 'UCI MTB World Cup 2014: Fort William, UK - Downhill Finals',
96             },
97         },
98         {
99             # playlist test
100             # from http://support.brightcove.com/en/video-cloud/docs/playlist-support-single-video-players
101             'url': 'http://c.brightcove.com/services/viewer/htmlFederated?playerID=3550052898001&playerKey=AQ%7E%7E%2CAAABmA9XpXk%7E%2C-Kp7jNgisre1fG5OdqpAFUTcs0lP_ZoL',
102             'info_dict': {
103                 'title': 'Sealife',
104                 'id': '3550319591001',
105             },
106             'playlist_mincount': 7,
107         },
108     ]
109
110     @classmethod
111     def _build_brighcove_url(cls, object_str):
112         """
113         Build a Brightcove url from a xml string containing
114         <object class="BrightcoveExperience">{params}</object>
115         """
116
117         # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
118         object_str = re.sub(r'(<param(?:\s+[a-zA-Z0-9_]+="[^"]*")*)>',
119                             lambda m: m.group(1) + '/>', object_str)
120         # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
121         object_str = object_str.replace('<--', '<!--')
122         # remove namespace to simplify extraction
123         object_str = re.sub(r'(<object[^>]*)(xmlns=".*?")', r'\1', object_str)
124         object_str = fix_xml_ampersands(object_str)
125
126         try:
127             object_doc = compat_etree_fromstring(object_str.encode('utf-8'))
128         except compat_xml_parse_error:
129             return
130
131         fv_el = find_xpath_attr(object_doc, './param', 'name', 'flashVars')
132         if fv_el is not None:
133             flashvars = dict(
134                 (k, v[0])
135                 for k, v in compat_parse_qs(fv_el.attrib['value']).items())
136         else:
137             flashvars = {}
138
139         def find_param(name):
140             if name in flashvars:
141                 return flashvars[name]
142             node = find_xpath_attr(object_doc, './param', 'name', name)
143             if node is not None:
144                 return node.attrib['value']
145             return None
146
147         params = {}
148
149         playerID = find_param('playerID')
150         if playerID is None:
151             raise ExtractorError('Cannot find player ID')
152         params['playerID'] = playerID
153
154         playerKey = find_param('playerKey')
155         # Not all pages define this value
156         if playerKey is not None:
157             params['playerKey'] = playerKey
158         # These fields hold the id of the video
159         videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
160         if videoPlayer is not None:
161             params['@videoPlayer'] = videoPlayer
162         linkBase = find_param('linkBaseURL')
163         if linkBase is not None:
164             params['linkBaseURL'] = linkBase
165         return cls._make_brightcove_url(params)
166
167     @classmethod
168     def _build_brighcove_url_from_js(cls, object_js):
169         # The layout of JS is as follows:
170         # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
171         #   // build Brightcove <object /> XML
172         # }
173         m = re.search(
174             r'''(?x)customBC.\createVideo\(
175                 .*?                                                  # skipping width and height
176                 ["\'](?P<playerID>\d+)["\']\s*,\s*                   # playerID
177                 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s*  # playerKey begins with AQ and is 50 characters
178                                                                      # in length, however it's appended to itself
179                                                                      # in places, so truncate
180                 ["\'](?P<videoID>\d+)["\']                           # @videoPlayer
181             ''', object_js)
182         if m:
183             return cls._make_brightcove_url(m.groupdict())
184
185     @classmethod
186     def _make_brightcove_url(cls, params):
187         return update_url_query(cls._FEDERATED_URL, params)
188
189     @classmethod
190     def _extract_brightcove_url(cls, webpage):
191         """Try to extract the brightcove url from the webpage, returns None
192         if it can't be found
193         """
194         urls = cls._extract_brightcove_urls(webpage)
195         return urls[0] if urls else None
196
197     @classmethod
198     def _extract_brightcove_urls(cls, webpage):
199         """Return a list of all Brightcove URLs from the webpage """
200
201         url_m = re.search(
202             r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
203             webpage)
204         if url_m:
205             url = unescapeHTML(url_m.group(1))
206             # Some sites don't add it, we can't download with this url, for example:
207             # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
208             if 'playerKey' in url or 'videoId' in url:
209                 return [url]
210
211         matches = re.findall(
212             r'''(?sx)<object
213             (?:
214                 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
215                 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
216             ).+?>\s*</object>''',
217             webpage)
218         if matches:
219             return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
220
221         return list(filter(None, [
222             cls._build_brighcove_url_from_js(custom_bc)
223             for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
224
225     def _real_extract(self, url):
226         url, smuggled_data = unsmuggle_url(url, {})
227
228         # Change the 'videoId' and others field to '@videoPlayer'
229         url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
230         # Change bckey (used by bcove.me urls) to playerKey
231         url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
232         mobj = re.match(self._VALID_URL, url)
233         query_str = mobj.group('query')
234         query = compat_urlparse.parse_qs(query_str)
235
236         videoPlayer = query.get('@videoPlayer')
237         if videoPlayer:
238             # We set the original url as the default 'Referer' header
239             referer = smuggled_data.get('Referer', url)
240             return self._get_video_info(
241                 videoPlayer[0], query, referer=referer)
242         elif 'playerKey' in query:
243             player_key = query['playerKey']
244             return self._get_playlist_info(player_key[0])
245         else:
246             raise ExtractorError(
247                 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
248                 expected=True)
249
250     def _get_video_info(self, video_id, query, referer=None):
251         headers = {}
252         linkBase = query.get('linkBaseURL')
253         if linkBase is not None:
254             referer = linkBase[0]
255         if referer is not None:
256             headers['Referer'] = referer
257         webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
258
259         error_msg = self._html_search_regex(
260             r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
261             'error message', default=None)
262         if error_msg is not None:
263             raise ExtractorError(
264                 'brightcove said: %s' % error_msg, expected=True)
265
266         self.report_extraction(video_id)
267         info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
268         info = json.loads(info)['data']
269         video_info = info['programmedContent']['videoPlayer']['mediaDTO']
270         video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
271
272         return self._extract_video_info(video_info)
273
274     def _get_playlist_info(self, player_key):
275         info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
276         playlist_info = self._download_webpage(
277             info_url, player_key, 'Downloading playlist information')
278
279         json_data = json.loads(playlist_info)
280         if 'videoList' not in json_data:
281             raise ExtractorError('Empty playlist')
282         playlist_info = json_data['videoList']
283         videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
284
285         return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
286                                     playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
287
288     def _extract_video_info(self, video_info):
289         info = {
290             'id': compat_str(video_info['id']),
291             'title': video_info['displayName'].strip(),
292             'description': video_info.get('shortDescription'),
293             'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
294             'uploader': video_info.get('publisherName'),
295         }
296
297         renditions = video_info.get('renditions')
298         if renditions:
299             formats = []
300             for rend in renditions:
301                 url = rend['defaultURL']
302                 if not url:
303                     continue
304                 ext = None
305                 if rend['remote']:
306                     url_comp = compat_urllib_parse_urlparse(url)
307                     if url_comp.path.endswith('.m3u8'):
308                         formats.extend(
309                             self._extract_m3u8_formats(url, info['id'], 'mp4'))
310                         continue
311                     elif 'akamaihd.net' in url_comp.netloc:
312                         # This type of renditions are served through
313                         # akamaihd.net, but they don't use f4m manifests
314                         url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
315                         ext = 'flv'
316                 if ext is None:
317                     ext = determine_ext(url)
318                 size = rend.get('size')
319                 formats.append({
320                     'url': url,
321                     'ext': ext,
322                     'height': rend.get('frameHeight'),
323                     'width': rend.get('frameWidth'),
324                     'filesize': size if size != 0 else None,
325                 })
326             self._sort_formats(formats)
327             info['formats'] = formats
328         elif video_info.get('FLVFullLengthURL') is not None:
329             info.update({
330                 'url': video_info['FLVFullLengthURL'],
331             })
332
333         if self._downloader.params.get('include_ads', False):
334             adServerURL = video_info.get('_youtubedl_adServerURL')
335             if adServerURL:
336                 ad_info = {
337                     '_type': 'url',
338                     'url': adServerURL,
339                 }
340                 if 'url' in info:
341                     return {
342                         '_type': 'playlist',
343                         'title': info['title'],
344                         'entries': [ad_info, info],
345                     }
346                 else:
347                     return ad_info
348
349         if 'url' not in info and not info.get('formats'):
350             raise ExtractorError('Unable to extract video url for %s' % info['id'])
351         return info
352
353
354 class BrightcoveNewIE(InfoExtractor):
355     IE_NAME = 'brightcove:new'
356     _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
357     _TESTS = [{
358         'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
359         'md5': 'c8100925723840d4b0d243f7025703be',
360         'info_dict': {
361             'id': '4463358922001',
362             'ext': 'mp4',
363             'title': 'Meet the man behind Popcorn Time',
364             'description': 'md5:eac376a4fe366edc70279bfb681aea16',
365             'duration': 165.768,
366             'timestamp': 1441391203,
367             'upload_date': '20150904',
368             'uploader_id': '929656772001',
369             'formats': 'mincount:22',
370         },
371     }, {
372         # with rtmp streams
373         'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
374         'info_dict': {
375             'id': '4279049078001',
376             'ext': 'mp4',
377             'title': 'Titansgrave: Chapter 0',
378             'description': 'Titansgrave: Chapter 0',
379             'duration': 1242.058,
380             'timestamp': 1433556729,
381             'upload_date': '20150606',
382             'uploader_id': '4036320279001',
383             'formats': 'mincount:41',
384         },
385         'params': {
386             'skip_download': True,
387         }
388     }, {
389         # ref: prefixed video id
390         'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
391         'only_matching': True,
392     }, {
393         # non numeric ref: prefixed video id
394         'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
395         'only_matching': True,
396     }]
397
398     @staticmethod
399     def _extract_url(webpage):
400         urls = BrightcoveNewIE._extract_urls(webpage)
401         return urls[0] if urls else None
402
403     @staticmethod
404     def _extract_urls(webpage):
405         # Reference:
406         # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
407         # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
408         # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
409         # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
410
411         entries = []
412
413         # Look for iframe embeds [1]
414         for _, url in re.findall(
415                 r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
416             entries.append(url if url.startswith('http') else 'http:' + url)
417
418         # Look for embed_in_page embeds [2]
419         for video_id, account_id, player_id, embed in re.findall(
420                 # According to examples from [3] it's unclear whether video id
421                 # may be optional and what to do when it is
422                 # According to [4] data-video-id may be prefixed with ref:
423                 r'''(?sx)
424                     <video[^>]+
425                         data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
426                     </video>.*?
427                     <script[^>]+
428                         src=["\'](?:https?:)?//players\.brightcove\.net/
429                         (\d+)/([\da-f-]+)_([^/]+)/index(?:\.min)?\.js
430                 ''', webpage):
431             entries.append(
432                 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
433                 % (account_id, player_id, embed, video_id))
434
435         return entries
436
437     def _real_extract(self, url):
438         account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
439
440         webpage = self._download_webpage(
441             'http://players.brightcove.net/%s/%s_%s/index.min.js'
442             % (account_id, player_id, embed), video_id)
443
444         policy_key = None
445
446         catalog = self._search_regex(
447             r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
448         if catalog:
449             catalog = self._parse_json(
450                 js_to_json(catalog), video_id, fatal=False)
451             if catalog:
452                 policy_key = catalog.get('policyKey')
453
454         if not policy_key:
455             policy_key = self._search_regex(
456                 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
457                 webpage, 'policy key', group='pk')
458
459         api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
460         try:
461             json_data = self._download_json(api_url, video_id, headers={
462                 'Accept': 'application/json;pk=%s' % policy_key
463             })
464         except ExtractorError as e:
465             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
466                 json_data = self._parse_json(e.cause.read().decode(), video_id)
467                 raise ExtractorError(json_data[0]['message'], expected=True)
468             raise
469
470         title = json_data['name']
471
472         formats = []
473         for source in json_data.get('sources', []):
474             container = source.get('container')
475             source_type = source.get('type')
476             src = source.get('src')
477             if source_type == 'application/x-mpegURL' or container == 'M2TS':
478                 if not src:
479                     continue
480                 formats.extend(self._extract_m3u8_formats(
481                     src, video_id, 'mp4', m3u8_id='hls', fatal=False))
482             elif source_type == 'application/dash+xml':
483                 if not src:
484                     continue
485                 formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
486             else:
487                 streaming_src = source.get('streaming_src')
488                 stream_name, app_name = source.get('stream_name'), source.get('app_name')
489                 if not src and not streaming_src and (not stream_name or not app_name):
490                     continue
491                 tbr = float_or_none(source.get('avg_bitrate'), 1000)
492                 height = int_or_none(source.get('height'))
493                 width = int_or_none(source.get('width'))
494                 f = {
495                     'tbr': tbr,
496                     'filesize': int_or_none(source.get('size')),
497                     'container': container,
498                     'ext': container.lower(),
499                 }
500                 if width == 0 and height == 0:
501                     f.update({
502                         'vcodec': 'none',
503                     })
504                 else:
505                     f.update({
506                         'width': width,
507                         'height': height,
508                         'vcodec': source.get('codec'),
509                     })
510
511                 def build_format_id(kind):
512                     format_id = kind
513                     if tbr:
514                         format_id += '-%dk' % int(tbr)
515                     if height:
516                         format_id += '-%dp' % height
517                     return format_id
518
519                 if src or streaming_src:
520                     f.update({
521                         'url': src or streaming_src,
522                         'format_id': build_format_id('http' if src else 'http-streaming'),
523                         'preference': 2 if src else 1,
524                     })
525                 else:
526                     f.update({
527                         'url': app_name,
528                         'play_path': stream_name,
529                         'format_id': build_format_id('rtmp'),
530                     })
531                 formats.append(f)
532         self._sort_formats(formats)
533
534         description = json_data.get('description')
535         thumbnail = json_data.get('thumbnail')
536         timestamp = parse_iso8601(json_data.get('published_at'))
537         duration = float_or_none(json_data.get('duration'), 1000)
538         tags = json_data.get('tags', [])
539
540         return {
541             'id': video_id,
542             'title': title,
543             'description': description,
544             'thumbnail': thumbnail,
545             'duration': duration,
546             'timestamp': timestamp,
547             'uploader_id': account_id,
548             'formats': formats,
549             'tags': tags,
550         }