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 _real_initialize(self
):
169 username
, password
= self
._get
_login
_info
()
173 login_page
= self
._download
_webpage
(
174 self
._LOGIN
_URL
, None, 'Downloading login page')
176 login_form
= self
._hidden
_inputs
(login_page
)
179 'Username': username
,
180 'Password': password
,
183 post_url
= self
._search
_regex
(
184 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', login_page,
185 'post url
', default=self._LOGIN_URL, group='url
')
187 if not post_url.startswith('http
'):
188 post_url = compat_urlparse.urljoin(self._LOGIN_URL, post_url)
190 response = self._download_webpage(
191 post_url, None, 'Logging
in',
192 data=urlencode_postdata(login_form),
193 headers={'Content-Type': 'application/x-www-form-urlencoded'})
195 error = self._search_regex(
196 r'<span
[^
>]+class="field-validation-error"[^
>]*>([^
<]+)</span
>',
197 response, 'error message
', default=None)
199 raise ExtractorError('Unable to login
: %s' % error, expected=True)
201 if all(not re.search(p, response) for p in (
202 r'__INITIAL_STATE__
', r'["\']currentUser["\']',
204 r'>\s
*Sign out\s
*<')):
205 BLOCKED = 'Your account has been blocked due to suspicious activity
'
206 if BLOCKED in response:
207 raise ExtractorError(
208 'Unable to login
: %s' % BLOCKED, expected=True)
209 MUST_AGREE = 'To
continue using Pluralsight
, you must agree to
'
210 if any(p in response for p in (MUST_AGREE, '>Disagree
<', '>Agree
<')):
211 raise ExtractorError(
212 'Unable to login
: %s some documents
. Go to pluralsight
.com
, '
213 'log
in and agree
with what Pluralsight requires
.'
214 % MUST_AGREE, expected=True)
216 raise ExtractorError('Unable to log
in')
218 def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
221 captions = self._download_json(
222 '%s/transcript
/api
/v1
/caption
/json
/%s/%s'
223 % (self._API_BASE, clip_id, lang), video_id,
224 'Downloading captions JSON
', 'Unable to download captions JSON
',
233 captions = self._download_json(
234 '%s/player
/retrieve
-captions
' % self._API_BASE, video_id,
235 'Downloading captions JSON
', 'Unable to download captions JSON
',
236 fatal=False, data=json.dumps(captions_post).encode('utf
-8'),
237 headers={'Content-Type': 'application/json;charset=utf-8'})
242 'data
': json.dumps(captions),
245 'data
': self._convert_subtitles(duration, captions),
250 def _convert_subtitles(duration, subs):
252 TIME_OFFSET_KEYS = ('displayTimeOffset
', 'DisplayTimeOffset
')
253 TEXT_KEYS = ('text
', 'Text
')
254 for num, current in enumerate(subs):
257 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
258 dict_get(current, TEXT_KEYS))
259 if start is None or text is None:
261 end = duration if num == len(subs) - 1 else float_or_none(
262 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
265 srt += os.linesep.join(
269 srt_subtitles_timecode(start),
270 srt_subtitles_timecode(end)),
276 def _real_extract(self, url):
279 author = qs.get('author
', [None])[0]
280 name = qs.get('name
', [None])[0]
281 clip_idx = qs.get('clip
', [None])[0]
282 course_name = qs.get('course
', [None])[0]
284 if any(not f for f in (author, name, clip_idx, course_name,)):
285 raise ExtractorError('Invalid URL
', expected=True)
287 display_id = '%s-%s' % (name, clip_idx)
289 course = self._download_course(course_name, url, display_id)
291 collection = course['modules
']
295 for module_ in collection:
296 if name in (module_.get('moduleName
'), module_.get('name
')):
297 for clip_ in module_.get('clips
', []):
298 clip_index = clip_.get('clipIndex
')
299 if clip_index is None:
300 clip_index = clip_.get('index
')
301 if clip_index is None:
303 if compat_str(clip_index) == clip_idx:
308 raise ExtractorError('Unable to resolve clip
')
310 title = clip['title
']
311 clip_id = clip.get('clipName
') or clip.get('name
') or clip['clipId
']
314 'low
': {'width': 640, 'height': 480},
315 'medium
': {'width': 848, 'height': 640},
316 'high
': {'width': 1024, 'height': 768},
317 'high
-widescreen
': {'width': 1280, 'height': 720},
320 QUALITIES_PREFERENCE = ('low
', 'medium
', 'high
', 'high
-widescreen
',)
321 quality_key = qualities(QUALITIES_PREFERENCE)
323 AllowedQuality = collections.namedtuple('AllowedQuality
', ['ext
', 'qualities
'])
325 ALLOWED_QUALITIES = (
326 AllowedQuality('webm
', ['high
', ]),
327 AllowedQuality('mp4
', ['low
', 'medium
', 'high
', ]),
330 # Some courses also offer widescreen resolution for high quality (see
331 # https://github.com/ytdl-org/youtube-dl/issues/7766)
332 widescreen = course.get('supportsWideScreenVideoFormats
') is True
333 best_quality = 'high
-widescreen
' if widescreen else 'high
'
335 for allowed_quality in ALLOWED_QUALITIES:
336 allowed_quality.qualities.append(best_quality)
338 # In order to minimize the number of calls to ViewClip API and reduce
339 # the probability of being throttled or banned by Pluralsight we will request
340 # only single format until formats listing was explicitly requested.
341 if self.get_param('listformats
', False):
342 allowed_qualities = ALLOWED_QUALITIES
344 def guess_allowed_qualities():
345 req_format = self.get_param('format
') or 'best
'
346 req_format_split = req_format.split('-', 1)
347 if len(req_format_split) > 1:
348 req_ext, req_quality = req_format_split
349 req_quality = '-'.join(req_quality.split('-')[:2])
350 for allowed_quality in ALLOWED_QUALITIES:
351 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
352 return (AllowedQuality(req_ext, (req_quality, )), )
353 req_ext = 'webm
' if self.get_param('prefer_free_formats
') else 'mp4
'
354 return (AllowedQuality(req_ext, (best_quality, )), )
355 allowed_qualities = guess_allowed_qualities()
358 for ext, qualities_ in allowed_qualities:
359 for quality in qualities_:
360 f = QUALITIES[quality].copy()
363 'includeCaptions
': 'false
',
364 'clipIndex
': int(clip_idx),
365 'courseName
': course_name,
369 'quality
': '%dx%d' % (f['width
'], f['height
']),
371 format_id = '%s-%s' % (ext, quality)
374 viewclip = self._download_json(
375 self._GRAPHQL_EP, display_id,
376 'Downloading
%s viewclip graphql
' % format_id,
378 'query
': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
381 headers=self._GRAPHQL_HEADERS)['data
']['viewClip
']
382 except ExtractorError:
383 # Still works but most likely will go soon
384 viewclip = self._download_json(
385 '%s/video
/clips
/viewclip
' % self._API_BASE, display_id,
386 'Downloading
%s viewclip JSON
' % format_id, fatal=False,
387 data=json.dumps(clip_post).encode('utf
-8'),
388 headers={'Content-Type': 'application/json;charset=utf-8'})
390 # Pluralsight tracks multiple sequential calls to ViewClip API and start
391 # to return 429 HTTP errors after some time (see
392 # https://github.com/ytdl-org/youtube-dl/pull/6989). Moreover it may even lead
393 # to account ban (see https://github.com/ytdl-org/youtube-dl/issues/6842).
394 # To somewhat reduce the probability of these consequences
395 # we will sleep random amount of time before each call to ViewClip.
397 random.randint(5, 10), display_id,
398 '%(video_id)s: Waiting
for %(timeout)s seconds to avoid throttling
')
403 clip_urls = viewclip.get('urls
')
404 if not isinstance(clip_urls, list):
407 for clip_url_data in clip_urls:
408 clip_url = clip_url_data.get('url
')
411 cdn = clip_url_data.get('cdn
')
416 'format_id
': '%s-%s' % (format_id, cdn) if cdn else format_id,
417 'quality
': quality_key(quality),
418 'source_preference
': int_or_none(clip_url_data.get('rank
')),
420 formats.append(clip_f)
422 self._sort_formats(formats)
424 duration = int_or_none(
425 clip.get('duration
')) or parse_duration(clip.get('formattedDuration
'))
427 # TODO: other languages?
428 subtitles = self.extract_subtitles(
429 author, clip_idx, clip.get('clipId
'), 'en
', name, duration, display_id)
434 'duration
': duration,
437 'subtitles
': subtitles,
441 class PluralsightCourseIE(PluralsightBaseIE):
442 IE_NAME = 'pluralsight
:course
'
443 _VALID_URL = r'https?
://(?
:(?
:www|app
)\
.)?pluralsight\
.com
/(?
:library
/)?courses
/(?P
<id>[^
/]+)'
445 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
446 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
447 'url
': 'http
://www
.pluralsight
.com
/courses
/hosting
-sql
-server
-windows
-azure
-iaas
',
449 'id': 'hosting
-sql
-server
-windows
-azure
-iaas
',
450 'title
': 'Hosting SQL Server
in Microsoft Azure IaaS Fundamentals
',
451 'description
': 'md5
:61b37e60f21c4b2f91dc621a977d0986
',
453 'playlist_count
': 31,
455 # available without pluralsight account
456 'url
': 'https
://www
.pluralsight
.com
/courses
/angularjs
-get
-started
',
457 'only_matching
': True,
459 'url
': 'https
://app
.pluralsight
.com
/library
/courses
/understanding
-microsoft
-azure
-amazon
-aws
/table
-of
-contents
',
460 'only_matching
': True,
463 def _real_extract(self, url):
464 course_id = self._match_id(url)
468 course = self._download_course(course_id, url, course_id)
470 title = course['title
']
471 course_name = course['name
']
472 course_data = course['modules
']
473 description = course.get('description
') or course.get('shortDescription
')
476 for num, module in enumerate(course_data, 1):
477 author = module.get('author
')
478 module_name = module.get('name
')
479 if not author or not module_name:
481 for clip in module.get('clips
', []):
482 clip_index = int_or_none(clip.get('index
'))
483 if clip_index is None:
485 clip_url = update_url_query(
486 '%s/player
' % self._API_BASE, query={
488 'course
': course_name,
494 '_type
': 'url_transparent
',
496 'ie_key
': PluralsightIE.ie_key(),
497 'chapter
': module.get('title
'),
498 'chapter_number
': num,
499 'chapter_id
': module.get('moduleRef
'),
502 return self.playlist_result(entries, course_id, title, description)