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.

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