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.

406 lines
16 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. 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_id, lang, name, duration, video_id):
  120. captions_post = {
  121. 'a': author,
  122. 'cn': clip_id,
  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_id = qs.get('clip', [None])[0]
  172. course_name = qs.get('course', [None])[0]
  173. if any(not f for f in (author, name, clip_id, course_name,)):
  174. raise ExtractorError('Invalid URL', expected=True)
  175. display_id = '%s-%s' % (name, clip_id)
  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_id:
  188. clip = clip_
  189. break
  190. if not clip:
  191. raise ExtractorError('Unable to resolve clip')
  192. title = clip['title']
  193. QUALITIES = {
  194. 'low': {'width': 640, 'height': 480},
  195. 'medium': {'width': 848, 'height': 640},
  196. 'high': {'width': 1024, 'height': 768},
  197. 'high-widescreen': {'width': 1280, 'height': 720},
  198. }
  199. QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
  200. quality_key = qualities(QUALITIES_PREFERENCE)
  201. AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
  202. ALLOWED_QUALITIES = (
  203. AllowedQuality('webm', ['high', ]),
  204. AllowedQuality('mp4', ['low', 'medium', 'high', ]),
  205. )
  206. # Some courses also offer widescreen resolution for high quality (see
  207. # https://github.com/rg3/youtube-dl/issues/7766)
  208. widescreen = course.get('supportsWideScreenVideoFormats') is True
  209. best_quality = 'high-widescreen' if widescreen else 'high'
  210. if widescreen:
  211. for allowed_quality in ALLOWED_QUALITIES:
  212. allowed_quality.qualities.append(best_quality)
  213. # In order to minimize the number of calls to ViewClip API and reduce
  214. # the probability of being throttled or banned by Pluralsight we will request
  215. # only single format until formats listing was explicitly requested.
  216. if self._downloader.params.get('listformats', False):
  217. allowed_qualities = ALLOWED_QUALITIES
  218. else:
  219. def guess_allowed_qualities():
  220. req_format = self._downloader.params.get('format') or 'best'
  221. req_format_split = req_format.split('-', 1)
  222. if len(req_format_split) > 1:
  223. req_ext, req_quality = req_format_split
  224. req_quality = '-'.join(req_quality.split('-')[:2])
  225. for allowed_quality in ALLOWED_QUALITIES:
  226. if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
  227. return (AllowedQuality(req_ext, (req_quality, )), )
  228. req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
  229. return (AllowedQuality(req_ext, (best_quality, )), )
  230. allowed_qualities = guess_allowed_qualities()
  231. formats = []
  232. for ext, qualities_ in allowed_qualities:
  233. for quality in qualities_:
  234. f = QUALITIES[quality].copy()
  235. clip_post = {
  236. 'author': author,
  237. 'includeCaptions': False,
  238. 'clipIndex': int(clip_id),
  239. 'courseName': course_name,
  240. 'locale': 'en',
  241. 'moduleName': name,
  242. 'mediaType': ext,
  243. 'quality': '%dx%d' % (f['width'], f['height']),
  244. }
  245. format_id = '%s-%s' % (ext, quality)
  246. viewclip = self._download_json(
  247. '%s/video/clips/viewclip' % self._API_BASE, display_id,
  248. 'Downloading %s viewclip JSON' % format_id, fatal=False,
  249. data=json.dumps(clip_post).encode('utf-8'),
  250. headers={'Content-Type': 'application/json;charset=utf-8'})
  251. # Pluralsight tracks multiple sequential calls to ViewClip API and start
  252. # to return 429 HTTP errors after some time (see
  253. # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
  254. # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
  255. # To somewhat reduce the probability of these consequences
  256. # we will sleep random amount of time before each call to ViewClip.
  257. self._sleep(
  258. random.randint(2, 5), display_id,
  259. '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
  260. if not viewclip:
  261. continue
  262. clip_urls = viewclip.get('urls')
  263. if not isinstance(clip_urls, list):
  264. continue
  265. for clip_url_data in clip_urls:
  266. clip_url = clip_url_data.get('url')
  267. if not clip_url:
  268. continue
  269. cdn = clip_url_data.get('cdn')
  270. clip_f = f.copy()
  271. clip_f.update({
  272. 'url': clip_url,
  273. 'ext': ext,
  274. 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
  275. 'quality': quality_key(quality),
  276. 'source_preference': int_or_none(clip_url_data.get('rank')),
  277. })
  278. formats.append(clip_f)
  279. self._sort_formats(formats)
  280. duration = int_or_none(
  281. clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
  282. # TODO: other languages?
  283. subtitles = self.extract_subtitles(
  284. author, clip_id, 'en', name, duration, display_id)
  285. return {
  286. 'id': clip.get('clipName') or clip['name'],
  287. 'title': title,
  288. 'duration': duration,
  289. 'creator': author,
  290. 'formats': formats,
  291. 'subtitles': subtitles,
  292. }
  293. class PluralsightCourseIE(PluralsightBaseIE):
  294. IE_NAME = 'pluralsight:course'
  295. _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
  296. _TESTS = [{
  297. # Free course from Pluralsight Starter Subscription for Microsoft TechNet
  298. # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
  299. 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
  300. 'info_dict': {
  301. 'id': 'hosting-sql-server-windows-azure-iaas',
  302. 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
  303. 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
  304. },
  305. 'playlist_count': 31,
  306. }, {
  307. # available without pluralsight account
  308. 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
  309. 'only_matching': True,
  310. }, {
  311. 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
  312. 'only_matching': True,
  313. }]
  314. def _real_extract(self, url):
  315. course_id = self._match_id(url)
  316. # TODO: PSM cookie
  317. course = self._download_course(course_id, url, course_id)
  318. title = course['title']
  319. course_name = course['name']
  320. course_data = course['modules']
  321. description = course.get('description') or course.get('shortDescription')
  322. entries = []
  323. for num, module in enumerate(course_data, 1):
  324. author = module.get('author')
  325. module_name = module.get('name')
  326. if not author or not module_name:
  327. continue
  328. for clip in module.get('clips', []):
  329. clip_index = int_or_none(clip.get('index'))
  330. if clip_index is None:
  331. continue
  332. clip_url = update_url_query(
  333. '%s/player' % self._API_BASE, query={
  334. 'mode': 'live',
  335. 'course': course_name,
  336. 'author': author,
  337. 'name': module_name,
  338. 'clip': clip_index,
  339. })
  340. entries.append({
  341. '_type': 'url_transparent',
  342. 'url': clip_url,
  343. 'ie_key': PluralsightIE.ie_key(),
  344. 'chapter': module.get('title'),
  345. 'chapter_number': num,
  346. 'chapter_id': module.get('moduleRef'),
  347. })
  348. return self.playlist_result(entries, course_id, title, description)