]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/wistia.py
[extractors] Use new framework for existing embeds (#4307)
[yt-dlp.git] / yt_dlp / extractor / wistia.py
1 import re
2
3 from .common import InfoExtractor
4 from ..utils import (
5 ExtractorError,
6 float_or_none,
7 int_or_none,
8 try_call,
9 try_get,
10 )
11
12
13 class WistiaBaseIE(InfoExtractor):
14 _VALID_ID_REGEX = r'(?P<id>[a-z0-9]{10})'
15 _VALID_URL_BASE = r'https?://(?:\w+\.)?wistia\.(?:net|com)/(?:embed/)?'
16 _EMBED_BASE_URL = 'http://fast.wistia.com/embed/'
17
18 def _download_embed_config(self, config_type, config_id, referer):
19 base_url = self._EMBED_BASE_URL + '%ss/%s' % (config_type, config_id)
20 embed_config = self._download_json(
21 base_url + '.json', config_id, headers={
22 'Referer': referer if referer.startswith('http') else base_url, # Some videos require this.
23 })
24
25 if isinstance(embed_config, dict) and embed_config.get('error'):
26 raise ExtractorError(
27 'Error while getting the playlist', expected=True)
28
29 return embed_config
30
31 def _extract_media(self, embed_config):
32 data = embed_config['media']
33 video_id = data['hashedId']
34 title = data['name']
35
36 formats = []
37 thumbnails = []
38 for a in data['assets']:
39 aurl = a.get('url')
40 if not aurl:
41 continue
42 astatus = a.get('status')
43 atype = a.get('type')
44 if (astatus is not None and astatus != 2) or atype in ('preview', 'storyboard'):
45 continue
46 elif atype in ('still', 'still_image'):
47 thumbnails.append({
48 'url': aurl,
49 'width': int_or_none(a.get('width')),
50 'height': int_or_none(a.get('height')),
51 'filesize': int_or_none(a.get('size')),
52 })
53 else:
54 aext = a.get('ext')
55 display_name = a.get('display_name')
56 format_id = atype
57 if atype and atype.endswith('_video') and display_name:
58 format_id = '%s-%s' % (atype[:-6], display_name)
59 f = {
60 'format_id': format_id,
61 'url': aurl,
62 'tbr': int_or_none(a.get('bitrate')) or None,
63 'quality': 1 if atype == 'original' else None,
64 }
65 if display_name == 'Audio':
66 f.update({
67 'vcodec': 'none',
68 })
69 else:
70 f.update({
71 'width': int_or_none(a.get('width')),
72 'height': int_or_none(a.get('height')),
73 'vcodec': a.get('codec'),
74 })
75 if a.get('container') == 'm3u8' or aext == 'm3u8':
76 ts_f = f.copy()
77 ts_f.update({
78 'ext': 'ts',
79 'format_id': f['format_id'].replace('hls-', 'ts-'),
80 'url': f['url'].replace('.bin', '.ts'),
81 })
82 formats.append(ts_f)
83 f.update({
84 'ext': 'mp4',
85 'protocol': 'm3u8_native',
86 })
87 else:
88 f.update({
89 'container': a.get('container'),
90 'ext': aext,
91 'filesize': int_or_none(a.get('size')),
92 })
93 formats.append(f)
94
95 self._sort_formats(formats)
96
97 subtitles = {}
98 for caption in data.get('captions', []):
99 language = caption.get('language')
100 if not language:
101 continue
102 subtitles[language] = [{
103 'url': self._EMBED_BASE_URL + 'captions/' + video_id + '.vtt?language=' + language,
104 }]
105
106 return {
107 'id': video_id,
108 'title': title,
109 'description': data.get('seoDescription'),
110 'formats': formats,
111 'thumbnails': thumbnails,
112 'duration': float_or_none(data.get('duration')),
113 'timestamp': int_or_none(data.get('createdAt')),
114 'subtitles': subtitles,
115 }
116
117
118 class WistiaIE(WistiaBaseIE):
119 _VALID_URL = r'(?:wistia:|%s(?:iframe|medias)/)%s' % (WistiaBaseIE._VALID_URL_BASE, WistiaBaseIE._VALID_ID_REGEX)
120 _EMBED_REGEX = [r'<(?:meta[^>]+?content|(?:iframe|script)[^>]+?src)=["\'](?P<url>(?:https?:)?//(?:fast\.)?wistia\.(?:net|com)/embed/(?:iframe|medias)/[a-z0-9]{10})']
121 _TESTS = [{
122 # with hls video
123 'url': 'wistia:807fafadvk',
124 'md5': 'daff0f3687a41d9a71b40e0e8c2610fe',
125 'info_dict': {
126 'id': '807fafadvk',
127 'ext': 'mp4',
128 'title': 'Drip Brennan Dunn Workshop',
129 'description': 'a JV Webinars video',
130 'upload_date': '20160518',
131 'timestamp': 1463607249,
132 'duration': 4987.11,
133 },
134 }, {
135 'url': 'wistia:sh7fpupwlt',
136 'only_matching': True,
137 }, {
138 'url': 'http://fast.wistia.net/embed/iframe/sh7fpupwlt',
139 'only_matching': True,
140 }, {
141 'url': 'http://fast.wistia.com/embed/iframe/sh7fpupwlt',
142 'only_matching': True,
143 }, {
144 'url': 'http://fast.wistia.net/embed/medias/sh7fpupwlt.json',
145 'only_matching': True,
146 }]
147
148 # https://wistia.com/support/embed-and-share/video-on-your-website
149 @classmethod
150 def _extract_embed_urls(cls, url, webpage):
151 urls = list(super()._extract_embed_urls(url, webpage))
152
153 for match in re.finditer(
154 r'''(?sx)
155 <div[^>]+class=(["'])(?:(?!\1).)*?\bwistia_async_(?P<id>[a-z0-9]{10})\b(?:(?!\1).)*?\1
156 ''', webpage):
157 urls.append('wistia:%s' % match.group('id'))
158 for match in re.finditer(r'(?:data-wistia-?id=["\']|Wistia\.embed\(["\']|id=["\']wistia_)(?P<id>[a-z0-9]{10})', webpage):
159 urls.append('wistia:%s' % match.group('id'))
160 return urls
161
162 @classmethod
163 def _extract_from_webpage(cls, url, webpage):
164 from .teachable import TeachableIE
165
166 if list(TeachableIE._extract_embed_urls(url, webpage)):
167 return
168
169 for entry in super()._extract_from_webpage(url, webpage):
170 yield {
171 **entry,
172 '_type': 'url_transparent',
173 'uploader': try_call(lambda: re.match(r'(?:https?://)?([^/]+)/', url).group(1)),
174 }
175
176 def _real_extract(self, url):
177 video_id = self._match_id(url)
178 embed_config = self._download_embed_config('media', video_id, url)
179 return self._extract_media(embed_config)
180
181
182 class WistiaPlaylistIE(WistiaBaseIE):
183 _VALID_URL = r'%splaylists/%s' % (WistiaBaseIE._VALID_URL_BASE, WistiaBaseIE._VALID_ID_REGEX)
184
185 _TEST = {
186 'url': 'https://fast.wistia.net/embed/playlists/aodt9etokc',
187 'info_dict': {
188 'id': 'aodt9etokc',
189 },
190 'playlist_count': 3,
191 }
192
193 def _real_extract(self, url):
194 playlist_id = self._match_id(url)
195 playlist = self._download_embed_config('playlist', playlist_id, url)
196
197 entries = []
198 for media in (try_get(playlist, lambda x: x[0]['medias']) or []):
199 embed_config = media.get('embed_config')
200 if not embed_config:
201 continue
202 entries.append(self._extract_media(embed_config))
203
204 return self.playlist_result(entries, playlist_id)