[brightcove] fix format sorting
[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         data_url = object_doc.attrib.get('data', '')
140         data_url_params = compat_parse_qs(compat_urllib_parse_urlparse(data_url).query)
141
142         def find_param(name):
143             if name in flashvars:
144                 return flashvars[name]
145             node = find_xpath_attr(object_doc, './param', 'name', name)
146             if node is not None:
147                 return node.attrib['value']
148             return data_url_params.get(name)
149
150         params = {}
151
152         playerID = find_param('playerID')
153         if playerID is None:
154             raise ExtractorError('Cannot find player ID')
155         params['playerID'] = playerID
156
157         playerKey = find_param('playerKey')
158         # Not all pages define this value
159         if playerKey is not None:
160             params['playerKey'] = playerKey
161         # These fields hold the id of the video
162         videoPlayer = find_param('@videoPlayer') or find_param('videoId') or find_param('videoID') or find_param('@videoList')
163         if videoPlayer is not None:
164             params['@videoPlayer'] = videoPlayer
165         linkBase = find_param('linkBaseURL')
166         if linkBase is not None:
167             params['linkBaseURL'] = linkBase
168         return cls._make_brightcove_url(params)
169
170     @classmethod
171     def _build_brighcove_url_from_js(cls, object_js):
172         # The layout of JS is as follows:
173         # customBC.createVideo = function (width, height, playerID, playerKey, videoPlayer, VideoRandomID) {
174         #   // build Brightcove <object /> XML
175         # }
176         m = re.search(
177             r'''(?x)customBC.\createVideo\(
178                 .*?                                                  # skipping width and height
179                 ["\'](?P<playerID>\d+)["\']\s*,\s*                   # playerID
180                 ["\'](?P<playerKey>AQ[^"\']{48})[^"\']*["\']\s*,\s*  # playerKey begins with AQ and is 50 characters
181                                                                      # in length, however it's appended to itself
182                                                                      # in places, so truncate
183                 ["\'](?P<videoID>\d+)["\']                           # @videoPlayer
184             ''', object_js)
185         if m:
186             return cls._make_brightcove_url(m.groupdict())
187
188     @classmethod
189     def _make_brightcove_url(cls, params):
190         return update_url_query(cls._FEDERATED_URL, params)
191
192     @classmethod
193     def _extract_brightcove_url(cls, webpage):
194         """Try to extract the brightcove url from the webpage, returns None
195         if it can't be found
196         """
197         urls = cls._extract_brightcove_urls(webpage)
198         return urls[0] if urls else None
199
200     @classmethod
201     def _extract_brightcove_urls(cls, webpage):
202         """Return a list of all Brightcove URLs from the webpage """
203
204         url_m = re.search(
205             r'<meta\s+property=[\'"]og:video[\'"]\s+content=[\'"](https?://(?:secure|c)\.brightcove.com/[^\'"]+)[\'"]',
206             webpage)
207         if url_m:
208             url = unescapeHTML(url_m.group(1))
209             # Some sites don't add it, we can't download with this url, for example:
210             # http://www.ktvu.com/videos/news/raw-video-caltrain-releases-video-of-man-almost/vCTZdY/
211             if 'playerKey' in url or 'videoId' in url:
212                 return [url]
213
214         matches = re.findall(
215             r'''(?sx)<object
216             (?:
217                 [^>]+?class=[\'"][^>]*?BrightcoveExperience.*?[\'"] |
218                 [^>]*?>\s*<param\s+name="movie"\s+value="https?://[^/]*brightcove\.com/
219             ).+?>\s*</object>''',
220             webpage)
221         if matches:
222             return list(filter(None, [cls._build_brighcove_url(m) for m in matches]))
223
224         return list(filter(None, [
225             cls._build_brighcove_url_from_js(custom_bc)
226             for custom_bc in re.findall(r'(customBC\.createVideo\(.+?\);)', webpage)]))
227
228     def _real_extract(self, url):
229         url, smuggled_data = unsmuggle_url(url, {})
230
231         # Change the 'videoId' and others field to '@videoPlayer'
232         url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
233         # Change bckey (used by bcove.me urls) to playerKey
234         url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
235         mobj = re.match(self._VALID_URL, url)
236         query_str = mobj.group('query')
237         query = compat_urlparse.parse_qs(query_str)
238
239         videoPlayer = query.get('@videoPlayer')
240         if videoPlayer:
241             # We set the original url as the default 'Referer' header
242             referer = smuggled_data.get('Referer', url)
243             return self._get_video_info(
244                 videoPlayer[0], query, referer=referer)
245         elif 'playerKey' in query:
246             player_key = query['playerKey']
247             return self._get_playlist_info(player_key[0])
248         else:
249             raise ExtractorError(
250                 'Cannot find playerKey= variable. Did you forget quotes in a shell invocation?',
251                 expected=True)
252
253     def _get_video_info(self, video_id, query, referer=None):
254         headers = {}
255         linkBase = query.get('linkBaseURL')
256         if linkBase is not None:
257             referer = linkBase[0]
258         if referer is not None:
259             headers['Referer'] = referer
260         webpage = self._download_webpage(self._FEDERATED_URL, video_id, headers=headers, query=query)
261
262         error_msg = self._html_search_regex(
263             r"<h1>We're sorry.</h1>([\s\n]*<p>.*?</p>)+", webpage,
264             'error message', default=None)
265         if error_msg is not None:
266             raise ExtractorError(
267                 'brightcove said: %s' % error_msg, expected=True)
268
269         self.report_extraction(video_id)
270         info = self._search_regex(r'var experienceJSON = ({.*});', webpage, 'json')
271         info = json.loads(info)['data']
272         video_info = info['programmedContent']['videoPlayer']['mediaDTO']
273         video_info['_youtubedl_adServerURL'] = info.get('adServerURL')
274
275         return self._extract_video_info(video_info)
276
277     def _get_playlist_info(self, player_key):
278         info_url = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s' % player_key
279         playlist_info = self._download_webpage(
280             info_url, player_key, 'Downloading playlist information')
281
282         json_data = json.loads(playlist_info)
283         if 'videoList' not in json_data:
284             raise ExtractorError('Empty playlist')
285         playlist_info = json_data['videoList']
286         videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
287
288         return self.playlist_result(videos, playlist_id='%s' % playlist_info['id'],
289                                     playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
290
291     def _extract_video_info(self, video_info):
292         info = {
293             'id': compat_str(video_info['id']),
294             'title': video_info['displayName'].strip(),
295             'description': video_info.get('shortDescription'),
296             'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
297             'uploader': video_info.get('publisherName'),
298         }
299
300         renditions = video_info.get('renditions', []) + video_info.get('IOSRenditions', [])
301         if renditions:
302             formats = []
303             for rend in renditions:
304                 url = rend['defaultURL']
305                 if not url:
306                     continue
307                 ext = None
308                 if rend['remote']:
309                     url_comp = compat_urllib_parse_urlparse(url)
310                     if url_comp.path.endswith('.m3u8'):
311                         formats.extend(
312                             self._extract_m3u8_formats(url, info['id'], 'mp4'))
313                         continue
314                     elif 'akamaihd.net' in url_comp.netloc:
315                         # This type of renditions are served through
316                         # akamaihd.net, but they don't use f4m manifests
317                         url = url.replace('control/', '') + '?&v=3.3.0&fp=13&r=FEEFJ&g=RTSJIMBMPFPB'
318                         ext = 'flv'
319                 if ext is None:
320                     ext = determine_ext(url)
321                 size = rend.get('size')
322                 a_format = {
323                     'url': url,
324                     'ext': ext,
325                     'height': rend.get('frameHeight'),
326                     'width': rend.get('frameWidth'),
327                     'filesize': size if size != 0 else None,
328                 }
329
330                 # m3u8 manifests with remote == false are media playlists
331                 # Not calling _extract_m3u8_formats here to save network traffic
332                 if ext == 'm3u8':
333                     a_format.update({
334                         'ext': 'mp4',
335                         'protocol': 'm3u8',
336                     })
337
338                 formats.append(a_format)
339             self._sort_formats(formats)
340             info['formats'] = formats
341         elif video_info.get('FLVFullLengthURL') is not None:
342             info.update({
343                 'url': video_info['FLVFullLengthURL'],
344             })
345
346         if self._downloader.params.get('include_ads', False):
347             adServerURL = video_info.get('_youtubedl_adServerURL')
348             if adServerURL:
349                 ad_info = {
350                     '_type': 'url',
351                     'url': adServerURL,
352                 }
353                 if 'url' in info:
354                     return {
355                         '_type': 'playlist',
356                         'title': info['title'],
357                         'entries': [ad_info, info],
358                     }
359                 else:
360                     return ad_info
361
362         if 'url' not in info and not info.get('formats'):
363             raise ExtractorError('Unable to extract video url for %s' % info['id'])
364         return info
365
366
367 class BrightcoveNewIE(InfoExtractor):
368     IE_NAME = 'brightcove:new'
369     _VALID_URL = r'https?://players\.brightcove\.net/(?P<account_id>\d+)/(?P<player_id>[^/]+)_(?P<embed>[^/]+)/index\.html\?.*videoId=(?P<video_id>\d+|ref:[^&]+)'
370     _TESTS = [{
371         'url': 'http://players.brightcove.net/929656772001/e41d32dc-ec74-459e-a845-6c69f7b724ea_default/index.html?videoId=4463358922001',
372         'md5': 'c8100925723840d4b0d243f7025703be',
373         'info_dict': {
374             'id': '4463358922001',
375             'ext': 'mp4',
376             'title': 'Meet the man behind Popcorn Time',
377             'description': 'md5:eac376a4fe366edc70279bfb681aea16',
378             'duration': 165.768,
379             'timestamp': 1441391203,
380             'upload_date': '20150904',
381             'uploader_id': '929656772001',
382             'formats': 'mincount:22',
383         },
384     }, {
385         # with rtmp streams
386         'url': 'http://players.brightcove.net/4036320279001/5d112ed9-283f-485f-a7f9-33f42e8bc042_default/index.html?videoId=4279049078001',
387         'info_dict': {
388             'id': '4279049078001',
389             'ext': 'mp4',
390             'title': 'Titansgrave: Chapter 0',
391             'description': 'Titansgrave: Chapter 0',
392             'duration': 1242.058,
393             'timestamp': 1433556729,
394             'upload_date': '20150606',
395             'uploader_id': '4036320279001',
396             'formats': 'mincount:41',
397         },
398         'params': {
399             # m3u8 download
400             'skip_download': True,
401         }
402     }, {
403         # ref: prefixed video id
404         'url': 'http://players.brightcove.net/3910869709001/21519b5c-4b3b-4363-accb-bdc8f358f823_default/index.html?videoId=ref:7069442',
405         'only_matching': True,
406     }, {
407         # non numeric ref: prefixed video id
408         'url': 'http://players.brightcove.net/710858724001/default_default/index.html?videoId=ref:event-stream-356',
409         'only_matching': True,
410     }]
411
412     @staticmethod
413     def _extract_url(webpage):
414         urls = BrightcoveNewIE._extract_urls(webpage)
415         return urls[0] if urls else None
416
417     @staticmethod
418     def _extract_urls(webpage):
419         # Reference:
420         # 1. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideoiniframe
421         # 2. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/publish-video.html#setvideousingjavascript
422         # 3. http://docs.brightcove.com/en/video-cloud/brightcove-player/guides/embed-in-page.html
423         # 4. https://support.brightcove.com/en/video-cloud/docs/dynamically-assigning-videos-player
424
425         entries = []
426
427         # Look for iframe embeds [1]
428         for _, url in re.findall(
429                 r'<iframe[^>]+src=(["\'])((?:https?:)?//players\.brightcove\.net/\d+/[^/]+/index\.html.+?)\1', webpage):
430             entries.append(url if url.startswith('http') else 'http:' + url)
431
432         # Look for embed_in_page embeds [2]
433         for video_id, account_id, player_id, embed in re.findall(
434                 # According to examples from [3] it's unclear whether video id
435                 # may be optional and what to do when it is
436                 # According to [4] data-video-id may be prefixed with ref:
437                 r'''(?sx)
438                     <video[^>]+
439                         data-video-id=["\'](\d+|ref:[^"\']+)["\'][^>]*>.*?
440                     </video>.*?
441                     <script[^>]+
442                         src=["\'](?:https?:)?//players\.brightcove\.net/
443                         (\d+)/([^/]+)_([^/]+)/index(?:\.min)?\.js
444                 ''', webpage):
445             entries.append(
446                 'http://players.brightcove.net/%s/%s_%s/index.html?videoId=%s'
447                 % (account_id, player_id, embed, video_id))
448
449         return entries
450
451     def _real_extract(self, url):
452         account_id, player_id, embed, video_id = re.match(self._VALID_URL, url).groups()
453
454         webpage = self._download_webpage(
455             'http://players.brightcove.net/%s/%s_%s/index.min.js'
456             % (account_id, player_id, embed), video_id)
457
458         policy_key = None
459
460         catalog = self._search_regex(
461             r'catalog\(({.+?})\);', webpage, 'catalog', default=None)
462         if catalog:
463             catalog = self._parse_json(
464                 js_to_json(catalog), video_id, fatal=False)
465             if catalog:
466                 policy_key = catalog.get('policyKey')
467
468         if not policy_key:
469             policy_key = self._search_regex(
470                 r'policyKey\s*:\s*(["\'])(?P<pk>.+?)\1',
471                 webpage, 'policy key', group='pk')
472
473         api_url = 'https://edge.api.brightcove.com/playback/v1/accounts/%s/videos/%s' % (account_id, video_id)
474         try:
475             json_data = self._download_json(api_url, video_id, headers={
476                 'Accept': 'application/json;pk=%s' % policy_key
477             })
478         except ExtractorError as e:
479             if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
480                 json_data = self._parse_json(e.cause.read().decode(), video_id)
481                 raise ExtractorError(json_data[0]['message'], expected=True)
482             raise
483
484         title = json_data['name']
485
486         formats = []
487         for source in json_data.get('sources', []):
488             container = source.get('container')
489             source_type = source.get('type')
490             src = source.get('src')
491             if source_type == 'application/x-mpegURL' or container == 'M2TS':
492                 if not src:
493                     continue
494                 formats.extend(self._extract_m3u8_formats(
495                     src, video_id, 'mp4', m3u8_id='hls', fatal=False))
496             elif source_type == 'application/dash+xml':
497                 if not src:
498                     continue
499                 formats.extend(self._extract_mpd_formats(src, video_id, 'dash', fatal=False))
500             else:
501                 streaming_src = source.get('streaming_src')
502                 stream_name, app_name = source.get('stream_name'), source.get('app_name')
503                 if not src and not streaming_src and (not stream_name or not app_name):
504                     continue
505                 tbr = float_or_none(source.get('avg_bitrate'), 1000)
506                 height = int_or_none(source.get('height'))
507                 width = int_or_none(source.get('width'))
508                 f = {
509                     'tbr': tbr,
510                     'filesize': int_or_none(source.get('size')),
511                     'container': container,
512                     'ext': container.lower(),
513                 }
514                 if width == 0 and height == 0:
515                     f.update({
516                         'vcodec': 'none',
517                     })
518                 else:
519                     f.update({
520                         'width': width,
521                         'height': height,
522                         'vcodec': source.get('codec'),
523                     })
524
525                 def build_format_id(kind):
526                     format_id = kind
527                     if tbr:
528                         format_id += '-%dk' % int(tbr)
529                     if height:
530                         format_id += '-%dp' % height
531                     return format_id
532
533                 if src or streaming_src:
534                     f.update({
535                         'url': src or streaming_src,
536                         'format_id': build_format_id('http' if src else 'http-streaming'),
537                         'source_preference': 0 if src else -1,
538                     })
539                 else:
540                     f.update({
541                         'url': app_name,
542                         'play_path': stream_name,
543                         'format_id': build_format_id('rtmp'),
544                     })
545                 formats.append(f)
546         self._sort_formats(formats)
547
548         description = json_data.get('description')
549         thumbnail = json_data.get('thumbnail')
550         timestamp = parse_iso8601(json_data.get('published_at'))
551         duration = float_or_none(json_data.get('duration'), 1000)
552         tags = json_data.get('tags', [])
553
554         return {
555             'id': video_id,
556             'title': title,
557             'description': description,
558             'thumbnail': thumbnail,
559             'duration': duration,
560             'timestamp': timestamp,
561             'uploader_id': account_id,
562             'formats': formats,
563             'tags': tags,
564         }