You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

354 lines
14 KiB

  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. ExtractorError,
  13. float_or_none,
  14. int_or_none,
  15. parse_duration,
  16. qualities,
  17. srt_subtitles_timecode,
  18. urlencode_postdata,
  19. )
  20. class PluralsightBaseIE(InfoExtractor):
  21. _API_BASE = 'https://app.pluralsight.com'
  22. class PluralsightIE(PluralsightBaseIE):
  23. IE_NAME = 'pluralsight'
  24. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
  25. _LOGIN_URL = 'https://app.pluralsight.com/id/'
  26. _NETRC_MACHINE = 'pluralsight'
  27. _TESTS = [{
  28. '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',
  29. 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
  30. 'info_dict': {
  31. 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
  32. 'ext': 'mp4',
  33. 'title': 'Management of SQL Server - Demo Monitoring',
  34. 'duration': 338,
  35. },
  36. 'skip': 'Requires pluralsight account credentials',
  37. }, {
  38. 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
  39. 'only_matching': True,
  40. }, {
  41. # available without pluralsight account
  42. 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
  43. 'only_matching': True,
  44. }, {
  45. 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
  46. 'only_matching': True,
  47. }]
  48. def _real_initialize(self):
  49. self._login()
  50. def _login(self):
  51. (username, password) = self._get_login_info()
  52. if username is None:
  53. return
  54. login_page = self._download_webpage(
  55. self._LOGIN_URL, None, 'Downloading login page')
  56. login_form = self._hidden_inputs(login_page)
  57. login_form.update({
  58. 'Username': username,
  59. 'Password': password,
  60. })
  61. post_url = self._search_regex(
  62. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  63. 'post url', default=self._LOGIN_URL, group='url')
  64. if not post_url.startswith('http'):
  65. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  66. response = self._download_webpage(
  67. post_url, None, 'Logging in as %s' % username,
  68. data=urlencode_postdata(login_form),
  69. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  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/player/retrieve-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. if end is None:
  111. continue
  112. srt += os.linesep.join(
  113. (
  114. '%d' % num,
  115. '%s --> %s' % (
  116. srt_subtitles_timecode(start),
  117. srt_subtitles_timecode(end)),
  118. text,
  119. os.linesep,
  120. ))
  121. return srt
  122. def _real_extract(self, url):
  123. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  124. author = qs.get('author', [None])[0]
  125. name = qs.get('name', [None])[0]
  126. clip_id = qs.get('clip', [None])[0]
  127. course_name = qs.get('course', [None])[0]
  128. if any(not f for f in (author, name, clip_id, course_name,)):
  129. raise ExtractorError('Invalid URL', expected=True)
  130. display_id = '%s-%s' % (name, clip_id)
  131. parsed_url = compat_urlparse.urlparse(url)
  132. payload_url = compat_urlparse.urlunparse(parsed_url._replace(
  133. netloc='app.pluralsight.com', path='player/api/v1/payload'))
  134. course = self._download_json(
  135. payload_url, display_id, headers={'Referer': url})['payload']['course']
  136. collection = course['modules']
  137. module, clip = None, None
  138. for module_ in collection:
  139. if name in (module_.get('moduleName'), module_.get('name')):
  140. module = module_
  141. for clip_ in module_.get('clips', []):
  142. clip_index = clip_.get('clipIndex')
  143. if clip_index is None:
  144. clip_index = clip_.get('index')
  145. if clip_index is None:
  146. continue
  147. if compat_str(clip_index) == clip_id:
  148. clip = clip_
  149. break
  150. if not clip:
  151. raise ExtractorError('Unable to resolve clip')
  152. title = '%s - %s' % (module['title'], clip['title'])
  153. QUALITIES = {
  154. 'low': {'width': 640, 'height': 480},
  155. 'medium': {'width': 848, 'height': 640},
  156. 'high': {'width': 1024, 'height': 768},
  157. 'high-widescreen': {'width': 1280, 'height': 720},
  158. }
  159. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  160. quality_key = qualities(QUALITIES_PREFERENCE)
  161. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  162. ALLOWED_QUALITIES = (
  163. AllowedQuality('webm', ['high', ]),
  164. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  165. )
  166. # Some courses also offer widescreen resolution for high quality (see
  167. # https://github.com/rg3/youtube-dl/issues/7766)
  168. widescreen = course.get('supportsWideScreenVideoFormats') is True
  169. best_quality = 'high-widescreen' if widescreen else 'high'
  170. if widescreen:
  171. for allowed_quality in ALLOWED_QUALITIES:
  172. allowed_quality.qualities.append(best_quality)
  173. # In order to minimize the number of calls to ViewClip API and reduce
  174. # the probability of being throttled or banned by Pluralsight we will request
  175. # only single format until formats listing was explicitly requested.
  176. if self._downloader.params.get('listformats', False):
  177. allowed_qualities = ALLOWED_QUALITIES
  178. else:
  179. def guess_allowed_qualities():
  180. req_format = self._downloader.params.get('format') or 'best'
  181. req_format_split = req_format.split('-', 1)
  182. if len(req_format_split) > 1:
  183. req_ext, req_quality = req_format_split
  184. for allowed_quality in ALLOWED_QUALITIES:
  185. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  186. return (AllowedQuality(req_ext, (req_quality, )), )
  187. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  188. return (AllowedQuality(req_ext, (best_quality, )), )
  189. allowed_qualities = guess_allowed_qualities()
  190. formats = []
  191. for ext, qualities_ in allowed_qualities:
  192. for quality in qualities_:
  193. f = QUALITIES[quality].copy()
  194. clip_post = {
  195. 'author': author,
  196. 'includeCaptions': False,
  197. 'clipIndex': int(clip_id),
  198. 'courseName': course_name,
  199. 'locale': 'en',
  200. 'moduleName': name,
  201. 'mediaType': ext,
  202. 'quality': '%dx%d' % (f['width'], f['height']),
  203. }
  204. format_id = '%s-%s' % (ext, quality)
  205. viewclip = self._download_json(
  206. '%s/video/clips/viewclip' % self._API_BASE, display_id,
  207. 'Downloading %s viewclip JSON' % format_id, fatal=False,
  208. data=json.dumps(clip_post).encode('utf-8'),
  209. headers={'Content-Type': 'application/json;charset=utf-8'})
  210. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  211. # to return 429 HTTP errors after some time (see
  212. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  213. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  214. # To somewhat reduce the probability of these consequences
  215. # we will sleep random amount of time before each call to ViewClip.
  216. self._sleep(
  217. random.randint(2, 5), display_id,
  218. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  219. if not viewclip:
  220. continue
  221. clip_urls = viewclip.get('urls')
  222. if not isinstance(clip_urls, list):
  223. continue
  224. for clip_url_data in clip_urls:
  225. clip_url = clip_url_data.get('url')
  226. if not clip_url:
  227. continue
  228. cdn = clip_url_data.get('cdn')
  229. clip_f = f.copy()
  230. clip_f.update({
  231. 'url': clip_url,
  232. 'ext': ext,
  233. 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
  234. 'quality': quality_key(quality),
  235. 'source_preference': int_or_none(clip_url_data.get('rank')),
  236. })
  237. formats.append(clip_f)
  238. self._sort_formats(formats)
  239. duration = int_or_none(
  240. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  241. # TODO: other languages?
  242. subtitles = self.extract_subtitles(
  243. author, clip_id, 'en', name, duration, display_id)
  244. return {
  245. 'id': clip.get('clipName') or clip['name'],
  246. 'title': title,
  247. 'duration': duration,
  248. 'creator': author,
  249. 'formats': formats,
  250. 'subtitles': subtitles,
  251. }
  252. class PluralsightCourseIE(PluralsightBaseIE):
  253. IE_NAME = 'pluralsight:course'
  254. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  255. _TESTS = [{
  256. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  257. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  258. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  259. 'info_dict': {
  260. 'id': 'hosting-sql-server-windows-azure-iaas',
  261. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  262. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  263. },
  264. 'playlist_count': 31,
  265. }, {
  266. # available without pluralsight account
  267. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  268. 'only_matching': True,
  269. }, {
  270. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  271. 'only_matching': True,
  272. }]
  273. def _real_extract(self, url):
  274. course_id = self._match_id(url)
  275. # TODO: PSM cookie
  276. course = self._download_json(
  277. '%s/data/course/%s' % (self._API_BASE, course_id),
  278. course_id, 'Downloading course JSON')
  279. title = course['title']
  280. description = course.get('description') or course.get('shortDescription')
  281. course_data = self._download_json(
  282. '%s/data/course/content/%s' % (self._API_BASE, course_id),
  283. course_id, 'Downloading course data JSON')
  284. entries = []
  285. for num, module in enumerate(course_data, 1):
  286. for clip in module.get('clips', []):
  287. player_parameters = clip.get('playerParameters')
  288. if not player_parameters:
  289. continue
  290. entries.append({
  291. '_type': 'url_transparent',
  292. 'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
  293. 'ie_key': PluralsightIE.ie_key(),
  294. 'chapter': module.get('title'),
  295. 'chapter_number': num,
  296. 'chapter_id': module.get('moduleRef'),
  297. })
  298. return self.playlist_result(entries, course_id, title, description)