pluralsight.py 13 KB

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