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.

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