pluralsight.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 = 'http://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/training/Player/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 = qs.get('course', [None])[0]
  129. if any(not f for f in (author, name, clip_id, course,)):
  130. raise ExtractorError('Invalid URL', expected=True)
  131. display_id = '%s-%s' % (name, clip_id)
  132. webpage = self._download_webpage(url, display_id)
  133. modules = self._search_regex(
  134. r'moduleCollection\s*:\s*new\s+ModuleCollection\((\[.+?\])\s*,\s*\$rootScope\)',
  135. webpage, 'modules', default=None)
  136. if modules:
  137. collection = self._parse_json(modules, display_id)
  138. else:
  139. # Webpage may be served in different layout (see
  140. # https://github.com/rg3/youtube-dl/issues/7607)
  141. collection = self._parse_json(
  142. self._search_regex(
  143. r'var\s+initialState\s*=\s*({.+?});\n', webpage, 'initial state'),
  144. display_id)['course']['modules']
  145. module, clip = None, None
  146. for module_ in collection:
  147. if name in (module_.get('moduleName'), module_.get('name')):
  148. module = module_
  149. for clip_ in module_.get('clips', []):
  150. clip_index = clip_.get('clipIndex')
  151. if clip_index is None:
  152. clip_index = clip_.get('index')
  153. if clip_index is None:
  154. continue
  155. if compat_str(clip_index) == clip_id:
  156. clip = clip_
  157. break
  158. if not clip:
  159. raise ExtractorError('Unable to resolve clip')
  160. title = '%s - %s' % (module['title'], clip['title'])
  161. QUALITIES = {
  162. 'low': {'width': 640, 'height': 480},
  163. 'medium': {'width': 848, 'height': 640},
  164. 'high': {'width': 1024, 'height': 768},
  165. 'high-widescreen': {'width': 1280, 'height': 720},
  166. }
  167. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  168. quality_key = qualities(QUALITIES_PREFERENCE)
  169. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  170. ALLOWED_QUALITIES = (
  171. AllowedQuality('webm', ['high', ]),
  172. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  173. )
  174. # Some courses also offer widescreen resolution for high quality (see
  175. # https://github.com/rg3/youtube-dl/issues/7766)
  176. widescreen = True if re.search(
  177. r'courseSupportsWidescreenVideoFormats\s*:\s*true', webpage) else False
  178. best_quality = 'high-widescreen' if widescreen else 'high'
  179. if widescreen:
  180. for allowed_quality in ALLOWED_QUALITIES:
  181. allowed_quality.qualities.append(best_quality)
  182. # In order to minimize the number of calls to ViewClip API and reduce
  183. # the probability of being throttled or banned by Pluralsight we will request
  184. # only single format until formats listing was explicitly requested.
  185. if self._downloader.params.get('listformats', False):
  186. allowed_qualities = ALLOWED_QUALITIES
  187. else:
  188. def guess_allowed_qualities():
  189. req_format = self._downloader.params.get('format') or 'best'
  190. req_format_split = req_format.split('-', 1)
  191. if len(req_format_split) > 1:
  192. req_ext, req_quality = req_format_split
  193. for allowed_quality in ALLOWED_QUALITIES:
  194. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  195. return (AllowedQuality(req_ext, (req_quality, )), )
  196. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  197. return (AllowedQuality(req_ext, (best_quality, )), )
  198. allowed_qualities = guess_allowed_qualities()
  199. formats = []
  200. for ext, qualities_ in allowed_qualities:
  201. for quality in qualities_:
  202. f = QUALITIES[quality].copy()
  203. clip_post = {
  204. 'a': author,
  205. 'cap': 'false',
  206. 'cn': clip_id,
  207. 'course': course,
  208. 'lc': 'en',
  209. 'm': name,
  210. 'mt': ext,
  211. 'q': '%dx%d' % (f['width'], f['height']),
  212. }
  213. format_id = '%s-%s' % (ext, quality)
  214. clip_url = self._download_webpage(
  215. '%s/training/Player/ViewClip' % self._API_BASE, display_id,
  216. 'Downloading %s URL' % format_id, fatal=False,
  217. data=json.dumps(clip_post).encode('utf-8'),
  218. headers={'Content-Type': 'application/json;charset=utf-8'})
  219. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  220. # to return 429 HTTP errors after some time (see
  221. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  222. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  223. # To somewhat reduce the probability of these consequences
  224. # we will sleep random amount of time before each call to ViewClip.
  225. self._sleep(
  226. random.randint(2, 5), display_id,
  227. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  228. if not clip_url:
  229. continue
  230. f.update({
  231. 'url': clip_url,
  232. 'ext': ext,
  233. 'format_id': format_id,
  234. 'quality': quality_key(quality),
  235. })
  236. formats.append(f)
  237. self._sort_formats(formats)
  238. duration = int_or_none(
  239. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  240. # TODO: other languages?
  241. subtitles = self.extract_subtitles(
  242. author, clip_id, 'en', name, duration, display_id)
  243. return {
  244. 'id': clip.get('clipName') or clip['name'],
  245. 'title': title,
  246. 'duration': duration,
  247. 'creator': author,
  248. 'formats': formats,
  249. 'subtitles': subtitles,
  250. }
  251. class PluralsightCourseIE(PluralsightBaseIE):
  252. IE_NAME = 'pluralsight:course'
  253. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  254. _TESTS = [{
  255. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  256. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  257. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  258. 'info_dict': {
  259. 'id': 'hosting-sql-server-windows-azure-iaas',
  260. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  261. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  262. },
  263. 'playlist_count': 31,
  264. }, {
  265. # available without pluralsight account
  266. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  267. 'only_matching': True,
  268. }, {
  269. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  270. 'only_matching': True,
  271. }]
  272. def _real_extract(self, url):
  273. course_id = self._match_id(url)
  274. # TODO: PSM cookie
  275. course = self._download_json(
  276. '%s/data/course/%s' % (self._API_BASE, course_id),
  277. course_id, 'Downloading course JSON')
  278. title = course['title']
  279. description = course.get('description') or course.get('shortDescription')
  280. course_data = self._download_json(
  281. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  282. course_id, 'Downloading course data JSON')
  283. entries = []
  284. for num, module in enumerate(course_data, 1):
  285. for clip in module.get('clips', []):
  286. player_parameters = clip.get('playerParameters')
  287. if not player_parameters:
  288. continue
  289. entries.append({
  290. '_type': 'url_transparent',
  291. 'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
  292. 'ie_key': PluralsightIE.ie_key(),
  293. 'chapter': module.get('title'),
  294. 'chapter_number': num,
  295. 'chapter_id': module.get('moduleRef'),
  296. })
  297. return self.playlist_result(entries, course_id, title, description)