logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

condenast.py (9737B)


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