pluralsight.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. from __future__ import unicode_literals
  2. import collections
  3. import json
  4. import os
  5. import random
  6. import re
  7. from .common import InfoExtractor
  8. from ..compat import (
  9. compat_str,
  10. compat_urlparse,
  11. )
  12. from ..utils import (
  13. ExtractorError,
  14. float_or_none,
  15. int_or_none,
  16. parse_duration,
  17. qualities,
  18. srt_subtitles_timecode,
  19. urlencode_postdata,
  20. )
  21. class PluralsightBaseIE(InfoExtractor):
  22. _API_BASE = 'https://app.pluralsight.com'
  23. class PluralsightIE(PluralsightBaseIE):
  24. IE_NAME = 'pluralsight'
  25. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
  26. _LOGIN_URL = 'https://app.pluralsight.com/id/'
  27. _NETRC_MACHINE = 'pluralsight'
  28. _TESTS = [{
  29. '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',
  30. 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
  31. 'info_dict': {
  32. 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
  33. 'ext': 'mp4',
  34. 'title': 'Management of SQL Server - Demo Monitoring',
  35. 'duration': 338,
  36. },
  37. 'skip': 'Requires pluralsight account credentials',
  38. }, {
  39. 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
  40. 'only_matching': True,
  41. }, {
  42. # available without pluralsight account
  43. 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
  44. 'only_matching': True,
  45. }, {
  46. 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
  47. 'only_matching': True,
  48. }]
  49. def _real_initialize(self):
  50. self._login()
  51. def _login(self):
  52. (username, password) = self._get_login_info()
  53. if username is None:
  54. return
  55. login_page = self._download_webpage(
  56. self._LOGIN_URL, None, 'Downloading login page')
  57. login_form = self._hidden_inputs(login_page)
  58. login_form.update({
  59. 'Username': username,
  60. 'Password': password,
  61. })
  62. post_url = self._search_regex(
  63. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  64. 'post url', default=self._LOGIN_URL, group='url')
  65. if not post_url.startswith('http'):
  66. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  67. response = self._download_webpage(
  68. post_url, None, 'Logging in as %s' % username,
  69. data=urlencode_postdata(login_form),
  70. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  71. error = self._search_regex(
  72. r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
  73. response, 'error message', default=None)
  74. if error:
  75. raise ExtractorError('Unable to login: %s' % error, expected=True)
  76. if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
  77. raise ExtractorError('Unable to log in')
  78. def _get_subtitles(self, author, clip_id, lang, name, duration, video_id):
  79. captions_post = {
  80. 'a': author,
  81. 'cn': clip_id,
  82. 'lc': lang,
  83. 'm': name,
  84. }
  85. captions = self._download_json(
  86. '%s/player/retrieve-captions' % self._API_BASE, video_id,
  87. 'Downloading captions JSON', 'Unable to download captions JSON',
  88. fatal=False, data=json.dumps(captions_post).encode('utf-8'),
  89. headers={'Content-Type': 'application/json;charset=utf-8'})
  90. if captions:
  91. return {
  92. lang: [{
  93. 'ext': 'json',
  94. 'data': json.dumps(captions),
  95. }, {
  96. 'ext': 'srt',
  97. 'data': self._convert_subtitles(duration, captions),
  98. }]
  99. }
  100. @staticmethod
  101. def _convert_subtitles(duration, subs):
  102. srt = ''
  103. for num, current in enumerate(subs):
  104. current = subs[num]
  105. start, text = float_or_none(
  106. current.get('DisplayTimeOffset')), current.get('Text')
  107. if start is None or text is None:
  108. continue
  109. end = duration if num == len(subs) - 1 else float_or_none(
  110. subs[num + 1].get('DisplayTimeOffset'))
  111. if end is None:
  112. continue
  113. srt += os.linesep.join(
  114. (
  115. '%d' % num,
  116. '%s --> %s' % (
  117. srt_subtitles_timecode(start),
  118. srt_subtitles_timecode(end)),
  119. text,
  120. os.linesep,
  121. ))
  122. return srt
  123. def _real_extract(self, url):
  124. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  125. author = qs.get('author', [None])[0]
  126. name = qs.get('name', [None])[0]
  127. clip_id = qs.get('clip', [None])[0]
  128. course_name = qs.get('course', [None])[0]
  129. if any(not f for f in (author, name, clip_id, course_name,)):
  130. raise ExtractorError('Invalid URL', expected=True)
  131. display_id = '%s-%s' % (name, clip_id)
  132. parsed_url = compat_urlparse.urlparse(url)
  133. payload_url = compat_urlparse.urlunparse(parsed_url._replace(
  134. netloc='app.pluralsight.com', path='player/api/v1/payload'))
  135. course = self._download_json(
  136. payload_url, display_id, headers={'Referer': url})['payload']['course']
  137. collection = course['modules']
  138. module, clip = None, None
  139. for module_ in collection:
  140. if name in (module_.get('moduleName'), module_.get('name')):
  141. module = module_
  142. for clip_ in module_.get('clips', []):
  143. clip_index = clip_.get('clipIndex')
  144. if clip_index is None:
  145. clip_index = clip_.get('index')
  146. if clip_index is None:
  147. continue
  148. if compat_str(clip_index) == clip_id:
  149. clip = clip_
  150. break
  151. if not clip:
  152. raise ExtractorError('Unable to resolve clip')
  153. title = '%s - %s' % (module['title'], clip['title'])
  154. QUALITIES = {
  155. 'low': {'width': 640, 'height': 480},
  156. 'medium': {'width': 848, 'height': 640},
  157. 'high': {'width': 1024, 'height': 768},
  158. 'high-widescreen': {'width': 1280, 'height': 720},
  159. }
  160. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  161. quality_key = qualities(QUALITIES_PREFERENCE)
  162. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  163. ALLOWED_QUALITIES = (
  164. AllowedQuality('webm', ['high', ]),
  165. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  166. )
  167. # Some courses also offer widescreen resolution for high quality (see
  168. # https://github.com/rg3/youtube-dl/issues/7766)
  169. widescreen = course.get('supportsWideScreenVideoFormats') is True
  170. best_quality = 'high-widescreen' if widescreen else 'high'
  171. if widescreen:
  172. for allowed_quality in ALLOWED_QUALITIES:
  173. allowed_quality.qualities.append(best_quality)
  174. # In order to minimize the number of calls to ViewClip API and reduce
  175. # the probability of being throttled or banned by Pluralsight we will request
  176. # only single format until formats listing was explicitly requested.
  177. if self._downloader.params.get('listformats', False):
  178. allowed_qualities = ALLOWED_QUALITIES
  179. else:
  180. def guess_allowed_qualities():
  181. req_format = self._downloader.params.get('format') or 'best'
  182. req_format_split = req_format.split('-', 1)
  183. if len(req_format_split) > 1:
  184. req_ext, req_quality = req_format_split
  185. for allowed_quality in ALLOWED_QUALITIES:
  186. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  187. return (AllowedQuality(req_ext, (req_quality, )), )
  188. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  189. return (AllowedQuality(req_ext, (best_quality, )), )
  190. allowed_qualities = guess_allowed_qualities()
  191. formats = []
  192. for ext, qualities_ in allowed_qualities:
  193. for quality in qualities_:
  194. f = QUALITIES[quality].copy()
  195. clip_post = {
  196. 'author': author,
  197. 'includeCaptions': False,
  198. 'clipIndex': int(clip_id),
  199. 'courseName': course_name,
  200. 'locale': 'en',
  201. 'moduleName': name,
  202. 'mediaType': ext,
  203. 'quality': '%dx%d' % (f['width'], f['height']),
  204. }
  205. format_id = '%s-%s' % (ext, quality)
  206. clip_url = self._download_webpage(
  207. '%s/video/clips/viewclip' % self._API_BASE, display_id,
  208. 'Downloading %s URL' % format_id, fatal=False,
  209. data=json.dumps(clip_post).encode('utf-8'),
  210. headers={'Content-Type': 'application/json;charset=utf-8'})
  211. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  212. # to return 429 HTTP errors after some time (see
  213. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  214. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  215. # To somewhat reduce the probability of these consequences
  216. # we will sleep random amount of time before each call to ViewClip.
  217. self._sleep(
  218. random.randint(2, 5), display_id,
  219. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  220. if not clip_url:
  221. continue
  222. f.update({
  223. 'url': clip_url,
  224. 'ext': ext,
  225. 'format_id': format_id,
  226. 'quality': quality_key(quality),
  227. })
  228. formats.append(f)
  229. self._sort_formats(formats)
  230. duration = int_or_none(
  231. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  232. # TODO: other languages?
  233. subtitles = self.extract_subtitles(
  234. author, clip_id, 'en', name, duration, display_id)
  235. return {
  236. 'id': clip.get('clipName') or clip['name'],
  237. 'title': title,
  238. 'duration': duration,
  239. 'creator': author,
  240. 'formats': formats,
  241. 'subtitles': subtitles,
  242. }
  243. class PluralsightCourseIE(PluralsightBaseIE):
  244. IE_NAME = 'pluralsight:course'
  245. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  246. _TESTS = [{
  247. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  248. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  249. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  250. 'info_dict': {
  251. 'id': 'hosting-sql-server-windows-azure-iaas',
  252. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  253. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  254. },
  255. 'playlist_count': 31,
  256. }, {
  257. # available without pluralsight account
  258. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  259. 'only_matching': True,
  260. }, {
  261. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  262. 'only_matching': True,
  263. }]
  264. def _real_extract(self, url):
  265. course_id = self._match_id(url)
  266. # TODO: PSM cookie
  267. course = self._download_json(
  268. '%s/data/course/%s' % (self._API_BASE, course_id),
  269. course_id, 'Downloading course JSON')
  270. title = course['title']
  271. description = course.get('description') or course.get('shortDescription')
  272. course_data = self._download_json(
  273. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  274. course_id, 'Downloading course data JSON')
  275. entries = []
  276. for num, module in enumerate(course_data, 1):
  277. for clip in module.get('clips', []):
  278. player_parameters = clip.get('playerParameters')
  279. if not player_parameters:
  280. continue
  281. entries.append({
  282. '_type': 'url_transparent',
  283. 'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
  284. 'ie_key': PluralsightIE.ie_key(),
  285. 'chapter': module.get('title'),
  286. 'chapter_number': num,
  287. 'chapter_id': module.get('moduleRef'),
  288. })
  289. return self.playlist_result(entries, course_id, title, description)