wistia.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import base64
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..networking import HEADRequest
  6. from ..networking.exceptions import HTTPError
  7. from ..utils import (
  8. ExtractorError,
  9. determine_ext,
  10. float_or_none,
  11. int_or_none,
  12. parse_qs,
  13. traverse_obj,
  14. try_get,
  15. update_url_query,
  16. urlhandle_detect_ext,
  17. )
  18. class WistiaBaseIE(InfoExtractor):
  19. _VALID_ID_REGEX = r'(?P<id>[a-z0-9]{10})'
  20. _VALID_URL_BASE = r'https?://(?:\w+\.)?wistia\.(?:net|com)/(?:embed/)?'
  21. _EMBED_BASE_URL = 'http://fast.wistia.net/embed/'
  22. def _download_embed_config(self, config_type, config_id, referer):
  23. base_url = self._EMBED_BASE_URL + f'{config_type}/{config_id}'
  24. embed_config = self._download_json(
  25. base_url + '.json', config_id, headers={
  26. 'Referer': referer if referer.startswith('http') else base_url, # Some videos require this.
  27. })
  28. error = traverse_obj(embed_config, 'error')
  29. if error:
  30. raise ExtractorError(
  31. f'Error while getting the playlist: {error}', expected=True)
  32. return embed_config
  33. def _get_real_ext(self, url):
  34. ext = determine_ext(url, default_ext='bin')
  35. if ext == 'bin':
  36. urlh = self._request_webpage(
  37. HEADRequest(url), None, note='Checking media extension',
  38. errnote='HEAD request returned error', fatal=False)
  39. if urlh:
  40. ext = urlhandle_detect_ext(urlh, default='bin')
  41. return 'mp4' if ext == 'mov' else ext
  42. def _extract_media(self, embed_config):
  43. data = embed_config['media']
  44. video_id = data['hashedId']
  45. title = data['name']
  46. formats = []
  47. thumbnails = []
  48. for a in data['assets']:
  49. aurl = a.get('url')
  50. if not aurl:
  51. continue
  52. astatus = a.get('status')
  53. atype = a.get('type')
  54. if (astatus is not None and astatus != 2) or atype in ('preview', 'storyboard'):
  55. continue
  56. elif atype in ('still', 'still_image'):
  57. thumbnails.append({
  58. 'url': aurl.replace('.bin', f'.{self._get_real_ext(aurl)}'),
  59. 'width': int_or_none(a.get('width')),
  60. 'height': int_or_none(a.get('height')),
  61. 'filesize': int_or_none(a.get('size')),
  62. })
  63. else:
  64. aext = a.get('ext') or self._get_real_ext(aurl)
  65. display_name = a.get('display_name')
  66. format_id = atype
  67. if atype and atype.endswith('_video') and display_name:
  68. format_id = f'{atype[:-6]}-{display_name}'
  69. f = {
  70. 'format_id': format_id,
  71. 'url': aurl,
  72. 'tbr': int_or_none(a.get('bitrate')) or None,
  73. 'quality': 1 if atype == 'original' else None,
  74. }
  75. if display_name == 'Audio':
  76. f.update({
  77. 'vcodec': 'none',
  78. })
  79. else:
  80. f.update({
  81. 'width': int_or_none(a.get('width')),
  82. 'height': int_or_none(a.get('height')),
  83. 'vcodec': a.get('codec'),
  84. })
  85. if a.get('container') == 'm3u8' or aext == 'm3u8':
  86. ts_f = f.copy()
  87. ts_f.update({
  88. 'ext': 'ts',
  89. 'format_id': f['format_id'].replace('hls-', 'ts-'),
  90. 'url': f['url'].replace('.bin', '.ts'),
  91. })
  92. formats.append(ts_f)
  93. f.update({
  94. 'ext': 'mp4',
  95. 'protocol': 'm3u8_native',
  96. })
  97. else:
  98. f.update({
  99. 'container': a.get('container'),
  100. 'ext': aext,
  101. 'filesize': int_or_none(a.get('size')),
  102. })
  103. formats.append(f)
  104. subtitles = {}
  105. for caption in data.get('captions', []):
  106. language = caption.get('language')
  107. if not language:
  108. continue
  109. subtitles[language] = [{
  110. 'url': self._EMBED_BASE_URL + 'captions/' + video_id + '.vtt?language=' + language,
  111. }]
  112. return {
  113. 'id': video_id,
  114. 'title': title,
  115. 'description': data.get('seoDescription'),
  116. 'formats': formats,
  117. 'thumbnails': thumbnails,
  118. 'duration': float_or_none(data.get('duration')),
  119. 'timestamp': int_or_none(data.get('createdAt')),
  120. 'subtitles': subtitles,
  121. }
  122. @classmethod
  123. def _extract_from_webpage(cls, url, webpage):
  124. from .teachable import TeachableIE
  125. if list(TeachableIE._extract_embed_urls(url, webpage)):
  126. return
  127. yield from super()._extract_from_webpage(url, webpage)
  128. @classmethod
  129. def _extract_wistia_async_embed(cls, webpage):
  130. # https://wistia.com/support/embed-and-share/video-on-your-website
  131. # https://wistia.com/support/embed-and-share/channel-embeds
  132. yield from re.finditer(
  133. r'''(?sx)
  134. <(?:div|section)[^>]+class=([\"'])(?:(?!\1).)*?(?P<type>wistia[a-z_0-9]+)\s*\bwistia_async_(?P<id>[a-z0-9]{10})\b(?:(?!\1).)*?\1
  135. ''', webpage)
  136. @classmethod
  137. def _extract_url_media_id(cls, url):
  138. mobj = re.search(r'(?:wmediaid|wvideo(?:id)?)]?=(?P<id>[a-z0-9]{10})', urllib.parse.unquote_plus(url))
  139. if mobj:
  140. return mobj.group('id')
  141. class WistiaIE(WistiaBaseIE):
  142. _VALID_URL = rf'(?:wistia:|{WistiaBaseIE._VALID_URL_BASE}(?:iframe|medias)/){WistiaBaseIE._VALID_ID_REGEX}'
  143. _EMBED_REGEX = [
  144. r'''(?x)
  145. <(?:meta[^>]+?content|(?:iframe|script)[^>]+?src)=["\']
  146. (?P<url>(?:https?:)?//(?:fast\.)?wistia\.(?:net|com)/embed/(?:iframe|medias)/[a-z0-9]{10})
  147. ''']
  148. _TESTS = [{
  149. # with hls video
  150. 'url': 'wistia:807fafadvk',
  151. 'md5': 'daff0f3687a41d9a71b40e0e8c2610fe',
  152. 'info_dict': {
  153. 'id': '807fafadvk',
  154. 'ext': 'mp4',
  155. 'title': 'Drip Brennan Dunn Workshop',
  156. 'description': 'a JV Webinars video',
  157. 'upload_date': '20160518',
  158. 'timestamp': 1463607249,
  159. 'duration': 4987.11,
  160. },
  161. 'skip': 'video unavailable',
  162. }, {
  163. 'url': 'wistia:a6ndpko1wg',
  164. 'md5': '10c1ce9c4dde638202513ed17a3767bd',
  165. 'info_dict': {
  166. 'id': 'a6ndpko1wg',
  167. 'ext': 'mp4',
  168. 'title': 'Episode 2: Boxed Water\'s retention is thirsty',
  169. 'upload_date': '20210324',
  170. 'description': 'md5:da5994c2c2d254833b412469d9666b7a',
  171. 'duration': 966.0,
  172. 'timestamp': 1616614369,
  173. 'thumbnail': 'https://embed-ssl.wistia.com/deliveries/53dc60239348dc9b9fba3755173ea4c2.png',
  174. },
  175. }, {
  176. 'url': 'wistia:5vd7p4bct5',
  177. 'md5': 'b9676d24bf30945d97060638fbfe77f0',
  178. 'info_dict': {
  179. 'id': '5vd7p4bct5',
  180. 'ext': 'mp4',
  181. 'title': 'md5:eaa9f64c4efd7b5f098b9b6118597679',
  182. 'description': 'md5:a9bea0315f0616aa5df2dc413ddcdd0f',
  183. 'upload_date': '20220915',
  184. 'timestamp': 1663258727,
  185. 'duration': 623.019,
  186. 'thumbnail': r're:https?://embed(?:-ssl)?.wistia.com/.+\.jpg$',
  187. },
  188. }, {
  189. 'url': 'wistia:sh7fpupwlt',
  190. 'only_matching': True,
  191. }, {
  192. 'url': 'http://fast.wistia.net/embed/iframe/sh7fpupwlt',
  193. 'only_matching': True,
  194. }, {
  195. 'url': 'http://fast.wistia.com/embed/iframe/sh7fpupwlt',
  196. 'only_matching': True,
  197. }, {
  198. 'url': 'http://fast.wistia.net/embed/medias/sh7fpupwlt.json',
  199. 'only_matching': True,
  200. }]
  201. _WEBPAGE_TESTS = [{
  202. 'url': 'https://www.weidert.com/blog/wistia-channels-video-marketing-tool',
  203. 'info_dict': {
  204. 'id': 'cqwukac3z1',
  205. 'ext': 'mp4',
  206. 'title': 'How Wistia Channels Can Help Capture Inbound Value From Your Video Content',
  207. 'duration': 158.125,
  208. 'timestamp': 1618974400,
  209. 'description': 'md5:27abc99a758573560be72600ef95cece',
  210. 'upload_date': '20210421',
  211. 'thumbnail': 'https://embed-ssl.wistia.com/deliveries/6c551820ae950cdee2306d6cbe9ef742.jpg',
  212. },
  213. }, {
  214. 'url': 'https://study.com/academy/lesson/north-american-exploration-failed-colonies-of-spain-france-england.html#lesson',
  215. 'md5': 'b9676d24bf30945d97060638fbfe77f0',
  216. 'info_dict': {
  217. 'id': '5vd7p4bct5',
  218. 'ext': 'mp4',
  219. 'title': 'paywall_north-american-exploration-failed-colonies-of-spain-france-england',
  220. 'upload_date': '20220915',
  221. 'timestamp': 1663258727,
  222. 'duration': 623.019,
  223. 'thumbnail': 'https://embed-ssl.wistia.com/deliveries/83e6ec693e2c05a0ce65809cbaead86a.jpg',
  224. 'description': 'a Paywall Videos video',
  225. },
  226. }]
  227. def _real_extract(self, url):
  228. video_id = self._match_id(url)
  229. embed_config = self._download_embed_config('medias', video_id, url)
  230. return self._extract_media(embed_config)
  231. @classmethod
  232. def _extract_embed_urls(cls, url, webpage):
  233. urls = list(super()._extract_embed_urls(url, webpage))
  234. for match in cls._extract_wistia_async_embed(webpage):
  235. if match.group('type') != 'wistia_channel':
  236. urls.append('wistia:{}'.format(match.group('id')))
  237. for match in re.finditer(r'(?:data-wistia-?id=["\']|Wistia\.embed\(["\']|id=["\']wistia_)(?P<id>[a-z0-9]{10})',
  238. webpage):
  239. urls.append('wistia:{}'.format(match.group('id')))
  240. if not WistiaChannelIE._extract_embed_urls(url, webpage): # Fallback
  241. media_id = cls._extract_url_media_id(url)
  242. if media_id:
  243. urls.append('wistia:{}'.format(match.group('id')))
  244. return urls
  245. class WistiaPlaylistIE(WistiaBaseIE):
  246. _VALID_URL = rf'{WistiaBaseIE._VALID_URL_BASE}playlists/{WistiaBaseIE._VALID_ID_REGEX}'
  247. _TEST = {
  248. 'url': 'https://fast.wistia.net/embed/playlists/aodt9etokc',
  249. 'info_dict': {
  250. 'id': 'aodt9etokc',
  251. },
  252. 'playlist_count': 3,
  253. }
  254. def _real_extract(self, url):
  255. playlist_id = self._match_id(url)
  256. playlist = self._download_embed_config('playlists', playlist_id, url)
  257. entries = []
  258. for media in (try_get(playlist, lambda x: x[0]['medias']) or []):
  259. embed_config = media.get('embed_config')
  260. if not embed_config:
  261. continue
  262. entries.append(self._extract_media(embed_config))
  263. return self.playlist_result(entries, playlist_id)
  264. class WistiaChannelIE(WistiaBaseIE):
  265. _VALID_URL = rf'(?:wistiachannel:|{WistiaBaseIE._VALID_URL_BASE}channel/){WistiaBaseIE._VALID_ID_REGEX}'
  266. _TESTS = [{
  267. # JSON Embed API returns 403, should fall back to webpage
  268. 'url': 'https://fast.wistia.net/embed/channel/yvyvu7wjbg?wchannelid=yvyvu7wjbg',
  269. 'info_dict': {
  270. 'id': 'yvyvu7wjbg',
  271. 'title': 'Copysmith Tutorials and Education!',
  272. 'description': 'Learn all things Copysmith via short and informative videos!',
  273. },
  274. 'playlist_mincount': 7,
  275. 'expected_warnings': ['falling back to webpage'],
  276. }, {
  277. 'url': 'https://fast.wistia.net/embed/channel/3802iirk0l',
  278. 'info_dict': {
  279. 'id': '3802iirk0l',
  280. 'title': 'The Roof',
  281. },
  282. 'playlist_mincount': 20,
  283. }, {
  284. # link to popup video, follow --no-playlist
  285. 'url': 'https://fast.wistia.net/embed/channel/3802iirk0l?wchannelid=3802iirk0l&wmediaid=sp5dqjzw3n',
  286. 'info_dict': {
  287. 'id': 'sp5dqjzw3n',
  288. 'ext': 'mp4',
  289. 'title': 'The Roof S2: The Modern CRO',
  290. 'thumbnail': 'https://embed-ssl.wistia.com/deliveries/dadfa9233eaa505d5e0c85c23ff70741.png',
  291. 'duration': 86.487,
  292. 'description': 'A sales leader on The Roof? Man, they really must be letting anyone up here this season.\n',
  293. 'timestamp': 1619790290,
  294. 'upload_date': '20210430',
  295. },
  296. 'params': {'noplaylist': True, 'skip_download': True},
  297. }]
  298. _WEBPAGE_TESTS = [{
  299. 'url': 'https://www.profitwell.com/recur/boxed-out',
  300. 'info_dict': {
  301. 'id': '6jyvmqz6zs',
  302. 'title': 'Boxed Out',
  303. 'description': 'md5:14a8a93a1dbe236718e6a59f8c8c7bae',
  304. },
  305. 'playlist_mincount': 30,
  306. }, {
  307. # section instead of div
  308. 'url': 'https://360learning.com/studio/onboarding-joei/',
  309. 'info_dict': {
  310. 'id': 'z874k93n2o',
  311. 'title': 'Onboarding Joei.',
  312. 'description': 'Coming to you weekly starting Feb 19th.',
  313. },
  314. 'playlist_mincount': 20,
  315. }, {
  316. 'url': 'https://amplitude.com/amplify-sessions?amp%5Bwmediaid%5D=pz0m0l0if3&amp%5Bwvideo%5D=pz0m0l0if3&wchannelid=emyjmwjf79&wmediaid=i8um783bdt',
  317. 'info_dict': {
  318. 'id': 'pz0m0l0if3',
  319. 'title': 'A Framework for Improving Product Team Performance',
  320. 'ext': 'mp4',
  321. 'timestamp': 1653935275,
  322. 'upload_date': '20220530',
  323. 'description': 'Learn how to help your company improve and achieve your product related goals.',
  324. 'duration': 1854.39,
  325. 'thumbnail': 'https://embed-ssl.wistia.com/deliveries/12fd19e56413d9d6f04e2185c16a6f8854e25226.png',
  326. },
  327. 'params': {'noplaylist': True, 'skip_download': True},
  328. }]
  329. def _real_extract(self, url):
  330. channel_id = self._match_id(url)
  331. media_id = self._extract_url_media_id(url)
  332. if not self._yes_playlist(channel_id, media_id, playlist_label='channel'):
  333. return self.url_result(f'wistia:{media_id}', 'Wistia')
  334. try:
  335. data = self._download_embed_config('channel', channel_id, url)
  336. except (ExtractorError, HTTPError):
  337. # Some channels give a 403 from the JSON API
  338. self.report_warning('Failed to download channel data from API, falling back to webpage.')
  339. webpage = self._download_webpage(f'https://fast.wistia.net/embed/channel/{channel_id}', channel_id)
  340. data = self._parse_json(
  341. self._search_regex(rf'wchanneljsonp-{channel_id}\'\]\s*=[^\"]*\"([A-Za-z0-9=/]*)', webpage, 'jsonp', channel_id),
  342. channel_id, transform_source=lambda x: urllib.parse.unquote_plus(base64.b64decode(x).decode('utf-8')))
  343. # XXX: can there be more than one series?
  344. series = traverse_obj(data, ('series', 0), default={})
  345. entries = [
  346. self.url_result(f'wistia:{video["hashedId"]}', WistiaIE, title=video.get('name'))
  347. for video in traverse_obj(series, ('sections', ..., 'videos', ...)) or []
  348. if video.get('hashedId')
  349. ]
  350. return self.playlist_result(
  351. entries, channel_id, playlist_title=series.get('title'), playlist_description=series.get('description'))
  352. @classmethod
  353. def _extract_embed_urls(cls, url, webpage):
  354. yield from super()._extract_embed_urls(url, webpage)
  355. for match in cls._extract_wistia_async_embed(webpage):
  356. if match.group('type') == 'wistia_channel':
  357. # original url may contain wmediaid query param
  358. yield update_url_query(f'wistiachannel:{match.group("id")}', parse_qs(url))