1 from __future__ import unicode_literals
8 from .common import InfoExtractor
20 srt_subtitles_timecode,
27 class PluralsightBaseIE(InfoExtractor):
28 _API_BASE = 'https://app.pluralsight.com'
30 _GRAPHQL_EP = '%s/player/api/graphql' % _API_BASE
32 'Content-Type': 'application/json;charset=UTF-8',
34 _GRAPHQL_COURSE_TMPL = '''
35 query BootstrapPlayer {
48 course(courseId: "%s") {
52 translationLanguages {
56 supportsWideScreenVideoFormats
84 def _download_course(self, course_id, url, display_id):
86 return self._download_course_rpc(course_id, url, display_id)
87 except ExtractorError:
89 return self._download_json(
90 'https://app.pluralsight.com/player/user/api/v1/player/payload',
91 display_id, data=urlencode_postdata({'courseId': course_id}),
92 headers={'Referer': url})
94 def _download_course_rpc(self, course_id, url, display_id):
95 response = self._download_json(
96 self._GRAPHQL_EP, display_id, data=json.dumps({
97 'query': self._GRAPHQL_COURSE_TMPL % course_id,
99 }).encode('utf-8'), headers=self._GRAPHQL_HEADERS)
102 response, lambda x: x['data']['rpc']['bootstrapPlayer']['course'],
107 raise ExtractorError(
108 '%s said: %s' % (self.IE_NAME, response['error']['message']),
112 class PluralsightIE(PluralsightBaseIE):
113 IE_NAME = 'pluralsight'
114 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
115 _LOGIN_URL = 'https://app.pluralsight.com/id/'
117 _NETRC_MACHINE = 'pluralsight'
120 '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',
121 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
123 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
125 'title': 'Demo Monitoring',
128 'skip': 'Requires pluralsight account credentials',
130 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
131 'only_matching': True,
133 # available without pluralsight account
134 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
135 'only_matching': True,
137 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
138 'only_matching': True,
141 GRAPHQL_VIEWCLIP_TMPL = '''
144 author: "%(author)s",
145 clipIndex: %(clipIndex)d,
146 courseName: "%(courseName)s",
147 includeCaptions: %(includeCaptions)s,
148 locale: "%(locale)s",
149 mediaType: "%(mediaType)s",
150 moduleName: "%(moduleName)s",
151 quality: "%(quality)s"
163 def _real_initialize(self):
167 username, password = self._get_login_info()
171 login_page = self._download_webpage(
172 self._LOGIN_URL, None, 'Downloading login page')
174 login_form = self._hidden_inputs(login_page)
177 'Username': username,
178 'Password': password,
181 post_url = self._search_regex(
182 r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
183 'post url', default=self._LOGIN_URL, group='url')
185 if not post_url.startswith('http'):
186 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
188 response = self._download_webpage(
189 post_url, None, 'Logging in',
190 data=urlencode_postdata(login_form),
191 headers={'Content-Type': 'application/x-www-form-urlencoded'})
193 error = self._search_regex(
194 r'<span[^>]+class="field-validation-error"[^>]*>([^<]+)</span>',
195 response, 'error message', default=None)
197 raise ExtractorError('Unable to login: %s' % error, expected=True)
199 if all(p not in response for p in ('__INITIAL_STATE__', '"currentUser"')):
200 BLOCKED = 'Your account has been blocked due to suspicious activity'
201 if BLOCKED in response:
202 raise ExtractorError(
203 'Unable to login: %s' % BLOCKED, expected=True)
204 MUST_AGREE = 'To continue using Pluralsight, you must agree to'
205 if any(p in response for p in (MUST_AGREE, '>Disagree<', '>Agree<')):
206 raise ExtractorError(
207 'Unable to login: %s some documents. Go to pluralsight.com, '
208 'log in and agree with what Pluralsight requires.'
209 % MUST_AGREE, expected=True)
211 raise ExtractorError('Unable to log in')
213 def _get_subtitles(self, author, clip_idx, lang, name, duration, video_id):
220 captions = self._download_json(
221 '%s/player/retrieve-captions' % self._API_BASE, video_id,
222 'Downloading captions JSON', 'Unable to download captions JSON',
223 fatal=False, data=json.dumps(captions_post).encode('utf-8'),
224 headers={'Content-Type': 'application/json;charset=utf-8'})
229 'data': json.dumps(captions),
232 'data': self._convert_subtitles(duration, captions),
237 def _convert_subtitles(duration, subs):
239 TIME_OFFSET_KEYS = ('displayTimeOffset', 'DisplayTimeOffset')
240 TEXT_KEYS = ('text', 'Text')
241 for num, current in enumerate(subs):
244 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
245 dict_get(current, TEXT_KEYS))
246 if start is None or text is None:
248 end = duration if num == len(subs) - 1 else float_or_none(
249 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
252 srt += os.linesep.join(
256 srt_subtitles_timecode(start),
257 srt_subtitles_timecode(end)),
263 def _real_extract(self, url):
264 qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
266 author = qs.get('author', [None])[0]
267 name = qs.get('name', [None])[0]
268 clip_idx = qs.get('clip', [None])[0]
269 course_name = qs.get('course', [None])[0]
271 if any(not f for f in (author, name, clip_idx, course_name,)):
272 raise ExtractorError('Invalid URL', expected=True)
274 display_id = '%s-%s' % (name, clip_idx)
276 course = self._download_course(course_name, url, display_id)
278 collection = course['modules']
282 for module_ in collection:
283 if name in (module_.get('moduleName'), module_.get('name')):
284 for clip_ in module_.get('clips', []):
285 clip_index = clip_.get('clipIndex')
286 if clip_index is None:
287 clip_index = clip_.get('index')
288 if clip_index is None:
290 if compat_str(clip_index) == clip_idx:
295 raise ExtractorError('Unable to resolve clip')
297 title = clip['title']
298 clip_id = clip.get('clipName') or clip.get('name') or clip['clipId']
301 'low': {'width': 640, 'height': 480},
302 'medium': {'width': 848, 'height': 640},
303 'high': {'width': 1024, 'height': 768},
304 'high-widescreen': {'width': 1280, 'height': 720},
307 QUALITIES_PREFERENCE = ('low', 'medium', 'high', 'high-widescreen',)
308 quality_key = qualities(QUALITIES_PREFERENCE)
310 AllowedQuality = collections.namedtuple('AllowedQuality', ['ext', 'qualities'])
312 ALLOWED_QUALITIES = (
313 AllowedQuality('webm', ['high', ]),
314 AllowedQuality('mp4', ['low', 'medium', 'high', ]),
317 # Some courses also offer widescreen resolution for high quality (see
318 # https://github.com/rg3/youtube-dl/issues/7766)
319 widescreen = course.get('supportsWideScreenVideoFormats') is True
320 best_quality = 'high-widescreen' if widescreen else 'high'
322 for allowed_quality in ALLOWED_QUALITIES:
323 allowed_quality.qualities.append(best_quality)
325 # In order to minimize the number of calls to ViewClip API and reduce
326 # the probability of being throttled or banned by Pluralsight we will request
327 # only single format until formats listing was explicitly requested.
328 if self._downloader.params.get('listformats', False):
329 allowed_qualities = ALLOWED_QUALITIES
331 def guess_allowed_qualities():
332 req_format = self._downloader.params.get('format') or 'best'
333 req_format_split = req_format.split('-', 1)
334 if len(req_format_split) > 1:
335 req_ext, req_quality = req_format_split
336 req_quality = '-'.join(req_quality.split('-')[:2])
337 for allowed_quality in ALLOWED_QUALITIES:
338 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
339 return (AllowedQuality(req_ext, (req_quality, )), )
340 req_ext = 'webm' if self._downloader.params.get('prefer_free_formats') else 'mp4'
341 return (AllowedQuality(req_ext, (best_quality, )), )
342 allowed_qualities = guess_allowed_qualities()
345 for ext, qualities_ in allowed_qualities:
346 for quality in qualities_:
347 f = QUALITIES[quality].copy()
350 'includeCaptions': 'false',
351 'clipIndex': int(clip_idx),
352 'courseName': course_name,
356 'quality': '%dx%d' % (f['width'], f['height']),
358 format_id = '%s-%s' % (ext, quality)
361 viewclip = self._download_json(
362 self._GRAPHQL_EP, display_id,
363 'Downloading %s viewclip graphql' % format_id,
365 'query': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
368 headers=self._GRAPHQL_HEADERS)['data']['viewClip']
369 except ExtractorError:
370 # Still works but most likely will go soon
371 viewclip = self._download_json(
372 '%s/video/clips/viewclip' % self._API_BASE, display_id,
373 'Downloading %s viewclip JSON' % format_id, fatal=False,
374 data=json.dumps(clip_post).encode('utf-8'),
375 headers={'Content-Type': 'application/json;charset=utf-8'})
377 # Pluralsight tracks multiple sequential calls to ViewClip API and start
378 # to return 429 HTTP errors after some time (see
379 # https://github.com/rg3/youtube-dl/pull/6989). Moreover it may even lead
380 # to account ban (see https://github.com/rg3/youtube-dl/issues/6842).
381 # To somewhat reduce the probability of these consequences
382 # we will sleep random amount of time before each call to ViewClip.
384 random.randint(2, 5), display_id,
385 '%(video_id)s: Waiting for %(timeout)s seconds to avoid throttling')
390 clip_urls = viewclip.get('urls')
391 if not isinstance(clip_urls, list):
394 for clip_url_data in clip_urls:
395 clip_url = clip_url_data.get('url')
398 cdn = clip_url_data.get('cdn')
403 'format_id': '%s-%s' % (format_id, cdn) if cdn else format_id,
404 'quality': quality_key(quality),
405 'source_preference': int_or_none(clip_url_data.get('rank')),
407 formats.append(clip_f)
409 self._sort_formats(formats)
411 duration = int_or_none(
412 clip.get('duration')) or parse_duration(clip.get('formattedDuration'))
414 # TODO: other languages?
415 subtitles = self.extract_subtitles(
416 author, clip_idx, 'en', name, duration, display_id)
421 'duration': duration,
424 'subtitles': subtitles,
428 class PluralsightCourseIE(PluralsightBaseIE):
429 IE_NAME = 'pluralsight:course'
430 _VALID_URL = r'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:library/)?courses/(?P<id>[^/]+)'
432 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
433 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
434 'url': 'http://www.pluralsight.com/courses/hosting-sql-server-windows-azure-iaas',
436 'id': 'hosting-sql-server-windows-azure-iaas',
437 'title': 'Hosting SQL Server in Microsoft Azure IaaS Fundamentals',
438 'description': 'md5:61b37e60f21c4b2f91dc621a977d0986',
440 'playlist_count': 31,
442 # available without pluralsight account
443 'url': 'https://www.pluralsight.com/courses/angularjs-get-started',
444 'only_matching': True,
446 'url': 'https://app.pluralsight.com/library/courses/understanding-microsoft-azure-amazon-aws/table-of-contents',
447 'only_matching': True,
450 def _real_extract(self, url):
451 course_id = self._match_id(url)
455 course = self._download_course(course_id, url, course_id)
457 title = course['title']
458 course_name = course['name']
459 course_data = course['modules']
460 description = course.get('description') or course.get('shortDescription')
463 for num, module in enumerate(course_data, 1):
464 author = module.get('author')
465 module_name = module.get('name')
466 if not author or not module_name:
468 for clip in module.get('clips', []):
469 clip_index = int_or_none(clip.get('index'))
470 if clip_index is None:
472 clip_url = update_url_query(
473 '%s/player' % self._API_BASE, query={
475 'course': course_name,
481 '_type': 'url_transparent',
483 'ie_key': PluralsightIE.ie_key(),
484 'chapter': module.get('title'),
485 'chapter_number': num,
486 'chapter_id': module.get('moduleRef'),
489 return self.playlist_result(entries, course_id, title, description)