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.

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