8 from .common
import InfoExtractor
17 srt_subtitles_timecode
,
24 class PluralsightBaseIE(InfoExtractor
):
25 _API_BASE
= 'https://app.pluralsight.com'
27 _GRAPHQL_EP
= f
'{_API_BASE}/player/api/graphql'
29 'Content-Type': 'application/json;charset=UTF-8',
31 _GRAPHQL_COURSE_TMPL
= '''
32 query BootstrapPlayer {
45 course(courseId: "%s") {
49 translationLanguages {
53 supportsWideScreenVideoFormats
81 def _download_course(self
, course_id
, url
, display_id
):
83 return self
._download
_course
_rpc
(course_id
, url
, display_id
)
84 except ExtractorError
:
86 return self
._download
_json
(
87 'https://app.pluralsight.com/player/user/api/v1/player/payload',
88 display_id
, data
=urlencode_postdata({'courseId': course_id
}),
89 headers
={'Referer': url
})
91 def _download_course_rpc(self
, course_id
, url
, display_id
):
92 response
= self
._download
_json
(
93 self
._GRAPHQL
_EP
, display_id
, data
=json
.dumps({
94 'query': self
._GRAPHQL
_COURSE
_TMPL
% course_id
,
96 }).encode(), headers
=self
._GRAPHQL
_HEADERS
)
99 response
, lambda x
: x
['data']['rpc']['bootstrapPlayer']['course'],
104 raise ExtractorError(
105 '{} said: {}'.format(self
.IE_NAME
, response
['error']['message']),
109 class PluralsightIE(PluralsightBaseIE
):
110 IE_NAME
= 'pluralsight'
111 _VALID_URL
= r
'https?://(?:(?:www|app)\.)?pluralsight\.com/(?:training/)?player\?'
112 _LOGIN_URL
= 'https://app.pluralsight.com/id/'
114 _NETRC_MACHINE
= 'pluralsight'
117 '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',
118 'md5': '4d458cf5cf4c593788672419a8dd4cf8',
120 'id': 'hosting-sql-server-windows-azure-iaas-m7-mgmt-04',
122 'title': 'Demo Monitoring',
125 'skip': 'Requires pluralsight account credentials',
127 'url': 'https://app.pluralsight.com/training/player?course=angularjs-get-started&author=scott-allen&name=angularjs-get-started-m1-introduction&clip=0&mode=live',
128 'only_matching': True,
130 # available without pluralsight account
131 'url': 'http://app.pluralsight.com/training/player?author=scott-allen&name=angularjs-get-started-m1-introduction&mode=live&clip=0&course=angularjs-get-started',
132 'only_matching': True,
134 'url': 'https://app.pluralsight.com/player?course=ccna-intro-networking&author=ross-bagurdes&name=ccna-intro-networking-m06&clip=0',
135 'only_matching': True,
138 GRAPHQL_VIEWCLIP_TMPL
= '''
141 author: "%(author)s",
142 clipIndex: %(clipIndex)d,
143 courseName: "%(courseName)s",
144 includeCaptions: %(includeCaptions)s,
145 locale: "%(locale)s",
146 mediaType: "%(mediaType)s",
147 moduleName: "%(moduleName)s",
148 quality: "%(quality)s"
160 def _perform_login(self
, username
, password
):
161 login_page
= self
._download
_webpage
(
162 self
._LOGIN
_URL
, None, 'Downloading login page')
164 login_form
= self
._hidden
_inputs
(login_page
)
167 'Username': username
,
168 'Password': password
,
171 post_url
= self
._search
_regex
(
172 r
'<form[^>]+action=(["\'])(?P
<url
>.+?
)\
1', login_page,
173 'post url
', default=self._LOGIN_URL, group='url
')
175 if not post_url.startswith('http
'):
176 post_url = urllib.parse.urljoin(self._LOGIN_URL, post_url)
178 response = self._download_webpage(
179 post_url, None, 'Logging
in',
180 data=urlencode_postdata(login_form),
181 headers={'Content
-Type
': 'application
/x
-www
-form
-urlencoded
'})
183 error = self._search_regex(
184 r'<span
[^
>]+class="field-validation-error"[^
>]*>([^
<]+)</span
>',
185 response, 'error message
', default=None)
187 raise ExtractorError(f'Unable to login
: {error}
', expected=True)
189 if all(not re.search(p, response) for p in (
190 r'__INITIAL_STATE__
', r'["\']currentUser["\']',
192 r'>\s
*Sign out\s
*<')):
193 BLOCKED = 'Your account has been blocked due to suspicious activity
'
194 if BLOCKED in response:
195 raise ExtractorError(
196 f'Unable to login
: {BLOCKED}
', expected=True)
197 MUST_AGREE = 'To
continue using Pluralsight
, you must agree to
'
198 if any(p in response for p in (MUST_AGREE, '>Disagree
<', '>Agree
<')):
199 raise ExtractorError(
200 f'Unable to login
: {MUST_AGREE} some documents
. Go to pluralsight
.com
, '
201 'log
in and agree with what Pluralsight requires
.', expected=True)
203 raise ExtractorError('Unable to log
in')
205 def _get_subtitles(self, author, clip_idx, clip_id, lang, name, duration, video_id):
208 captions = self._download_json(
209 f'{self
._API
_BASE
}/transcript
/api
/v1
/caption
/json
/{clip_id}
/{lang}
', video_id,
210 'Downloading captions JSON
', 'Unable to download captions JSON
',
219 captions = self._download_json(
220 f'{self
._API
_BASE
}/player
/retrieve
-captions
', video_id,
221 'Downloading captions JSON
', 'Unable to download captions JSON
',
222 fatal=False, data=json.dumps(captions_post).encode(),
223 headers={'Content
-Type
': 'application
/json
;charset
=utf
-8'})
228 'data
': json.dumps(captions),
231 'data
': self._convert_subtitles(duration, captions),
236 def _convert_subtitles(duration, subs):
238 TIME_OFFSET_KEYS = ('displayTimeOffset
', 'DisplayTimeOffset
')
239 TEXT_KEYS = ('text
', 'Text
')
240 for num, current in enumerate(subs):
243 float_or_none(dict_get(current, TIME_OFFSET_KEYS, skip_false_values=False)),
244 dict_get(current, TEXT_KEYS))
245 if start is None or text is None:
247 end = duration if num == len(subs) - 1 else float_or_none(
248 dict_get(subs[num + 1], TIME_OFFSET_KEYS, skip_false_values=False))
251 srt += os.linesep.join(
254 f'{srt_subtitles_timecode(start
)} --> {srt_subtitles_timecode(end
)}',
260 def _real_extract(self, url):
263 author = qs.get('author
', [None])[0]
264 name = qs.get('name
', [None])[0]
265 clip_idx = qs.get('clip
', [None])[0]
266 course_name = qs.get('course
', [None])[0]
268 if any(not f for f in (author, name, clip_idx, course_name)):
269 raise ExtractorError('Invalid URL
', expected=True)
271 display_id = f'{name}
-{clip_idx}
'
273 course = self._download_course(course_name, url, display_id)
275 collection = course['modules
']
279 for module_ in collection:
280 if name in (module_.get('moduleName
'), module_.get('name
')):
281 for clip_ in module_.get('clips
', []):
282 clip_index = clip_.get('clipIndex
')
283 if clip_index is None:
284 clip_index = clip_.get('index
')
285 if clip_index is None:
287 if str(clip_index) == clip_idx:
292 raise ExtractorError('Unable to resolve clip
')
294 title = clip['title
']
295 clip_id = clip.get('clipName
') or clip.get('name
') or clip['clipId
']
298 'low
': {'width
': 640, 'height
': 480},
299 'medium
': {'width
': 848, 'height
': 640},
300 'high
': {'width
': 1024, 'height
': 768},
301 'high
-widescreen
': {'width
': 1280, 'height
': 720},
304 QUALITIES_PREFERENCE = ('low
', 'medium
', 'high
', 'high
-widescreen
')
305 quality_key = qualities(QUALITIES_PREFERENCE)
307 AllowedQuality = collections.namedtuple('AllowedQuality
', ['ext
', 'qualities
'])
309 ALLOWED_QUALITIES = (
310 AllowedQuality('webm
', ['high
']),
311 AllowedQuality('mp4
', ['low
', 'medium
', 'high
']),
314 # Some courses also offer widescreen resolution for high quality (see
315 # https://github.com/ytdl-org/youtube-dl/issues/7766)
316 widescreen = course.get('supportsWideScreenVideoFormats
') is True
317 best_quality = 'high
-widescreen
' if widescreen else 'high
'
319 for allowed_quality in ALLOWED_QUALITIES:
320 allowed_quality.qualities.append(best_quality)
322 # In order to minimize the number of calls to ViewClip API and reduce
323 # the probability of being throttled or banned by Pluralsight we will request
324 # only single format until formats listing was explicitly requested.
325 if self.get_param('listformats
', False):
326 allowed_qualities = ALLOWED_QUALITIES
328 def guess_allowed_qualities():
329 req_format = self.get_param('format
') or 'best
'
330 req_format_split = req_format.split('-', 1)
331 if len(req_format_split) > 1:
332 req_ext, req_quality = req_format_split
333 req_quality = '-'.join(req_quality.split('-')[:2])
334 for allowed_quality in ALLOWED_QUALITIES:
335 if req_ext == allowed_quality.ext and req_quality in allowed_quality.qualities:
336 return (AllowedQuality(req_ext, (req_quality, )), )
337 req_ext = 'webm
' if self.get_param('prefer_free_formats
') else 'mp4
'
338 return (AllowedQuality(req_ext, (best_quality, )), )
339 allowed_qualities = guess_allowed_qualities()
342 for ext, qualities_ in allowed_qualities:
343 for quality in qualities_:
344 f = QUALITIES[quality].copy()
347 'includeCaptions
': 'false
',
348 'clipIndex
': int(clip_idx),
349 'courseName
': course_name,
353 'quality
': '%dx%d' % (f['width
'], f['height
']),
355 format_id = f'{ext}
-{quality}
'
358 viewclip = self._download_json(
359 self._GRAPHQL_EP, display_id,
360 f'Downloading {format_id} viewclip graphql
',
362 'query
': self.GRAPHQL_VIEWCLIP_TMPL % clip_post,
365 headers=self._GRAPHQL_HEADERS)['data
']['viewClip
']
366 except ExtractorError:
367 # Still works but most likely will go soon
368 viewclip = self._download_json(
369 f'{self
._API
_BASE
}/video
/clips
/viewclip
', display_id,
370 f'Downloading {format_id} viewclip JSON
', fatal=False,
371 data=json.dumps(clip_post).encode(),
372 headers={'Content
-Type
': 'application
/json
;charset
=utf
-8'})
374 # Pluralsight tracks multiple sequential calls to ViewClip API and start
375 # to return 429 HTTP errors after some time (see
376 # https://github.com/ytdl-org/youtube-dl/pull/6989). Moreover it may even lead
377 # to account ban (see https://github.com/ytdl-org/youtube-dl/issues/6842).
378 # To somewhat reduce the probability of these consequences
379 # we will sleep random amount of time before each call to ViewClip.
381 random.randint(5, 10), display_id,
382 '%(video_id)s: Waiting
for %(timeout)s seconds to avoid throttling
')
387 clip_urls = viewclip.get('urls
')
388 if not isinstance(clip_urls, list):
391 for clip_url_data in clip_urls:
392 clip_url = clip_url_data.get('url
')
395 cdn = clip_url_data.get('cdn
')
400 'format_id
': f'{format_id}
-{cdn}
' if cdn else format_id,
401 'quality
': quality_key(quality),
402 'source_preference
': int_or_none(clip_url_data.get('rank
')),
404 formats.append(clip_f)
406 duration = int_or_none(
407 clip.get('duration
')) or parse_duration(clip.get('formattedDuration
'))
409 # TODO: other languages?
410 subtitles = self.extract_subtitles(
411 author, clip_idx, clip.get('clipId
'), 'en
', name, duration, display_id)
416 'duration
': duration,
419 'subtitles
': subtitles,
423 class PluralsightCourseIE(PluralsightBaseIE):
424 IE_NAME = 'pluralsight
:course
'
425 _VALID_URL = r'https?
://(?
:(?
:www|app
)\
.)?pluralsight\
.com
/(?
:library
/)?courses
/(?P
<id>[^
/]+)'
427 # Free course from Pluralsight Starter Subscription for Microsoft TechNet
428 # https://offers.pluralsight.com/technet?loc=zTS3z&prod=zOTprodz&tech=zOttechz&prog=zOTprogz&type=zSOz&media=zOTmediaz&country=zUSz
429 'url
': 'http
://www
.pluralsight
.com
/courses
/hosting
-sql
-server
-windows
-azure
-iaas
',
431 'id': 'hosting
-sql
-server
-windows
-azure
-iaas
',
432 'title
': 'Hosting SQL Server
in Microsoft Azure IaaS Fundamentals
',
433 'description
': 'md5
:61b37e60f21c4b2f91dc621a977d0986
',
435 'playlist_count
': 31,
437 # available without pluralsight account
438 'url
': 'https
://www
.pluralsight
.com
/courses
/angularjs
-get
-started
',
439 'only_matching
': True,
441 'url
': 'https
://app
.pluralsight
.com
/library
/courses
/understanding
-microsoft
-azure
-amazon
-aws
/table
-of
-contents
',
442 'only_matching
': True,
445 def _real_extract(self, url):
446 course_id = self._match_id(url)
450 course = self._download_course(course_id, url, course_id)
452 title = course['title
']
453 course_name = course['name
']
454 course_data = course['modules
']
455 description = course.get('description
') or course.get('shortDescription
')
458 for num, module in enumerate(course_data, 1):
459 author = module.get('author
')
460 module_name = module.get('name
')
461 if not author or not module_name:
463 for clip in module.get('clips
', []):
464 clip_index = int_or_none(clip.get('index
'))
465 if clip_index is None:
467 clip_url = update_url_query(
468 f'{self
._API
_BASE
}/player
', query={
470 'course
': course_name,
476 '_type
': 'url_transparent
',
478 'ie_key
': PluralsightIE.ie_key(),
479 'chapter
': module.get('title
'),
480 'chapter_number
': num,
481 'chapter_id
': module.get('moduleRef
'),
484 return self.playlist_result(entries, course_id, title, description)