theplatform.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 ..compat import (
  10. compat_str,
  11. )
  12. from ..utils import (
  13. determine_ext,
  14. ExtractorError,
  15. xpath_with_ns,
  16. unsmuggle_url,
  17. )
  18. _x = lambda p: xpath_with_ns(p, {'smil': 'http://www.w3.org/2005/SMIL21/Language'})
  19. class ThePlatformIE(InfoExtractor):
  20. _VALID_URL = r'''(?x)
  21. (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
  22. (?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/)?
  23. |theplatform:)(?P<id>[^/\?&]+)'''
  24. _TESTS = [{
  25. # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
  26. 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
  27. 'info_dict': {
  28. 'id': 'e9I_cZgTgIPd',
  29. 'ext': 'flv',
  30. 'title': 'Blackberry\'s big, bold Z30',
  31. 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
  32. 'duration': 247,
  33. },
  34. 'params': {
  35. # rtmp download
  36. 'skip_download': True,
  37. },
  38. # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
  39. }, {
  40. 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
  41. 'info_dict': {
  42. 'id': '22d_qsQ6MIRT',
  43. 'ext': 'flv',
  44. 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
  45. 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
  46. },
  47. 'params': {
  48. # rtmp download
  49. 'skip_download': True,
  50. }
  51. }]
  52. @staticmethod
  53. def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
  54. flags = '10' if include_qs else '00'
  55. expiration_date = '%x' % (int(time.time()) + life)
  56. def str_to_hex(str):
  57. return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
  58. def hex_to_str(hex):
  59. return binascii.a2b_hex(hex)
  60. relative_path = url.split('http://link.theplatform.com/s/')[1].split('?')[0]
  61. clear_text = hex_to_str(flags + expiration_date + str_to_hex(relative_path))
  62. checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
  63. sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
  64. return '%s&sig=%s' % (url, sig)
  65. def _real_extract(self, url):
  66. url, smuggled_data = unsmuggle_url(url, {})
  67. mobj = re.match(self._VALID_URL, url)
  68. provider_id = mobj.group('provider_id')
  69. video_id = mobj.group('id')
  70. if not provider_id:
  71. provider_id = 'dJ5BDC'
  72. if smuggled_data.get('force_smil_url', False):
  73. smil_url = url
  74. elif mobj.group('config'):
  75. config_url = url + '&form=json'
  76. config_url = config_url.replace('swf/', 'config/')
  77. config_url = config_url.replace('onsite/', 'onsite/config/')
  78. config = self._download_json(config_url, video_id, 'Downloading config')
  79. smil_url = config['releaseUrl'] + '&format=SMIL&formats=MPEG4&manifest=f4m'
  80. else:
  81. smil_url = ('http://link.theplatform.com/s/{0}/{1}/meta.smil?'
  82. 'format=smil&mbr=true'.format(provider_id, video_id))
  83. sig = smuggled_data.get('sig')
  84. if sig:
  85. smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
  86. meta = self._download_xml(smil_url, video_id)
  87. try:
  88. error_msg = next(
  89. n.attrib['abstract']
  90. for n in meta.findall(_x('.//smil:ref'))
  91. if n.attrib.get('title') == 'Geographic Restriction' or n.attrib.get('title') == 'Expired')
  92. except StopIteration:
  93. pass
  94. else:
  95. raise ExtractorError(error_msg, expected=True)
  96. info_url = 'http://link.theplatform.com/s/{0}/{1}?format=preview'.format(provider_id, video_id)
  97. info_json = self._download_webpage(info_url, video_id)
  98. info = json.loads(info_json)
  99. subtitles = {}
  100. captions = info.get('captions')
  101. if isinstance(captions, list):
  102. for caption in captions:
  103. lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
  104. subtitles[lang] = [{
  105. 'ext': 'srt' if mime == 'text/srt' else 'ttml',
  106. 'url': src,
  107. }]
  108. head = meta.find(_x('smil:head'))
  109. body = meta.find(_x('smil:body'))
  110. f4m_node = body.find(_x('smil:seq//smil:video'))
  111. if f4m_node is not None and '.f4m' in f4m_node.attrib['src']:
  112. f4m_url = f4m_node.attrib['src']
  113. if 'manifest.f4m?' not in f4m_url:
  114. f4m_url += '?'
  115. # the parameters are from syfy.com, other sites may use others,
  116. # they also work for nbc.com
  117. f4m_url += '&g=UXWGVKRWHFSP&hdcore=3.0.3'
  118. formats = self._extract_f4m_formats(f4m_url, video_id)
  119. else:
  120. formats = []
  121. switch = body.find(_x('.//smil:switch'))
  122. if switch is not None:
  123. base_url = head.find(_x('smil:meta')).attrib['base']
  124. for f in switch.findall(_x('smil:video')):
  125. attr = f.attrib
  126. width = int(attr['width'])
  127. height = int(attr['height'])
  128. vbr = int(attr['system-bitrate']) // 1000
  129. format_id = '%dx%d_%dk' % (width, height, vbr)
  130. formats.append({
  131. 'format_id': format_id,
  132. 'url': base_url,
  133. 'play_path': 'mp4:' + attr['src'],
  134. 'ext': 'flv',
  135. 'width': width,
  136. 'height': height,
  137. 'vbr': vbr,
  138. })
  139. else:
  140. switch = body.find(_x('smil:seq//smil:switch'))
  141. for f in switch.findall(_x('smil:video')):
  142. attr = f.attrib
  143. vbr = int(attr['system-bitrate']) // 1000
  144. ext = determine_ext(attr['src'])
  145. if ext == 'once':
  146. ext = 'mp4'
  147. formats.append({
  148. 'format_id': compat_str(vbr),
  149. 'url': attr['src'],
  150. 'vbr': vbr,
  151. 'ext': ext,
  152. })
  153. self._sort_formats(formats)
  154. return {
  155. 'id': video_id,
  156. 'title': info['title'],
  157. 'subtitles': subtitles,
  158. 'formats': formats,
  159. 'description': info['description'],
  160. 'thumbnail': info['defaultThumbnailUrl'],
  161. 'duration': info['duration'] // 1000,
  162. }