brightcove.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # encoding: utf-8
  2. import re
  3. import json
  4. import xml.etree.ElementTree
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. compat_urllib_parse,
  8. find_xpath_attr,
  9. compat_urlparse,
  10. compat_str,
  11. ExtractorError,
  12. )
  13. class BrightcoveIE(InfoExtractor):
  14. _VALID_URL = r'https?://.*brightcove\.com/(services|viewer).*\?(?P<query>.*)'
  15. _FEDERATED_URL_TEMPLATE = 'http://c.brightcove.com/services/viewer/htmlFederated?%s'
  16. _PLAYLIST_URL_TEMPLATE = 'http://c.brightcove.com/services/json/experience/runtime/?command=get_programming_for_experience&playerKey=%s'
  17. _TESTS = [
  18. {
  19. # From http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/
  20. u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1654948606001&flashID=myExperience&%40videoPlayer=2371591881001',
  21. u'file': u'2371591881001.mp4',
  22. u'md5': u'8eccab865181d29ec2958f32a6a754f5',
  23. u'note': u'Test Brightcove downloads and detection in GenericIE',
  24. u'info_dict': {
  25. u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
  26. u'uploader': u'8TV',
  27. u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
  28. }
  29. },
  30. {
  31. # From http://medianetwork.oracle.com/video/player/1785452137001
  32. u'url': u'http://c.brightcove.com/services/viewer/htmlFederated?playerID=1217746023001&flashID=myPlayer&%40videoPlayer=1785452137001',
  33. u'file': u'1785452137001.flv',
  34. u'info_dict': {
  35. u'title': u'JVMLS 2012: Arrays 2.0 - Opportunities and Challenges',
  36. u'description': u'John Rose speaks at the JVM Language Summit, August 1, 2012.',
  37. u'uploader': u'Oracle',
  38. },
  39. },
  40. {
  41. # From http://mashable.com/2013/10/26/thermoelectric-bracelet-lets-you-control-your-body-temperature/
  42. u'url': u'http://c.brightcove.com/services/viewer/federated_f9?&playerID=1265504713001&publisherID=AQ%7E%7E%2CAAABBzUwv1E%7E%2CxP-xFHVUstiMFlNYfvF4G9yFnNaqCw_9&videoID=2750934548001',
  43. u'info_dict': {
  44. u'id': u'2750934548001',
  45. u'ext': u'mp4',
  46. u'title': u'This Bracelet Acts as a Personal Thermostat',
  47. u'description': u'md5:547b78c64f4112766ccf4e151c20b6a0',
  48. u'uploader': u'Mashable',
  49. },
  50. },
  51. ]
  52. @classmethod
  53. def _build_brighcove_url(cls, object_str):
  54. """
  55. Build a Brightcove url from a xml string containing
  56. <object class="BrightcoveExperience">{params}</object>
  57. """
  58. # Fix up some stupid HTML, see https://github.com/rg3/youtube-dl/issues/1553
  59. object_str = re.sub(r'(<param name="[^"]+" value="[^"]+")>',
  60. lambda m: m.group(1) + '/>', object_str)
  61. # Fix up some stupid XML, see https://github.com/rg3/youtube-dl/issues/1608
  62. object_str = object_str.replace(u'<--', u'<!--')
  63. object_doc = xml.etree.ElementTree.fromstring(object_str)
  64. assert u'BrightcoveExperience' in object_doc.attrib['class']
  65. params = {'flashID': object_doc.attrib['id'],
  66. 'playerID': find_xpath_attr(object_doc, './param', 'name', 'playerID').attrib['value'],
  67. }
  68. playerKey = find_xpath_attr(object_doc, './param', 'name', 'playerKey')
  69. # Not all pages define this value
  70. if playerKey is not None:
  71. params['playerKey'] = playerKey.attrib['value']
  72. videoPlayer = find_xpath_attr(object_doc, './param', 'name', '@videoPlayer')
  73. if videoPlayer is not None:
  74. params['@videoPlayer'] = videoPlayer.attrib['value']
  75. data = compat_urllib_parse.urlencode(params)
  76. return cls._FEDERATED_URL_TEMPLATE % data
  77. @classmethod
  78. def _extract_brightcove_url(cls, webpage):
  79. """Try to extract the brightcove url from the wepbage, returns None
  80. if it can't be found
  81. """
  82. m_brightcove = re.search(
  83. r'<object[^>]+?class=([\'"])[^>]*?BrightcoveExperience.*?\1.+?</object>',
  84. webpage, re.DOTALL)
  85. if m_brightcove is not None:
  86. return cls._build_brighcove_url(m_brightcove.group())
  87. else:
  88. return None
  89. def _real_extract(self, url):
  90. # Change the 'videoId' and others field to '@videoPlayer'
  91. url = re.sub(r'(?<=[?&])(videoI(d|D)|bctid)', '%40videoPlayer', url)
  92. # Change bckey (used by bcove.me urls) to playerKey
  93. url = re.sub(r'(?<=[?&])bckey', 'playerKey', url)
  94. mobj = re.match(self._VALID_URL, url)
  95. query_str = mobj.group('query')
  96. query = compat_urlparse.parse_qs(query_str)
  97. videoPlayer = query.get('@videoPlayer')
  98. if videoPlayer:
  99. return self._get_video_info(videoPlayer[0], query_str)
  100. else:
  101. player_key = query['playerKey']
  102. return self._get_playlist_info(player_key[0])
  103. def _get_video_info(self, video_id, query):
  104. request_url = self._FEDERATED_URL_TEMPLATE % query
  105. webpage = self._download_webpage(request_url, video_id)
  106. self.report_extraction(video_id)
  107. info = self._search_regex(r'var experienceJSON = ({.*?});', webpage, 'json')
  108. info = json.loads(info)['data']
  109. video_info = info['programmedContent']['videoPlayer']['mediaDTO']
  110. return self._extract_video_info(video_info)
  111. def _get_playlist_info(self, player_key):
  112. playlist_info = self._download_webpage(self._PLAYLIST_URL_TEMPLATE % player_key,
  113. player_key, u'Downloading playlist information')
  114. json_data = json.loads(playlist_info)
  115. if 'videoList' not in json_data:
  116. raise ExtractorError(u'Empty playlist')
  117. playlist_info = json_data['videoList']
  118. videos = [self._extract_video_info(video_info) for video_info in playlist_info['mediaCollectionDTO']['videoDTOs']]
  119. return self.playlist_result(videos, playlist_id=playlist_info['id'],
  120. playlist_title=playlist_info['mediaCollectionDTO']['displayName'])
  121. def _extract_video_info(self, video_info):
  122. info = {
  123. 'id': compat_str(video_info['id']),
  124. 'title': video_info['displayName'],
  125. 'description': video_info.get('shortDescription'),
  126. 'thumbnail': video_info.get('videoStillURL') or video_info.get('thumbnailURL'),
  127. 'uploader': video_info.get('publisherName'),
  128. }
  129. renditions = video_info.get('renditions')
  130. if renditions:
  131. renditions = sorted(renditions, key=lambda r: r['size'])
  132. info['formats'] = [{
  133. 'url': rend['defaultURL'],
  134. 'height': rend.get('frameHeight'),
  135. 'width': rend.get('frameWidth'),
  136. } for rend in renditions]
  137. elif video_info.get('FLVFullLengthURL') is not None:
  138. info.update({
  139. 'url': video_info['FLVFullLengthURL'],
  140. })
  141. else:
  142. raise ExtractorError(u'Unable to extract video url for %s' % info['id'])
  143. return info