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