pluralsight.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import collections
  2. import json
  3. import os
  4. import random
  5. import re
  6. import urllib.parse
  7. from .common import InfoExtractor
  8. from ..utils import (
  9. ExtractorError,
  10. dict_get,
  11. float_or_none,
  12. int_or_none,
  13. parse_duration,
  14. parse_qs,
  15. qualities,
  16. srt_subtitles_timecode,
  17. try_get,
  18. update_url_query,
  19. urlencode_postdata,
  20. )
  21. class PluralsightBaseIE(InfoExtractor):
  22. _API_BASE = 'https://app.pluralsight.com'
  23. _GRAPHQL_EP = f'{_API_BASE}/player/api/graphql'
  24. _GRAPHQL_HEADERS = {
  25. 'Content-Type': 'application/json;charset=UTF-8',
  26. }
  27. _GRAPHQL_COURSE_TMPL = '''
  28. query BootstrapPlayer {
  29. rpc {
  30. bootstrapPlayer {
  31. profile {
  32. firstName
  33. lastName
  34. email
  35. username
  36. userHandle
  37. authed
  38. isAuthed
  39. plan
  40. }
  41. course(courseId: "%s") {
  42. name
  43. title
  44. courseHasCaptions
  45. translationLanguages {
  46. code
  47. name
  48. }
  49. supportsWideScreenVideoFormats
  50. timestamp
  51. modules {
  52. name
  53. title
  54. duration
  55. formattedDuration
  56. author
  57. authorized
  58. clips {
  59. authorized
  60. clipId
  61. duration
  62. formattedDuration
  63. id
  64. index
  65. moduleIndex
  66. moduleTitle
  67. name
  68. title
  69. watched
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }'''
  76. def _download_course(self, course_id, url, display_id):
  77. try:
  78. return self._download_course_rpc(course_id, url, display_id)
  79. except ExtractorError:
  80. # Old API fallback
  81. return self._download_json(
  82. 'https://app.pluralsight.com/player/user/api/v1/player/payload',
  83. display_id, data=urlencode_postdata({'courseId': course_id}),
  84. headers={'Referer': url})
  85. def _download_course_rpc(self, course_id, url, display_id):
  86. response = self._download_json(
  87. self._GRAPHQL_EP, display_id, data=json.dumps({
  88. 'query': self._GRAPHQL_COURSE_TMPL % course_id,
  89. 'variables': {},
  90. }).encode(), headers=self._GRAPHQL_HEADERS)
  91. course = try_get(
  92. response, lambda x: x['data']['rpc']['bootstrapPlayer']['course'],
  93. dict)
  94. if course:
  95. return course
  96. raise ExtractorError(
  97. '{} said: {}'.format(self.IE_NAME, response['error']['message']),
  98. expected=True)
  99. class PluralsightIE(PluralsightBaseIE):
  100. IE_NAME = 'pluralsight'
  101. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
  102. _LOGIN_URL = 'https://app.pluralsight.com/id/'
  103. _NETRC_MACHINE = 'pluralsight'
  104. _TESTS = [{
  105. 'url': 'http://www.pluralsight.com/training/player?author=mike-mckeown&name=hosting-sql-server-windows-azure-iaas-m7-mgmt&mode=live&clip=3&course=hosting-sql-server-windows-azure-iaas',
  106. 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
  107. 'info_dict': {
  108. 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
  109. 'ext': 'mp4',
  110. 'title': 'Demo Monitoring',
  111. 'duration': 338,
  112. },
  113. 'skip': 'Requires pluralsight account credentials',
  114. }, {
  115. 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
  116. 'only_matching': True,
  117. }, {
  118. # available without pluralsight account
  119. 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
  120. 'only_matching': True,
  121. }, {
  122. 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
  123. 'only_matching': True,
  124. }]
  125. GRAPHQL_VIEWCLIP_TMPL = '''
  126. query viewClip {
  127. viewClip(input: {
  128. author: "%(author)s",
  129. clipIndex: %(clipIndex)d,
  130. courseName: "%(courseName)s",
  131. includeCaptions: %(includeCaptions)s,
  132. locale: "%(locale)s",
  133. mediaType: "%(mediaType)s",
  134. moduleName: "%(moduleName)s",
  135. quality: "%(quality)s"
  136. }) {
  137. urls {
  138. url
  139. cdn
  140. rank
  141. source
  142. },
  143. status
  144. }
  145. }'''
  146. def _perform_login(self, username, password):
  147. login_page = self._download_webpage(
  148. self._LOGIN_URL, None, 'Downloading login page')
  149. login_form = self._hidden_inputs(login_page)
  150. login_form.update({
  151. 'Username': username,
  152. 'Password': password,
  153. })
  154. post_url = self._search_regex(
  155. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  156. 'post url', default=self._LOGIN_URL, group='url')
  157. if not post_url.startswith('http'):
  158. post_url = urllib.parse.urljoin(self._LOGIN_URL, post_url)
  159. response = self._download_webpage(
  160. post_url, None, 'Logging in',
  161. data=urlencode_postdata(login_form),
  162. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  163. error = self._search_regex(
  164. r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
  165. response, 'error message', default=None)
  166. if error:
  167. raise ExtractorError(f'Unable to login: {error}', expected=True)
  168. if all(not re.search(p, response) for p in (
  169. r'__INITIAL_STATE__', r'["\']currentUser["\']',
  170. # new layout?
  171. r'>\s*Sign out\s*<')):
  172. BLOCKED = 'Your account has been blocked due to suspicious activity'
  173. if BLOCKED in response:
  174. raise ExtractorError(
  175. f'Unable to login: {BLOCKED}', expected=True)
  176. MUST_AGREE = 'To continue using Pluralsight, you must agree to'
  177. if any(p in response for p in (MUST_AGREE, '>Disagree<', '>Agree<')):
  178. raise ExtractorError(
  179. f'Unable to login: {MUST_AGREE} some documents. Go to pluralsight.com, '
  180. 'log in and agree with what Pluralsight requires.', expected=True)
  181. raise ExtractorError('Unable to log in')
  182. def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
  183. captions = None
  184. if clip_id:
  185. captions = self._download_json(
  186. f'{self._API_BASE}/transcript/api/v1/caption/json/{clip_id}/{lang}', video_id,
  187. 'Downloading captions JSON', 'Unable to download captions JSON',
  188. fatal=False)
  189. if not captions:
  190. captions_post = {
  191. 'a': author,
  192. 'cn': int(clip_idx),
  193. 'lc': lang,
  194. 'm': name,
  195. }
  196. captions = self._download_json(
  197. f'{self._API_BASE}/player/retrieve-captions', video_id,
  198. 'Downloading captions JSON', 'Unable to download captions JSON',
  199. fatal=False, data=json.dumps(captions_post).encode(),
  200. headers={'Content-Type': 'application/json;charset=utf-8'})
  201. if captions:
  202. return {
  203. lang: [{
  204. 'ext': 'json',
  205. 'data': json.dumps(captions),
  206. }, {
  207. 'ext': 'srt',
  208. 'data': self._convert_subtitles(duration, captions),
  209. }],
  210. }
  211. @staticmethod
  212. def _convert_subtitles(duration, subs):
  213. srt = ''
  214. TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
  215. TEXT_KEYS = ('text', 'Text')
  216. for num, current in enumerate(subs):
  217. current = subs[num]
  218. start, text = (
  219. float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
  220. dict_get(current, TEXT_KEYS))
  221. if start is None or text is None:
  222. continue
  223. end = duration if num == len(subs) - 1 else float_or_none(
  224. dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
  225. if end is None:
  226. continue
  227. srt += os.linesep.join(
  228. (
  229. f'{num}',
  230. f'{srt_subtitles_timecode(start)} --> {srt_subtitles_timecode(end)}',
  231. text,
  232. os.linesep,
  233. ))
  234. return srt
  235. def _real_extract(self, url):
  236. qs = parse_qs(url)
  237. author = qs.get('author', [None])[0]
  238. name = qs.get('name', [None])[0]
  239. clip_idx = qs.get('clip', [None])[0]
  240. course_name = qs.get('course', [None])[0]
  241. if any(not f for f in (author, name, clip_idx, course_name)):
  242. raise ExtractorError('Invalid URL', expected=True)
  243. display_id = f'{name}-{clip_idx}'
  244. course = self._download_course(course_name, url, display_id)
  245. collection = course['modules']
  246. clip = None
  247. for module_ in collection:
  248. if name in (module_.get('moduleName'), module_.get('name')):
  249. for clip_ in module_.get('clips', []):
  250. clip_index = clip_.get('clipIndex')
  251. if clip_index is None:
  252. clip_index = clip_.get('index')
  253. if clip_index is None:
  254. continue
  255. if str(clip_index) == clip_idx:
  256. clip = clip_
  257. break
  258. if not clip:
  259. raise ExtractorError('Unable to resolve clip')
  260. title = clip['title']
  261. clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
  262. QUALITIES = {
  263. 'low': {'width': 640, 'height': 480},
  264. 'medium': {'width': 848, 'height': 640},
  265. 'high': {'width': 1024, 'height': 768},
  266. 'high-widescreen': {'width': 1280, 'height': 720},
  267. }
  268. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen')
  269. quality_key = qualities(QUALITIES_PREFERENCE)
  270. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  271. ALLOWED_QUALITIES = (
  272. AllowedQuality('webm', ['high']),
  273. AllowedQuality('mp4', ['low', 'medium', 'high']),
  274. )
  275. # Some courses also offer widescreen resolution for high quality (see
  276. # https://github.com/ytdl-org/youtube-dl/issues/7766)
  277. widescreen = course.get('supportsWideScreenVideoFormats') is True
  278. best_quality = 'high-widescreen' if widescreen else 'high'
  279. if widescreen:
  280. for allowed_quality in ALLOWED_QUALITIES:
  281. allowed_quality.qualities.append(best_quality)
  282. # In order to minimize the number of calls to ViewClip API and reduce
  283. # the probability of being throttled or banned by Pluralsight we will request
  284. # only single format until formats listing was explicitly requested.
  285. if self.get_param('listformats', False):
  286. allowed_qualities = ALLOWED_QUALITIES
  287. else:
  288. def guess_allowed_qualities():
  289. req_format = self.get_param('format') or 'best'
  290. req_format_split = req_format.split('-', 1)
  291. if len(req_format_split) > 1:
  292. req_ext, req_quality = req_format_split
  293. req_quality = '-'.join(req_quality.split('-')[:2])
  294. for allowed_quality in ALLOWED_QUALITIES:
  295. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  296. return (AllowedQuality(req_ext, (req_quality, )), )
  297. req_ext = 'webm' if self.get_param('prefer_free_formats') else 'mp4'
  298. return (AllowedQuality(req_ext, (best_quality, )), )
  299. allowed_qualities = guess_allowed_qualities()
  300. formats = []
  301. for ext, qualities_ in allowed_qualities:
  302. for quality in qualities_:
  303. f = QUALITIES[quality].copy()
  304. clip_post = {
  305. 'author': author,
  306. 'includeCaptions': 'false',
  307. 'clipIndex': int(clip_idx),
  308. 'courseName': course_name,
  309. 'locale': 'en',
  310. 'moduleName': name,
  311. 'mediaType': ext,
  312. 'quality': '%dx%d' % (f['width'], f['height']),
  313. }
  314. format_id = f'{ext}-{quality}'
  315. try:
  316. viewclip = self._download_json(
  317. self._GRAPHQL_EP, display_id,
  318. f'Downloading {format_id} viewclip graphql',
  319. data=json.dumps({
  320. 'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
  321. 'variables': {},
  322. }).encode(),
  323. headers=self._GRAPHQL_HEADERS)['data']['viewClip']
  324. except ExtractorError:
  325. # Still works but most likely will go soon
  326. viewclip = self._download_json(
  327. f'{self._API_BASE}/video/clips/viewclip', display_id,
  328. f'Downloading {format_id} viewclip JSON', fatal=False,
  329. data=json.dumps(clip_post).encode(),
  330. headers={'Content-Type': 'application/json;charset=utf-8'})
  331. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  332. # to return 429 HTTP errors after some time (see
  333. # https://github.com/ytdl-org/youtube-dl/pull/6989). Moreover it may even lead
  334. # to account ban (see https://github.com/ytdl-org/youtube-dl/issues/6842).
  335. # To somewhat reduce the probability of these consequences
  336. # we will sleep random amount of time before each call to ViewClip.
  337. self._sleep(
  338. random.randint(5, 10), display_id,
  339. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  340. if not viewclip:
  341. continue
  342. clip_urls = viewclip.get('urls')
  343. if not isinstance(clip_urls, list):
  344. continue
  345. for clip_url_data in clip_urls:
  346. clip_url = clip_url_data.get('url')
  347. if not clip_url:
  348. continue
  349. cdn = clip_url_data.get('cdn')
  350. clip_f = f.copy()
  351. clip_f.update({
  352. 'url': clip_url,
  353. 'ext': ext,
  354. 'format_id': f'{format_id}-{cdn}' if cdn else format_id,
  355. 'quality': quality_key(quality),
  356. 'source_preference': int_or_none(clip_url_data.get('rank')),
  357. })
  358. formats.append(clip_f)
  359. duration = int_or_none(
  360. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  361. # TODO: other languages?
  362. subtitles = self.extract_subtitles(
  363. author, clip_idx, clip.get('clipId'), 'en', name, duration, display_id)
  364. return {
  365. 'id': clip_id,
  366. 'title': title,
  367. 'duration': duration,
  368. 'creator': author,
  369. 'formats': formats,
  370. 'subtitles': subtitles,
  371. }
  372. class PluralsightCourseIE(PluralsightBaseIE):
  373. IE_NAME = 'pluralsight:course'
  374. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  375. _TESTS = [{
  376. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  377. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  378. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  379. 'info_dict': {
  380. 'id': 'hosting-sql-server-windows-azure-iaas',
  381. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  382. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  383. },
  384. 'playlist_count': 31,
  385. }, {
  386. # available without pluralsight account
  387. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  388. 'only_matching': True,
  389. }, {
  390. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  391. 'only_matching': True,
  392. }]
  393. def _real_extract(self, url):
  394. course_id = self._match_id(url)
  395. # TODO: PSM cookie
  396. course = self._download_course(course_id, url, course_id)
  397. title = course['title']
  398. course_name = course['name']
  399. course_data = course['modules']
  400. description = course.get('description') or course.get('shortDescription')
  401. entries = []
  402. for num, module in enumerate(course_data, 1):
  403. author = module.get('author')
  404. module_name = module.get('name')
  405. if not author or not module_name:
  406. continue
  407. for clip in module.get('clips', []):
  408. clip_index = int_or_none(clip.get('index'))
  409. if clip_index is None:
  410. continue
  411. clip_url = update_url_query(
  412. f'{self._API_BASE}/player', query={
  413. 'mode': 'live',
  414. 'course': course_name,
  415. 'author': author,
  416. 'name': module_name,
  417. 'clip': clip_index,
  418. })
  419. entries.append({
  420. '_type': 'url_transparent',
  421. 'url': clip_url,
  422. 'ie_key': PluralsightIE.ie_key(),
  423. 'chapter': module.get('title'),
  424. 'chapter_number': num,
  425. 'chapter_id': module.get('moduleRef'),
  426. })
  427. return self.playlist_result(entries, course_id, title, description)