pluralsight.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. if self._downloader.params.get('listformats', False):
  111. allowed_qualities = ALLOWED_QUALITIES
  112. else:
  113. def guess_allowed_qualities():
  114. req_format = self._downloader.params.get('format') or 'best'
  115. req_format_split = req_format.split('-')
  116. if len(req_format_split) > 1:
  117. req_ext, req_quality = req_format_split
  118. for allowed_quality in ALLOWED_QUALITIES:
  119. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  120. return (AllowedQuality(req_ext, (req_quality, )), )
  121. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  122. return (AllowedQuality(req_ext, ('high', )), )
  123. allowed_qualities = guess_allowed_qualities()
  124. formats = []
  125. for ext, qualities in allowed_qualities:
  126. for quality in qualities:
  127. f = QUALITIES[quality].copy()
  128. clip_post = {
  129. 'a': author,
  130. 'cap': 'false',
  131. 'cn': clip_id,
  132. 'course': course,
  133. 'lc': 'en',
  134. 'm': name,
  135. 'mt': ext,
  136. 'q': '%dx%d' % (f['width'], f['height']),
  137. }
  138. request = compat_urllib_request.Request(
  139. '%s/training/Player/ViewClip' % self._API_BASE,
  140. json.dumps(clip_post).encode('utf-8'))
  141. request.add_header('Content-Type', 'application/json;charset=utf-8')
  142. format_id = '%s-%s' % (ext, quality)
  143. clip_url = self._download_webpage(
  144. request, display_id, 'Downloading %s URL' % format_id, fatal=False)
  145. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  146. # to return 429 HTTP errors after some time (see
  147. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  148. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  149. # To somewhat reduce the probability of these consequences
  150. # we will sleep random amount of time before each call to ViewClip.
  151. self._sleep(
  152. random.randint(2, 5), display_id,
  153. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  154. if not clip_url:
  155. continue
  156. f.update({
  157. 'url': clip_url,
  158. 'ext': ext,
  159. 'format_id': format_id,
  160. })
  161. formats.append(f)
  162. self._sort_formats(formats)
  163. # TODO: captions
  164. # http://www.pluralsight.com/training/Player/ViewClip + cap = true
  165. # or
  166. # http://www.pluralsight.com/training/Player/Captions
  167. # { a = author, cn = clip_id, lc = end, m = name }
  168. return {
  169. 'id': clip['clipName'],
  170. 'title': '%s - %s' % (module['title'], clip['title']),
  171. 'duration': int_or_none(clip.get('duration')) or parse_duration(clip.get('formattedDuration')),
  172. 'creator': author,
  173. 'formats': formats
  174. }
  175. class PluralsightCourseIE(PluralsightBaseIE):
  176. IE_NAME = 'pluralsight:course'
  177. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  178. _TESTS = [{
  179. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  180. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  181. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  182. 'info_dict': {
  183. 'id': 'hosting-sql-server-windows-azure-iaas',
  184. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  185. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  186. },
  187. 'playlist_count': 31,
  188. }, {
  189. # available without pluralsight account
  190. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  191. 'only_matching': True,
  192. }, {
  193. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  194. 'only_matching': True,
  195. }]
  196. def _real_extract(self, url):
  197. course_id = self._match_id(url)
  198. # TODO: PSM cookie
  199. course = self._download_json(
  200. '%s/data/course/%s' % (self._API_BASE, course_id),
  201. course_id, 'Downloading course JSON')
  202. title = course['title']
  203. description = course.get('description') or course.get('shortDescription')
  204. course_data = self._download_json(
  205. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  206. course_id, 'Downloading course data JSON')
  207. entries = []
  208. for module in course_data:
  209. for clip in module.get('clips', []):
  210. player_parameters = clip.get('playerParameters')
  211. if not player_parameters:
  212. continue
  213. entries.append(self.url_result(
  214. '%s/training/player?%s' % (self._API_BASE, player_parameters),
  215. 'Pluralsight'))
  216. return self.playlist_result(entries, course_id, title, description)