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.

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