theplatform.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. from __future__ import unicode_literals
  2. import re
  3. import json
  4. import time
  5. import hmac
  6. import binascii
  7. import hashlib
  8. from .common import InfoExtractor
  9. from ..utils import (
  10. determine_ext,
  11. ExtractorError,
  12. xpath_with_ns,
  13. unsmuggle_url,
  14. int_or_none,
  15. url_basename,
  16. float_or_none,
  17. )
  18. default_ns = 'http://www.w3.org/2005/SMIL21/Language'
  19. _x = lambda p: xpath_with_ns(p, {'smil': default_ns})
  20. class ThePlatformBaseIE(InfoExtractor):
  21. def _extract_theplatform_smil_formats(self, smil_url, video_id, note='Downloading SMIL data'):
  22. meta = self._download_xml(smil_url, video_id, note=note)
  23. try:
  24. error_msg = next(
  25. n.attrib['abstract']
  26. for n in meta.findall(_x('.//smil:ref'))
  27. if n.attrib.get('title') == 'Geographic Restriction' or n.attrib.get('title') == 'Expired')
  28. except StopIteration:
  29. pass
  30. else:
  31. raise ExtractorError(error_msg, expected=True)
  32. formats = self._parse_smil_formats(
  33. meta, smil_url, video_id, namespace=default_ns,
  34. # the parameters are from syfy.com, other sites may use others,
  35. # they also work for nbc.com
  36. f4m_params={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'},
  37. transform_rtmp_url=lambda streamer, src: (streamer, 'mp4:' + src))
  38. for _format in formats:
  39. ext = determine_ext(_format['url'])
  40. if ext == 'once':
  41. _format['ext'] = 'mp4'
  42. self._sort_formats(formats)
  43. return formats
  44. def get_metadata(self, path, video_id):
  45. info_url = 'http://link.theplatform.com/s/%s?format=preview' % path
  46. info_json = self._download_webpage(info_url, video_id)
  47. info = json.loads(info_json)
  48. subtitles = {}
  49. captions = info.get('captions')
  50. if isinstance(captions, list):
  51. for caption in captions:
  52. lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
  53. subtitles[lang] = [{
  54. 'ext': 'srt' if mime == 'text/srt' else 'ttml',
  55. 'url': src,
  56. }]
  57. return {
  58. 'title': info['title'],
  59. 'subtitles': subtitles,
  60. 'description': info['description'],
  61. 'thumbnail': info['defaultThumbnailUrl'],
  62. 'duration': int_or_none(info.get('duration'), 1000),
  63. }
  64. class ThePlatformIE(ThePlatformBaseIE):
  65. _VALID_URL = r'''(?x)
  66. (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
  67. (?:(?P<media>(?:[^/]+/)+select/media/)|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
  68. |theplatform:)(?P<id>[^/\?&]+)'''
  69. _TESTS = [{
  70. # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
  71. 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
  72. 'info_dict': {
  73. 'id': 'e9I_cZgTgIPd',
  74. 'ext': 'flv',
  75. 'title': 'Blackberry\'s big, bold Z30',
  76. 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
  77. 'duration': 247,
  78. },
  79. 'params': {
  80. # rtmp download
  81. 'skip_download': True,
  82. },
  83. }, {
  84. # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
  85. 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
  86. 'info_dict': {
  87. 'id': '22d_qsQ6MIRT',
  88. 'ext': 'flv',
  89. 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
  90. 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
  91. },
  92. 'params': {
  93. # rtmp download
  94. 'skip_download': True,
  95. }
  96. }, {
  97. 'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
  98. 'info_dict': {
  99. 'id': 'yMBg9E8KFxZD',
  100. 'ext': 'mp4',
  101. 'description': 'md5:644ad9188d655b742f942bf2e06b002d',
  102. 'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
  103. }
  104. }, {
  105. 'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
  106. 'only_matching': True,
  107. }]
  108. @staticmethod
  109. def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
  110. flags = '10' if include_qs else '00'
  111. expiration_date = '%x' % (int(time.time()) + life)
  112. def str_to_hex(str):
  113. return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
  114. def hex_to_str(hex):
  115. return binascii.a2b_hex(hex)
  116. relative_path = url.split('http://link.theplatform.com/s/')[1].split('?')[0]
  117. clear_text = hex_to_str(flags + expiration_date + str_to_hex(relative_path))
  118. checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
  119. sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
  120. return '%s&sig=%s' % (url, sig)
  121. def _real_extract(self, url):
  122. url, smuggled_data = unsmuggle_url(url, {})
  123. mobj = re.match(self._VALID_URL, url)
  124. provider_id = mobj.group('provider_id')
  125. video_id = mobj.group('id')
  126. if not provider_id:
  127. provider_id = 'dJ5BDC'
  128. path = provider_id
  129. if mobj.group('media'):
  130. path += '/media'
  131. path += '/' + video_id
  132. if smuggled_data.get('force_smil_url', False):
  133. smil_url = url
  134. elif mobj.group('config'):
  135. config_url = url + '&form=json'
  136. config_url = config_url.replace('swf/', 'config/')
  137. config_url = config_url.replace('onsite/', 'onsite/config/')
  138. config = self._download_json(config_url, video_id, 'Downloading config')
  139. if 'releaseUrl' in config:
  140. release_url = config['releaseUrl']
  141. else:
  142. release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
  143. smil_url = release_url + '&format=SMIL&formats=MPEG4&manifest=f4m'
  144. else:
  145. smil_url = 'http://link.theplatform.com/s/%s/meta.smil?format=smil&mbr=true' % path
  146. sig = smuggled_data.get('sig')
  147. if sig:
  148. smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
  149. formats = self._extract_theplatform_smil_formats(smil_url, video_id)
  150. ret = self.get_metadata(path, video_id)
  151. ret.update({
  152. 'id': video_id,
  153. 'formats': formats,
  154. })
  155. return ret
  156. class ThePlatformFeedIE(ThePlatformBaseIE):
  157. _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&byGuid=%s'
  158. _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*byGuid=(?P<id>[a-zA-Z0-9_]+)'
  159. _TEST = {
  160. # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
  161. 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
  162. 'md5': '22d2b84f058d3586efcd99e57d59d314',
  163. 'info_dict': {
  164. 'id': 'n_hardball_5biden_140207',
  165. 'ext': 'mp4',
  166. 'title': 'The Biden factor: will Joe run in 2016?',
  167. 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
  168. 'thumbnail': 're:^https?://.*\.jpg$',
  169. 'upload_date': '20140208',
  170. 'timestamp': 1391824260,
  171. 'duration': 467.0,
  172. 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
  173. },
  174. }
  175. def _real_extract(self, url):
  176. mobj = re.match(self._VALID_URL, url)
  177. video_id = mobj.group('id')
  178. provider_id = mobj.group('provider_id')
  179. feed_id = mobj.group('feed_id')
  180. real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, video_id)
  181. feed = self._download_json(real_url, video_id)
  182. entry = feed['entries'][0]
  183. formats = []
  184. first_video_id = None
  185. duration = None
  186. for item in entry['media$content']:
  187. smil_url = item['plfile$url'] + '&format=SMIL&Tracking=true&Embedded=true&formats=MPEG4,F4M'
  188. cur_video_id = url_basename(smil_url)
  189. if first_video_id is None:
  190. first_video_id = cur_video_id
  191. duration = float_or_none(item.get('plfile$duration'))
  192. formats.extend(self._extract_theplatform_smil_formats(smil_url, video_id, 'Downloading SMIL data for %s' % cur_video_id))
  193. self._sort_formats(formats)
  194. thumbnails = [{
  195. 'url': thumbnail['plfile$url'],
  196. 'width': int_or_none(thumbnail.get('plfile$width')),
  197. 'height': int_or_none(thumbnail.get('plfile$height')),
  198. } for thumbnail in entry.get('media$thumbnails', [])]
  199. timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
  200. categories = [item['media$name'] for item in entry.get('media$categories', [])]
  201. ret = self.get_metadata('%s/%s' % (provider_id, first_video_id), video_id)
  202. ret.update({
  203. 'id': video_id,
  204. 'formats': formats,
  205. 'thumbnails': thumbnails,
  206. 'duration': duration,
  207. 'timestamp': timestamp,
  208. 'categories': categories,
  209. })
  210. return ret