1 from __future__
import unicode_literals
9 from .common
import InfoExtractor
10 from ..compat
import (
22 srt_subtitles_timecode
,
29 class PluralsightBaseIE(InfoExtractor
):
30 _API_BASE
= 'https://app.pluralsight.com'
32 _GRAPHQL_EP
= '%s/player/api/graphql' % _API_BASE
34 'Content-Type': 'application/json;charset=UTF-8',
36 _GRAPHQL_COURSE_TMPL
= '''
37 query BootstrapPlayer {
50 course(courseId: "%s") {
54 translationLanguages {
58 supportsWideScreenVideoFormats
86 def _download_course(self
, course_id
, url
, display_id
):
88 return self
._download
_course
_rpc
(course_id
, url
, display_id
)
89 except ExtractorError
:
91 return self
._download
_json
(
92 'https://app.pluralsight.com/player/user/api/v1/player/payload',
93 display_id
, data
=urlencode_postdata({'courseId': course_id}
),
94 headers
={'Referer': url}
)
96 def _download_course_rpc(self
, course_id
, url
, display_id
):
97 response
= self
._download
_json
(
98 self
._GRAPHQL
_EP
, display_id
, data
=json
.dumps({
99 'query': self
._GRAPHQL
_COURSE
_TMPL
% course_id
,
101 }).encode('utf-8'), headers
=self
._GRAPHQL
_HEADERS
)
104 response
, lambda x
: x
['data']['rpc']['bootstrapPlayer']['course'],
109 raise ExtractorError(
110 '%s said: %s' % (self
.IE_NAME
, response
['error']['message']),
114 class PluralsightIE(PluralsightBaseIE
):
115 IE_NAME
= 'pluralsight'
116 _VALID_URL
= r
'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
117 _LOGIN_URL
= 'https://app.pluralsight.com/id/'
119 _NETRC_MACHINE
= 'pluralsight'
122 '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',
123 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
125 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
127 'title': 'Demo Monitoring',
130 'skip': 'Requires pluralsight account credentials',
132 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
133 'only_matching': True,
135 # available without pluralsight account
136 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
137 'only_matching': True,
139 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
140 'only_matching': True,
143 GRAPHQL_VIEWCLIP_TMPL
= '''
146 author: "%(author)s",
147 clipIndex: %(clipIndex)d,
148 courseName: "%(courseName)s",
149 includeCaptions: %(includeCaptions)s,
150 locale: "%(locale)s",
151 mediaType: "%(mediaType)s",
152 moduleName: "%(moduleName)s",
153 quality: "%(quality)s"
165 def _perform_login(self
, username
, password
):
166 login_page
= self
._download
_webpage
(
167 self
._LOGIN
_URL
, None, 'Downloading login page')
169 login_form
= self
._hidden
_inputs
(login_page
)
172 'Username': username
,
173 'Password': password
,
176 post_url
= self
._search
_regex
(
177 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', login_page,
178 'post url
', default=self._LOGIN_URL, group='url
')
180 if not post_url.startswith('http
'):
181 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
183 response = self._download_webpage(
184 post_url, None, 'Logging
in',
185 data=urlencode_postdata(login_form),
186 headers={'Content-Type': 'application/x-www-form-urlencoded'})
188 error = self._search_regex(
189 r'<span
[^
>]+class="field-validation-error"[^
>]*>([^
<]+)</span
>',
190 response, 'error message
', default=None)
192 raise ExtractorError('Unable to login
: %s' % error, expected=True)
194 if all(not re.search(p, response) for p in (
195 r'__INITIAL_STATE__
', r'["\']currentUser["\']',
197 r'>\s
*Sign out\s
*<')):
198 BLOCKED = 'Your account has been blocked due to suspicious activity
'
199 if BLOCKED in response:
200 raise ExtractorError(
201 'Unable to login
: %s' % BLOCKED, expected=True)
202 MUST_AGREE = 'To
continue using Pluralsight
, you must agree to
'
203 if any(p in response for p in (MUST_AGREE, '>Disagree
<', '>Agree
<')):
204 raise ExtractorError(
205 'Unable to login
: %s some documents
. Go to pluralsight
.com
, '
206 'log
in and agree
with what Pluralsight requires
.'
207 % MUST_AGREE, expected=True)
209 raise ExtractorError('Unable to log
in')
211 def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
214 captions = self._download_json(
215 '%s/transcript
/api
/v1
/caption
/json
/%s/%s'
216 % (self._API_BASE, clip_id, lang), video_id,
217 'Downloading captions JSON
', 'Unable to download captions JSON
',
226 captions = self._download_json(
227 '%s/player
/retrieve
-captions
' % self._API_BASE, video_id,
228 'Downloading captions JSON
', 'Unable to download captions JSON
',
229 fatal=False, data=json.dumps(captions_post).encode('utf
-8'),
230 headers={'Content-Type': 'application/json;charset=utf-8'})
235 'data
': json.dumps(captions),
238 'data
': self._convert_subtitles(duration, captions),
243 def _convert_subtitles(duration, subs):
245 TIME_OFFSET_KEYS = ('displayTimeOffset
', 'DisplayTimeOffset
')
246 TEXT_KEYS = ('text
', 'Text
')
247 for num, current in enumerate(subs):
250 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
251 dict_get(current, TEXT_KEYS))
252 if start is None or text is None:
254 end = duration if num == len(subs) - 1 else float_or_none(
255 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
258 srt += os.linesep.join(
262 srt_subtitles_timecode(start),
263 srt_subtitles_timecode(end)),
269 def _real_extract(self, url):
272 author = qs.get('author
', [None])[0]
273 name = qs.get('name
', [None])[0]
274 clip_idx = qs.get('clip
', [None])[0]
275 course_name = qs.get('course
', [None])[0]
277 if any(not f for f in (author, name, clip_idx, course_name,)):
278 raise ExtractorError('Invalid URL
', expected=True)
280 display_id = '%s-%s' % (name, clip_idx)
282 course = self._download_course(course_name, url, display_id)
284 collection = course['modules
']
288 for module_ in collection:
289 if name in (module_.get('moduleName
'), module_.get('name
')):
290 for clip_ in module_.get('clips
', []):
291 clip_index = clip_.get('clipIndex
')
292 if clip_index is None:
293 clip_index = clip_.get('index
')
294 if clip_index is None:
296 if compat_str(clip_index) == clip_idx:
301 raise ExtractorError('Unable to resolve clip
')
303 title = clip['title
']
304 clip_id = clip.get('clipName
') or clip.get('name
') or clip['clipId
']
307 'low
': {'width': 640, 'height': 480},
308 'medium
': {'width': 848, 'height': 640},
309 'high
': {'width': 1024, 'height': 768},
310 'high
-widescreen
': {'width': 1280, 'height': 720},
313 QUALITIES_PREFERENCE = ('low
', 'medium
', 'high
', 'high
-widescreen
',)
314 quality_key = qualities(QUALITIES_PREFERENCE)
316 AllowedQuality = collections.namedtuple('AllowedQuality
', ['ext
', 'qualities
'])
318 ALLOWED_QUALITIES = (
319 AllowedQuality('webm
', ['high
', ]),
320 AllowedQuality('mp4
', ['low
', 'medium
', 'high
', ]),
323 # Some courses also offer widescreen resolution for high quality (see
324 # https://github.com/ytdl-org/youtube-dl/issues/7766)
325 widescreen = course.get('supportsWideScreenVideoFormats
') is True
326 best_quality = 'high
-widescreen
' if widescreen else 'high
'
328 for allowed_quality in ALLOWED_QUALITIES:
329 allowed_quality.qualities.append(best_quality)
331 # In order to minimize the number of calls to ViewClip API and reduce
332 # the probability of being throttled or banned by Pluralsight we will request
333 # only single format until formats listing was explicitly requested.
334 if self.get_param('listformats
', False):
335 allowed_qualities = ALLOWED_QUALITIES
337 def guess_allowed_qualities():
338 req_format = self.get_param('format
') or 'best
'
339 req_format_split = req_format.split('-', 1)
340 if len(req_format_split) > 1:
341 req_ext, req_quality = req_format_split
342 req_quality = '-'.join(req_quality.split('-')[:2])
343 for allowed_quality in ALLOWED_QUALITIES:
344 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
345 return (AllowedQuality(req_ext, (req_quality, )), )
346 req_ext = 'webm
' if self.get_param('prefer_free_formats
') else 'mp4
'
347 return (AllowedQuality(req_ext, (best_quality, )), )
348 allowed_qualities = guess_allowed_qualities()
351 for ext, qualities_ in allowed_qualities:
352 for quality in qualities_:
353 f = QUALITIES[quality].copy()
356 'includeCaptions
': 'false
',
357 'clipIndex
': int(clip_idx),
358 'courseName
': course_name,
362 'quality
': '%dx%d' % (f['width
'], f['height
']),
364 format_id = '%s-%s' % (ext, quality)
367 viewclip = self._download_json(
368 self._GRAPHQL_EP, display_id,
369 'Downloading
%s viewclip graphql
' % format_id,
371 'query
': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
374 headers=self._GRAPHQL_HEADERS)['data
']['viewClip
']
375 except ExtractorError:
376 # Still works but most likely will go soon
377 viewclip = self._download_json(
378 '%s/video
/clips
/viewclip
' % self._API_BASE, display_id,
379 'Downloading
%s viewclip JSON
' % format_id, fatal=False,
380 data=json.dumps(clip_post).encode('utf
-8'),
381 headers={'Content-Type': 'application/json;charset=utf-8'})
383 # Pluralsight tracks multiple sequential calls to ViewClip API and start
384 # to return 429 HTTP errors after some time (see
385 # https://github.com/ytdl-org/youtube-dl/pull/6989). Moreover it may even lead
386 # to account ban (see https://github.com/ytdl-org/youtube-dl/issues/6842).
387 # To somewhat reduce the probability of these consequences
388 # we will sleep random amount of time before each call to ViewClip.
390 random.randint(5, 10), display_id,
391 '%(video_id)s: Waiting
for %(timeout)s seconds to avoid throttling
')
396 clip_urls = viewclip.get('urls
')
397 if not isinstance(clip_urls, list):
400 for clip_url_data in clip_urls:
401 clip_url = clip_url_data.get('url
')
404 cdn = clip_url_data.get('cdn
')
409 'format_id
': '%s-%s' % (format_id, cdn) if cdn else format_id,
410 'quality
': quality_key(quality),
411 'source_preference
': int_or_none(clip_url_data.get('rank
')),
413 formats.append(clip_f)
415 self._sort_formats(formats)
417 duration = int_or_none(
418 clip.get('duration
')) or parse_duration(clip.get('formattedDuration
'))
420 # TODO: other languages?
421 subtitles = self.extract_subtitles(
422 author, clip_idx, clip.get('clipId
'), 'en
', name, duration, display_id)
427 'duration
': duration,
430 'subtitles
': subtitles,
434 class PluralsightCourseIE(PluralsightBaseIE):
435 IE_NAME = 'pluralsight
:course
'
436 _VALID_URL = r'https?
://(?
:(?
:www|app
)\
.)?pluralsight\
.com
/(?
:library
/)?courses
/(?P
<id>[^
/]+)'
438 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
439 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
440 'url
': 'http
://www
.pluralsight
.com
/courses
/hosting
-sql
-server
-windows
-azure
-iaas
',
442 'id': 'hosting
-sql
-server
-windows
-azure
-iaas
',
443 'title
': 'Hosting SQL Server
in Microsoft Azure IaaS Fundamentals
',
444 'description
': 'md5
:61b37e60f21c4b2f91dc621a977d0986
',
446 'playlist_count
': 31,
448 # available without pluralsight account
449 'url
': 'https
://www
.pluralsight
.com
/courses
/angularjs
-get
-started
',
450 'only_matching
': True,
452 'url
': 'https
://app
.pluralsight
.com
/library
/courses
/understanding
-microsoft
-azure
-amazon
-aws
/table
-of
-contents
',
453 'only_matching
': True,
456 def _real_extract(self, url):
457 course_id = self._match_id(url)
461 course = self._download_course(course_id, url, course_id)
463 title = course['title
']
464 course_name = course['name
']
465 course_data = course['modules
']
466 description = course.get('description
') or course.get('shortDescription
')
469 for num, module in enumerate(course_data, 1):
470 author = module.get('author
')
471 module_name = module.get('name
')
472 if not author or not module_name:
474 for clip in module.get('clips
', []):
475 clip_index = int_or_none(clip.get('index
'))
476 if clip_index is None:
478 clip_url = update_url_query(
479 '%s/player
' % self._API_BASE, query={
481 'course
': course_name,
487 '_type
': 'url_transparent
',
489 'ie_key
': PluralsightIE.ie_key(),
490 'chapter
': module.get('title
'),
491 'chapter_number
': num,
492 'chapter_id
': module.get('moduleRef
'),
495 return self.playlist_result(entries, course_id, title, description)