condenast.py 9.5 KB

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