theplatform.py 17 KB

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