1 from __future__ import unicode_literals
8 from .common import InfoExtractor
19 srt_subtitles_timecode,
24 class PluralsightBaseIE(InfoExtractor):
25 _API_BASE = 'https://app.pluralsight.com'
28 class PluralsightIE(PluralsightBaseIE):
29 IE_NAME = 'pluralsight'
30 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
31 _LOGIN_URL = 'https://app.pluralsight.com/id/'
33 _NETRC_MACHINE = 'pluralsight'
36 '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',
37 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
39 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
41 'title': 'Management of SQL Server - Demo Monitoring',
44 'skip': 'Requires pluralsight account credentials',
46 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
47 'only_matching': True,
49 # available without pluralsight account
50 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
51 'only_matching': True,
53 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
54 'only_matching': True,
57 def _real_initialize(self):
61 (username, password) = self._get_login_info()
65 login_page = self._download_webpage(
66 self._LOGIN_URL, None, 'Downloading login page')
68 login_form = self._hidden_inputs(login_page)
75 post_url = self._search_regex(
76 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
77 'post url', default=self._LOGIN_URL, group='url')
79 if not post_url.startswith('http'):
80 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
82 response = self._download_webpage(
83 post_url, None, 'Logging in as %s' % username,
84 data=urlencode_postdata(login_form),
85 headers={'Content-Type': 'application/x-www-form-urlencoded'})
87 error = self._search_regex(
88 r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
89 response, 'error message', default=None)
91 raise ExtractorError('Unable to login: %s' % error, expected=True)
93 if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
94 raise ExtractorError('Unable to log in')
96 def _get_subtitles(self, author, clip_id, lang, name, duration, video_id):
103 captions = self._download_json(
104 '%s/player/retrieve-captions' % self._API_BASE, video_id,
105 'Downloading captions JSON', 'Unable to download captions JSON',
106 fatal=False, data=json.dumps(captions_post).encode('utf-8'),
107 headers={'Content-Type': 'application/json;charset=utf-8'})
112 'data': json.dumps(captions),
115 'data': self._convert_subtitles(duration, captions),
120 def _convert_subtitles(duration, subs):
122 for num, current in enumerate(subs):
124 start, text = float_or_none(
125 current.get('DisplayTimeOffset')), current.get('Text')
126 if start is None or text is None:
128 end = duration if num == len(subs) - 1 else float_or_none(
129 subs[num + 1].get('DisplayTimeOffset'))
132 srt += os.linesep.join(
136 srt_subtitles_timecode(start),
137 srt_subtitles_timecode(end)),
143 def _real_extract(self, url):
144 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
146 author = qs.get('author', [None])[0]
147 name = qs.get('name', [None])[0]
148 clip_id = qs.get('clip', [None])[0]
149 course_name = qs.get('course', [None])[0]
151 if any(not f for f in (author, name, clip_id, course_name,)):
152 raise ExtractorError('Invalid URL', expected=True)
154 display_id = '%s-%s' % (name, clip_id)
156 parsed_url = compat_urlparse.urlparse(url)
158 payload_url = compat_urlparse.urlunparse(parsed_url._replace(
159 netloc='app.pluralsight.com', path='player/api/v1/payload'))
161 course = self._download_json(
162 payload_url, display_id, headers={'Referer': url})['payload']['course']
164 collection = course['modules']
166 module, clip = None, None
168 for module_ in collection:
169 if name in (module_.get('moduleName'), module_.get('name')):
171 for clip_ in module_.get('clips', []):
172 clip_index = clip_.get('clipIndex')
173 if clip_index is None:
174 clip_index = clip_.get('index')
175 if clip_index is None:
177 if compat_str(clip_index) == clip_id:
182 raise ExtractorError('Unable to resolve clip')
184 title = '%s - %s' % (module['title'], clip['title'])
187 'low': {'width': 640, 'height': 480},
188 'medium': {'width': 848, 'height': 640},
189 'high': {'width': 1024, 'height': 768},
190 'high-widescreen': {'width': 1280, 'height': 720},
193 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
194 quality_key = qualities(QUALITIES_PREFERENCE)
196 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
198 ALLOWED_QUALITIES = (
199 AllowedQuality('webm', ['high', ]),
200 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
203 # Some courses also offer widescreen resolution for high quality (see
204 # https://github.com/rg3/youtube-dl/issues/7766)
205 widescreen = course.get('supportsWideScreenVideoFormats') is True
206 best_quality = 'high-widescreen' if widescreen else 'high'
208 for allowed_quality in ALLOWED_QUALITIES:
209 allowed_quality.qualities.append(best_quality)
211 # In order to minimize the number of calls to ViewClip API and reduce
212 # the probability of being throttled or banned by Pluralsight we will request
213 # only single format until formats listing was explicitly requested.
214 if self._downloader.params.get('listformats', False):
215 allowed_qualities = ALLOWED_QUALITIES
217 def guess_allowed_qualities():
218 req_format = self._downloader.params.get('format') or 'best'
219 req_format_split = req_format.split('-', 1)
220 if len(req_format_split) > 1:
221 req_ext, req_quality = req_format_split
222 for allowed_quality in ALLOWED_QUALITIES:
223 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
224 return (AllowedQuality(req_ext, (req_quality, )), )
225 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
226 return (AllowedQuality(req_ext, (best_quality, )), )
227 allowed_qualities = guess_allowed_qualities()
230 for ext, qualities_ in allowed_qualities:
231 for quality in qualities_:
232 f = QUALITIES[quality].copy()
235 'includeCaptions': False,
236 'clipIndex': int(clip_id),
237 'courseName': course_name,
241 'quality': '%dx%d' % (f['width'], f['height']),
243 format_id = '%s-%s' % (ext, quality)
244 viewclip = self._download_json(
245 '%s/video/clips/viewclip' % self._API_BASE, display_id,
246 'Downloading %s viewclip JSON' % format_id, fatal=False,
247 data=json.dumps(clip_post).encode('utf-8'),
248 headers={'Content-Type': 'application/json;charset=utf-8'})
250 # Pluralsight tracks multiple sequential calls to ViewClip API and start
251 # to return 429 HTTP errors after some time (see
252 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
253 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
254 # To somewhat reduce the probability of these consequences
255 # we will sleep random amount of time before each call to ViewClip.
257 random.randint(2, 5), display_id,
258 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
263 clip_urls = viewclip.get('urls')
264 if not isinstance(clip_urls, list):
267 for clip_url_data in clip_urls:
268 clip_url = clip_url_data.get('url')
271 cdn = clip_url_data.get('cdn')
276 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
277 'quality': quality_key(quality),
278 'source_preference': int_or_none(clip_url_data.get('rank')),
280 formats.append(clip_f)
282 self._sort_formats(formats)
284 duration = int_or_none(
285 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
287 # TODO: other languages?
288 subtitles = self.extract_subtitles(
289 author, clip_id, 'en', name, duration, display_id)
292 'id': clip.get('clipName') or clip['name'],
294 'duration': duration,
297 'subtitles': subtitles,
301 class PluralsightCourseIE(PluralsightBaseIE):
302 IE_NAME = 'pluralsight:course'
303 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
305 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
306 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
307 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
309 'id': 'hosting-sql-server-windows-azure-iaas',
310 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
311 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
313 'playlist_count': 31,
315 # available without pluralsight account
316 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
317 'only_matching': True,
319 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
320 'only_matching': True,
323 def _real_extract(self, url):
324 course_id = self._match_id(url)
328 course = self._download_json(
329 '%s/data/course/%s' % (self._API_BASE, course_id),
330 course_id, 'Downloading course JSON')
332 title = course['title']
333 description = course.get('description') or course.get('shortDescription')
335 course_data = self._download_json(
336 '%s/data/course/content/%s' % (self._API_BASE, course_id),
337 course_id, 'Downloading course data JSON')
340 for num, module in enumerate(course_data, 1):
341 for clip in module.get('clips', []):
342 player_parameters = clip.get('playerParameters')
343 if not player_parameters:
346 '_type': 'url_transparent',
347 'url': '%s/training/player?%s' % (self._API_BASE, player_parameters),
348 'ie_key': PluralsightIE.ie_key(),
349 'chapter': module.get('title'),
350 'chapter_number': num,
351 'chapter_id': module.get('moduleRef'),
354 return self.playlist_result(entries, course_id, title, description)