You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

402 lines
16 KiB

10 years ago
10 years ago
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import time
  5. import hmac
  6. import binascii
  7. import hashlib
  8. from .once import OnceIE
  9. from .adobepass import AdobePassIE
  10. from ..compat import (
  11. compat_parse_qs,
  12. compat_urllib_parse_urlparse,
  13. )
  14. from ..utils import (
  15. determine_ext,
  16. ExtractorError,
  17. float_or_none,
  18. int_or_none,
  19. sanitized_Request,
  20. unsmuggle_url,
  21. update_url_query,
  22. xpath_with_ns,
  23. mimetype2ext,
  24. find_xpath_attr,
  25. )
  26. default_ns = 'http://www.w3.org/2005/SMIL21/Language'
  27. _x = lambda p: xpath_with_ns(p, {'smil': default_ns})
  28. class ThePlatformBaseIE(OnceIE):
  29. _TP_TLD = 'com'
  30. def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'):
  31. meta = self._download_xml(
  32. smil_url, video_id, note=note, query={'format': 'SMIL'},
  33. headers=self.geo_verification_headers())
  34. error_element = find_xpath_attr(meta, _x('.//smil:ref'), 'src')
  35. if error_element is not None and error_element.attrib['src'].startswith(
  36. 'http://link.theplatform.%s/s/errorFiles/Unavailable.' % self._TP_TLD):
  37. raise ExtractorError(error_element.attrib['abstract'], expected=True)
  38. smil_formats = self._parse_smil_formats(
  39. meta, smil_url, video_id, namespace=default_ns,
  40. # the parameters are from syfy.com, other sites may use others,
  41. # they also work for nbc.com
  42. f4m_params={'g': 'UXWGVKRWHFSP', 'hdcore': '3.0.3'},
  43. transform_rtmp_url=lambda streamer, src: (streamer, 'mp4:' + src))
  44. formats = []
  45. for _format in smil_formats:
  46. if OnceIE.suitable(_format['url']):
  47. formats.extend(self._extract_once_formats(_format['url']))
  48. else:
  49. media_url = _format['url']
  50. if determine_ext(media_url) == 'm3u8':
  51. hdnea2 = self._get_cookies(media_url).get('hdnea2')
  52. if hdnea2:
  53. _format['url'] = update_url_query(media_url, {'hdnea3': hdnea2.value})
  54. formats.append(_format)
  55. subtitles = self._parse_smil_subtitles(meta, default_ns)
  56. return formats, subtitles
  57. def _download_theplatform_metadata(self, path, video_id):
  58. info_url = 'http://link.theplatform.%s/s/%s?format=preview' % (self._TP_TLD, path)
  59. return self._download_json(info_url, video_id)
  60. def _parse_theplatform_metadata(self, info):
  61. subtitles = {}
  62. captions = info.get('captions')
  63. if isinstance(captions, list):
  64. for caption in captions:
  65. lang, src, mime = caption.get('lang', 'en'), caption.get('src'), caption.get('type')
  66. subtitles.setdefault(lang, []).append({
  67. 'ext': mimetype2ext(mime),
  68. 'url': src,
  69. })
  70. duration = info.get('duration')
  71. tp_chapters = info.get('chapters', [])
  72. chapters = []
  73. if tp_chapters:
  74. def _add_chapter(start_time, end_time):
  75. start_time = float_or_none(start_time, 1000)
  76. end_time = float_or_none(end_time, 1000)
  77. if start_time is None or end_time is None:
  78. return
  79. chapters.append({
  80. 'start_time': start_time,
  81. 'end_time': end_time,
  82. })
  83. for chapter in tp_chapters[:-1]:
  84. _add_chapter(chapter.get('startTime'), chapter.get('endTime'))
  85. _add_chapter(tp_chapters[-1].get('startTime'), tp_chapters[-1].get('endTime') or duration)
  86. return {
  87. 'title': info['title'],
  88. 'subtitles': subtitles,
  89. 'description': info['description'],
  90. 'thumbnail': info['defaultThumbnailUrl'],
  91. 'duration': float_or_none(duration, 1000),
  92. 'timestamp': int_or_none(info.get('pubDate'), 1000) or None,
  93. 'uploader': info.get('billingCode'),
  94. 'chapters': chapters,
  95. }
  96. def _extract_theplatform_metadata(self, path, video_id):
  97. info = self._download_theplatform_metadata(path, video_id)
  98. return self._parse_theplatform_metadata(info)
  99. class ThePlatformIE(ThePlatformBaseIE, AdobePassIE):
  100. _VALID_URL = r'''(?x)
  101. (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
  102. (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)?|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
  103. |theplatform:)(?P<id>[^/\?&]+)'''
  104. _TESTS = [{
  105. # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
  106. 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
  107. 'info_dict': {
  108. 'id': 'e9I_cZgTgIPd',
  109. 'ext': 'flv',
  110. 'title': 'Blackberry\'s big, bold Z30',
  111. 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
  112. 'duration': 247,
  113. 'timestamp': 1383239700,
  114. 'upload_date': '20131031',
  115. 'uploader': 'CBSI-NEW',
  116. },
  117. 'params': {
  118. # rtmp download
  119. 'skip_download': True,
  120. },
  121. 'skip': '404 Not Found',
  122. }, {
  123. # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
  124. 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
  125. 'info_dict': {
  126. 'id': '22d_qsQ6MIRT',
  127. 'ext': 'flv',
  128. 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
  129. 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
  130. 'timestamp': 1426176191,
  131. 'upload_date': '20150312',
  132. 'uploader': 'CBSI-NEW',
  133. },
  134. 'params': {
  135. # rtmp download
  136. 'skip_download': True,
  137. }
  138. }, {
  139. 'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
  140. 'info_dict': {
  141. 'id': 'yMBg9E8KFxZD',
  142. 'ext': 'mp4',
  143. 'description': 'md5:644ad9188d655b742f942bf2e06b002d',
  144. 'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
  145. 'uploader': 'EGSM',
  146. }
  147. }, {
  148. 'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
  149. 'only_matching': True,
  150. }, {
  151. 'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701',
  152. 'md5': 'fb96bb3d85118930a5b055783a3bd992',
  153. 'info_dict': {
  154. 'id': 'tdy_or_siri_150701',
  155. 'ext': 'mp4',
  156. 'title': 'iPhone Siri’s sassy response to a math question has people talking',
  157. 'description': 'md5:a565d1deadd5086f3331d57298ec6333',
  158. 'duration': 83.0,
  159. 'thumbnail': r're:^https?://.*\.jpg$',
  160. 'timestamp': 1435752600,
  161. 'upload_date': '20150701',
  162. 'uploader': 'NBCU-NEWS',
  163. },
  164. }, {
  165. # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
  166. # geo-restricted (US), HLS encrypted with AES-128
  167. 'url': 'http://player.theplatform.com/p/NnzsPC/onsite_universal/select/media/guid/2410887629/2928790?fwsitesection=nbc_the_blacklist_video_library&autoPlay=true&carouselID=137781',
  168. 'only_matching': True,
  169. }]
  170. @classmethod
  171. def _extract_urls(cls, webpage):
  172. m = re.search(
  173. r'''(?x)
  174. <meta\s+
  175. property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
  176. content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2
  177. ''', webpage)
  178. if m:
  179. return [m.group('url')]
  180. # Are whitesapces ignored in URLs?
  181. # https://github.com/rg3/youtube-dl/issues/12044
  182. matches = re.findall(
  183. r'(?s)<(?:iframe|script)[^>]+src=(["\'])((?:https?:)?//player\.theplatform\.com/p/.+?)\1', webpage)
  184. if matches:
  185. return [re.sub(r'\s', '', list(zip(*matches))[1][0])]
  186. @staticmethod
  187. def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
  188. flags = '10' if include_qs else '00'
  189. expiration_date = '%x' % (int(time.time()) + life)
  190. def str_to_hex(str):
  191. return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
  192. def hex_to_bytes(hex):
  193. return binascii.a2b_hex(hex.encode('ascii'))
  194. relative_path = re.match(r'https?://link\.theplatform\.com/s/([^?]+)', url).group(1)
  195. clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
  196. checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
  197. sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
  198. return '%s&sig=%s' % (url, sig)
  199. def _real_extract(self, url):
  200. url, smuggled_data = unsmuggle_url(url, {})
  201. mobj = re.match(self._VALID_URL, url)
  202. provider_id = mobj.group('provider_id')
  203. video_id = mobj.group('id')
  204. if not provider_id:
  205. provider_id = 'dJ5BDC'
  206. path = provider_id + '/'
  207. if mobj.group('media'):
  208. path += mobj.group('media')
  209. path += video_id
  210. qs_dict = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  211. if 'guid' in qs_dict:
  212. webpage = self._download_webpage(url, video_id)
  213. scripts = re.findall(r'<script[^>]+src="([^"]+)"', webpage)
  214. feed_id = None
  215. # feed id usually locates in the last script.
  216. # Seems there's no pattern for the interested script filename, so
  217. # I try one by one
  218. for script in reversed(scripts):
  219. feed_script = self._download_webpage(
  220. self._proto_relative_url(script, 'http:'),
  221. video_id, 'Downloading feed script')
  222. feed_id = self._search_regex(
  223. r'defaultFeedId\s*:\s*"([^"]+)"', feed_script,
  224. 'default feed id', default=None)
  225. if feed_id is not None:
  226. break
  227. if feed_id is None:
  228. raise ExtractorError('Unable to find feed id')
  229. return self.url_result('http://feed.theplatform.com/f/%s/%s?byGuid=%s' % (
  230. provider_id, feed_id, qs_dict['guid'][0]))
  231. if smuggled_data.get('force_smil_url', False):
  232. smil_url = url
  233. # Explicitly specified SMIL (see https://github.com/rg3/youtube-dl/issues/7385)
  234. elif '/guid/' in url:
  235. headers = {}
  236. source_url = smuggled_data.get('source_url')
  237. if source_url:
  238. headers['Referer'] = source_url
  239. request = sanitized_Request(url, headers=headers)
  240. webpage = self._download_webpage(request, video_id)
  241. smil_url = self._search_regex(
  242. r'<link[^>]+href=(["\'])(?P<url>.+?)\1[^>]+type=["\']application/smil\+xml',
  243. webpage, 'smil url', group='url')
  244. path = self._search_regex(
  245. r'link\.theplatform\.com/s/((?:[^/?#&]+/)+[^/?#&]+)', smil_url, 'path')
  246. smil_url += '?' if '?' not in smil_url else '&' + 'formats=m3u,mpeg4'
  247. elif mobj.group('config'):
  248. config_url = url + '&form=json'
  249. config_url = config_url.replace('swf/', 'config/')
  250. config_url = config_url.replace('onsite/', 'onsite/config/')
  251. config = self._download_json(config_url, video_id, 'Downloading config')
  252. if 'releaseUrl' in config:
  253. release_url = config['releaseUrl']
  254. else:
  255. release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
  256. smil_url = release_url + '&formats=MPEG4&manifest=f4m'
  257. else:
  258. smil_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
  259. sig = smuggled_data.get('sig')
  260. if sig:
  261. smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
  262. formats, subtitles = self._extract_theplatform_smil(smil_url, video_id)
  263. self._sort_formats(formats)
  264. ret = self._extract_theplatform_metadata(path, video_id)
  265. combined_subtitles = self._merge_subtitles(ret.get('subtitles', {}), subtitles)
  266. ret.update({
  267. 'id': video_id,
  268. 'formats': formats,
  269. 'subtitles': combined_subtitles,
  270. })
  271. return ret
  272. class ThePlatformFeedIE(ThePlatformBaseIE):
  273. _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
  274. _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[^&]+))'
  275. _TESTS = [{
  276. # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
  277. 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
  278. 'md5': '6e32495b5073ab414471b615c5ded394',
  279. 'info_dict': {
  280. 'id': 'n_hardball_5biden_140207',
  281. 'ext': 'mp4',
  282. 'title': 'The Biden factor: will Joe run in 2016?',
  283. 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
  284. 'thumbnail': r're:^https?://.*\.jpg$',
  285. 'upload_date': '20140208',
  286. 'timestamp': 1391824260,
  287. 'duration': 467.0,
  288. 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
  289. 'uploader': 'NBCU-NEWS',
  290. },
  291. }, {
  292. 'url': 'http://feed.theplatform.com/f/2E2eJC/nnd_NBCNews?byGuid=nn_netcast_180306.Copy.01',
  293. 'only_matching': True,
  294. }]
  295. def _extract_feed_info(self, provider_id, feed_id, filter_query, video_id, custom_fields=None, asset_types_query={}, account_id=None):
  296. real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, filter_query)
  297. entry = self._download_json(real_url, video_id)['entries'][0]
  298. main_smil_url = 'http://link.theplatform.com/s/%s/media/guid/%d/%s' % (provider_id, account_id, entry['guid']) if account_id else None
  299. formats = []
  300. subtitles = {}
  301. first_video_id = None
  302. duration = None
  303. asset_types = []
  304. for item in entry['media$content']:
  305. smil_url = item['plfile$url']
  306. cur_video_id = ThePlatformIE._match_id(smil_url)
  307. if first_video_id is None:
  308. first_video_id = cur_video_id
  309. duration = float_or_none(item.get('plfile$duration'))
  310. for asset_type in item['plfile$assetTypes']:
  311. if asset_type in asset_types:
  312. continue
  313. asset_types.append(asset_type)
  314. query = {
  315. 'mbr': 'true',
  316. 'formats': item['plfile$format'],
  317. 'assetTypes': asset_type,
  318. }
  319. if asset_type in asset_types_query:
  320. query.update(asset_types_query[asset_type])
  321. cur_formats, cur_subtitles = self._extract_theplatform_smil(update_url_query(
  322. main_smil_url or smil_url, query), video_id, 'Downloading SMIL data for %s' % asset_type)
  323. formats.extend(cur_formats)
  324. subtitles = self._merge_subtitles(subtitles, cur_subtitles)
  325. self._sort_formats(formats)
  326. thumbnails = [{
  327. 'url': thumbnail['plfile$url'],
  328. 'width': int_or_none(thumbnail.get('plfile$width')),
  329. 'height': int_or_none(thumbnail.get('plfile$height')),
  330. } for thumbnail in entry.get('media$thumbnails', [])]
  331. timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
  332. categories = [item['media$name'] for item in entry.get('media$categories', [])]
  333. ret = self._extract_theplatform_metadata('%s/%s' % (provider_id, first_video_id), video_id)
  334. subtitles = self._merge_subtitles(subtitles, ret['subtitles'])
  335. ret.update({
  336. 'id': video_id,
  337. 'formats': formats,
  338. 'subtitles': subtitles,
  339. 'thumbnails': thumbnails,
  340. 'duration': duration,
  341. 'timestamp': timestamp,
  342. 'categories': categories,
  343. })
  344. if custom_fields:
  345. ret.update(custom_fields(entry))
  346. return ret
  347. def _real_extract(self, url):
  348. mobj = re.match(self._VALID_URL, url)
  349. video_id = mobj.group('id')
  350. provider_id = mobj.group('provider_id')
  351. feed_id = mobj.group('feed_id')
  352. filter_query = mobj.group('filter')
  353. return self._extract_feed_info(provider_id, feed_id, filter_query, video_id)