condenast.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import re
  2. import urllib.parse
  3. from .common import InfoExtractor
  4. from ..utils import (
  5. determine_ext,
  6. extract_attributes,
  7. int_or_none,
  8. js_to_json,
  9. mimetype2ext,
  10. orderedSet,
  11. parse_iso8601,
  12. strip_or_none,
  13. try_get,
  14. )
  15. class CondeNastIE(InfoExtractor):
  16. """
  17. Condé Nast is a media group, some of its sites use a custom HTML5 player
  18. that works the same in all of them.
  19. """
  20. # The keys are the supported sites and the values are the name to be shown
  21. # to the user and in the extractor description.
  22. _SITES = {
  23. 'allure': 'Allure',
  24. 'architecturaldigest': 'Architectural Digest',
  25. 'arstechnica': 'Ars Technica',
  26. 'bonappetit': 'Bon Appétit',
  27. 'brides': 'Brides',
  28. 'cnevids': 'Condé Nast',
  29. 'cntraveler': 'Condé Nast Traveler',
  30. 'details': 'Details',
  31. 'epicurious': 'Epicurious',
  32. 'glamour': 'Glamour',
  33. 'golfdigest': 'Golf Digest',
  34. 'gq': 'GQ',
  35. 'newyorker': 'The New Yorker',
  36. 'self': 'SELF',
  37. 'teenvogue': 'Teen Vogue',
  38. 'vanityfair': 'Vanity Fair',
  39. 'vogue': 'Vogue',
  40. 'wired': 'WIRED',
  41. 'wmagazine': 'W Magazine',
  42. }
  43. _VALID_URL = r'''(?x)https?://(?:video|www|player(?:-backend)?)\.(?:{})\.com/
  44. (?:
  45. (?:
  46. embed(?:js)?|
  47. (?:script|inline)/video
  48. )/(?P<id>[0-9a-f]{{24}})(?:/(?P<player_id>[0-9a-f]{{24}}))?(?:.+?\btarget=(?P<target>[^&]+))?|
  49. (?P<type>watch|series|video)/(?P<display_id>[^/?#]+)
  50. )'''.format('|'.join(_SITES.keys()))
  51. IE_DESC = 'Condé Nast media group: {}'.format(', '.join(sorted(_SITES.values())))
  52. _EMBED_REGEX = [r'''(?x)
  53. <(?:iframe|script)[^>]+?src=(["\'])(?P<url>
  54. (?:https?:)?//player(?:-backend)?\.(?:{})\.com/(?:embed(?:js)?|(?:script|inline)/video)/.+?
  55. )\1'''.format('|'.join(_SITES.keys()))]
  56. _TESTS = [{
  57. 'url': 'http://video.wired.com/watch/3d-printed-speakers-lit-with-led',
  58. 'md5': '1921f713ed48aabd715691f774c451f7',
  59. 'info_dict': {
  60. 'id': '5171b343c2b4c00dd0c1ccb3',
  61. 'ext': 'mp4',
  62. 'title': '3D Printed Speakers Lit With LED',
  63. 'description': 'Check out these beautiful 3D printed LED speakers. You can\'t actually buy them, but LumiGeek is working on a board that will let you make you\'re own.',
  64. 'uploader': 'wired',
  65. 'upload_date': '20130314',
  66. 'timestamp': 1363219200,
  67. },
  68. }, {
  69. 'url': 'http://video.gq.com/watch/the-closer-with-keith-olbermann-the-only-true-surprise-trump-s-an-idiot?c=series',
  70. 'info_dict': {
  71. 'id': '58d1865bfd2e6126e2000015',
  72. 'ext': 'mp4',
  73. 'title': 'The Only True Surprise? Trump’s an Idiot',
  74. 'uploader': 'gq',
  75. 'upload_date': '20170321',
  76. 'timestamp': 1490126427,
  77. 'description': 'How much grimmer would things be if these people were competent?',
  78. },
  79. }, {
  80. # JS embed
  81. 'url': 'http://player.cnevids.com/embedjs/55f9cf8b61646d1acf00000c/5511d76261646d5566020000.js',
  82. 'md5': 'f1a6f9cafb7083bab74a710f65d08999',
  83. 'info_dict': {
  84. 'id': '55f9cf8b61646d1acf00000c',
  85. 'ext': 'mp4',
  86. 'title': '3D printed TSA Travel Sentry keys really do open TSA locks',
  87. 'uploader': 'arstechnica',
  88. 'upload_date': '20150916',
  89. 'timestamp': 1442434920,
  90. },
  91. }, {
  92. 'url': 'https://player.cnevids.com/inline/video/59138decb57ac36b83000005.js?target=js-cne-player',
  93. 'only_matching': True,
  94. }, {
  95. 'url': 'http://player-backend.cnevids.com/script/video/59138decb57ac36b83000005.js',
  96. 'only_matching': True,
  97. }]
  98. def _extract_series(self, url, webpage):
  99. title = self._html_search_regex(
  100. r'(?s)<div class="cne-series-info">.*?<h1>(.+?)</h1>',
  101. webpage, 'series title')
  102. url_object = urllib.parse.urlparse(url)
  103. base_url = f'{url_object.scheme}://{url_object.netloc}'
  104. m_paths = re.finditer(
  105. r'(?s)<p class="cne-thumb-title">.*?<a href="(/watch/.+?)["\?]', webpage)
  106. paths = orderedSet(m.group(1) for m in m_paths)
  107. build_url = lambda path: urllib.parse.urljoin(base_url, path)
  108. entries = [self.url_result(build_url(path), 'CondeNast') for path in paths]
  109. return self.playlist_result(entries, playlist_title=title)
  110. def _extract_video_params(self, webpage, display_id):
  111. query = self._parse_json(
  112. self._search_regex(
  113. r'(?s)var\s+params\s*=\s*({.+?})[;,]', webpage, 'player params',
  114. default='{}'),
  115. display_id, transform_source=js_to_json, fatal=False)
  116. if query:
  117. query['videoId'] = self._search_regex(
  118. r'(?:data-video-id=|currentVideoId\s*=\s*)["\']([\da-f]+)',
  119. webpage, 'video id', default=None)
  120. else:
  121. params = extract_attributes(self._search_regex(
  122. r'(<[^>]+data-js="video-player"[^>]+>)',
  123. webpage, 'player params element'))
  124. query.update({
  125. 'videoId': params['data-video'],
  126. 'playerId': params['data-player'],
  127. 'target': params['id'],
  128. })
  129. return query
  130. def _extract_video(self, params):
  131. video_id = params['videoId']
  132. video_info = None
  133. # New API path
  134. query = params.copy()
  135. query['embedType'] = 'inline'
  136. info_page = self._download_json(
  137. 'http://player.cnevids.com/embed-api.json', video_id,
  138. 'Downloading embed info', fatal=False, query=query)
  139. # Old fallbacks
  140. if not info_page:
  141. if params.get('playerId'):
  142. info_page = self._download_json(
  143. 'http://player.cnevids.com/player/video.js', video_id,
  144. 'Downloading video info', fatal=False, query=params)
  145. if info_page:
  146. video_info = info_page.get('video')
  147. if not video_info:
  148. info_page = self._download_webpage(
  149. 'http://player.cnevids.com/player/loader.js',
  150. video_id, 'Downloading loader info', query=params)
  151. if not video_info:
  152. info_page = self._download_webpage(
  153. f'https://player.cnevids.com/inline/video/{video_id}.js',
  154. video_id, 'Downloading inline info', query={
  155. 'target': params.get('target', 'embedplayer'),
  156. })
  157. if not video_info:
  158. video_info = self._parse_json(
  159. self._search_regex(
  160. r'(?s)var\s+config\s*=\s*({.+?});', info_page, 'config'),
  161. video_id, transform_source=js_to_json)['video']
  162. title = video_info['title']
  163. formats = []
  164. for fdata in video_info['sources']:
  165. src = fdata.get('src')
  166. if not src:
  167. continue
  168. ext = mimetype2ext(fdata.get('type')) or determine_ext(src)
  169. if ext == 'm3u8':
  170. formats.extend(self._extract_m3u8_formats(
  171. src, video_id, 'mp4', entry_protocol='m3u8_native',
  172. m3u8_id='hls', fatal=False))
  173. continue
  174. quality = fdata.get('quality')
  175. formats.append({
  176. 'format_id': ext + (f'-{quality}' if quality else ''),
  177. 'url': src,
  178. 'ext': ext,
  179. 'quality': 1 if quality == 'high' else 0,
  180. })
  181. subtitles = {}
  182. for t, caption in video_info.get('captions', {}).items():
  183. caption_url = caption.get('src')
  184. if not (t in ('vtt', 'srt', 'tml') and caption_url):
  185. continue
  186. subtitles.setdefault('en', []).append({'url': caption_url})
  187. return {
  188. 'id': video_id,
  189. 'formats': formats,
  190. 'title': title,
  191. 'thumbnail': video_info.get('poster_frame'),
  192. 'uploader': video_info.get('brand'),
  193. 'duration': int_or_none(video_info.get('duration')),
  194. 'tags': video_info.get('tags'),
  195. 'series': video_info.get('series_title'),
  196. 'season': video_info.get('season_title'),
  197. 'timestamp': parse_iso8601(video_info.get('premiere_date')),
  198. 'categories': video_info.get('categories'),
  199. 'subtitles': subtitles,
  200. }
  201. def _real_extract(self, url):
  202. video_id, player_id, target, url_type, display_id = self._match_valid_url(url).groups()
  203. if video_id:
  204. return self._extract_video({
  205. 'videoId': video_id,
  206. 'playerId': player_id,
  207. 'target': target,
  208. })
  209. webpage = self._download_webpage(url, display_id)
  210. if url_type == 'series':
  211. return self._extract_series(url, webpage)
  212. else:
  213. video = try_get(self._parse_json(self._search_regex(
  214. r'__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
  215. 'preload state', '{}'), display_id),
  216. lambda x: x['transformed']['video'])
  217. if video:
  218. params = {'videoId': video['id']}
  219. info = {'description': strip_or_none(video.get('description'))}
  220. else:
  221. params = self._extract_video_params(webpage, display_id)
  222. info = self._search_json_ld(
  223. webpage, display_id, fatal=False)
  224. info.update(self._extract_video(params))
  225. return info