pluralsight.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. 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. BLOCKED = 'Your account has been blocked due to suspicious activity'
  78. if BLOCKED in response:
  79. raise ExtractorError(
  80. 'Unable to login: %s' % BLOCKED, expected=True)
  81. raise ExtractorError('Unable to log in')
  82. def _get_subtitles(self, author, clip_id, lang, name, duration, video_id):
  83. captions_post = {
  84. 'a': author,
  85. 'cn': clip_id,
  86. 'lc': lang,
  87. 'm': name,
  88. }
  89. captions = self._download_json(
  90. '%s/player/retrieve-captions' % self._API_BASE, video_id,
  91. 'Downloading captions JSON', 'Unable to download captions JSON',
  92. fatal=False, data=json.dumps(captions_post).encode('utf-8'),
  93. headers={'Content-Type': 'application/json;charset=utf-8'})
  94. if captions:
  95. return {
  96. lang: [{
  97. 'ext': 'json',
  98. 'data': json.dumps(captions),
  99. }, {
  100. 'ext': 'srt',
  101. 'data': self._convert_subtitles(duration, captions),
  102. }]
  103. }
  104. @staticmethod
  105. def _convert_subtitles(duration, subs):
  106. srt = ''
  107. TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
  108. TEXT_KEYS = ('text', 'Text')
  109. for num, current in enumerate(subs):
  110. current = subs[num]
  111. start, text = (
  112. float_or_none(dict_get(current, TIME_OFFSET_KEYS)),
  113. dict_get(current, TEXT_KEYS))
  114. if start is None or text is None:
  115. continue
  116. end = duration if num == len(subs) - 1 else float_or_none(
  117. dict_get(subs[num + 1], TIME_OFFSET_KEYS))
  118. if end is None:
  119. continue
  120. srt += os.linesep.join(
  121. (
  122. '%d' % num,
  123. '%s --> %s' % (
  124. srt_subtitles_timecode(start),
  125. srt_subtitles_timecode(end)),
  126. text,
  127. os.linesep,
  128. ))
  129. return srt
  130. def _real_extract(self, url):
  131. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  132. author = qs.get('author', [None])[0]
  133. name = qs.get('name', [None])[0]
  134. clip_id = qs.get('clip', [None])[0]
  135. course_name = qs.get('course', [None])[0]
  136. if any(not f for f in (author, name, clip_id, course_name,)):
  137. raise ExtractorError('Invalid URL', expected=True)
  138. display_id = '%s-%s' % (name, clip_id)
  139. course = self._download_json(
  140. 'https://app.pluralsight.com/player/user/api/v1/player/payload',
  141. display_id, data=urlencode_postdata({'courseId': course_name}),
  142. headers={'Referer': url})
  143. collection = course['modules']
  144. module, clip = None, None
  145. for module_ in collection:
  146. if name in (module_.get('moduleName'), module_.get('name')):
  147. module = module_
  148. for clip_ in module_.get('clips', []):
  149. clip_index = clip_.get('clipIndex')
  150. if clip_index is None:
  151. clip_index = clip_.get('index')
  152. if clip_index is None:
  153. continue
  154. if compat_str(clip_index) == clip_id:
  155. clip = clip_
  156. break
  157. if not clip:
  158. raise ExtractorError('Unable to resolve clip')
  159. title = '%s - %s' % (module['title'], clip['title'])
  160. QUALITIES = {
  161. 'low': {'width': 640, 'height': 480},
  162. 'medium': {'width': 848, 'height': 640},
  163. 'high': {'width': 1024, 'height': 768},
  164. 'high-widescreen': {'width': 1280, 'height': 720},
  165. }
  166. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  167. quality_key = qualities(QUALITIES_PREFERENCE)
  168. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  169. ALLOWED_QUALITIES = (
  170. AllowedQuality('webm', ['high', ]),
  171. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  172. )
  173. # Some courses also offer widescreen resolution for high quality (see
  174. # https://github.com/rg3/youtube-dl/issues/7766)
  175. widescreen = course.get('supportsWideScreenVideoFormats') is True
  176. best_quality = 'high-widescreen' if widescreen else 'high'
  177. if widescreen:
  178. for allowed_quality in ALLOWED_QUALITIES:
  179. allowed_quality.qualities.append(best_quality)
  180. # In order to minimize the number of calls to ViewClip API and reduce
  181. # the probability of being throttled or banned by Pluralsight we will request
  182. # only single format until formats listing was explicitly requested.
  183. if self._downloader.params.get('listformats', False):
  184. allowed_qualities = ALLOWED_QUALITIES
  185. else:
  186. def guess_allowed_qualities():
  187. req_format = self._downloader.params.get('format') or 'best'
  188. req_format_split = req_format.split('-', 1)
  189. if len(req_format_split) > 1:
  190. req_ext, req_quality = req_format_split
  191. for allowed_quality in ALLOWED_QUALITIES:
  192. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  193. return (AllowedQuality(req_ext, (req_quality, )), )
  194. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  195. return (AllowedQuality(req_ext, (best_quality, )), )
  196. allowed_qualities = guess_allowed_qualities()
  197. formats = []
  198. for ext, qualities_ in allowed_qualities:
  199. for quality in qualities_:
  200. f = QUALITIES[quality].copy()
  201. clip_post = {
  202. 'author': author,
  203. 'includeCaptions': False,
  204. 'clipIndex': int(clip_id),
  205. 'courseName': course_name,
  206. 'locale': 'en',
  207. 'moduleName': name,
  208. 'mediaType': ext,
  209. 'quality': '%dx%d' % (f['width'], f['height']),
  210. }
  211. format_id = '%s-%s' % (ext, quality)
  212. viewclip = self._download_json(
  213. '%s/video/clips/viewclip' % self._API_BASE, display_id,
  214. 'Downloading %s viewclip JSON' % format_id, fatal=False,
  215. data=json.dumps(clip_post).encode('utf-8'),
  216. headers={'Content-Type': 'application/json;charset=utf-8'})
  217. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  218. # to return 429 HTTP errors after some time (see
  219. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  220. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  221. # To somewhat reduce the probability of these consequences
  222. # we will sleep random amount of time before each call to ViewClip.
  223. self._sleep(
  224. random.randint(2, 5), display_id,
  225. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  226. if not viewclip:
  227. continue
  228. clip_urls = viewclip.get('urls')
  229. if not isinstance(clip_urls, list):
  230. continue
  231. for clip_url_data in clip_urls:
  232. clip_url = clip_url_data.get('url')
  233. if not clip_url:
  234. continue
  235. cdn = clip_url_data.get('cdn')
  236. clip_f = f.copy()
  237. clip_f.update({
  238. 'url': clip_url,
  239. 'ext': ext,
  240. 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
  241. 'quality': quality_key(quality),
  242. 'source_preference': int_or_none(clip_url_data.get('rank')),
  243. })
  244. formats.append(clip_f)
  245. self._sort_formats(formats)
  246. duration = int_or_none(
  247. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  248. # TODO: other languages?
  249. subtitles = self.extract_subtitles(
  250. author, clip_id, 'en', name, duration, display_id)
  251. return {
  252. 'id': clip.get('clipName') or clip['name'],
  253. 'title': title,
  254. 'duration': duration,
  255. 'creator': author,
  256. 'formats': formats,
  257. 'subtitles': subtitles,
  258. }
  259. class PluralsightCourseIE(PluralsightBaseIE):
  260. IE_NAME = 'pluralsight:course'
  261. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  262. _TESTS = [{
  263. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  264. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  265. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  266. 'info_dict': {
  267. 'id': 'hosting-sql-server-windows-azure-iaas',
  268. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  269. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  270. },
  271. 'playlist_count': 31,
  272. }, {
  273. # available without pluralsight account
  274. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  275. 'only_matching': True,
  276. }, {
  277. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  278. 'only_matching': True,
  279. }]
  280. def _real_extract(self, url):
  281. course_id = self._match_id(url)
  282. # TODO: PSM cookie
  283. course = self._download_json(
  284. '%s/data/course/%s' % (self._API_BASE, course_id),
  285. course_id, 'Downloading course JSON')
  286. title = course['title']
  287. description = course.get('description') or course.get('shortDescription')
  288. course_data = self._download_json(
  289. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  290. course_id, 'Downloading course data JSON')
  291. entries = []
  292. for num, module in enumerate(course_data, 1):
  293. for clip in module.get('clips', []):
  294. player_parameters = clip.get('playerParameters')
  295. if not player_parameters:
  296. continue
  297. entries.append({
  298. '_type': 'url_transparent',
  299. 'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
  300. 'ie_key': PluralsightIE.ie_key(),
  301. 'chapter': module.get('title'),
  302. 'chapter_number': num,
  303. 'chapter_id': module.get('moduleRef'),
  304. })
  305. return self.playlist_result(entries, course_id, title, description)