wistia.py 15 KB

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