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.

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