pluralsight.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. from __future__ import unicode_literals
  2. import json
  3. import random
  4. import collections
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urllib_parse,
  9. compat_urllib_request,
  10. compat_urlparse,
  11. )
  12. from ..utils import (
  13. ExtractorError,
  14. int_or_none,
  15. parse_duration,
  16. )
  17. class PluralsightBaseIE(InfoExtractor):
  18. _API_BASE = 'http://app.pluralsight.com'
  19. class PluralsightIE(PluralsightBaseIE):
  20. IE_NAME = 'pluralsight'
  21. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/training/player\?'
  22. _LOGIN_URL = 'https://app.pluralsight.com/id/'
  23. _NETRC_MACHINE = 'pluralsight'
  24. _TESTS = [{
  25. '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',
  26. 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
  27. 'info_dict': {
  28. 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
  29. 'ext': 'mp4',
  30. 'title': 'Management of SQL Server - Demo Monitoring',
  31. 'duration': 338,
  32. },
  33. 'skip': 'Requires pluralsight account credentials',
  34. }, {
  35. 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
  36. 'only_matching': True,
  37. }, {
  38. # available without pluralsight account
  39. 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
  40. 'only_matching': True,
  41. }]
  42. def _real_initialize(self):
  43. self._login()
  44. def _login(self):
  45. (username, password) = self._get_login_info()
  46. if username is None:
  47. return
  48. login_page = self._download_webpage(
  49. self._LOGIN_URL, None, 'Downloading login page')
  50. login_form = self._hidden_inputs(login_page)
  51. login_form.update({
  52. 'Username': username.encode('utf-8'),
  53. 'Password': password.encode('utf-8'),
  54. })
  55. post_url = self._search_regex(
  56. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  57. 'post url', default=self._LOGIN_URL, group='url')
  58. if not post_url.startswith('http'):
  59. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  60. request = compat_urllib_request.Request(
  61. post_url, compat_urllib_parse.urlencode(login_form).encode('utf-8'))
  62. request.add_header('Content-Type', 'application/x-www-form-urlencoded')
  63. response = self._download_webpage(
  64. request, None, 'Logging in as %s' % username)
  65. error = self._search_regex(
  66. r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
  67. response, 'error message', default=None)
  68. if error:
  69. raise ExtractorError('Unable to login: %s' % error, expected=True)
  70. if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
  71. raise ExtractorError('Unable to log in')
  72. def _real_extract(self, url):
  73. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  74. author = qs.get('author', [None])[0]
  75. name = qs.get('name', [None])[0]
  76. clip_id = qs.get('clip', [None])[0]
  77. course = qs.get('course', [None])[0]
  78. if any(not f for f in (author, name, clip_id, course,)):
  79. raise ExtractorError('Invalid URL', expected=True)
  80. display_id = '%s-%s' % (name, clip_id)
  81. webpage = self._download_webpage(url, display_id)
  82. collection = self._parse_json(
  83. self._search_regex(
  84. r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
  85. webpage, 'modules'),
  86. display_id)
  87. module, clip = None, None
  88. for module_ in collection:
  89. if module_.get('moduleName') == name:
  90. module = module_
  91. for clip_ in module_.get('clips', []):
  92. clip_index = clip_.get('clipIndex')
  93. if clip_index is None:
  94. continue
  95. if compat_str(clip_index) == clip_id:
  96. clip = clip_
  97. break
  98. if not clip:
  99. raise ExtractorError('Unable to resolve clip')
  100. QUALITIES = {
  101. 'low': {'width': 640, 'height': 480},
  102. 'medium': {'width': 848, 'height': 640},
  103. 'high': {'width': 1024, 'height': 768},
  104. }
  105. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  106. ALLOWED_QUALITIES = (
  107. AllowedQuality('webm', ('high',)),
  108. AllowedQuality('mp4', ('low', 'medium', 'high',)),
  109. )
  110. # In order to minimize the number of calls to ViewClip API and reduce
  111. # the probability of being throttled or banned by Pluralsight we will request
  112. # only single format until formats listing was explicitly requested.
  113. if self._downloader.params.get('listformats', False):
  114. allowed_qualities = ALLOWED_QUALITIES
  115. else:
  116. def guess_allowed_qualities():
  117. req_format = self._downloader.params.get('format') or 'best'
  118. req_format_split = req_format.split('-')
  119. if len(req_format_split) > 1:
  120. req_ext, req_quality = req_format_split
  121. for allowed_quality in ALLOWED_QUALITIES:
  122. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  123. return (AllowedQuality(req_ext, (req_quality, )), )
  124. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  125. return (AllowedQuality(req_ext, ('high', )), )
  126. allowed_qualities = guess_allowed_qualities()
  127. formats = []
  128. for ext, qualities in allowed_qualities:
  129. for quality in qualities:
  130. f = QUALITIES[quality].copy()
  131. clip_post = {
  132. 'a': author,
  133. 'cap': 'false',
  134. 'cn': clip_id,
  135. 'course': course,
  136. 'lc': 'en',
  137. 'm': name,
  138. 'mt': ext,
  139. 'q': '%dx%d' % (f['width'], f['height']),
  140. }
  141. request = compat_urllib_request.Request(
  142. '%s/training/Player/ViewClip' % self._API_BASE,
  143. json.dumps(clip_post).encode('utf-8'))
  144. request.add_header('Content-Type', 'application/json;charset=utf-8')
  145. format_id = '%s-%s' % (ext, quality)
  146. clip_url = self._download_webpage(
  147. request, display_id, 'Downloading %s URL' % format_id, fatal=False)
  148. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  149. # to return 429 HTTP errors after some time (see
  150. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  151. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  152. # To somewhat reduce the probability of these consequences
  153. # we will sleep random amount of time before each call to ViewClip.
  154. self._sleep(
  155. random.randint(2, 5), display_id,
  156. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  157. if not clip_url:
  158. continue
  159. f.update({
  160. 'url': clip_url,
  161. 'ext': ext,
  162. 'format_id': format_id,
  163. })
  164. formats.append(f)
  165. self._sort_formats(formats)
  166. # TODO: captions
  167. # http://www.pluralsight.com/training/Player/ViewClip + cap = true
  168. # or
  169. # http://www.pluralsight.com/training/Player/Captions
  170. # { a = author, cn = clip_id, lc = end, m = name }
  171. return {
  172. 'id': clip['clipName'],
  173. 'title': '%s - %s' % (module['title'], clip['title']),
  174. 'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
  175. 'creator': author,
  176. 'formats': formats
  177. }
  178. class PluralsightCourseIE(PluralsightBaseIE):
  179. IE_NAME = 'pluralsight:course'
  180. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  181. _TESTS = [{
  182. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  183. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  184. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  185. 'info_dict': {
  186. 'id': 'hosting-sql-server-windows-azure-iaas',
  187. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  188. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  189. },
  190. 'playlist_count': 31,
  191. }, {
  192. # available without pluralsight account
  193. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  194. 'only_matching': True,
  195. }, {
  196. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  197. 'only_matching': True,
  198. }]
  199. def _real_extract(self, url):
  200. course_id = self._match_id(url)
  201. # TODO: PSM cookie
  202. course = self._download_json(
  203. '%s/data/course/%s' % (self._API_BASE, course_id),
  204. course_id, 'Downloading course JSON')
  205. title = course['title']
  206. description = course.get('description') or course.get('shortDescription')
  207. course_data = self._download_json(
  208. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  209. course_id, 'Downloading course data JSON')
  210. entries = []
  211. for module in course_data:
  212. for clip in module.get('clips', []):
  213. player_parameters = clip.get('playerParameters')
  214. if not player_parameters:
  215. continue
  216. entries.append(self.url_result(
  217. '%s/training/player?%s' % (self._API_BASE, player_parameters),
  218. 'Pluralsight'))
  219. return self.playlist_result(entries, course_id, title, description)