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.

466 lines
20 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. import netrc
  9. from .once import OnceIE
  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. unescapeHTML,
  26. urlencode_postdata,
  27. unified_timestamp,
  28. )
  29. default_ns = 'http://www.w3.org/2005/SMIL21/Language'
  30. _x = lambda p: xpath_with_ns(p, {'smil': default_ns})
  31. class ThePlatformBaseIE(OnceIE):
  32. def _extract_theplatform_smil(self, smil_url, video_id, note='Downloading SMIL data'):
  33. meta = self._download_xml(smil_url, video_id, note=note, query={'format': 'SMIL'})
  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.com/s/errorFiles/Unavailable.'):
  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.com/s/%s?format=preview' % 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[lang] = [{
  67. 'ext': mimetype2ext(mime),
  68. 'url': src,
  69. }]
  70. return {
  71. 'title': info['title'],
  72. 'subtitles': subtitles,
  73. 'description': info['description'],
  74. 'thumbnail': info['defaultThumbnailUrl'],
  75. 'duration': int_or_none(info.get('duration'), 1000),
  76. 'timestamp': int_or_none(info.get('pubDate'), 1000) or None,
  77. 'uploader': info.get('billingCode'),
  78. }
  79. def _extract_theplatform_metadata(self, path, video_id):
  80. info = self._download_theplatform_metadata(path, video_id)
  81. return self._parse_theplatform_metadata(info)
  82. class ThePlatformIE(ThePlatformBaseIE):
  83. _VALID_URL = r'''(?x)
  84. (?:https?://(?:link|player)\.theplatform\.com/[sp]/(?P<provider_id>[^/]+)/
  85. (?:(?:(?:[^/]+/)+select/)?(?P<media>media/(?:guid/\d+/)?)|(?P<config>(?:[^/\?]+/(?:swf|config)|onsite)/select/))?
  86. |theplatform:)(?P<id>[^/\?&]+)'''
  87. _TESTS = [{
  88. # from http://www.metacafe.com/watch/cb-e9I_cZgTgIPd/blackberrys_big_bold_z30/
  89. 'url': 'http://link.theplatform.com/s/dJ5BDC/e9I_cZgTgIPd/meta.smil?format=smil&Tracking=true&mbr=true',
  90. 'info_dict': {
  91. 'id': 'e9I_cZgTgIPd',
  92. 'ext': 'flv',
  93. 'title': 'Blackberry\'s big, bold Z30',
  94. 'description': 'The Z30 is Blackberry\'s biggest, baddest mobile messaging device yet.',
  95. 'duration': 247,
  96. 'timestamp': 1383239700,
  97. 'upload_date': '20131031',
  98. 'uploader': 'CBSI-NEW',
  99. },
  100. 'params': {
  101. # rtmp download
  102. 'skip_download': True,
  103. },
  104. }, {
  105. # from http://www.cnet.com/videos/tesla-model-s-a-second-step-towards-a-cleaner-motoring-future/
  106. 'url': 'http://link.theplatform.com/s/kYEXFC/22d_qsQ6MIRT',
  107. 'info_dict': {
  108. 'id': '22d_qsQ6MIRT',
  109. 'ext': 'flv',
  110. 'description': 'md5:ac330c9258c04f9d7512cf26b9595409',
  111. 'title': 'Tesla Model S: A second step towards a cleaner motoring future',
  112. 'timestamp': 1426176191,
  113. 'upload_date': '20150312',
  114. 'uploader': 'CBSI-NEW',
  115. },
  116. 'params': {
  117. # rtmp download
  118. 'skip_download': True,
  119. }
  120. }, {
  121. 'url': 'https://player.theplatform.com/p/D6x-PC/pulse_preview/embed/select/media/yMBg9E8KFxZD',
  122. 'info_dict': {
  123. 'id': 'yMBg9E8KFxZD',
  124. 'ext': 'mp4',
  125. 'description': 'md5:644ad9188d655b742f942bf2e06b002d',
  126. 'title': 'HIGHLIGHTS: USA bag first ever series Cup win',
  127. 'uploader': 'EGSM',
  128. }
  129. }, {
  130. 'url': 'http://player.theplatform.com/p/NnzsPC/widget/select/media/4Y0TlYUr_ZT7',
  131. 'only_matching': True,
  132. }, {
  133. 'url': 'http://player.theplatform.com/p/2E2eJC/nbcNewsOffsite?guid=tdy_or_siri_150701',
  134. 'md5': 'fb96bb3d85118930a5b055783a3bd992',
  135. 'info_dict': {
  136. 'id': 'tdy_or_siri_150701',
  137. 'ext': 'mp4',
  138. 'title': 'iPhone Siri’s sassy response to a math question has people talking',
  139. 'description': 'md5:a565d1deadd5086f3331d57298ec6333',
  140. 'duration': 83.0,
  141. 'thumbnail': 're:^https?://.*\.jpg$',
  142. 'timestamp': 1435752600,
  143. 'upload_date': '20150701',
  144. 'uploader': 'NBCU-NEWS',
  145. },
  146. }, {
  147. # From http://www.nbc.com/the-blacklist/video/sir-crispin-crandall/2928790?onid=137781#vc137781=1
  148. # geo-restricted (US), HLS encrypted with AES-128
  149. 'url': 'http://player.theplatform.com/p/NnzsPC/onsite_universal/select/media/guid/2410887629/2928790?fwsitesection=nbc_the_blacklist_video_library&autoPlay=true&carouselID=137781',
  150. 'only_matching': True,
  151. }]
  152. _SERVICE_PROVIDER_TEMPLATE = 'https://sp.auth.adobe.com/adobe-services/%s'
  153. @classmethod
  154. def _extract_urls(cls, webpage):
  155. m = re.search(
  156. r'''(?x)
  157. <meta\s+
  158. property=(["'])(?:og:video(?::(?:secure_)?url)?|twitter:player)\1\s+
  159. content=(["'])(?P<url>https?://player\.theplatform\.com/p/.+?)\2
  160. ''', webpage)
  161. if m:
  162. return [m.group('url')]
  163. matches = re.findall(
  164. r'<(?:iframe|script)[^>]+src=(["\'])((?:https?:)?//player\.theplatform\.com/p/.+?)\1', webpage)
  165. if matches:
  166. return list(zip(*matches))[1]
  167. @staticmethod
  168. def _sign_url(url, sig_key, sig_secret, life=600, include_qs=False):
  169. flags = '10' if include_qs else '00'
  170. expiration_date = '%x' % (int(time.time()) + life)
  171. def str_to_hex(str):
  172. return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
  173. def hex_to_bytes(hex):
  174. return binascii.a2b_hex(hex.encode('ascii'))
  175. relative_path = re.match(r'https?://link.theplatform.com/s/([^?]+)', url).group(1)
  176. clear_text = hex_to_bytes(flags + expiration_date + str_to_hex(relative_path))
  177. checksum = hmac.new(sig_key.encode('ascii'), clear_text, hashlib.sha1).hexdigest()
  178. sig = flags + expiration_date + checksum + str_to_hex(sig_secret)
  179. return '%s&sig=%s' % (url, sig)
  180. def _extract_mvpd_auth(self, url, video_id, requestor_id, resource):
  181. def xml_text(xml_str, tag):
  182. return self._search_regex(
  183. '<%s>(.+?)</%s>' % (tag, tag), xml_str, tag)
  184. mvpd_headers = {
  185. 'ap_42': 'anonymous',
  186. 'ap_11': 'Linux i686',
  187. 'ap_z': 'Mozilla/5.0 (X11; Linux i686; rv:47.0) Gecko/20100101 Firefox/47.0',
  188. 'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:47.0) Gecko/20100101 Firefox/47.0',
  189. }
  190. guid = xml_text(resource, 'guid')
  191. requestor_info = self._downloader.cache.load('mvpd', requestor_id) or {}
  192. authn_token = requestor_info.get('authn_token')
  193. if authn_token:
  194. token_expires = unified_timestamp(xml_text(authn_token, 'simpleTokenExpires').replace('_GMT', ''))
  195. if token_expires and token_expires >= time.time():
  196. authn_token = None
  197. if not authn_token:
  198. # TODO add support for other TV Providers
  199. mso_id = 'DTV'
  200. login_info = netrc.netrc().authenticators(mso_id)
  201. if not login_info:
  202. return None
  203. def post_form(form_page, note, data={}):
  204. post_url = self._html_search_regex(r'<form[^>]+action=(["\'])(?P<url>.+?)\1', form_page, 'post url', group='url')
  205. return self._download_webpage(
  206. post_url, video_id, note, data=urlencode_postdata(data or self._hidden_inputs(form_page)), headers={
  207. 'Content-Type': 'application/x-www-form-urlencoded',
  208. })
  209. provider_redirect_page = self._download_webpage(
  210. self._SERVICE_PROVIDER_TEMPLATE % 'authenticate/saml', video_id,
  211. 'Downloading Provider Redirect Page', query={
  212. 'noflash': 'true',
  213. 'mso_id': mso_id,
  214. 'requestor_id': requestor_id,
  215. 'no_iframe': 'false',
  216. 'domain_name': 'adobe.com',
  217. 'redirect_url': url,
  218. })
  219. provider_login_page = post_form(
  220. provider_redirect_page, 'Downloading Provider Login Page')
  221. mvpd_confirm_page = post_form(provider_login_page, 'Logging in', {
  222. 'username': login_info[0],
  223. 'password': login_info[2],
  224. })
  225. post_form(mvpd_confirm_page, 'Confirming Login')
  226. session = self._download_webpage(
  227. self._SERVICE_PROVIDER_TEMPLATE % 'session', video_id,
  228. 'Retrieving Session', data=urlencode_postdata({
  229. '_method': 'GET',
  230. 'requestor_id': requestor_id,
  231. }), headers=mvpd_headers)
  232. authn_token = unescapeHTML(xml_text(session, 'authnToken'))
  233. requestor_info['authn_token'] = authn_token
  234. self._downloader.cache.store('mvpd', requestor_id, requestor_info)
  235. authz_token = requestor_info.get(guid)
  236. if not authz_token:
  237. authorize = self._download_webpage(
  238. self._SERVICE_PROVIDER_TEMPLATE % 'authorize', video_id,
  239. 'Retrieving Authorization Token', data=urlencode_postdata({
  240. 'resource_id': resource,
  241. 'requestor_id': requestor_id,
  242. 'authentication_token': authn_token,
  243. 'mso_id': xml_text(authn_token, 'simpleTokenMsoID'),
  244. 'userMeta': '1',
  245. }), headers=mvpd_headers)
  246. authz_token = unescapeHTML(xml_text(authorize, 'authzToken'))
  247. requestor_info[guid] = authz_token
  248. self._downloader.cache.store('mvpd', requestor_id, requestor_info)
  249. mvpd_headers.update({
  250. 'ap_19': xml_text(authn_token, 'simpleSamlNameID'),
  251. 'ap_23': xml_text(authn_token, 'simpleSamlSessionIndex'),
  252. })
  253. return self._download_webpage(
  254. self._SERVICE_PROVIDER_TEMPLATE % 'shortAuthorize',
  255. video_id, 'Retrieving Media Token', data=urlencode_postdata({
  256. 'authz_token': authz_token,
  257. 'requestor_id': requestor_id,
  258. 'session_guid': xml_text(authn_token, 'simpleTokenAuthenticationGuid'),
  259. 'hashed_guid': 'false',
  260. }), headers=mvpd_headers)
  261. def _real_extract(self, url):
  262. url, smuggled_data = unsmuggle_url(url, {})
  263. mobj = re.match(self._VALID_URL, url)
  264. provider_id = mobj.group('provider_id')
  265. video_id = mobj.group('id')
  266. if not provider_id:
  267. provider_id = 'dJ5BDC'
  268. path = provider_id + '/'
  269. if mobj.group('media'):
  270. path += mobj.group('media')
  271. path += video_id
  272. qs_dict = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
  273. if 'guid' in qs_dict:
  274. webpage = self._download_webpage(url, video_id)
  275. scripts = re.findall(r'<script[^>]+src="([^"]+)"', webpage)
  276. feed_id = None
  277. # feed id usually locates in the last script.
  278. # Seems there's no pattern for the interested script filename, so
  279. # I try one by one
  280. for script in reversed(scripts):
  281. feed_script = self._download_webpage(
  282. self._proto_relative_url(script, 'http:'),
  283. video_id, 'Downloading feed script')
  284. feed_id = self._search_regex(
  285. r'defaultFeedId\s*:\s*"([^"]+)"', feed_script,
  286. 'default feed id', default=None)
  287. if feed_id is not None:
  288. break
  289. if feed_id is None:
  290. raise ExtractorError('Unable to find feed id')
  291. return self.url_result('http://feed.theplatform.com/f/%s/%s?byGuid=%s' % (
  292. provider_id, feed_id, qs_dict['guid'][0]))
  293. if smuggled_data.get('force_smil_url', False):
  294. smil_url = url
  295. # Explicitly specified SMIL (see https://github.com/rg3/youtube-dl/issues/7385)
  296. elif '/guid/' in url:
  297. headers = {}
  298. source_url = smuggled_data.get('source_url')
  299. if source_url:
  300. headers['Referer'] = source_url
  301. request = sanitized_Request(url, headers=headers)
  302. webpage = self._download_webpage(request, video_id)
  303. smil_url = self._search_regex(
  304. r'<link[^>]+href=(["\'])(?P<url>.+?)\1[^>]+type=["\']application/smil\+xml',
  305. webpage, 'smil url', group='url')
  306. path = self._search_regex(
  307. r'link\.theplatform\.com/s/((?:[^/?#&]+/)+[^/?#&]+)', smil_url, 'path')
  308. smil_url += '?' if '?' not in smil_url else '&' + 'formats=m3u,mpeg4'
  309. elif mobj.group('config'):
  310. config_url = url + '&form=json'
  311. config_url = config_url.replace('swf/', 'config/')
  312. config_url = config_url.replace('onsite/', 'onsite/config/')
  313. config = self._download_json(config_url, video_id, 'Downloading config')
  314. if 'releaseUrl' in config:
  315. release_url = config['releaseUrl']
  316. else:
  317. release_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
  318. smil_url = release_url + '&formats=MPEG4&manifest=f4m'
  319. else:
  320. smil_url = 'http://link.theplatform.com/s/%s?mbr=true' % path
  321. sig = smuggled_data.get('sig')
  322. if sig:
  323. smil_url = self._sign_url(smil_url, sig['key'], sig['secret'])
  324. formats, subtitles = self._extract_theplatform_smil(smil_url, video_id)
  325. self._sort_formats(formats)
  326. ret = self._extract_theplatform_metadata(path, video_id)
  327. combined_subtitles = self._merge_subtitles(ret.get('subtitles', {}), subtitles)
  328. ret.update({
  329. 'id': video_id,
  330. 'formats': formats,
  331. 'subtitles': combined_subtitles,
  332. })
  333. return ret
  334. class ThePlatformFeedIE(ThePlatformBaseIE):
  335. _URL_TEMPLATE = '%s//feed.theplatform.com/f/%s/%s?form=json&%s'
  336. _VALID_URL = r'https?://feed\.theplatform\.com/f/(?P<provider_id>[^/]+)/(?P<feed_id>[^?/]+)\?(?:[^&]+&)*(?P<filter>by(?:Gui|I)d=(?P<id>[\w-]+))'
  337. _TESTS = [{
  338. # From http://player.theplatform.com/p/7wvmTC/MSNBCEmbeddedOffSite?guid=n_hardball_5biden_140207
  339. 'url': 'http://feed.theplatform.com/f/7wvmTC/msnbc_video-p-test?form=json&pretty=true&range=-40&byGuid=n_hardball_5biden_140207',
  340. 'md5': '6e32495b5073ab414471b615c5ded394',
  341. 'info_dict': {
  342. 'id': 'n_hardball_5biden_140207',
  343. 'ext': 'mp4',
  344. 'title': 'The Biden factor: will Joe run in 2016?',
  345. 'description': 'Could Vice President Joe Biden be preparing a 2016 campaign? Mark Halperin and Sam Stein weigh in.',
  346. 'thumbnail': 're:^https?://.*\.jpg$',
  347. 'upload_date': '20140208',
  348. 'timestamp': 1391824260,
  349. 'duration': 467.0,
  350. 'categories': ['MSNBC/Issues/Democrats', 'MSNBC/Issues/Elections/Election 2016'],
  351. 'uploader': 'NBCU-NEWS',
  352. },
  353. }]
  354. def _extract_feed_info(self, provider_id, feed_id, filter_query, video_id, custom_fields=None, asset_types_query={}):
  355. real_url = self._URL_TEMPLATE % (self.http_scheme(), provider_id, feed_id, filter_query)
  356. entry = self._download_json(real_url, video_id)['entries'][0]
  357. formats = []
  358. subtitles = {}
  359. first_video_id = None
  360. duration = None
  361. asset_types = []
  362. for item in entry['media$content']:
  363. smil_url = item['plfile$url']
  364. cur_video_id = ThePlatformIE._match_id(smil_url)
  365. if first_video_id is None:
  366. first_video_id = cur_video_id
  367. duration = float_or_none(item.get('plfile$duration'))
  368. for asset_type in item['plfile$assetTypes']:
  369. if asset_type in asset_types:
  370. continue
  371. asset_types.append(asset_type)
  372. query = {
  373. 'mbr': 'true',
  374. 'formats': item['plfile$format'],
  375. 'assetTypes': asset_type,
  376. }
  377. if asset_type in asset_types_query:
  378. query.update(asset_types_query[asset_type])
  379. cur_formats, cur_subtitles = self._extract_theplatform_smil(update_url_query(
  380. smil_url, query), video_id, 'Downloading SMIL data for %s' % asset_type)
  381. formats.extend(cur_formats)
  382. subtitles = self._merge_subtitles(subtitles, cur_subtitles)
  383. self._sort_formats(formats)
  384. thumbnails = [{
  385. 'url': thumbnail['plfile$url'],
  386. 'width': int_or_none(thumbnail.get('plfile$width')),
  387. 'height': int_or_none(thumbnail.get('plfile$height')),
  388. } for thumbnail in entry.get('media$thumbnails', [])]
  389. timestamp = int_or_none(entry.get('media$availableDate'), scale=1000)
  390. categories = [item['media$name'] for item in entry.get('media$categories', [])]
  391. ret = self._extract_theplatform_metadata('%s/%s' % (provider_id, first_video_id), video_id)
  392. subtitles = self._merge_subtitles(subtitles, ret['subtitles'])
  393. ret.update({
  394. 'id': video_id,
  395. 'formats': formats,
  396. 'subtitles': subtitles,
  397. 'thumbnails': thumbnails,
  398. 'duration': duration,
  399. 'timestamp': timestamp,
  400. 'categories': categories,
  401. })
  402. if custom_fields:
  403. ret.update(custom_fields(entry))
  404. return ret
  405. def _real_extract(self, url):
  406. mobj = re.match(self._VALID_URL, url)
  407. video_id = mobj.group('id')
  408. provider_id = mobj.group('provider_id')
  409. feed_id = mobj.group('feed_id')
  410. filter_query = mobj.group('filter')
  411. return self._extract_feed_info(provider_id, feed_id, filter_query, video_id)