pluralsight.py 18 KB

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