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.

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