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.

501 lines
18 KiB

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