pluralsight.py 16 KB

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