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.

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