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.

378 lines
15 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. update_url_query,
  20. urlencode_postdata,
  21. )
  22. class PluralsightBaseIE(InfoExtractor):
  23. _API_BASE = 'https://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': '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. 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
  48. 'only_matching': True,
  49. }]
  50. def _real_initialize(self):
  51. self._login()
  52. def _login(self):
  53. (username, password) = self._get_login_info()
  54. if username is None:
  55. return
  56. login_page = self._download_webpage(
  57. self._LOGIN_URL, None, 'Downloading login page')
  58. login_form = self._hidden_inputs(login_page)
  59. login_form.update({
  60. 'Username': username,
  61. 'Password': password,
  62. })
  63. post_url = self._search_regex(
  64. r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
  65. 'post url', default=self._LOGIN_URL, group='url')
  66. if not post_url.startswith('http'):
  67. post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
  68. response = self._download_webpage(
  69. post_url, None, 'Logging in as %s' % username,
  70. data=urlencode_postdata(login_form),
  71. headers={'Content-Type': 'application/x-www-form-urlencoded'})
  72. error = self._search_regex(
  73. r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
  74. response, 'error message', default=None)
  75. if error:
  76. raise ExtractorError('Unable to login: %s' % error, expected=True)
  77. if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
  78. BLOCKED = 'Your account has been blocked due to suspicious activity'
  79. if BLOCKED in response:
  80. raise ExtractorError(
  81. 'Unable to login: %s' % BLOCKED, expected=True)
  82. raise ExtractorError('Unable to log in')
  83. def _get_subtitles(self, author, clip_id, lang, name, duration, video_id):
  84. captions_post = {
  85. 'a': author,
  86. 'cn': clip_id,
  87. 'lc': lang,
  88. 'm': name,
  89. }
  90. captions = self._download_json(
  91. '%s/player/retrieve-captions' % self._API_BASE, video_id,
  92. 'Downloading captions JSON', 'Unable to download captions JSON',
  93. fatal=False, data=json.dumps(captions_post).encode('utf-8'),
  94. headers={'Content-Type': 'application/json;charset=utf-8'})
  95. if captions:
  96. return {
  97. lang: [{
  98. 'ext': 'json',
  99. 'data': json.dumps(captions),
  100. }, {
  101. 'ext': 'srt',
  102. 'data': self._convert_subtitles(duration, captions),
  103. }]
  104. }
  105. @staticmethod
  106. def _convert_subtitles(duration, subs):
  107. srt = ''
  108. TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
  109. TEXT_KEYS = ('text', 'Text')
  110. for num, current in enumerate(subs):
  111. current = subs[num]
  112. start, text = (
  113. float_or_none(dict_get(current, TIME_OFFSET_KEYS)),
  114. dict_get(current, TEXT_KEYS))
  115. if start is None or text is None:
  116. continue
  117. end = duration if num == len(subs) - 1 else float_or_none(
  118. dict_get(subs[num + 1], TIME_OFFSET_KEYS))
  119. if end is None:
  120. continue
  121. srt += os.linesep.join(
  122. (
  123. '%d' % num,
  124. '%s --> %s' % (
  125. srt_subtitles_timecode(start),
  126. srt_subtitles_timecode(end)),
  127. text,
  128. os.linesep,
  129. ))
  130. return srt
  131. def _real_extract(self, url):
  132. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  133. author = qs.get('author', [None])[0]
  134. name = qs.get('name', [None])[0]
  135. clip_id = qs.get('clip', [None])[0]
  136. course_name = qs.get('course', [None])[0]
  137. if any(not f for f in (author, name, clip_id, course_name,)):
  138. raise ExtractorError('Invalid URL', expected=True)
  139. display_id = '%s-%s' % (name, clip_id)
  140. course = self._download_json(
  141. 'https://app.pluralsight.com/player/user/api/v1/player/payload',
  142. display_id, data=urlencode_postdata({'courseId': course_name}),
  143. headers={'Referer': url})
  144. collection = course['modules']
  145. clip = None
  146. for module_ in collection:
  147. if name in (module_.get('moduleName'), module_.get('name')):
  148. for clip_ in module_.get('clips', []):
  149. clip_index = clip_.get('clipIndex')
  150. if clip_index is None:
  151. clip_index = clip_.get('index')
  152. if clip_index is None:
  153. continue
  154. if compat_str(clip_index) == clip_id:
  155. clip = clip_
  156. break
  157. if not clip:
  158. raise ExtractorError('Unable to resolve clip')
  159. title = clip['title']
  160. QUALITIES = {
  161. 'low': {'width': 640, 'height': 480},
  162. 'medium': {'width': 848, 'height': 640},
  163. 'high': {'width': 1024, 'height': 768},
  164. 'high-widescreen': {'width': 1280, 'height': 720},
  165. }
  166. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  167. quality_key = qualities(QUALITIES_PREFERENCE)
  168. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  169. ALLOWED_QUALITIES = (
  170. AllowedQuality('webm', ['high', ]),
  171. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  172. )
  173. # Some courses also offer widescreen resolution for high quality (see
  174. # https://github.com/rg3/youtube-dl/issues/7766)
  175. widescreen = course.get('supportsWideScreenVideoFormats') is True
  176. best_quality = 'high-widescreen' if widescreen else 'high'
  177. if widescreen:
  178. for allowed_quality in ALLOWED_QUALITIES:
  179. allowed_quality.qualities.append(best_quality)
  180. # In order to minimize the number of calls to ViewClip API and reduce
  181. # the probability of being throttled or banned by Pluralsight we will request
  182. # only single format until formats listing was explicitly requested.
  183. if self._downloader.params.get('listformats', False):
  184. allowed_qualities = ALLOWED_QUALITIES
  185. else:
  186. def guess_allowed_qualities():
  187. req_format = self._downloader.params.get('format') or 'best'
  188. req_format_split = req_format.split('-', 1)
  189. if len(req_format_split) > 1:
  190. req_ext, req_quality = req_format_split
  191. for allowed_quality in ALLOWED_QUALITIES:
  192. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  193. return (AllowedQuality(req_ext, (req_quality, )), )
  194. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  195. return (AllowedQuality(req_ext, (best_quality, )), )
  196. allowed_qualities = guess_allowed_qualities()
  197. formats = []
  198. for ext, qualities_ in allowed_qualities:
  199. for quality in qualities_:
  200. f = QUALITIES[quality].copy()
  201. clip_post = {
  202. 'author': author,
  203. 'includeCaptions': False,
  204. 'clipIndex': int(clip_id),
  205. 'courseName': course_name,
  206. 'locale': 'en',
  207. 'moduleName': name,
  208. 'mediaType': ext,
  209. 'quality': '%dx%d' % (f['width'], f['height']),
  210. }
  211. format_id = '%s-%s' % (ext, quality)
  212. viewclip = self._download_json(
  213. '%s/video/clips/viewclip' % self._API_BASE, display_id,
  214. 'Downloading %s viewclip JSON' % format_id, fatal=False,
  215. data=json.dumps(clip_post).encode('utf-8'),
  216. headers={'Content-Type': 'application/json;charset=utf-8'})
  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 viewclip:
  227. continue
  228. clip_urls = viewclip.get('urls')
  229. if not isinstance(clip_urls, list):
  230. continue
  231. for clip_url_data in clip_urls:
  232. clip_url = clip_url_data.get('url')
  233. if not clip_url:
  234. continue
  235. cdn = clip_url_data.get('cdn')
  236. clip_f = f.copy()
  237. clip_f.update({
  238. 'url': clip_url,
  239. 'ext': ext,
  240. 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
  241. 'quality': quality_key(quality),
  242. 'source_preference': int_or_none(clip_url_data.get('rank')),
  243. })
  244. formats.append(clip_f)
  245. self._sort_formats(formats)
  246. duration = int_or_none(
  247. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  248. # TODO: other languages?
  249. subtitles = self.extract_subtitles(
  250. author, clip_id, 'en', name, duration, display_id)
  251. return {
  252. 'id': clip.get('clipName') or clip['name'],
  253. 'title': title,
  254. 'duration': duration,
  255. 'creator': author,
  256. 'formats': formats,
  257. 'subtitles': subtitles,
  258. }
  259. class PluralsightCourseIE(PluralsightBaseIE):
  260. IE_NAME = 'pluralsight:course'
  261. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  262. _TESTS = [{
  263. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  264. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  265. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  266. 'info_dict': {
  267. 'id': 'hosting-sql-server-windows-azure-iaas',
  268. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  269. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  270. },
  271. 'playlist_count': 31,
  272. }, {
  273. # available without pluralsight account
  274. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  275. 'only_matching': True,
  276. }, {
  277. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  278. 'only_matching': True,
  279. }]
  280. def _real_extract(self, url):
  281. course_id = self._match_id(url)
  282. # TODO: PSM cookie
  283. course = self._download_json(
  284. '%s/player/functions/rpc' % self._API_BASE, course_id,
  285. 'Downloading course JSON',
  286. data=json.dumps({
  287. 'fn': 'bootstrapPlayer',
  288. 'payload': {
  289. 'courseId': course_id,
  290. }
  291. }).encode('utf-8'),
  292. headers={
  293. 'Content-Type': 'application/json;charset=utf-8'
  294. })['payload']['course']
  295. title = course['title']
  296. course_name = course['name']
  297. course_data = course['modules']
  298. description = course.get('description') or course.get('shortDescription')
  299. entries = []
  300. for num, module in enumerate(course_data, 1):
  301. author = module.get('author')
  302. module_name = module.get('name')
  303. if not author or not module_name:
  304. continue
  305. for clip in module.get('clips', []):
  306. clip_index = int_or_none(clip.get('index'))
  307. if clip_index is None:
  308. continue
  309. clip_url = update_url_query(
  310. '%s/player' % self._API_BASE, query={
  311. 'mode': 'live',
  312. 'course': course_name,
  313. 'author': author,
  314. 'name': module_name,
  315. 'clip': clip_index,
  316. })
  317. entries.append({
  318. '_type': 'url_transparent',
  319. 'url': clip_url,
  320. 'ie_key': PluralsightIE.ie_key(),
  321. 'chapter': module.get('title'),
  322. 'chapter_number': num,
  323. 'chapter_id': module.get('moduleRef'),
  324. })
  325. return self.playlist_result(entries, course_id, title, description)